Compare commits

..
49 Commits
Author SHA1 Message Date
tajniak81andClaude Opus 5.5 3db12dba63 Connected cars: update the odometer automatically
The provider tab gets an "Update odometer automatically" switch and an
interval (30 minutes to a week, daily by default). The API Server does
the updating on the scheduler's ticker, so it carries on with no page
open: every five minutes it takes the provider's odometer for each due
car and stores it when it is ahead, never backwards, the same as the
Update odometer button.

The setting belongs to the car. Readings are fetched under the account
of whoever switched it on, and stop if that user can no longer edit the
car. Each attempt and its error, if any, are stored on the car and shown
under the switch. The switch also shows when the provider can't be
reached, so updates that are failing can still be switched off.

New car fields odometer_auto_sync, odometer_sync_minutes,
odometer_sync_by, odometer_synced_at and odometer_sync_error; new route
PUT /api/cars/{id}/provider/auto-sync. Unlinking leaves the setting as
it is; the sweep only looks at linked cars.

launch.json gains api-server-8081 / web-app-8081 for when 8080 is taken.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:07:02 +01:00
tajniak81andClaude Opus 5.5 914aeeee23 Toyota Connected: Toyota, Lexus and Subaru as three plugins
One connector, registered once per brand with the brand fixed, so the
panel, the Web App and the Phone App each list Toyota, Lexus and Subaru
separately: own card, own account, own enable switch, own
/api/integrations/{brand} routes and vehicle provider. The brand picker
is gone.

Settings saved before the split under pluginSettings.toyota with brand
L or S move onto their brand's key on read, and are written back on the
next save. Cars linked as provider "toyota" read through their make's
brand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:32:35 +01:00
tajniak81andClaude Opus 5.5 9d8636ee73 Anker Solix: a 403 that is not about the token spends no login
anker-solix-api v3.9.1 (2026-10-25) and ha-anker-solix 3.9.1.1 (2026-10-30).
The release is mostly PPS, F3000 and A91B2 work, and none of it reaches an
A5191. The emergency fix does. On 29 October Anker retired an endpoint by
answering it 403. Clients took every 403 for an evicted token and logged in
again on every poll, and that ended in a 24-hour IP ban, code 100041 "Hit max
login error limit" (ha-anker-solix #658, #659). This connector treated a 403
the same way. A successful login clears the backoff, so nothing would have
stopped the loop.

A refused token now costs a login only when one could help:
- A token issued less than two minutes ago was not evicted, so its refusal is
  the endpoint saying no.
- If another request has already replaced the token, the retry uses that
  token and no new login is made.
- An endpoint that refuses a fresh token is left alone for an hour. Its
  requests still go out and fail on their own, and no further logins are
  spent on it.
- Code 100041 holds the next login attempt back for an hour. More attempts
  only add to the count, and only a new public IP lifts the ban early.

Already as upstream now has it: the MQTT client does not mark a topic
subscribed when its SUBACK refuses it, and a malformed message is dropped
without touching the connection. The v3.9.1 signature comment (secret[:16]
after the handshake, presetKey only for the exchange) matches
payloadcrypto.go.

Toyota: pytoyoda has nothing after 6.0.0, which e7d2ef8 ported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:44:43 +01:00
tajniak81andClaude Opus 5.5 0ea562a80a SeaweedFS: S3 gateway on the compose network only
PocketBase reaches the gateway over the compose network (or inside the
AIO container), so publishing 8333 on the host only made a second
SeaweedFS stack fail with "port is already allocated". Drop the binding
and SEAWEED_S3_BIND/SEAWEED_S3_PORT.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 18:07:08 +01:00
tajniak81andClaude Opus 5.5 8849fcfb40 Anker Solix: what upstream v3.9.0 changed for a charger
anker-solix-api v3.9.0 (2026-09-29) is mostly PPS work — time-of-use plans
over the cloud API, device energy queries, a condensed V2 command map — and
none of that reaches an A5191; its MQTT map and command definitions are
unchanged from v3.8.1. Three things do:

- Singapore accounts live on the EU server (ha-anker-solix #593), so SG
  leaves the .com list.
- A charger still showing a finished session can be started again. The app
  offers Start while status is completed; the mode options did not
  (ha-anker-solix #629, #630).
- A re-login after a rejected token drops the payload handshake with the
  token, as upstream now does on a failed login. It was never reused — a
  successful login cleared it and ensureCipher refuses without a token —
  but it no longer outlives the token it was run under.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 17:22:35 +02:00
tajniak81andClaude Opus 5.5 e7d2ef84cd Toyota: the electric read moves too, and a plug-in hybrid gets its fuel
pytoyoda went from 5.2.7 to 6.0.0. Two changes cross over to a connector that
returns raw JSON.

The electric status read was the one route left on /v1/global/remote after the
mid-2026 retirement. Toyota has now fenced it the same way, and the app reads
the same data from /v1/vehicle/electric/status; that is where the electric
capability now points. Upstream took the route from a capture of the app and
has proved it only with unit tests, so the old route is kept: when the new one
answers 403 or 404, the read is tried once on the old one before it fails.

Upstream also widened the electric gate from fuelType "E" to "E" or "I", since
"I" is Toyota's code for a plug-in hybrid. The car importer passed the code
through the generic normalizer, which knows neither letter, so an imported
Toyota came in without a fuel type. "E" now imports as electric and "I" as
hybrid; other letters stay unset because nothing pins them down.

The plugin is now 0.4.0.

Left where they were: phevUsableBatteryLevel, a new field on the electric
payload, already reaches the card because the payload is passed through
whole. The trip list has stopped returning routes, which are now one call per
trip on /v1/trips/{id}; this connector has never read trips.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 17:11:02 +02:00
tajniak81andClaude Opus 5 143917f0bb Ignore the protocol maps, Toyota's beside Anker's
The Anker protocol maps are kept out of the tree as local copies of published
artifacts; the Toyota API map is the same kind of file and joins the rule. The
file itself stays on disk.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 17:38:04 +02:00
tajniak81andClaude Opus 5 f8b39fa0a3 Anker Solix: the encrypted transport the app uses, ported from upstream v3.8.2
anker-solix-api v3.8.2 (2026-09-13) worked out the mobile app's REST payload
encryption end to end — a second ECDH handshake after login, then every body
AES-sealed and HMAC-signed both ways. Anker's servers still accept the plain
JSON this connector has always sent, and upstream leaves the mode off for that
reason; this ports it so that the day they stop is a config change rather than
an outage.

payloadcrypto.go holds the handshake (openapi/oauth/key/exchange, both public
keys wrapped under the app's presetKey) and the per-request envelope
(AES-128-CBC under secret[:16], x-signature keyed on its ascii hex). The
handshake lives beside the token in the shared session and is dropped with it,
so a fresh login is a fresh handshake before the retry. The switch is a
global-layer field, payloadEncryption, default off: it is how the connector
talks to Anker rather than whose account it talks as, so it does not cascade —
ankerCloudConfig copies it into every per-user config, and the six places that
built that map by hand now go through it.

Verified against a fake cloud that implements the server half from upstream's
description, not against Anker's; the switch should be tried on a test account
before it is relied on. Nothing else in v3.8.2 reaches an EV charger: the
Solarbank expansion sizing, the Gen 2 smart meter and the new site parameter
types are other devices, and the A5191 MQTT block is unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 16:40:43 +02:00
tajniak81andClaude Opus 5 a26c608fc3 Toyota: the Subaru realm, and the header the app now sends everywhere
pytoyoda moved from 5.2.0 to 5.2.7 in the four days before this, and most of
it is Pydantic defaults and pagination that a connector returning raw JSON
never had. Two things cross over.

The Solterra is a Toyota underneath and lives on the same Connected Europe
backend, but a Subaru account does not log in as the MyToyota app: it has its
own ForgeRock realm (alliance-subaru), its own OAuth client and redirect, and
its own client credentials, on the same host. The four login URLs that were
constants become a brandAuth chosen at Init — Toyota and Lexus keep the tme
realm and the oneapp client, Subaru gets its own — and the three URLs are
derived from the parts that differ, because the shape is ForgeRock's and does
not vary by realm. Past the login nothing changes: same data API, same
endpoints, same headers, which is why it is a third option on the connector
rather than a fourth connector. A brand on the wrong realm authenticates
against a directory it is not in and reads as a bad password, so a test pins
each brand to its realm and client.

The app now sends x-user-region on every call. The gateway only insists on it
for remote commands on Suzuki-badged DCM24 cars, which this connector never
issues; but a read that is identical to the app's is cheaper to keep than one
that is deliberately distinct, so it goes out too. The x-appbrand/brand pair
that Lexus already sent goes out for Subaru as well; a Toyota account still
sends neither.

The brand is chosen in three places that do not read the descriptor — the Web
App and Phone App settings forms hard-code their options — so Subaru is added
to both, and to the six translation files behind them. The car importer
expands "S" to Subaru so an imported Solterra gets its make.

Left where they were: the trips endpoint, which predates the last sync and
wants a date range and a card, and the wake calls, which a read-only
connector does not make.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 16:28:50 +02:00
tajniak81andClaude Opus 5 c9a95131a5 The single-process object store follows its split sibling into the image
Dockerfile.seaweedfs bakes `weed server -s3` into the all-in-one as a
fourth supervisord program, sharing every build stage and the nginx
config with Dockerfile.seaweedfs.split. The gateway's single identity is
mapped from the PB_S3_* pair PocketBase already authenticates with, and
an empty pair refuses to start rather than serving allow-anyone. The
seaweedfs-init container becomes a step in PocketBase's program — wait
for the gateway, create the bucket, then serve — so the bucket exists
before the API Server's bootstrap checks it, in the order compose kept
with depends_on. The volume server moves to 8081 because 8080 is the API
Server; weed server has one bind flag for all four roles, so it stays
open and the comment says never to publish it.

docker-compose.prod.seaweedfs.yml goes from three services to one, with
build: and image: both set under a registry name of its own. The env
example and README follow.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-11 14:59:16 +02:00
tajniak81andClaude Opus 5 28f5fda451 The split object store moves into the image it was kept out of
Dockerfile.seaweedfs.split bakes SeaweedFS master, volume, filer, S3
gateway and admin UI into the all-in-one as five more supervisord
programs, with the weed binary copied from the official image and pinned
by SEAWEED_VERSION. The readiness chain the compose split expressed with
depends_on and healthchecks becomes until-wget loops: master, volume,
filer, then the gateway, which seeds the bucket and PocketBase's identity
and refuses to serve if the grep gate fails. The volume server sits on
8081 because 8080 is the API Server; every role except the gateway and
the admin UI binds loopback.

docker-compose.prod.seaweedfs.split.yml goes from six services to one,
with build: and image: both set so the same file builds, pushes and
pulls, under a registry name of its own since this image expects three
volumes. The env example and README follow.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-11 14:43:49 +02:00
tajniak81andClaude Opus 5 dcdc437efa The brace that closed nothing took the car screens with it
CarStrings' placeholder pattern escaped its opening brace and left the
closing one bare. Desktop java.util.regex reads a lone "}" as a literal;
Android compiles through ICU, which refuses it. So the companion object
threw PatternSyntaxException the first time anything touched it, which is
VaultScreen's constructor, which is every car screen there is — the host
bound the service, the app died, and the head unit sat black with nothing
in the log but a clean bind.

i18n.dart, which this is the twin of, escapes both. Do the same.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-06 22:16:55 +02:00
tajniak81andClaude Opus 5 6393543bf5 The car is not somewhere you can sideload an app into
Android Auto's Unknown sources setting covers media, messaging and
parked apps; it has never covered the Car App Library, so the README's
advice to turn it on could not have worked. A head unit lists DriverVault
only when Play was the installer — an internal track is enough — and the
Desktop Head Unit is what takes a sideloaded build. Say that instead, and
say which APK the DHU wants, since only a debug build allows its host.

minCarApiLevel also claimed a floor lower than the screens stand on:
GarageScreen asks for ConstraintManager, which is level 2.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-06 21:24:30 +02:00
tajniak81andClaude Opus 5 3c34b708b9 A mode that does not work stops being on the menu
The control-mode picker offered all five paths to everyone, always. When one of
them is broken in a deployment — OCPP is, right now — there was nothing to do
about it: the superadmin could pick a different mode for the global layer, but
the option stayed in every organization's and every user's dropdown, waiting to
be chosen. The cascade could impose a mode. It could not withdraw one.

So each layer now carries a second, separate thing: a list of the modes it hides
from the layers below it. controlModesDisabled sits beside controlMode, on the
global layer as a plugin config field and on an organization as part of the same
pluginSettings blob its credentials already live in. A superadmin ticking Own
CSMS and Proxy CSMS takes both OCPP paths out of every picker underneath; an org
admin ticking Modbus takes it out of their own users'.

Three decisions are worth naming.

A hide-list governs the layers below, not the layer holding it. The superadmin
can keep running Proxy globally while hiding it from everyone else, which is
what you want while a mode is being repaired rather than retired: the operator
testing the fix is the one person who still needs to select it. The alternative,
a list that also invalidates its own layer's choice, would have made the panel
contradict itself — a mode chosen in one field and switched off in the one below
it.

But a hidden mode really is hidden, not merely absent from a dropdown. A user
who had picked Proxy last month stops resolving to Proxy the moment the
superadmin hides it, and falls back to monitoring only. Filtering the picker
alone would have left every existing charger on the broken path and quietly
disagreed with the list the operator had just filled in. Resolution now walks
the layers accumulating what each hides from the next, so a stored value only
takes effect if the layers above it still permit it.

And off is never hideable. It is what a charger falls back to and what an empty
cascade resolves to, so a layer that could take it away could leave the layer
below with a picker holding no valid choice at all. It is not among the
checkboxes in any of the three clients, and the parser drops it if it arrives
anyway.

The panel needed a field shape it did not have — several options, any number
chosen — so ConfigField grows a "multiselect" type, stored as the
comma-separated string that fits the flat map every other field already uses.
That is generic: any plugin can declare one now, and the PUT body is unchanged.
The phone's field specs grew the same way, a scopeOptions hook that narrows a
declared option list to what the server still offers, rather than teaching the
integration card about control modes specifically.

Both clients clamp a stored mode that has since been hidden back to off before
drawing the picker, so the box shows what will actually happen rather than a
choice that would be dropped on save.

Verified: Go tests pass, both frontends build, flutter analyze is clean, and the
panel's new checkbox field was rendered against the real stylesheet. The
end-to-end path — superadmin hides a mode, an org admin and then a user reload
and find it gone — has not been walked on a live stack; the panel is embedded in
the Go binary, so the remote deployment needs a rebuild before any of this is
visible there.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-05 12:54:30 +02:00
tajniak81andClaude Opus 5 d4b9d0870e The server notices its own token has run out
Signing in worked and everything after it did not: the login screen took the
password, PocketBase handed back the record and the token, and then /api/me
answered "The requested resource wasn't found." The three symptoms underneath
looked unrelated — a 404 on the profile, an organization whose name came back
empty, a user list with nobody in it — and they are one thing. The API Server's
superuser token had expired.

PocketBase does not say so. A record call carrying a token it no longer accepts
is not refused; the header is ignored and the request is served as a guest, and
the collection rules answer in the transport's place. The organizations
collection is superuser-only, so it 403s. A user record is guarded by a view
rule, so it 404s — hidden rather than denied. The users list is rule-filtered,
so it comes back 200 with an empty array. Not one of those is a 401, and a 401
was the only thing that made this client sign in again.

So the token was acquired once at startup and then kept for the life of the
container, and the retry meant to renew it could never fire. Uptime longer than
the token's lifetime was all it took. Nothing had to change for it to break,
which is why it broke on a stack nobody had touched.

The client now reads the exp claim PocketBase stamps into the token and renews
before spending it, a minute early so a call cannot land just after it lapses.
A token with no readable expiry is still taken at face value, and the 401 retry
stays where it is as the backstop for the case this does not cover.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-05 11:52:39 +02:00
tajniak81andClaude Opus 5 fe1e314df9 The store comes apart into the four roles it always had
`weed server -s3` was never one thing. Master, volume, filer and the S3
gateway ran as four goroutines under one process, on one volume, sharing one
fate. Splitting them into four containers changes nothing a client can see —
the same bucket answers on the same port — but it makes three things possible
that were not: the SeaweedFS admin UI, which wants a cluster to look at; a
restart or an upgrade of one role without the others; and, eventually, a second
volume server somewhere else. A fifth container carries the panel itself.

The single-process files stay exactly as they were. These are `.split.` twins
beside them, four in all, one per folder per shape, each with the .env example
of the same name that both READMEs already promise.

Identities are the part that could not simply be copied across. SeaweedFS picks
its credentials from one source, in order: an -s3.config file, the filer's IAM
store, then AWS_ACCESS_KEY_ID and its secret — and a higher source replaces a
lower one rather than adding to it. The existing files use the env pair, which
is fine precisely because nothing else writes identities there. Hand somebody a
panel that can, and the first user they create lands in the filer's store, the
store outranks the environment, and PocketBase's key stops existing — with the
first failed upload as the notification. So the gateway here is started with no
config file and no AWS_* at all, and the init container seeds PocketBase's
identity into the filer's store instead: the same store the panel writes. One
source of truth, PocketBase's key sitting in Object Store → Users beside every
other, keys minted there picked up without a restart, and a rotated
PB_S3_SECRET re-applied in place on the next boot rather than added as a second
identity.

That seeding is now allowed to fail. The bucket-create it grew out of was
best-effort — `|| true`, on the reasoning that the API Server's own S3 check
would report a gateway that was genuinely unreachable. That reasoning does not
survive the change: a gateway whose IAM store is empty does not refuse anyone,
it serves everyone, and the bucket would be wide open rather than unreachable.
So the step ends by grepping the configuration back for the access key, the
gateway waits on it completing successfully, and a seed that did not land stops
the stack instead of opening it.

The prod files publish the gateway and the panel, both on loopback, and nothing
else. Port 8080 on the volume server hands out file content by file id with no
authentication of any kind — the S3 credentials have no bearing on it — so
publishing it would publish every attachment in the stack, and the panel shows
what that port and the master's would. The panel's own password is required
rather than defaulted, because weed serves it with authentication switched off
entirely when it is empty, and a page that mints bucket credentials is the
bucket. It is passed as WEED_ADMIN_PASSWORD rather than a flag so it stays off
the process command line, and SEAWEED_ADMIN_BIND is the knob a remote host
needs, named after PB_BIND and API_BIND for the same reason.

Master, volume and filer share one /data mount rather than taking three of
their own. That is precisely the layout `weed server -dir=/data` writes — the
master's raft state, the volume's .dat and .idx, the filer's filerldb2, no two
of them naming the same file — so a stack can move between the single-process
file and its twin in either direction with nothing to migrate. A second volume
server would need its own, and the files say so where somebody would go looking.

The dev files map the volume server to 8081 on the host: 8080 there is already
the API Server, and in the all-in-one it is the API Server inside the image.

Unexercised: written on a machine without Docker, so none of the four has been
brought up. Every flag, health path and env name was read out of the pinned
4.45 source rather than recalled — -mdir, -volumeSizeLimitMB, -defaultStoreDir,
-max, admin's -master and -dataDir and WEED_ADMIN_*, the filer's and gateway's
/healthz, the panel's unauthenticated /health — and the four files were parsed,
interpolated against their examples, and checked for duplicate host ports. A
`docker compose config` on the target host is still the first thing to run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 20:35:42 +02:00
tajniak81andClaude Opus 5 9a2a4ab72e The files leave the volume the database sits on
Every attachment — a document scan, a fuel receipt, a workshop invoice, a
photo of a part's box — has lived inside pb_data, in a directory beside the
SQLite file. One volume held both, so neither could be sized, backed up or
moved without the other. PocketBase can keep those bytes in an S3 bucket
instead, and now it is told to.

Nothing on the way to a client changes, because an attachment was never a
storage URL to begin with: it is fetched from GET /api/{records}/{id}/file,
which re-checks car access and asks PocketBase for the bytes as the service
account. PocketBase streams from the bucket through that same endpoint rather
than redirecting to it, so the web app, the phone and the plugin cannot tell
which side of the switch they are on.

The bootstrap that already creates the collections now writes PocketBase's
files-storage settings too, from PB_S3_*, on every boot and only when they
differ from what is already there — then asks PocketBase to prove it can reach
the bucket, and says so in the log either way. Two asymmetries are deliberate.
A read of the settings masks the stored secret, so a rotation of the secret
alone is invisible from here and needs another PB_S3_* to move with it. And it
never turns S3 back off: files already written to a bucket are reachable only
while PocketBase still points at it, so dropping the configuration would strand
them rather than undo anything.

Each deployment shape is one compose file with an .env example of the same
name, not a base plus an overlay to remember — six of each per folder, for
Docker and Docker-AIO alike: the plain one, .seaweedfs, .s3, and the three prod
twins. The SeaweedFS files run master, volume, filer and gateway as one process
and a one-shot init container beside it, because PocketBase never issues a
CreateBucket and SeaweedFS will not conjure one on first upload. The credentials
do double duty there — the gateway's only identity is also what PocketBase
authenticates with. In the all-in-one that gateway is a second container rather
than a fourth process under supervisord: keeping the object store inside the
image, on the volume the files are being moved off, would have defeated the
point and would have meant rebuilding.

Files uploaded before the switch are not carried across; PocketBase copies
nothing, and both READMEs say so where an operator will read it.

The TLS overlay and its Caddyfile go. The section they served stays, without
them: nothing in the stack terminates TLS any more, so it now names the four
variables to set in front of whichever proxy already does — TRUST_FORWARDED_PROTO
being the one that decides whether a charger is believed about how it arrived.

Unexercised: this was written on a machine without Docker, so the pinned
SeaweedFS image, the bucket-create and the settings write have not been run
against a live stack. The Go side builds, vets and tests clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 19:32:19 +02:00
tajniak81andClaude Opus 5 181f55a849 The phone catches up with the month the web had
Twenty-eight commits landed on the web app and the API since the phone was
last touched, and the phone's own README opens by claiming full feature
parity. It was not a small drift: a whole tab, two whole cards, and the two
settings that decide how a time is read.

The scheduler arrives as the third charging tab. One list of tasks covering
every charger the account owns, where the charger's own cloud schedule is one
window inside one box. A task is a flow — start at 23:00, cap to 10 A at
01:00, stop at 06:30 — on the days and the chargers it names, and naming no
charger means all of them, including the ones imported later. The clock is the
server's, so the tab only writes tasks and reads back how each one last went,
and any step can be fired now to find out whether it will reach the charger
before the night it matters.

The RFID card comes with it: the list the account holds, a card added by its
number or by holding it against the charger's own reader, and the charger's
own list read back from the device. Both halves are written by every add and
remove and they can still come apart, so when they disagree the card says
which list each card is missing from — nothing else on the page would.

The charger settings card the phone never had at all goes in whole rather than
only its new half. Over Modbus that is the four writable registers; over the
cloud it is the charger's whole settings group in sections, drawn from the same
block table the web reads, one write per section because the charger takes a
command whole and a schedule carrying only its switch is a schedule whose times
have just been set to midnight.

The clock and the week become settings. format.dart grows formatTime, the
weekday order and the short names, with "auto" asking intl's own hour pattern
and FIRSTDAYOFWEEK rather than a table here; Settings › Appearance asks both
questions beneath the date. Flutter's own picker renders on the device locale,
which nothing in this app steers, so TimeField types four digits on whichever
clock is in force and keeps the meridiem as its own control — a box reading
13:45 beside a dial saying 01:45 PM is the disagreement the setting exists to
end.

The smaller ones travel too. The control card says which charger its buttons
drive, picture and name, because it follows a serial and not the highlighted
row; its two tiles take the names of the readings they actually hold; and the
limit slider leaves it wherever a settings card now owns that value. The list's
reachability re-asks every thirty seconds while the tab is in front, merged
rather than replaced — "we could not ask" is not an answer, and it certainly is
not "unknown". A settings frame that answers half a minute late is chased at
widening gaps and then given up on. The information card names the fields the
service sent under its own names and groups list records under their own, so
list[0].* stops being read as one alphabetical run. An inherited integration
field shows what it inherited rather than an example. The sign-in fields say
nothing until you type.

One gap stays open, and deliberately. The task form sends the phone's zone only
when Dart reports an IANA name; Android usually answers with an abbreviation
like CEST, which is not a zone, so it sends nothing and the server falls back to
its own clock. A name the server would misread is worse than no name.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 15:11:19 +02:00
tajniak81andClaude Opus 5 2b4f4f034d A task holds the whole night, not one end of it
One command per task was the wrong unit. A charging window is two commands
and reads as one intention, so it was two rows that had to be named twice,
switched off twice, and kept in step by hand — and there was nowhere to put
the third thing, the ease down to 10 A once the house is asleep.

So a task holds a flow. Steps are rows in the editor: an action, a time, and
the ceiling under the one action that takes one. The chargers and the days
belong to the task, because they are the same for every step of a night, and
the switch governs all of it.

The steps keep the order they were written rather than being sorted by the
clock. A night crosses midnight, and clock order files "start at 23:00" last,
behind the stop that closes it — which is not the flow anybody described.
Nothing about firing depends on the order: every step is timed on its own,
and the sweep asks each one whether its minute has come.

Run now moved onto the step. A flow is not a thing that can happen at once —
firing a start and the stop that closes it back to back would leave the
charger where it began and prove nothing — so the button fires the one line
it sits on, and the outcome names the step by its time.

The stored shape changes with it: action/amps/time give way to a steps list.
The collection was a day old and empty, so this replaces them outright rather
than carrying a compatibility path for a schema nothing has run on.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 23:32:07 +02:00
tajniak81andClaude Opus 5 0f48093d1a A week that starts where the person reading it starts theirs
The scheduler's day picker began on Sunday because that is where Intl
numbers the days from, which is a fact about the API and not about
anybody's week. Monday leads it across most of Europe. A row of seven
buttons in the wrong order is not just odd to read — it is easy to
misclick, and a misclicked day in a schedule is a car charging on the
wrong night.

So Settings › Appearance asks, beneath the date and the clock, as the
third question a region gets: first day of the week, following the region
unless it is answered outright. The same shape the time format already
had, and the same "auto" default, so nothing changes for an account that
never opens it.

The rule lives in lib/format.js beside the clock's, with the ordering, the
day names and the sort all coming from there. The two places that lay
weekdays out — the picker and the line each task is summarised on — read
it rather than each keeping an opinion, so a day set is written and read
back in the same order.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 23:12:10 +02:00
tajniak81andClaude Opus 5 5a4515978f One schedule for every charger, and a clock on the server to keep it
The charger's own cloud schedule is one window inside one box: charge
between these hours, every day, and that is the whole vocabulary. A third
tab on Charging holds a list instead — each line an action, a time, the
days it repeats on and the chargers it acts on — and one list covers the
whole account rather than each charger hiding its own.

The clock is the server's. A schedule that only fires while a tab is open
is a reminder, so a ticker sweeps every enabled task and fires whichever
minute has come. It sends by handing a synthesised request to the same
control endpoint the page's buttons use, so a scheduled command goes
through the same cascade, ownership gate, rate limit and audit trail —
what the owner cannot press by hand, the scheduler cannot send for them.

A task names its chargers, or names none, which means all of them and
keeps meaning that for a charger imported next year. Times are stored as
a wall clock plus the zone they were written in, so 23:00 stays 23:00
wherever the server sits. One action per task: a charging window is the
two tasks that open and close it, which is how it is read back, edited
and switched off.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 22:47:30 +02:00
tajniak81andClaude Opus 5 8e4c22cfcf The settings card takes a second look, because the charger answers late
Measured on an A5191 rather than guessed at. The settings frame is not
lost and it is not missed: it lands about half a minute after the read
that asked for it, by which time that read has long returned. The value
goes into the server's state and stays there — six polls afterwards all
carried the same settingsAt, served from cache in a dozen milliseconds.

What was missing was the second look. Nothing on the page took one, so a
card that came up before the answer arrived stayed empty until something
else happened to refresh it. That is the whole of "it doesn't always
load".

So a refresh that comes back without the settings half queues another, at
six seconds, twelve, twenty-four, forty-five, and then stops. Bounded
because the message the server asks with is one the reference reads as
carrying an Anker bug: a charger that never answers is a real
possibility, and a page left open all day must not poll one for ever. The
patience resets per charger, and the chase stops on an error and on
unmount.

The previous attempt at this treated it as a wait that was too short and
lengthened it from four seconds to twelve. That was the wrong half of the
problem — the delay is thirty-odd — and waiting it out inside a UI
request would be a poor trade. The longer wait is left where it is; it
was not wrong, only insufficient.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 22:05:40 +02:00
tajniak81andClaude Opus 5 4bcf1305be The bolts in the list keep asking who is reachable
Two things kept the charger list showing whatever was true when the tab
opened.

The map of who is online was replaced wholesale on every read, so a
service that would not answer took every charger it knows about grey with
it — and then the read marked the question asked, and the guard above it
meant nothing asked again. One failed call and the list sat colourless
until somebody pressed Refresh. It merges now, and only when something
actually answered: a provider that answered overwrites its own entries, a
provider that could not be reached leaves its last word standing. "We
could not ask" is not an answer, and it is not "unknown" either.

And it only ever asked once. There is a thirty-second poll now, running
only while the tab is being looked at — not on the public tab, not while
the page is hidden, and asking straight away on the way back rather than
waiting out an interval that was never going to fire.

The poll takes the reachability half alone, which is what the second
argument is for. That is one call per connected service, back in about a
quarter of a second. The per-charger views behind it are a dozen cloud
endpoints each, and a background poll has no business spending those.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 21:19:07 +02:00
tajniak81andClaude Opus 5 dd636bbe03 A time box that reads on the clock the user chose
The schedule windows met this account with "12:00 AM", clipped to
"12:00 A!" by a box too narrow for it, while the card above them printed
00:00. Both halves of that are the native control: <input type="time">
renders in the browser's locale, and its am/pm did not fit.

Nothing on the page moves it. lang= was measured rather than assumed —
five inputs set to en-US, en-GB, da-DK, pl-PL and nothing came out
identically wide, because the control follows navigator.languages and not
the document. That is the wall DateField hit for dates, so the answer has
its shape: the typing half is ours, the value stays 24-hour "HH:MM", and
what the box shows follows the setting.

Four digits, the colon inserted as they are typed, the meridiem its own
control rather than something to spell. No picker button: a calendar
earns one, four digits do not, and the browser's popup would have brought
the 12-hour reading back in with it. A half-typed or impossible time
emits nothing rather than the part of it that parses, so a block's Apply
leaves that field out instead of writing a time nobody meant.

format.js exports which clock is in force now, so what prints a time and
what accepts one cannot disagree about it.

The box is 80px because 12:30 measures 66 with its padding and the first
attempt at 64 clipped — which was the complaint.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 21:13:42 +02:00
tajniak81andClaude Opus 5 4ff73e5110 Brightness and the solar floor become sliders too
Both are a place on a short, known range, which is what the slider row
added for the current limit is for. Typing 70 into a box that only accepts
tens was the worse way to say it.

The solar minimum gets no floor note under it. The current limit's says
that below six amps the charger pauses rather than charging slowly, which
is a sentence about a ceiling; this is the least a solar charge will
draw, and the same words would be wrong about it.

Main breaker limit stays a box. Ten to five hundred amps is too wide a
range to aim at with a slider.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 21:01:01 +02:00
tajniak81andClaude Opus 5 c1b76a801d An inherited field shows what it inherited, not an example
Country read "DE" under the words "inherited from your organization",
while the organization it was inheriting from said DK. The DE was never
a value at all — it was the example placeholder, left in place when the
field locked, and an example in that position is not a hint. It is a
wrong answer to the question the box is being asked: which country am I
inheriting?

The server had already settled what may be shown. It sends the secrets
back as dots and everything else in the clear, country included, and only
the panel was throwing that away. So a locked field now placeholders its
effective value, and the example is kept for the case it was written for:
an empty box waiting to be filled in.

Applied to the non-secret cascading fields rather than to the one that
was noticed — Green Cell's port, serial, timeout and command topic had
the same example hardcoded a card further down, and would have told the
same lie the moment an org set them.

The dots are left alone. They are the panel's own masking, and rerouting
them through the server's effective value would be the same result by a
different path — not worth changing how a secret is displayed as a side
effect of this.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 20:51:57 +02:00
tajniak81andClaude Opus 5 830ef0cde5 The region says which clock, this app says how to punctuate it
Auto was the region's answer whole, dot and all, so Denmark got 13.45
while every explicit setting beside it wrote 13:45. One screen punctuating
a time differently from the next is not local colour, it is an
inconsistency, and it was ours to fix rather than the locale's.

So the region is asked one question now — does this reader expect 13:45
or 01:45 pm, which is a real difference in how people tell the time — and
the printing is the same two lines for all three settings. Denmark, Poland
and Japan read 24-hour and get 13:45 from auto; the US reads 12-hour and
gets 01:45 pm from it, with the same colon and the same marker as
everywhere else.

The marker reads in English wherever it appears. That is the trade the
setting already made when it offered a 12-hour clock to regions that do
not use one.

This drops the formatToParts pass from the commit before it: once both
halves are fully specified there is nothing left to ask the locale, and
the answer is shorter written out.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 20:34:51 +02:00
tajniak81andClaude Opus 5 263d35c688 Picking a clock picks its separator too
24-hour read as 13.45 in Denmark, because that is how Danish writes a
clock and toLocaleTimeString was doing as it was told. But somebody who
leaves "follow the region" and picks 24-hour has just said they want the
region to stop deciding — and they mean 13:45.

So the two explicit modes build the string from formatToParts and pin the
mark between the hour and the minute. Only that one literal is replaced:
everything else stays the locale's, which is why Japanese keeps 午後 in
front of it and English keeps its lowercase pm after. 12-hour got the
same for free — it had the identical 01.45 pm.

Auto is left alone. A setting that says to follow the region has no
business arguing with it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 20:29:49 +02:00
tajniak81andClaude Opus 5 4d51a34c44 The settings card stops emptying when one message is late
A snapshot has two halves and they travel separately: telemetry comes
from the trigger, the settings only when the charger has something to say
about itself. A read can land with the first and not the second — most
often the first read after a reconnect — and the card was seeded from
that answer alone, so it collapsed to the one control telemetry happens
to carry. That is the state of one message, not the state of the charger.

Three things, from the outside in.

The card keeps what the charger has reported, per serial, across reads. A
value stays until another replaces it. They are its own last word either
way, and the same ones the server fills a grouped command's siblings from
when a caller leaves them out.

A charger that goes quiet is no longer written off for good. The miss
counter decides whether a read waits for the settings frame at all, and
it only ever rose: three unanswered requests early on and no later read
waited again, however freely the charger answered afterwards. The comment
said "recently enough"; the code said "ever". Answering clears it now.

And the first settings are worth the wait a settings write already gives
them. Stale settings and never-reported settings were both allowed four
seconds. Stale has something to fall back on; never-reported is the empty
card, so it gets the full wait — still bounded by the miss counter, so a
charger that truly never answers costs it three times and no more.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 20:26:38 +02:00
tajniak81andClaude Opus 5 c65ce0c081 Two tiles named for what they were, not for what they show
The control card's first two tiles were named when OCPP was the only
thing they read. "Connector" is what an OCPP connector state is, and
"Energy" is what a meter total is. Both tiles learned to read the
charger's own snapshot instead — statusDesc and the session's own energy
— and neither name followed.

They take the readings card's names now, and only where they are showing
the readings card's values: the same statusDesc it calls Charging status,
the same session energy it calls Session energy. One value, one name, in
both places it appears. OCPP keeps the old two, which are right for what
it puts there.

Both strings were already translated, so this adds none.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 20:21:28 +02:00
tajniak81andClaude Opus 5 7b339d3dac Tap the card, and that is the whole enrolment
The reader already filled the number in; adding it still meant walking
back to the keyboard and pressing Add. That walk was the entire cost of
the two-step version, and the card is in your hand at the charger. One
press now opens the reader and writes whatever is held against it.

The name is the server's own convention — RFID and the card's last four
digits — because the name is left empty and rfidSaveCard fills it in.
Deriving the same pattern here would have been a second place for it to
drift; every card already on the account reads that way. A name typed
into the box still wins, since throwing away what somebody typed is
worse than the convention.

The reader is a value now rather than a side effect on the form, and the
write is shared with the typed path so the two cannot judge their answers
differently. The caller holds the busy flag across both halves: nothing
re-enables in the gap, where a second press would have opened a second
twenty-second window. The number lands in the box on the way past, so a
write that fails leaves something to retry rather than a card nobody can
name.

The old button stays for the times the number is wanted without the card
being added.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 20:10:13 +02:00
tajniak81andClaude Opus 5 e190364c77 One ceiling, one slider, in the card that owns it
The current limit sat in the control card and in the settings card at
once. Over the cloud those were not two settings that happen to agree:
the "limit" command builds its frame from the same table entry the
maxCurrentA setting does, so it was one wire field with two controls.
The control card gives it up wherever a settings card can take it —
which, now that the cloud has one, is both transports that read the
charger.

OCPP keeps its slider. A charging profile is not a setting the charger
reports, so there is no settings card to move it to, and clearing a
limit is OCPP's alone: the cloud sets a ceiling and has no message for
"no ceiling". Taking the control away there would have left those modes
unable to set a limit at all.

It arrives in the settings card as the slider it was, not as the number
box the table gave it. Slider rows stack — label and the value it is at
on one line, the track beneath, the floor hint under that — because a
ceiling is a thing you slide between two known ends rather than type.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 18:53:48 +02:00
tajniak81andClaude Opus 5 dde5410788 The clock stops being a side effect of the region
Whether a time read as 13.45 or 01.45 pm was decided by the region
picker, which also sets the decimal separator and the currency layout —
so a Dane who wanted a 12-hour clock had to move their numbers to get
one. Time format is its own setting now, beside the date format it is
the other half of.

It defaults to "auto", the region's own convention, which is what every
timestamp in the app already said: nothing moves until somebody picks
something. The 24-hour setting asks for hourCycle h23 rather than
hour12:false, because with hour12 the en-US formatter prints midnight as
24:00.

One helper, so it reaches everywhere at once: formatDateTime now calls
formatTime, and every clock the app draws goes through it — the
charger's telemetry and settings, a session's start, when a charger was
linked, the provider panel's own timestamp.

The users collection gains a time_format select in both places the
schema is declared; it is in reconcileOrder, so a restart adds the field
and nothing has to be migrated by hand.

The native time inputs in the charger's settings card are left alone:
the browser renders those in the OS convention whatever this says, and a
text box that respected the setting would be the worse control.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 18:32:52 +02:00
tajniak81andClaude Opus 5 3fddab6815 The control card says which charger the buttons move
The product shot was already in the account's charger list and already
relayed; only the information card ever drew it. The card whose buttons
start a session had no sign at all of which charger it meant — the name
lives two cards further down, and two A5191s on one account look alike in
a dropdown.

Identified by the serial in force rather than by the record highlighted
in the list beside it. They are usually the same charger, and when they
are not, a picture of the other one is worse than no picture. Either
source will do: the account's own list, or the live half held per
provider, which carry the same image.

A shot that will not load is remembered by its URL, so the picture stops
being drawn and comes back on its own if the service starts answering for
it again — nothing to reset when the serial changes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 18:20:33 +02:00
tajniak81andClaude Opus 5 9d4aecb668 The settings card stops being a Modbus card
Both transports that read the charger can also be told things, so both get
the card now. Modbus has four writable registers and keeps the four
controls it had. The cloud has the charger's whole settings group — two
dozen of them, everything the Anker app sets short of the card list — and
they were readable in the readings card and settable nowhere.

Drawn from a table rather than written out one control at a time, because
the charger's commands own sets of fields and take a command whole: a
schedule frame carrying only its switch is a schedule whose times have
just been set to midnight. So a section is one command, its fields are
sent together, and Apply is per section. Only what the charger has
reported gets a control — a blank box that writes whatever it was left at
is worse than no box when the value travels as a sibling.

The meter and monitor the balancing features watch stay read-only: there
is no command for them, and what their modes select is undocumented. The
phase select offers the automatic and single-phase this command carries,
and shows a reported three-phase rather than reading as something the
charger did not say.

Nothing left the readings card.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 15:19:57 +02:00
tajniak81andClaude Opus 5 3064bff8ad The charger's own card list gets a door, and says where it differs
0104 was already implemented and already in the action catalogue; nothing
routed to it, so the only way to see the device's list was as a side
effect of writing a card. It has an endpoint now, and the panel a button.

The two lists are compared where they meet: a card the charger holds and
the account has forgotten still opens it, and a card only the account
holds will not, and neither shows anywhere else. The comparison is drawn
only when they disagree, and the device's reading is dropped on a refresh
rather than measured against an account list from a later moment.

The new test asks all four card routes without a token: a capability the
plugin implements and the catalogue advertises is still unusable if
nothing routes to it, and no other test here would notice.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 14:35:27 +02:00
tajniak81andClaude Opus 5 7176867eb3 Tap the card on the charger and the number fills itself in
The enrolment the Anker app does, done here: 0108 a2=7 opens the reader,
0908 brings back the UID. The frames this sends are byte-for-byte the
ones the app was captured sending — checksum included — which is what the
new test asserts.

Adding and removing now write the charger as well as the account: the
device write is the app's own message, the account write is the inferred
one that carries the name, and either may fail without the other.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 13:45:00 +02:00
tajniak81andClaude Opus 5 4c73d4ac05 0103 writes a card, 0104 asks for the list, 0108 a2=7 opens the reader
Caught on the charger's own command topic while a card was removed and
added back in the Anker app. Enrolling at the charger is three MQTT
messages and no REST call: open the reader, take the UID the tap
publishes, write it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 13:30:14 +02:00
tajniak81andClaude Opus 5 62b0a29598 The reader speaks: 0904 is the card list, 0908 is the tap
Named from a live capture on an A5191: 0904 carried the nine UIDs the
account's own card list answers with, and 0908 arrived the moment a card
touched the reader, carrying its UID — and arrived without one when the
window closed empty. 0911 names the OCPP backend the charger is pointed
at. A UID is bytes, not a number, so type 0x04 now reads as hex.

With the frame log on, the command topic is subscribed too: the app's own
commands are the half no capture has seen.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 13:04:52 +02:00
tajniak81andClaude Opus 5 a7719fca6a A line per frame, for the frames nobody has named
ANKER_MQTT_FRAME_LOG logs every inbound cloud frame with its bytes,
decoded or not — the ones this package drops are exactly the ones worth
naming, so they are logged before the drop.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 12:08:53 +02:00
tajniak81andClaude Opus 5 245870a96a The add and remove buttons, and the read that checks them
Anker documents neither rfid write, so the bodies are inferred from the
field names get_device_cards answers with, and every write re-reads the
list: what the card shows is what the account holds, never what an
undocumented endpoint claimed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 10:50:00 +02:00
tajniak81andClaude Opus 5 a5842201c0 The cards that open the charger get a card of their own
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 10:36:52 +02:00
tajniak81andClaude Opus 5 4188d049cb An email is an email, whichever list it arrived in
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 10:00:48 +02:00
tajniak81andClaude Opus 5 928a39e03e Each RFID card as a card, not as list[3]
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 09:57:51 +02:00
tajniak81andClaude Opus 5 905eb24cc1 The service's own field names, said in the card's words
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 09:33:03 +02:00
tajniak81andClaude Opus 5 0657decbd1 The sign-in fields say nothing until you type
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 08:51:19 +02:00
tajniak81andClaude Opus 5 4ff6242c8f The last message in the map, and it reboots the charger
0108 was the one thing in the MQTT inventory nobody had wired: the device
power mode, whose single documented value restarts the charger. It is the
only way to reboot a charger that is on neither a CSMS nor the local
network — which is most of them — so the cloud transport sends it now,
and "reset" reaches it too, since that is what the OCPP path has always
called the same act.

Nothing waits for a confirmation: the device that would send it is the
device rebooting, so the command answers at once and says the charger
drops off the cloud for about a minute. The gate is unchanged and now
covers both spellings — an explicit confirm plus a password step-up,
audited either way. Modbus still refuses, because no register does this,
but its refusal now names both transports that can rather than only the
CSMS.

Both clients already had the reset button and its password prompt; they
were hidden in every mode that reads the device, which is why the cloud
never showed one. Modbus is now the only mode without it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-02 23:15:12 +02:00
tajniak81andClaude Opus 5 b2d333a63f The charger was never asked what it is set to
The trigger buys telemetry and only telemetry, so a charger that has been
read a hundred times and commanded none reports amps, volts and nothing
else: no schedule, no balancing, no Modbus server, not even its firmware.
The message that asks for that half is 0040, and the reference keeps it
commented out because the app sends its timestamp without a value type.
The app is what the charger answers, so the oddity is reproduced rather
than corrected — sent when the settings half is missing or older than ten
minutes, waited four seconds for, and after three unanswered requests
still sent but no longer waited on.

The three settings the panel has and the writer did not — swipe up, swipe
down, smart touch — are writable now, which is all eleven of the 0100
commands. Nothing else in the map was missing: every named field of every
message was already decoded, and the raw keys the card shows are fields
the reference does not name either.

Both cards drop a row with nothing in it, which turned a charger that
reports only its ceiling into a charger that reports no current range at
all. Half a range is still a bound.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-02 23:05:40 +02:00
tajniak81andClaude Opus 5 3f9d5b943f Four questions asked of an account that answers twenty-one
The connector called ten endpoints of the read surface the map lists, and
the charger card showed four views. Everything else an EV charger can
reach is now a capability too: the sessions and the history, the savings,
the sharing, the binding, the group, the Wi-Fi, the firmware and its
update log, the tamper records, the site's own detail, price, networks
and energy — plus the vehicle catalogue, dynamic pricing, the currencies
and the notification views. Thirty-eight endpoints, one action each. The
two message views are GET, so the request path grew a GET half that shares
the login retry with the POST one.

The per-charger fan-out asks all of them, six at a time rather than one
after another, and a charger that belongs to a site brings that site's
four views with it once the by-serial lookup has found it. A view that
answers with nothing now says so instead of vanishing: the station record
is empty for a standalone charger because it has no station, which is an
answer worth reading. And "source 0" in the OCPP box carries the address
the account's endpoint list gives it.

Anker's account-level writes stay out, as do the endpoints whose payloads
were only ever read out of the app package.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-02 22:53:36 +02:00
129 changed files with 18728 additions and 971 deletions

No files matched your search

+18
View File
@@ -17,6 +17,24 @@
"port": 5173, "port": 5173,
"autoPort": false "autoPort": false
}, },
{
"name": "api-server-8081",
"runtimeExecutable": "./bin/api-server.exe",
"runtimeArgs": [],
"cwd": "API Server",
"env": { "API_ADDR": ":8081" },
"port": 8081,
"autoPort": false
},
{
"name": "web-app-8081",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "dev"],
"cwd": "Web App/web",
"env": { "VITE_API_TARGET": "http://localhost:8081" },
"port": 5173,
"autoPort": false
},
{ {
"name": "web-bff", "name": "web-bff",
"runtimeExecutable": "go", "runtimeExecutable": "go",
+3 -2
View File
@@ -16,6 +16,7 @@ Thumbs.db
.env .env
*.env.local *.env.local
# Local reference copies of the published Anker protocol map artifacts # Local reference copies of the published protocol map artifacts
# (Modbus TCP, cloud MQTT, cloud REST API, OCPP) # (Anker: Modbus TCP, cloud MQTT, cloud REST API, OCPP; Toyota: cloud REST API)
anker-*-map.html anker-*-map.html
toyota-*-map.html
+16
View File
@@ -379,6 +379,22 @@ Copy `.env.example` to `.env` and fill in. Summary:
| `OCPP_PUBLIC_URL` | — | canonical `ws(s)://` base to point chargers at | | `OCPP_PUBLIC_URL` | — | canonical `ws(s)://` base to point chargers at |
| `PB_BOOTSTRAP` | `true` | run the on-boot schema create/reconcile (leave on across upgrades) | | `PB_BOOTSTRAP` | `true` | run the on-boot schema create/reconcile (leave on across upgrades) |
| `DRIVERVAULT_SUPERADMIN_EMAIL` / `_PASSWORD` / `_NAME` | — / — / `Administrator` | first `superadmin`, created on boot when absent | | `DRIVERVAULT_SUPERADMIN_EMAIL` / `_PASSWORD` / `_NAME` | — / — / `Administrator` | first `superadmin`, created on boot when absent |
| `PB_S3_ENABLED` | `false` | keep PocketBase's record files in an S3 bucket instead of on its own volume |
| `PB_S3_BUCKET` | `drivervault` | the bucket; it must already exist |
| `PB_S3_ENDPOINT` | — | e.g. `http://seaweedfs:8333`. No default: in-stack and external gateways are different addresses |
| `PB_S3_REGION` | `us-east-1` | SeaweedFS ignores it, PocketBase insists on one |
| `PB_S3_ACCESS_KEY` / `PB_S3_SECRET` | — | S3 credentials |
| `PB_S3_FORCE_PATH_STYLE` | `true` | path-style bucket addressing; `false` for AWS S3 proper |
The `PB_S3_*` block is applied by the same on-boot bootstrap that creates the
collections, and only when **all** of bucket, endpoint and credentials are set —
a half-filled config logs a warning and leaves uploads on the local volume. It
writes PocketBase's *Files storage* settings and nothing else: backups stay
where they are, and it never turns S3 back *off*, since files already in a bucket
are reachable only while PocketBase still points at it. Attachments are served
through this server either way ([`internal/api/attachments.go`](internal/api/attachments.go)),
so no client can tell the difference. See [`../Docker`](../Docker) for the compose
files that set these.
`PB_URL`, `PB_ADMIN_EMAIL`, `PB_ADMIN_PASSWORD`, `PORT` and `CORS_ORIGINS` are `PB_URL`, `PB_ADMIN_EMAIL`, `PB_ADMIN_PASSWORD`, `PORT` and `CORS_ORIGINS` are
still honoured for older deployments; the modern names win when both are set. still honoured for older deployments; the modern names win when both are set.
+23
View File
@@ -51,12 +51,31 @@ func main() {
// bad service account, must not stop the panel from coming up so a superadmin // bad service account, must not stop the panel from coming up so a superadmin
// can log in and fix the connection. // can log in and fix the connection.
if cfg.Bootstrap && cfg.AdminConfigured() { if cfg.Bootstrap && cfg.AdminConfigured() {
// Record files go to S3 only when the whole bucket is described. Asking
// for it and leaving half of it blank is a misconfiguration worth saying
// out loud, not a reason to point PocketBase at nowhere.
var s3 *bootstrap.S3Options
if cfg.StorageConfigured() {
s3 = &bootstrap.S3Options{
Enabled: true,
Bucket: cfg.S3Bucket,
Region: cfg.S3Region,
Endpoint: cfg.S3Endpoint,
AccessKey: cfg.S3AccessKey,
Secret: cfg.S3Secret,
ForcePathStyle: cfg.S3ForcePathStyle,
}
} else if cfg.S3Enabled {
log.Println("WARNING: PB_S3_ENABLED is set but the bucket, endpoint or credentials are incomplete — file storage stays on the local volume")
}
bootCtx, cancel := context.WithTimeout(context.Background(), 60*time.Second) bootCtx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
if err := bootstrap.Run(bootCtx, client, bootstrap.Options{ if err := bootstrap.Run(bootCtx, client, bootstrap.Options{
UsersCollection: cfg.UsersCollection, UsersCollection: cfg.UsersCollection,
SuperAdminEmail: cfg.SuperAdminEmail, SuperAdminEmail: cfg.SuperAdminEmail,
SuperAdminPassword: cfg.SuperAdminPassword, SuperAdminPassword: cfg.SuperAdminPassword,
SuperAdminName: cfg.SuperAdminName, SuperAdminName: cfg.SuperAdminName,
S3: s3,
}); err != nil { }); err != nil {
log.Printf("WARNING: bootstrap failed: %v", err) log.Printf("WARNING: bootstrap failed: %v", err)
} else { } else {
@@ -73,6 +92,10 @@ func main() {
// endpoints answer 503 until the read succeeds. // endpoints answer 503 until the read succeeds.
_ = srv.StartPlugins() _ = srv.StartPlugins()
// The home-charger scheduler's clock. A schedule that only fires while a
// browser tab is open is a reminder, not a schedule, so it is watched here.
srv.StartScheduler()
httpServer := &http.Server{ httpServer := &http.Server{
Addr: cfg.Addr, Addr: cfg.Addr,
Handler: srv.Handler(), Handler: srv.Handler(),
+1 -5
View File
@@ -127,11 +127,7 @@ func (ankerChargerSource) gate(ctx context.Context, s *Server, who *callerIdenti
if reason := ankerGate(res, true); reason != "" { if reason := ankerGate(res, true); reason != "" {
return nil, false, reason return nil, false, reason
} }
return map[string]string{ return ankerCloudConfig(res), true, ""
"email": res.eff.Email,
"password": res.eff.Password,
"country": res.eff.Country,
}, true, ""
} }
func (ankerChargerSource) chargers(raw json.RawMessage) []providerCharger { func (ankerChargerSource) chargers(raw json.RawMessage) []providerCharger {
+406
View File
@@ -0,0 +1,406 @@
package api
// The home-charger scheduler: the user's own list of charging tasks.
//
// The charger's own cloud schedule can say one thing — "charge between these
// hours" — and it says it inside one charger. This is a list, and each entry is
// a whole flow: start at 23:00, cap to 10 A at 01:00, stop at 06:30, on these
// chargers, on these days. One named thing, switched on and off as one.
//
// GET /api/charging-tasks — the caller's tasks, earliest first
// POST /api/charging-tasks — write one
// PATCH /api/charging-tasks/{id} — edit one (any subset of its fields)
// DELETE /api/charging-tasks/{id} — forget one
// POST /api/charging-tasks/{id}/steps/{n}/run — fire one step now
//
// A task belongs to the person, like the chargers it acts on, so there is no
// sharing here: everyone sees their own list only. Firing one is the business of
// chargingtasks_run.go, which is also what the ticker calls.
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"drivervault/apiserver/internal/models"
)
// The actions a step may carry. Each is a control command the charger already
// understands; the scheduler adds no verbs of its own, so a task can only ask
// for something the buttons on the Charging page can ask for by hand.
var taskActions = map[string]bool{
"start": true,
"stop": true,
"limit": true,
"boost": true,
}
// maxTaskSteps bounds one task's flow. Well past any real schedule — a night
// rate is two or three steps — and it keeps a client from parking an unbounded
// blob on the record, which the sweep then reads every thirty seconds.
const maxTaskSteps = 24
// chargingTaskRecord is the PocketBase-facing shape of a task.
type chargingTaskRecord struct {
ID string `json:"id"`
Name string `json:"name"`
Chargers []string `json:"chargers"`
Steps []models.ChargingStep `json:"steps"`
Zone string `json:"zone"`
Days []int `json:"days"`
Enabled bool `json:"enabled"`
LastRun string `json:"last_run"`
LastResult string `json:"last_result"`
Owner string `json:"owner"`
Created string `json:"created"`
}
func (rec chargingTaskRecord) toModel() models.ChargingTask {
// The lists are never null on the wire: the page iterates them, and a null
// would make "every charger" and "every day" read as an error there.
chargers := rec.Chargers
if chargers == nil {
chargers = []string{}
}
days := rec.Days
if days == nil {
days = []int{}
}
steps := rec.Steps
if steps == nil {
steps = []models.ChargingStep{}
}
return models.ChargingTask{
ID: rec.ID,
Name: rec.Name,
Chargers: chargers,
Steps: steps,
Zone: rec.Zone,
Days: days,
Enabled: rec.Enabled,
LastRun: rec.LastRun,
LastResult: rec.LastResult,
Created: rec.Created,
}
}
// firstStepTime is the time of day a task begins — its first step's, which is
// what the list is ordered by, so the evening's task sits below the morning's. A
// task with no steps cannot exist, but the ordering must not depend on that.
func (rec chargingTaskRecord) firstStepTime() string {
if len(rec.Steps) == 0 {
return "99:99"
}
return rec.Steps[0].Time
}
// chargingTaskBody is the write shape. Every field is a pointer so a PATCH can
// name one of them without the rest being read as "clear these" — a task
// switched off from the list must not lose its flow on the way.
type chargingTaskBody struct {
Name *string `json:"name"`
Chargers *[]string `json:"chargers"`
Steps *[]models.ChargingStep `json:"steps"`
Zone *string `json:"zone"`
Days *[]int `json:"days"`
Enabled *bool `json:"enabled"`
}
// parseHHMM splits a 24-hour clock time into its two numbers. "H:MM" is accepted
// as well as "HH:MM"; anything else is not a time of day.
func parseHHMM(raw string) (int, int, bool) {
hh, mm, found := strings.Cut(strings.TrimSpace(raw), ":")
if !found || len(hh) == 0 || len(hh) > 2 || len(mm) != 2 {
return 0, 0, false
}
h, err := strconv.Atoi(hh)
if err != nil {
return 0, 0, false
}
m, err := strconv.Atoi(mm)
if err != nil {
return 0, 0, false
}
if h < 0 || h > 23 || m < 0 || m > 59 {
return 0, 0, false
}
return h, m, true
}
// normalizeTaskTime returns the padded 24-hour form of a time of day, or "" for
// anything that is not one.
func normalizeTaskTime(raw string) string {
h, m, ok := parseHHMM(raw)
if !ok {
return ""
}
return fmt.Sprintf("%02d:%02d", h, m)
}
// normalizeDays drops anything that is not a weekday number and sorts what is
// left, so the stored list reads the same however the client sent it. Empty
// stays empty, which means every day.
func normalizeDays(days []int) []int {
seen := [7]bool{}
for _, d := range days {
if d >= 0 && d <= 6 {
seen[d] = true
}
}
out := []int{}
for d, ok := range seen {
if ok {
out = append(out, d)
}
}
return out
}
// normalizeSteps validates a flow, keeping the steps in the order they were
// written.
//
// Not sorted by time: a night crosses midnight, and clock order would file
// "start at 23:00" last, behind the stop that closes it. Nothing about firing
// depends on the order — every step is timed on its own — so the order is free
// to be the one that reads as the intention it is.
func normalizeSteps(steps []models.ChargingStep) ([]models.ChargingStep, error) {
if len(steps) == 0 {
return nil, fmt.Errorf("a task needs at least one step")
}
if len(steps) > maxTaskSteps {
return nil, fmt.Errorf("a task can hold at most %d steps", maxTaskSteps)
}
out := make([]models.ChargingStep, 0, len(steps))
for i, step := range steps {
action := strings.TrimSpace(step.Action)
if !taskActions[action] {
return nil, fmt.Errorf("step %d: unknown action: %s", i+1, action)
}
at := normalizeTaskTime(step.Time)
if at == "" {
return nil, fmt.Errorf("step %d: time must be a 24-hour clock time, e.g. 23:00", i+1)
}
// The ceiling only means anything to "limit", but it is kept whatever the
// action is: switching a step to "limit" and back should not lose the amps
// that were typed. 6 A is the charger's own floor — below it the box pauses
// rather than charging slowly — and its ratings top out at 32 A.
if step.Amps != 0 && (step.Amps < 6 || step.Amps > 32) {
return nil, fmt.Errorf("step %d: the current limit must be between 6 and 32 A", i+1)
}
// A limit step with no ceiling would fire and ask the charger for 0 A.
if action == "limit" && step.Amps <= 0 {
return nil, fmt.Errorf("step %d: a limit step needs the amps to limit to", i+1)
}
out = append(out, models.ChargingStep{Action: action, Amps: step.Amps, Time: at})
}
return out, nil
}
// taskPayload turns a write body into the PocketBase fields it names, validating
// as it goes. `full` demands the fields a task cannot exist without, so a POST is
// checked as a whole and a PATCH only where it speaks.
func taskPayload(body chargingTaskBody, full bool) (map[string]any, error) {
payload := map[string]any{}
if body.Name != nil {
name := strings.TrimSpace(*body.Name)
if name == "" {
return nil, fmt.Errorf("name is required")
}
payload["name"] = name
} else if full {
return nil, fmt.Errorf("name is required")
}
if body.Steps != nil {
steps, err := normalizeSteps(*body.Steps)
if err != nil {
return nil, err
}
payload["steps"] = steps
} else if full {
return nil, fmt.Errorf("a task needs at least one step")
}
if body.Chargers != nil {
ids := []string{}
for _, id := range *body.Chargers {
if id = strings.TrimSpace(id); id != "" {
ids = append(ids, id)
}
}
payload["chargers"] = ids
}
if body.Days != nil {
payload["days"] = normalizeDays(*body.Days)
}
if body.Zone != nil {
payload["zone"] = strings.TrimSpace(*body.Zone)
}
if body.Enabled != nil {
payload["enabled"] = *body.Enabled
} else if full {
// A task written without saying otherwise is on: nobody fills in a
// schedule in order to leave it switched off.
payload["enabled"] = true
}
return payload, nil
}
// listChargingTasks returns the caller's own tasks, the one that starts earliest
// first — the order the day runs them in, which is the order a schedule is read
// in. Ordered here rather than by PocketBase because the time a task starts is
// now inside its flow, which is not a column to sort on.
func (s *Server) listChargingTasks(w http.ResponseWriter, r *http.Request) {
me := s.currentUserID(r)
if me == "" {
writeError(w, http.StatusUnauthorized, "not authenticated")
return
}
res, err := s.pb.List(r.Context(), colChargingTasks, url.Values{
"filter": {fmt.Sprintf("owner='%s'", me)},
"perPage": {"200"},
})
if err != nil {
writePBError(w, err)
return
}
var recs []chargingTaskRecord
if err := json.Unmarshal(res.Items, &recs); err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
sort.SliceStable(recs, func(i, j int) bool {
return recs[i].firstStepTime() < recs[j].firstStepTime()
})
out := make([]models.ChargingTask, 0, len(recs))
for _, rec := range recs {
out = append(out, rec.toModel())
}
writeJSON(w, http.StatusOK, map[string]any{"tasks": out})
}
// ownedChargingTask fetches one task and checks it is the caller's. It writes the
// error response itself and returns ok=false when it is not.
func (s *Server) ownedChargingTask(w http.ResponseWriter, r *http.Request) (chargingTaskRecord, bool) {
var rec chargingTaskRecord
id := strings.TrimSpace(r.PathValue("id"))
if id == "" {
writeError(w, http.StatusBadRequest, "task id is required")
return rec, false
}
if err := s.pb.GetOne(r.Context(), colChargingTasks, id, &rec); err != nil {
writePBError(w, err)
return rec, false
}
// Someone else's task is not found rather than forbidden, as a charger is:
// whether a record exists is not this caller's business either.
if rec.Owner != s.currentUserID(r) {
writeError(w, http.StatusNotFound, "task not found")
return rec, false
}
return rec, true
}
func (s *Server) createChargingTask(w http.ResponseWriter, r *http.Request) {
me := s.currentUserID(r)
if me == "" {
writeError(w, http.StatusUnauthorized, "not authenticated")
return
}
var body chargingTaskBody
if err := decodeJSON(r, &body); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
payload, err := taskPayload(body, true)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
payload["owner"] = me
var rec chargingTaskRecord
if err := s.pb.Create(r.Context(), colChargingTasks, payload, &rec); err != nil {
writePBError(w, err)
return
}
writeJSON(w, http.StatusCreated, map[string]any{"task": rec.toModel()})
}
func (s *Server) updateChargingTask(w http.ResponseWriter, r *http.Request) {
rec, ok := s.ownedChargingTask(w, r)
if !ok {
return
}
var body chargingTaskBody
if err := decodeJSON(r, &body); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
payload, err := taskPayload(body, false)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if len(payload) == 0 {
writeJSON(w, http.StatusOK, map[string]any{"task": rec.toModel()})
return
}
var updated chargingTaskRecord
if err := s.pb.Update(r.Context(), colChargingTasks, rec.ID, payload, &updated); err != nil {
writePBError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]any{"task": updated.toModel()})
}
func (s *Server) deleteChargingTask(w http.ResponseWriter, r *http.Request) {
rec, ok := s.ownedChargingTask(w, r)
if !ok {
return
}
if err := s.pb.Delete(r.Context(), colChargingTasks, rec.ID); err != nil {
writePBError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// runChargingStepNow fires one step of a task on demand — the "Run now" beside
// it. One step rather than the whole flow, because a flow is not a thing that
// can happen at once: running a start and the stop that closes it back to back
// would leave the charger where it began and prove nothing.
//
// It takes the same path the ticker does, so what comes back is exactly what
// that step will do at its own time, errors included. A switched-off task still
// runs from here: the switch says whether the clock fires it, not whether the
// button does.
func (s *Server) runChargingStepNow(w http.ResponseWriter, r *http.Request) {
rec, ok := s.ownedChargingTask(w, r)
if !ok {
return
}
n, err := strconv.Atoi(strings.TrimSpace(r.PathValue("step")))
if err != nil || n < 0 || n >= len(rec.Steps) {
writeError(w, http.StatusNotFound, "this task has no such step")
return
}
who := caller(r)
if who == nil {
writeError(w, http.StatusUnauthorized, "not authenticated")
return
}
step := rec.Steps[n]
results := s.fireChargingSteps(r.Context(), who, rec, []models.ChargingStep{step})
s.recordTaskRun(r.Context(), rec, step, results)
// The same line that was just stored, so the row the caller updates from this
// answer reads identically to the one a page reload would fetch.
writeJSON(w, http.StatusOK, map[string]any{
"results": results,
"summary": taskRunLine(step, results),
})
}
@@ -0,0 +1,381 @@
package api
// Firing the scheduler's tasks: the ticker that watches the clock, and the one
// path a task takes whichever set it off.
//
// The scheduler is only worth having if it fires with nobody looking, so the
// clock is watched here rather than in the browser — a schedule that needs the
// page open is a reminder, not a schedule. The ticker sweeps every enabled task
// on the server, of every user, and fires whichever ones' minute has come.
//
// A task acts by sending exactly the control command the Charging page's own
// buttons send: the request is built here and handed to the same handler, so it
// goes through the same cascade, the same ownership gate, the same rate limit
// and the same audit trail. Nothing about a scheduled command is privileged —
// what the owner cannot press by hand, the scheduler cannot send for them.
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"sort"
"strings"
"time"
_ "time/tzdata" // tasks are timed in the user's own zone; hosts without a zone database are common on Windows
"drivervault/apiserver/internal/models"
)
// How often the clock is looked at. Tasks are timed to the minute, so a sweep
// twice a minute is enough to land in every minute without the drift a
// once-a-minute ticker accumulates.
const taskTick = 30 * time.Second
// How long one sweep may take. Generous rather than tight: the cloud transport
// alone allows 45 seconds for a single command, and a task can name several
// chargers. A sweep that overran would not overlap the next one — the ticker
// drops a tick nobody is waiting on — but it would abandon chargers halfway
// down a task's list, which is the worst of both.
const taskSweepTimeout = 5 * time.Minute
// taskRunResult is what happened to one charger in one firing.
type taskRunResult struct {
Charger string `json:"charger"` // home charger record id
Name string `json:"name"`
Serial string `json:"serial,omitempty"`
Status string `json:"status,omitempty"` // the charger's own answer ("Accepted", …)
Error string `json:"error,omitempty"`
}
// StartScheduler starts the ticker that fires due charging tasks. It is safe to
// call before PocketBase is reachable: a sweep that cannot read the tasks simply
// finds none and the next one tries again.
//
// One server runs one scheduler. Two API Servers pointed at the same database
// would both sweep and both fire; the deployment is a single server (see the
// README), and the last_run guard below narrows the window rather than closing
// it.
func (s *Server) StartScheduler() {
ctx, cancel := context.WithCancel(context.Background())
s.schedulerStop = cancel
// Automatic odometer updates ride on the same lifetime (odometersync.go).
s.startOdometerSync(ctx)
go func() {
t := time.NewTicker(taskTick)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
s.sweepChargingTasks(ctx)
}
}
}()
}
// sweepChargingTasks fires every task whose minute has come.
func (s *Server) sweepChargingTasks(ctx context.Context) {
if !s.pb.Configured() {
return
}
ctx, cancel := context.WithTimeout(ctx, taskSweepTimeout)
defer cancel()
res, err := s.pb.List(ctx, colChargingTasks, url.Values{
"filter": {"enabled=true"},
"perPage": {"500"},
})
if err != nil {
// A database that is not answering is not an error worth a line every
// thirty seconds; the tasks are still there when it comes back.
return
}
var recs []chargingTaskRecord
if err := json.Unmarshal(res.Items, &recs); err != nil {
return
}
now := time.Now()
for _, rec := range recs {
due := dueSteps(rec, now)
if len(due) == 0 {
continue
}
who, _, err := s.callerForUser(ctx, rec.Owner)
if err != nil {
log.Printf("scheduler: task %s (%s): owner unavailable: %v", rec.ID, rec.Name, err)
continue
}
// Two steps of one task timed to the same minute contradict each other,
// but nothing stops somebody writing them, so both are sent in the order
// the flow holds them rather than one silently winning.
for _, step := range due {
results := s.fireChargingSteps(ctx, who, rec, []models.ChargingStep{step})
s.recordTaskRun(ctx, rec, step, results)
log.Printf("scheduler: task %s (%s) step %s %s: %s",
rec.ID, rec.Name, step.Time, step.Action, summarizeTaskRun(results))
}
}
}
// dueSteps returns the steps of a task whose minute has come — usually one, and
// none at all for the rest of the day.
//
// The times are read in the task's own zone: the browser that wrote it said
// which, and the server's clock is not the one the user set 23:00 by. A zone the
// host has no database for falls back to the server's own rather than silently
// shifting the schedule to UTC.
//
// A minute that passed while the server was down is not caught up afterwards. A
// charging window that opened an hour ago is not a window anyone still wants
// opened, and firing a backlog on boot would be the surprising half of the
// choice.
func dueSteps(rec chargingTaskRecord, now time.Time) []models.ChargingStep {
loc := time.Local
if rec.Zone != "" {
if l, err := time.LoadLocation(rec.Zone); err == nil {
loc = l
}
}
local := now.In(loc)
if len(rec.Days) > 0 && !containsDay(rec.Days, int(local.Weekday())) {
return nil
}
// The guard against firing twice: the sweep runs more often than once a
// minute, so a task that has already run inside this minute is done. It is
// per task rather than per step because two steps never share a minute in
// any flow that means anything — and when they do, they are sent together.
if last, err := time.Parse(time.RFC3339, rec.LastRun); err == nil {
if !last.Before(local.Truncate(time.Minute)) {
return nil
}
}
var due []models.ChargingStep
for _, step := range rec.Steps {
h, m, ok := parseHHMM(step.Time)
if !ok {
continue // a step whose time is not a time of day fires nothing
}
if local.Hour() == h && local.Minute() == m {
due = append(due, step)
}
}
return due
}
func containsDay(days []int, day int) bool {
for _, d := range days {
if d == day {
return true
}
}
return false
}
// fireChargingSteps sends the given steps to each of the task's chargers and
// reports what each one said. A task naming no chargers acts on every charger
// its owner has — "all of them" is a standing wish, so a charger imported after
// the task was written is covered by it too.
func (s *Server) fireChargingSteps(ctx context.Context, who *callerIdentity,
rec chargingTaskRecord, steps []models.ChargingStep) []taskRunResult {
chargers, err := s.ownerChargers(ctx, rec.Owner)
if err != nil {
return []taskRunResult{{Error: err.Error()}}
}
wanted := rec.Chargers
results := []taskRunResult{}
for _, c := range chargers {
if len(wanted) > 0 && !containsID(wanted, c.ID) {
continue
}
out := taskRunResult{Charger: c.ID, Name: c.Name, Serial: c.Serial}
if c.Serial == "" {
// Every transport addresses a charger by its serial, so one without
// is not a charger anything can be sent to.
out.Error = "this charger has no serial number, so no command can be addressed to it"
results = append(results, out)
continue
}
for _, step := range steps {
one := out
status, err := s.sendStep(ctx, who, c.Serial, step)
if err != nil {
one.Error = err.Error()
} else {
one.Status = status
}
results = append(results, one)
}
}
if len(results) == 0 {
results = append(results, taskRunResult{Error: "this task names no charger that still exists"})
}
return results
}
// ownerChargers reads one user's imported chargers. The scheduler reads them
// itself rather than trusting the ids on the task: a charger removed from the
// account should stop being acted on, whether or not the task was edited.
func (s *Server) ownerChargers(ctx context.Context, owner string) ([]homeChargerRecord, error) {
res, err := s.pb.List(ctx, colHomeChargers, url.Values{
"filter": {fmt.Sprintf("owner='%s'", owner)},
"perPage": {"200"},
})
if err != nil {
return nil, err
}
var recs []homeChargerRecord
if err := json.Unmarshal(res.Items, &recs); err != nil {
return nil, err
}
return recs, nil
}
func containsID(ids []string, id string) bool {
for _, x := range ids {
if x == id {
return true
}
}
return false
}
// sendStep sends one step's command to one charger, through the control endpoint
// the page's own buttons use.
//
// The request is synthesised rather than the transports being called directly,
// so a scheduled command cannot end up on a different footing from a pressed
// one: the cascade, the ownership gate, the rate limit and the audit line are
// the endpoint's, and there is no second copy of them here to drift.
func (s *Server) sendStep(ctx context.Context, who *callerIdentity, serial string, step models.ChargingStep) (string, error) {
body := map[string]any{}
if step.Action == "limit" {
body["amps"] = step.Amps
}
raw, err := json.Marshal(body)
if err != nil {
return "", err
}
path := "/api/integrations/anker-solix/chargers/" + url.PathEscape(serial) + "/" + step.Action
req, err := http.NewRequestWithContext(
context.WithValue(ctx, ctxCaller, who), http.MethodPost, path, bytes.NewReader(raw))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
// The endpoint reads its charger and its verb from the route, which nothing
// matched here — this request never went through a mux.
req.SetPathValue("sn", serial)
req.SetPathValue("action", step.Action)
rw := &captureWriter{header: http.Header{}}
s.handleAnkerControlAction(rw, req)
return rw.controlOutcome()
}
// captureWriter is an http.ResponseWriter that keeps the response in memory,
// so a handler can be called without a connection to write down.
type captureWriter struct {
status int
header http.Header
body bytes.Buffer
}
func (c *captureWriter) Header() http.Header { return c.header }
func (c *captureWriter) WriteHeader(status int) {
if c.status == 0 {
c.status = status
}
}
func (c *captureWriter) Write(p []byte) (int, error) {
if c.status == 0 {
c.status = http.StatusOK
}
return c.body.Write(p)
}
// controlOutcome reads a captured control response as the charger's answer or
// the reason there wasn't one. The endpoint answers in one of two shapes — a
// status on success, an error envelope otherwise — and both are read here rather
// than the status code alone, because "why not" is the half worth keeping.
func (c *captureWriter) controlOutcome() (string, error) {
var out struct {
Status string `json:"status"`
Error string `json:"error"`
}
_ = json.Unmarshal(c.body.Bytes(), &out)
if c.status >= 200 && c.status < 300 {
if out.Status == "" {
return "sent", nil
}
return out.Status, nil
}
if out.Error != "" {
return "", fmt.Errorf("%s", out.Error)
}
return "", fmt.Errorf("the charger could not be reached (HTTP %d)", c.status)
}
// summarizeTaskRun says how a firing went in one line — what the list shows
// beside a task, and what goes in the log.
func summarizeTaskRun(results []taskRunResult) string {
ok, failed := 0, []string{}
for _, r := range results {
if r.Error == "" {
ok++
continue
}
name := r.Name
if name == "" {
name = r.Serial
}
if name != "" {
failed = append(failed, name+": "+r.Error)
} else {
failed = append(failed, r.Error)
}
}
sort.Strings(failed)
switch {
case len(failed) == 0:
return fmt.Sprintf("%d of %d sent", ok, len(results))
case ok == 0 && len(failed) == 1:
return failed[0]
default:
return fmt.Sprintf("%d of %d sent — %s", ok, len(results), strings.Join(failed, "; "))
}
}
// taskRunLine is the outcome of one firing as the list shows it: which step, and
// how it went. A task holds several steps now, and "2 of 2 sent" says nothing
// about which of them it was.
//
// The step is named by its time rather than its action, because everything this
// server writes into last_result is in its own words — charger names, the
// control gate's refusals — while the page has a translation for every action.
// A clock time reads the same in all three languages.
func taskRunLine(step models.ChargingStep, results []taskRunResult) string {
return step.Time + " — " + summarizeTaskRun(results)
}
// recordTaskRun stamps a task with when it last fired and how it went.
//
// The stamp is also the guard that keeps a task from firing twice inside its
// minute, so a firing that could not be written down is worth a log line:
// without it the next sweep would send the command again.
func (s *Server) recordTaskRun(ctx context.Context, rec chargingTaskRecord,
step models.ChargingStep, results []taskRunResult) {
payload := map[string]any{
"last_run": time.Now().UTC().Format(time.RFC3339),
"last_result": taskRunLine(step, results),
}
if err := s.pb.Update(ctx, colChargingTasks, rec.ID, payload, nil); err != nil {
log.Printf("scheduler: task %s fired but its outcome could not be saved: %v", rec.ID, err)
}
}
@@ -0,0 +1,332 @@
package api
import (
"strings"
"testing"
"time"
"drivervault/apiserver/internal/models"
)
// The scheduler's clock is the part worth pinning down: it decides on its own,
// with nobody watching, whether to send a car a command. A step that fires in
// the wrong hour is worse than one that does not fire at all, so the zone, the
// weekday and the not-twice-in-one-minute guard are each checked here.
func step(action, at string, amps float64) models.ChargingStep {
return models.ChargingStep{Action: action, Time: at, Amps: amps}
}
func TestDueSteps(t *testing.T) {
warsaw, err := time.LoadLocation("Europe/Warsaw")
if err != nil {
t.Fatalf("Europe/Warsaw: %v", err)
}
// A Wednesday, 23:00 in Warsaw — 22:00 UTC.
at2300 := time.Date(2026, 9, 2, 23, 0, 30, 0, warsaw)
// A whole night in one task, which is the point of a flow: it opens, it
// eases off, it closes.
base := chargingTaskRecord{
Zone: "Europe/Warsaw",
Enabled: true,
Steps: []models.ChargingStep{
step("start", "23:00", 0),
step("limit", "01:00", 10),
step("stop", "06:30", 0),
},
}
due := dueSteps(base, at2300)
if len(due) != 1 || due[0].Action != "start" {
t.Fatalf("at 23:00 got %+v, want just the start step", due)
}
// The same instant handed over as UTC. The zone on the task is what the
// times are read in, so where the server thinks it is must not matter.
if got := dueSteps(base, at2300.UTC()); len(got) != 1 || got[0].Action != "start" {
t.Errorf("the step stopped being due when the same instant arrived as UTC: %+v", got)
}
// The other two steps, each in its own minute and no other.
if got := dueSteps(base, time.Date(2026, 9, 3, 1, 0, 5, 0, warsaw)); len(got) != 1 || got[0].Action != "limit" {
t.Errorf("at 01:00 got %+v, want the limit step", got)
}
if got := dueSteps(base, time.Date(2026, 9, 3, 6, 30, 5, 0, warsaw)); len(got) != 1 || got[0].Action != "stop" {
t.Errorf("at 06:30 got %+v, want the stop step", got)
}
// A minute the flow says nothing about fires nothing — the point being that
// a task with a step at 23:00 is not "on" from 23:00 onwards.
for _, at := range []time.Time{at2300.Add(time.Minute), at2300.Add(-time.Minute),
time.Date(2026, 9, 3, 3, 0, 0, 0, warsaw)} {
if got := dueSteps(base, at); len(got) != 0 {
t.Errorf("at %s got %+v, want nothing due", at.Format("15:04"), got)
}
}
// Weekdays gate the whole task. 2026-09-02 is a Wednesday (3).
weeknights := base
weeknights.Days = []int{1, 2, 3, 4, 5}
if len(dueSteps(weeknights, at2300)) != 1 {
t.Error("a weeknight task did not fire on a Wednesday")
}
weekends := base
weekends.Days = []int{0, 6}
if len(dueSteps(weekends, at2300)) != 0 {
t.Error("a weekend task fired on a Wednesday")
}
// Fired already inside this minute: the sweep runs more than once a minute,
// and the second sweep must not send the command again.
fired := base
fired.LastRun = at2300.UTC().Format(time.RFC3339)
if len(dueSteps(fired, at2300.Add(20*time.Second))) != 0 {
t.Error("a step fired twice inside its own minute")
}
// Yesterday's firing is not this minute's.
yesterday := base
yesterday.LastRun = at2300.Add(-24 * time.Hour).UTC().Format(time.RFC3339)
if len(dueSteps(yesterday, at2300)) != 1 {
t.Error("yesterday's run stopped today's from firing")
}
// A step whose time is not a time of day fires nothing rather than firing at
// midnight, which is what a zero hour and minute would have meant — and it
// does not take the rest of the flow down with it.
broken := base
broken.Steps = []models.ChargingStep{step("start", "later", 0), step("stop", "23:00", 0)}
got := dueSteps(broken, at2300)
if len(got) != 1 || got[0].Action != "stop" {
t.Errorf("got %+v, want only the readable step", got)
}
// Two steps timed to the same minute contradict each other, but nothing
// stops somebody writing them, so both are returned rather than one
// silently winning.
clash := base
clash.Steps = []models.ChargingStep{step("start", "23:00", 0), step("boost", "23:00", 0)}
if got := dueSteps(clash, at2300); len(got) != 2 {
t.Errorf("got %+v, want both steps sharing the minute", got)
}
}
// A zone the host has no database for falls back to the server's own clock
// rather than silently shifting the schedule to UTC.
func TestDueStepsUnknownZone(t *testing.T) {
now := time.Now()
rec := chargingTaskRecord{
Zone: "Mars/Olympus_Mons",
Steps: []models.ChargingStep{step("start", now.Format("15:04"), 0)},
}
if len(dueSteps(rec, now)) != 1 {
t.Error("a task in an unknown zone did not fall back to the server's clock")
}
}
func TestParseHHMM(t *testing.T) {
for _, tc := range []struct {
in string
h, m int
wantOK bool
}{
{in: "23:00", h: 23, m: 0, wantOK: true},
{in: "7:05", h: 7, m: 5, wantOK: true},
{in: " 00:00 ", h: 0, m: 0, wantOK: true},
{in: "24:00"},
{in: "12:60"},
{in: "12:5"}, // a half-typed minute is not a minute
{in: "123:00"}, // nor is a three-digit hour
{in: "12"},
{in: ""},
{in: "ab:cd"},
} {
h, m, ok := parseHHMM(tc.in)
if ok != tc.wantOK {
t.Errorf("parseHHMM(%q) ok = %v, want %v", tc.in, ok, tc.wantOK)
continue
}
if ok && (h != tc.h || m != tc.m) {
t.Errorf("parseHHMM(%q) = %d:%d, want %d:%d", tc.in, h, m, tc.h, tc.m)
}
}
}
func TestNormalizeDays(t *testing.T) {
got := normalizeDays([]int{5, 1, 5, 9, -1, 0})
want := []int{0, 1, 5}
if len(got) != len(want) {
t.Fatalf("normalizeDays = %v, want %v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("normalizeDays = %v, want %v", got, want)
}
}
// Empty means every day and stays empty rather than becoming all seven —
// the two read the same today, but only one keeps meaning "every day".
if len(normalizeDays(nil)) != 0 {
t.Error("normalizeDays(nil) invented days")
}
}
func TestNormalizeSteps(t *testing.T) {
// A night, written the way it is meant: it opens, it eases off, it closes.
// The half-written times are the client's business to send and this
// function's business to pad.
got, err := normalizeSteps([]models.ChargingStep{
step("start", "23:00", 0),
step("limit", "1:00", 10),
step("stop", "6:30", 0),
})
if err != nil {
t.Fatalf("normalizeSteps: %v", err)
}
// Kept in the order it was written. Sorting by the clock would file the
// 23:00 start last, behind the stop that closes it, which is not the flow
// anybody described — and firing does not depend on the order at all.
wantTimes := []string{"23:00", "01:00", "06:30"}
for i, want := range wantTimes {
if got[i].Time != want {
t.Errorf("step %d time = %q, want %q (whole flow: %+v)", i, got[i].Time, want, got)
}
}
for name, steps := range map[string][]models.ChargingStep{
"no steps at all": {},
"an unknown action": {step("melt", "23:00", 0)},
"a time that is not one": {step("start", "half past", 0)},
"a limit with no amps": {step("limit", "23:00", 0)},
"amps below the floor": {step("limit", "23:00", 3)},
"amps above the rating": {step("limit", "23:00", 40)},
} {
if _, err := normalizeSteps(steps); err == nil {
t.Errorf("normalizeSteps accepted %s", name)
}
}
// The cap bounds what the sweep re-reads every thirty seconds.
tooMany := make([]models.ChargingStep, maxTaskSteps+1)
for i := range tooMany {
tooMany[i] = step("start", "23:00", 0)
}
if _, err := normalizeSteps(tooMany); err == nil {
t.Errorf("normalizeSteps accepted %d steps, past the cap of %d", len(tooMany), maxTaskSteps)
}
}
func TestTaskPayloadValidation(t *testing.T) {
str := func(s string) *string { return &s }
steps := func(s ...models.ChargingStep) *[]models.ChargingStep { return &s }
full := chargingTaskBody{
Name: str(" Night rate "),
Steps: steps(step("start", "23:00", 0), step("stop", "6:30", 0)),
}
payload, err := taskPayload(full, true)
if err != nil {
t.Fatalf("taskPayload: %v", err)
}
if payload["name"] != "Night rate" {
t.Errorf("name = %v, want it trimmed", payload["name"])
}
if payload["enabled"] != true {
t.Error("a new task was written switched off; nobody fills in a schedule to leave it off")
}
if flow, _ := payload["steps"].([]models.ChargingStep); len(flow) != 2 || flow[0].Time != "23:00" {
t.Errorf("steps = %+v, want both, as written", payload["steps"])
}
// The two things a task cannot exist without.
for _, missing := range []chargingTaskBody{
{Steps: steps(step("start", "23:00", 0))},
{Name: str("x")},
{Name: str(" "), Steps: steps(step("start", "23:00", 0))},
} {
if _, err := taskPayload(missing, true); err == nil {
t.Errorf("taskPayload accepted an incomplete task: %+v", missing)
}
}
// A partial write says only what it names, so a task switched off from the
// list keeps its flow, its chargers and its days.
on := true
partial, err := taskPayload(chargingTaskBody{Enabled: &on}, false)
if err != nil {
t.Fatalf("taskPayload(partial): %v", err)
}
if len(partial) != 1 {
t.Errorf("a switch-only write touched %v, want only enabled", partial)
}
}
// The list is ordered by the time a task begins, which lives inside its flow
// rather than in a column PocketBase could sort on.
func TestFirstStepTime(t *testing.T) {
rec := chargingTaskRecord{Steps: []models.ChargingStep{step("start", "23:00", 0), step("stop", "06:30", 0)}}
if got := rec.firstStepTime(); got != "23:00" {
t.Errorf("firstStepTime = %q, want the first step's 23:00", got)
}
// A task with no steps cannot be written, but sorting must not depend on
// that — it sorts last rather than first.
if got := (chargingTaskRecord{}).firstStepTime(); got < "23:59" {
t.Errorf("an empty task sorted to %q, want it last", got)
}
}
func TestSummarizeTaskRun(t *testing.T) {
all := summarizeTaskRun([]taskRunResult{
{Name: "Home-DK", Status: "Accepted"},
{Name: "Home-PL", Status: "Accepted"},
})
if all != "2 of 2 sent" {
t.Errorf("summary = %q, want \"2 of 2 sent\"", all)
}
// One charger failing is the case the list has to be able to show: the
// summary names which, because "1 of 2 sent" alone is not actionable.
some := summarizeTaskRun([]taskRunResult{
{Name: "Home-DK", Status: "Accepted"},
{Name: "Home-PL", Error: "charger is not connected"},
})
if !strings.Contains(some, "Home-PL") || !strings.Contains(some, "not connected") {
t.Errorf("summary = %q, want it to name the charger that failed and why", some)
}
// A single failure is its own reason — no count to read past.
only := summarizeTaskRun([]taskRunResult{{Name: "Home-PL", Error: "control mode is off"}})
if only != "Home-PL: control mode is off" {
t.Errorf("summary = %q, want the bare reason", only)
}
}
// The runner reads a control response the same way whichever transport answered
// it: a status when the charger took the command, the endpoint's own words when
// it did not.
func TestCaptureWriterControlOutcome(t *testing.T) {
ok := &captureWriter{header: nil}
ok.WriteHeader(200)
_, _ = ok.Write([]byte(`{"status":"Accepted"}`))
if got, err := ok.controlOutcome(); err != nil || got != "Accepted" {
t.Errorf("controlOutcome = %q, %v; want Accepted", got, err)
}
// A 2xx with nothing to read still means the command went.
bare := &captureWriter{}
bare.WriteHeader(204)
if got, err := bare.controlOutcome(); err != nil || got != "sent" {
t.Errorf("controlOutcome = %q, %v; want sent", got, err)
}
bad := &captureWriter{}
bad.WriteHeader(409)
_, _ = bad.Write([]byte(`{"error":"charger is not connected to the control backend"}`))
_, err := bad.controlOutcome()
if err == nil || !strings.Contains(err.Error(), "not connected") {
t.Errorf("controlOutcome err = %v, want the endpoint's own reason", err)
}
// An error status with no envelope to read still has to say something.
mute := &captureWriter{}
mute.WriteHeader(502)
if _, err := mute.controlOutcome(); err == nil {
t.Error("a 502 with an empty body was read as a success")
}
}
-17
View File
@@ -1,17 +0,0 @@
(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const r of o.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&n(r)}).observe(document,{childList:!0,subtree:!0});function s(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(i){if(i.ep)return;i.ep=!0;const o=s(i);fetch(i.href,o)}})();/**
* @vue/shared v3.5.39
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/function cn(e){const t=Object.create(null);for(const s of e.split(","))t[s]=1;return s=>s in t}const ne={},Tt=[],Ze=()=>{},mi=()=>!1,Ss=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),Es=e=>e.startsWith("onUpdate:"),_e=Object.assign,un=(e,t)=>{const s=e.indexOf(t);s>-1&&e.splice(s,1)},$o=Object.prototype.hasOwnProperty,X=(e,t)=>$o.call(e,t),L=Array.isArray,St=e=>ts(e)==="[object Map]",zt=e=>ts(e)==="[object Set]",zn=e=>ts(e)==="[object Date]",W=e=>typeof e=="function",ue=e=>typeof e=="string",Je=e=>typeof e=="symbol",te=e=>e!==null&&typeof e=="object",bi=e=>(te(e)||W(e))&&W(e.then)&&W(e.catch),vi=Object.prototype.toString,ts=e=>vi.call(e),Oo=e=>ts(e).slice(8,-1),yi=e=>ts(e)==="[object Object]",dn=e=>ue(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,Bt=cn(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),Ps=e=>{const t=Object.create(null);return(s=>t[s]||(t[s]=e(s)))},Do=/-\w/g,je=Ps(e=>e.replace(Do,t=>t.slice(1).toUpperCase())),Ro=/\B([A-Z])/g,ft=Ps(e=>e.replace(Ro,"-$1").toLowerCase()),_i=Ps(e=>e.charAt(0).toUpperCase()+e.slice(1)),Ns=Ps(e=>e?`on${_i(e)}`:""),qe=(e,t)=>!Object.is(e,t),ps=(e,...t)=>{for(let s=0;s<e.length;s++)e[s](...t)},wi=(e,t,s,n=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:n,value:s})},Cs=e=>{const t=parseFloat(e);return isNaN(t)?e:t};let In;const As=()=>In||(In=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function pn(e){if(L(e)){const t={};for(let s=0;s<e.length;s++){const n=e[s],i=ue(n)?Uo(n):pn(n);if(i)for(const o in i)t[o]=i[o]}return t}else if(ue(e)||te(e))return e}const zo=/;(?![^(]*\))/g,Io=/:([^]+)/,jo=/\/\*[^]*?\*\//g;function Uo(e){const t={};return e.replace(jo,"").split(zo).forEach(s=>{if(s){const n=s.split(Io);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function Ee(e){let t="";if(ue(e))t=e;else if(L(e))for(let s=0;s<e.length;s++){const n=Ee(e[s]);n&&(t+=n+" ")}else if(te(e))for(const s in e)e[s]&&(t+=s+" ");return t.trim()}const No="itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly",Mo=cn(No);function xi(e){return!!e||e===""}function Lo(e,t){if(e.length!==t.length)return!1;let s=!0;for(let n=0;s&&n<e.length;n++)s=ut(e[n],t[n]);return s}function ut(e,t){if(e===t)return!0;let s=zn(e),n=zn(t);if(s||n)return s&&n?e.getTime()===t.getTime():!1;if(s=Je(e),n=Je(t),s||n)return e===t;if(s=L(e),n=L(t),s||n)return s&&n?Lo(e,t):!1;if(s=te(e),n=te(t),s||n){if(!s||!n)return!1;const i=Object.keys(e).length,o=Object.keys(t).length;if(i!==o)return!1;for(const r in e){const a=e.hasOwnProperty(r),l=t.hasOwnProperty(r);if(a&&!l||!a&&l||!ut(e[r],t[r]))return!1}}return String(e)===String(t)}function fn(e,t){return e.findIndex(s=>ut(s,t))}const ki=e=>!!(e&&e.__v_isRef===!0),m=e=>ue(e)?e:e==null?"":L(e)||te(e)&&(e.toString===vi||!W(e.toString))?ki(e)?m(e.value):JSON.stringify(e,Ti,2):String(e),Ti=(e,t)=>ki(t)?Ti(e,t.value):St(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((s,[n,i],o)=>(s[Ms(n,o)+" =>"]=i,s),{})}:zt(t)?{[`Set(${t.size})`]:[...t.values()].map(s=>Ms(s))}:Je(t)?Ms(t):te(t)&&!L(t)&&!yi(t)?String(t):t,Ms=(e,t="")=>{var s;return Je(e)?`Symbol(${(s=e.description)!=null?s:t})`:e};/**
* @vue/reactivity v3.5.39
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/let me;class Fo{constructor(t=!1){this.detached=t,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this._warnOnRun=!0,this.__v_skip=!0,!t&&me&&(me.active?(this.parent=me,this.index=(me.scopes||(me.scopes=[])).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let t,s;if(this.scopes)for(t=0,s=this.scopes.length;t<s;t++)this.scopes[t].pause();for(t=0,s=this.effects.length;t<s;t++)this.effects[t].pause()}}resume(){if(this._active&&this._isPaused){this._isPaused=!1;let t,s;if(this.scopes)for(t=0,s=this.scopes.length;t<s;t++)this.scopes[t].resume();for(t=0,s=this.effects.length;t<s;t++)this.effects[t].resume()}}run(t){if(this._active){const s=me;try{return me=this,t()}finally{me=s}}}on(){++this._on===1&&(this.prevScope=me,me=this)}off(){if(this._on>0&&--this._on===0){if(me===this)me=this.prevScope;else{let t=me;for(;t;){if(t.prevScope===this){t.prevScope=this.prevScope;break}t=t.prevScope}}this.prevScope=void 0}}stop(t){if(this._active){this._active=!1;let s,n;for(s=0,n=this.effects.length;s<n;s++)this.effects[s].stop();for(this.effects.length=0,s=0,n=this.cleanups.length;s<n;s++)this.cleanups[s]();if(this.cleanups.length=0,this.scopes){for(s=0,n=this.scopes.length;s<n;s++)this.scopes[s].stop(!0);this.scopes.length=0}if(!this.detached&&this.parent&&!t){const i=this.parent.scopes.pop();i&&i!==this&&(this.parent.scopes[this.index]=i,i.index=this.index)}this.parent=void 0}}}function Bo(){return me}let oe;const Ls=new WeakSet;class Si{constructor(t){this.fn=t,this.deps=void 0,this.depsTail=void 0,this.flags=5,this.next=void 0,this.cleanup=void 0,this.scheduler=void 0,me&&(me.active?me.effects.push(this):this.flags&=-2)}pause(){this.flags|=64}resume(){this.flags&64&&(this.flags&=-65,Ls.has(this)&&(Ls.delete(this),this.trigger()))}notify(){this.flags&2&&!(this.flags&32)||this.flags&8||Pi(this)}run(){if(!(this.flags&1))return this.fn();this.flags|=2,jn(this),Ci(this);const t=oe,s=Ue;oe=this,Ue=!0;try{return this.fn()}finally{Ai(this),oe=t,Ue=s,this.flags&=-3}}stop(){if(this.flags&1){for(let t=this.deps;t;t=t.nextDep)mn(t);this.deps=this.depsTail=void 0,jn(this),this.onStop&&this.onStop(),this.flags&=-2}}trigger(){this.flags&64?Ls.add(this):this.scheduler?this.scheduler():this.runIfDirty()}runIfDirty(){Js(this)&&this.run()}get dirty(){return Js(this)}}let Ei=0,Ht,Vt;function Pi(e,t=!1){if(e.flags|=8,t){e.next=Vt,Vt=e;return}e.next=Ht,Ht=e}function hn(){Ei++}function gn(){if(--Ei>0)return;if(Vt){let t=Vt;for(Vt=void 0;t;){const s=t.next;t.next=void 0,t.flags&=-9,t=s}}let e;for(;Ht;){let t=Ht;for(Ht=void 0;t;){const s=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(n){e||(e=n)}t=s}}if(e)throw e}function Ci(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function Ai(e){let t,s=e.depsTail,n=s;for(;n;){const i=n.prevDep;n.version===-1?(n===s&&(s=i),mn(n),Ho(n)):t=n,n.dep.activeLink=n.prevActiveLink,n.prevActiveLink=void 0,n=i}e.deps=t,e.depsTail=s}function Js(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&($i(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function $i(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===Zt)||(e.globalVersion=Zt,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!Js(e))))return;e.flags|=2;const t=e.dep,s=oe,n=Ue;oe=e,Ue=!0;try{Ci(e);const i=e.fn(e._value);(t.version===0||qe(i,e._value))&&(e.flags|=128,e._value=i,t.version++)}catch(i){throw t.version++,i}finally{oe=s,Ue=n,Ai(e),e.flags&=-3}}function mn(e,t=!1){const{dep:s,prevSub:n,nextSub:i}=e;if(n&&(n.nextSub=i,e.prevSub=void 0),i&&(i.prevSub=n,e.nextSub=void 0),s.subs===e&&(s.subs=n,!n&&s.computed)){s.computed.flags&=-5;for(let o=s.computed.deps;o;o=o.nextDep)mn(o,!0)}!t&&!--s.sc&&s.map&&s.map.delete(s.key)}function Ho(e){const{prevDep:t,nextDep:s}=e;t&&(t.nextDep=s,e.prevDep=void 0),s&&(s.prevDep=t,e.nextDep=void 0)}let Ue=!0;const Oi=[];function Ye(){Oi.push(Ue),Ue=!1}function Xe(){const e=Oi.pop();Ue=e===void 0?!0:e}function jn(e){const{cleanup:t}=e;if(e.cleanup=void 0,t){const s=oe;oe=void 0;try{t()}finally{oe=s}}}let Zt=0;class Vo{constructor(t,s){this.sub=t,this.dep=s,this.version=s.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class bn{constructor(t){this.computed=t,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(t){if(!oe||!Ue||oe===this.computed)return;let s=this.activeLink;if(s===void 0||s.sub!==oe)s=this.activeLink=new Vo(oe,this),oe.deps?(s.prevDep=oe.depsTail,oe.depsTail.nextDep=s,oe.depsTail=s):oe.deps=oe.depsTail=s,Di(s);else if(s.version===-1&&(s.version=this.version,s.nextDep)){const n=s.nextDep;n.prevDep=s.prevDep,s.prevDep&&(s.prevDep.nextDep=n),s.prevDep=oe.depsTail,s.nextDep=void 0,oe.depsTail.nextDep=s,oe.depsTail=s,oe.deps===s&&(oe.deps=n)}return s}trigger(t){this.versiLine truncated
* @vue/runtime-core v3.5.39
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/function ss(e,t,s,n){try{return n?e(...n):e()}catch(i){Os(i,t,s)}}function Me(e,t,s,n){if(W(e)){const i=ss(e,t,s,n);return i&&bi(i)&&i.catch(o=>{Os(o,t,s)}),i}if(L(e)){const i=[];for(let o=0;o<e.length;o++)i.push(Me(e[o],t,s,n));return i}}function Os(e,t,s,n=!0){const i=t?t.vnode:null,{errorHandler:o,throwUnhandledErrorInProduction:r}=t&&t.appContext.config||ne;if(t){let a=t.parent;const l=t.proxy,g=`https://vuejs.org/error-reference/#runtime-${s}`;for(;a;){const d=a.ec;if(d){for(let b=0;b<d.length;b++)if(d[b](e,l,g)===!1)return}a=a.parent}if(o){Ye(),ss(o,null,10,[e,l,g]),Xe();return}}gr(e,s,i,n,r)}function gr(e,t,s,n=!0,i=!1){if(i)throw e;console.error(e)}const ke=[];let Ge=-1;const Et=[];let ct=null,kt=0;const Li=Promise.resolve();let bs=null;function Fi(e){const t=bs||Li;return e?t.then(this?e.bind(this):e):t}function mr(e){let t=Ge+1,s=ke.length;for(;t<s;){const n=t+s>>>1,i=ke[n],o=Xt(i);o<e||o===e&&i.flags&2?t=n+1:s=n}return t}function wn(e){if(!(e.flags&1)){const t=Xt(e),s=ke[ke.length-1];!s||!(e.flags&2)&&t>=Xt(s)?ke.push(e):ke.splice(mr(t),0,e),e.flags|=1,Bi()}}function Bi(){bs||(bs=Li.then(Vi))}function br(e){L(e)?Et.push(...e):ct&&e.id===-1?ct.splice(kt+1,0,e):e.flags&1||(Et.push(e),e.flags|=1),Bi()}function Nn(e,t,s=Ge+1){for(;s<ke.length;s++){const n=ke[s];if(n&&n.flags&2){if(e&&n.id!==e.uid)continue;ke.splice(s,1),s--,n.flags&4&&(n.flags&=-2),n(),n.flags&4||(n.flags&=-2)}}}function Hi(e){if(Et.length){const t=[...new Set(Et)].sort((s,n)=>Xt(s)-Xt(n));if(Et.length=0,ct){ct.push(...t);return}for(ct=t,kt=0;kt<ct.length;kt++){const s=ct[kt];s.flags&4&&(s.flags&=-2),s.flags&8||s(),s.flags&=-2}ct=null,kt=0}}const Xt=e=>e.id==null?e.flags&2?-1:1/0:e.id;function Vi(e){try{for(Ge=0;Ge<ke.length;Ge++){const t=ke[Ge];t&&!(t.flags&8)&&(t.flags&4&&(t.flags&=-2),ss(t,t.i,t.i?15:14),t.flags&4||(t.flags&=-2))}}finally{for(;Ge<ke.length;Ge++){const t=ke[Ge];t&&(t.flags&=-2)}Ge=-1,ke.length=0,Hi(),bs=null,(ke.length||Et.length)&&Vi()}}let Re=null,Gi=null;function vs(e){const t=Re;return Re=e,Gi=e&&e.type.__scopeId||null,t}function vr(e,t=Re,s){if(!t||e._n)return e;const n=(...i)=>{n._d&&Zn(-1);const o=vs(t);let r;try{r=e(...i)}finally{vs(o),n._d&&Zn(1)}return r};return n._n=!0,n._c=!0,n._d=!0,n}function pe(e,t){if(Re===null)return e;const s=Is(Re),n=e.dirs||(e.dirs=[]);for(let i=0;i<t.length;i++){let[o,r,a,l=ne]=t[i];o&&(W(o)&&(o={mounted:o,updated:o}),o.deep&&it(r),n.push({dir:o,instance:s,value:r,oldValue:void 0,arg:a,modifiers:l}))}return e}function mt(e,t,s,n){const i=e.dirs,o=t&&t.dirs;for(let r=0;r<i.length;r++){const a=i[r];o&&(a.oldValue=o[r].value);let l=a.dir[n];l&&(Ye(),Me(l,s,8,[e.el,a,e,t]),Xe())}}function yr(e,t){if(Te){let s=Te.provides;const n=Te.parent&&Te.parent.provides;n===s&&(s=Te.provides=Object.create(n)),s[e]=t}}function fs(e,t,s=!1){const n=ma();if(n||Pt){let i=Pt?Pt._context.provides:n?n.parent==null||n.ce?n.vnode.appContext&&n.vnode.appContext.provides:n.parent.provides:void 0;if(i&&e in i)return i[e];if(arguments.length>1)return s&&W(t)?t.call(n&&n.proxy):t}}const _r=Symbol.for("v-scx"),wr=()=>fs(_r);function Hs(e,t,s){return Ki(e,t,s)}function Ki(e,t,s=ne){const{immediate:n,deep:i,flush:o,once:r}=s,a=_e({},s),l=t&&n||!t&&o!=="post";let g;if(es){if(o==="sync"){const A=wr();g=A.__watcherHandles||(A.__watcherHandles=[])}else if(!l){const A=()=>{};return A.stop=Ze,A.resume=Ze,A.pause=Ze,A}}const d=Te;a.call=(A,V,x)=>Me(A,d,V,x);let b=!1;o==="post"?a.scheduler=A=>{Se(A,d&&d.suspense)}:o!=="sync"&&(b=!0,a.scheduler=(A,V)=>{V?A():wn(A)}),a.augmentJob=A=>{t&&(A.flags|=4),b&&(A.flags|=2,d&&(A.id=d.uid,A.i=d))};const E=hr(e,t,a);return es&&(g?g.push(E):l&&E()),E}function xr(e,t,s){const n=this.proxy,i=ue(e)?e.includes(".")?Wi(n,e):()=>n[e]:e.bind(n,n);let o;W(t)?o=t:(o=t.handler,s=t);const r=ns(this),a=Ki(i,o.bind(n),s);return r(),a}function Wi(e,t){const s=t.split(".");return()=>{let n=e;for(let i=0;i<s.length&&n;i++)n=n[s[i]];return n}}const kr=Symbol("_vte"),Tr=e=>e.__isTeleport,Vs=Symbol("_leaveCb");function xn(e,t){e.shapeFlag&6&&e.component?(e.transition=t,xn(e.component.subTree,t)):e.shapeFlag&128?(e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback)):e.transition=t}function qi(e){e.ids=[e.ids[0]+e.ids[2]+++"-",0,0]}function Mn(e,t){let s;return!!((s=Object.getOwnPropertyDescriptor(e,t))&&!s.configurable)}const ys=new WeakMap;function Gt(e,t,s,n,i=!1){if(L(e)){e.forEach((x,N)=>Gt(x,t&&(L(t)?t[N]:t),s,n,i));return}if(Kt(n)&&!i){n.shapeFlag&512&&n.type.__asyncResolved&&n.component.subTree.component&&Gt(e,t,s,n.component.subTree);return}const o=n.shapeFlag&4?Is(n.component):n.el,r=i?null:o,{i:a,r:l}=e,g=t&&t.r,d=a.refs===ne?a.refs={}:a.refs,b=a.setupState,E=Y(b),A=b===ne?mi:x=>Mn(d,x)?!1:X(E,x),V=(x,N)=>!(N&&Mn(d,N));if(g!=null&&g!==l){if(Ln(t),ue(g))d[g]=null,A(g)&&(b[g]=null);else if(ye(g)){const x=t;V(g,x.k)&&(g.value=null),x.k&&(d[x.k]=null)}}if(W(l)){Ye();try{ss(l,a,12,[r,d])}finally{Xe()}}else{const x=ue(l),N=ye(l);if(x||N){const R=()=>{if(e.f Line truncated
* @vue/runtime-dom v3.5.39
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/let an;const Xn=typeof window<"u"&&window.trustedTypes;if(Xn)try{an=Xn.createPolicy("vue",{createHTML:e=>e})}catch{}const _o=an?e=>an.createHTML(e):e=>e,ka="http://www.w3.org/2000/svg",Ta="http://www.w3.org/1998/Math/MathML",tt=typeof document<"u"?document:null,Qn=tt&&tt.createElement("template"),Sa={insert:(e,t,s)=>{t.insertBefore(e,s||null)},remove:e=>{const t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,s,n)=>{const i=t==="svg"?tt.createElementNS(ka,e):t==="mathml"?tt.createElementNS(Ta,e):s?tt.createElement(e,{is:s}):tt.createElement(e);return e==="select"&&n&&n.multiple!=null&&i.setAttribute("multiple",n.multiple),i},createText:e=>tt.createTextNode(e),createComment:e=>tt.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>tt.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},insertStaticContent(e,t,s,n,i,o){const r=s?s.previousSibling:t.lastChild;if(i&&(i===o||i.nextSibling))for(;t.insertBefore(i.cloneNode(!0),s),!(i===o||!(i=i.nextSibling)););else{Qn.innerHTML=_o(n==="svg"?`<svg>${e}</svg>`:n==="mathml"?`<math>${e}</math>`:e);const a=Qn.content;if(n==="svg"||n==="mathml"){const l=a.firstChild;for(;l.firstChild;)a.appendChild(l.firstChild);a.removeChild(l)}t.insertBefore(a,s)}return[r?r.nextSibling:t.firstChild,s?s.previousSibling:t.lastChild]}},Ea=Symbol("_vtc");function Pa(e,t,s){const n=e[Ea];n&&(t=(t?[t,...n]:[...n]).join(" ")),t==null?e.removeAttribute("class"):s?e.setAttribute("class",t):e.className=t}const ei=Symbol("_vod"),Ca=Symbol("_vsh"),Aa=Symbol(""),$a=/(?:^|;)\s*display\s*:/;function Oa(e,t,s){const n=e.style,i=ue(s);let o=!1;if(s&&!i){if(t)if(ue(t))for(const r of t.split(";")){const a=r.slice(0,r.indexOf(":")).trim();s[a]==null&&Ft(n,a,"")}else for(const r in t)s[r]==null&&Ft(n,r,"");for(const r in s){r==="display"&&(o=!0);const a=s[r];a!=null?Ra(e,r,!ue(t)&&t?t[r]:void 0,a)||Ft(n,r,a):Ft(n,r,"")}}else if(i){if(t!==s){const r=n[Aa];r&&(s+=";"+r),n.cssText=s,o=$a.test(s)}}else t&&e.removeAttribute("style");ei in e&&(e[ei]=o?n.display:"",e[Ca]&&(n.display="none"))}const ti=/\s*!important$/;function Ft(e,t,s){if(L(s))s.forEach(n=>Ft(e,t,n));else if(s==null&&(s=""),t.startsWith("--"))e.setProperty(t,s);else{const n=Da(e,t);ti.test(s)?e.setProperty(ft(n),s.replace(ti,""),"important"):e[n]=s}}const si=["Webkit","Moz","ms"],qs={};function Da(e,t){const s=qs[t];if(s)return s;let n=je(t);if(n!=="filter"&&n in e)return qs[t]=n;n=_i(n);for(let i=0;i<si.length;i++){const o=si[i]+n;if(o in e)return qs[t]=o}return t}function Ra(e,t,s,n){return e.tagName==="TEXTAREA"&&(t==="width"||t==="height")&&ue(n)&&s===n}const ni="http://www.w3.org/1999/xlink";function ii(e,t,s,n,i,o=Mo(t)){n&&t.startsWith("xlink:")?s==null?e.removeAttributeNS(ni,t.slice(6,t.length)):e.setAttributeNS(ni,t,s):s==null||o&&!xi(s)?e.removeAttribute(t):e.setAttribute(t,o?"":Je(s)?String(s):s)}function oi(e,t,s,n,i){if(t==="innerHTML"||t==="textContent"){s!=null&&(e[t]=t==="innerHTML"?_o(s):s);return}const o=e.tagName;if(t==="value"&&o!=="PROGRESS"&&!o.includes("-")){const a=o==="OPTION"?e.getAttribute("value")||"":e.value,l=s==null?e.type==="checkbox"?"on":"":String(s);(a!==l||!("_value"in e))&&(e.value=l),s==null&&e.removeAttribute(t),e._value=s;return}let r=!1;if(s===""||s==null){const a=typeof e[t];a==="boolean"?s=xi(s):s==null&&a==="string"?(s="",r=!0):a==="number"&&(s=0,r=!0)}try{e[t]=s}catch{}r&&e.removeAttribute(i||t)}function ot(e,t,s,n){e.addEventListener(t,s,n)}function za(e,t,s,n){e.removeEventListener(t,s,n)}const ri=Symbol("_vei");function Ia(e,t,s,n,i=null){const o=e[ri]||(e[ri]={}),r=o[t];if(n&&r)r.value=n;else{const[a,l]=Na(t);if(n){const g=o[t]=Fa(n,i);ot(e,a,g,l)}else r&&(za(e,a,r,l),o[t]=void 0)}}const ja=/(Once|Passive|Capture)$/,Ua=/^on:?(?:Once|Passive|Capture)$/;function Na(e){let t,s;for(;(s=e.match(ja))&&!Ua.test(e);)t||(t={}),e=e.slice(0,e.length-s[1].length),t[s[1].toLowerCase()]=!0;return[e[2]===":"?e.slice(3):ft(e.slice(2)),t]}let Zs=0;const Ma=Promise.resolve(),La=()=>Zs||(Ma.then(()=>Zs=0),Zs=Date.now());function Fa(e,t){const s=n=>{if(!n._vts)n._vts=Date.now();else if(n._vts<=s.attached)return;const i=s.value;if(L(i)){const o=n.stopImmediatePropagation;n.stopImmediatePropagation=()=>{o.call(n),n._stopped=!0};const r=i.slice(),a=[n];for(let l=0;l<r.length&&!n._stopped;l++){const g=r[l];g&&Me(g,t,5,a)}}else Me(i,t,5,[n])};return s.value=e,s.attached=La(),s}const ai=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,Ba=(e,t,s,n,i,o)=>{const r=i==="svg";t==="class"?Pa(e,n,r):t==="style"?Oa(e,s,n):Ss(t)?Es(t)||Ia(e,t,s,n,o):(t[0]==="."?(t=t.slice(1),!0):t[0]==="^"?(t=t.slice(1),!1):Ha(e,t,n,r))?(oi(e,t,n),!e.tagName.includes("-")&&(t==="value"||t==="checked"||t==="selected")&&ii(e,t,n,r,o,t!=="value")):e._isVueCE&&(Va(e,t)||e._def.__asyncLoader&&(/[A-Z]/.test(t)||!ue(n)))?oi(e,je(t),n,o,t):(t==="true-value"?e._trueValue=n:t==="false-value"&&(e._fals Line truncated
+17
View File
@@ -0,0 +1,17 @@
(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const r of o.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&n(r)}).observe(document,{childList:!0,subtree:!0});function s(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(i){if(i.ep)return;i.ep=!0;const o=s(i);fetch(i.href,o)}})();/**
* @vue/shared v3.5.39
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/function un(e){const t=Object.create(null);for(const s of e.split(","))t[s]=1;return s=>s in t}const ne={},Pt=[],Xe=()=>{},mi=()=>!1,Ps=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),Cs=e=>e.startsWith("onUpdate:"),xe=Object.assign,dn=(e,t)=>{const s=e.indexOf(t);s>-1&&e.splice(s,1)},$o=Object.prototype.hasOwnProperty,X=(e,t)=>$o.call(e,t),F=Array.isArray,Ct=e=>is(e)==="[object Map]",Ut=e=>is(e)==="[object Set]",zn=e=>is(e)==="[object Date]",W=e=>typeof e=="function",de=e=>typeof e=="string",Qe=e=>typeof e=="symbol",te=e=>e!==null&&typeof e=="object",bi=e=>(te(e)||W(e))&&W(e.then)&&W(e.catch),vi=Object.prototype.toString,is=e=>vi.call(e),Oo=e=>is(e).slice(8,-1),yi=e=>is(e)==="[object Object]",pn=e=>de(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,Gt=un(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),As=e=>{const t=Object.create(null);return(s=>t[s]||(t[s]=e(s)))},Do=/-\w/g,Ne=As(e=>e.replace(Do,t=>t.slice(1).toUpperCase())),Ro=/\B([A-Z])/g,bt=As(e=>e.replace(Ro,"-$1").toLowerCase()),_i=As(e=>e.charAt(0).toUpperCase()+e.slice(1)),Ns=As(e=>e?`on${_i(e)}`:""),Ye=(e,t)=>!Object.is(e,t),hs=(e,...t)=>{for(let s=0;s<e.length;s++)e[s](...t)},wi=(e,t,s,n=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:n,value:s})},$s=e=>{const t=parseFloat(e);return isNaN(t)?e:t};let In;const Os=()=>In||(In=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function fn(e){if(F(e)){const t={};for(let s=0;s<e.length;s++){const n=e[s],i=de(n)?Uo(n):fn(n);if(i)for(const o in i)t[o]=i[o]}return t}else if(de(e)||te(e))return e}const zo=/;(?![^(]*\))/g,Io=/:([^]+)/,jo=/\/\*[^]*?\*\//g;function Uo(e){const t={};return e.replace(jo,"").split(zo).forEach(s=>{if(s){const n=s.split(Io);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function $e(e){let t="";if(de(e))t=e;else if(F(e))for(let s=0;s<e.length;s++){const n=$e(e[s]);n&&(t+=n+" ")}else if(te(e))for(const s in e)e[s]&&(t+=s+" ");return t.trim()}const Mo="itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly",No=un(Mo);function xi(e){return!!e||e===""}function Lo(e,t){if(e.length!==t.length)return!1;let s=!0;for(let n=0;s&&n<e.length;n++)s=ht(e[n],t[n]);return s}function ht(e,t){if(e===t)return!0;let s=zn(e),n=zn(t);if(s||n)return s&&n?e.getTime()===t.getTime():!1;if(s=Qe(e),n=Qe(t),s||n)return e===t;if(s=F(e),n=F(t),s||n)return s&&n?Lo(e,t):!1;if(s=te(e),n=te(t),s||n){if(!s||!n)return!1;const i=Object.keys(e).length,o=Object.keys(t).length;if(i!==o)return!1;for(const r in e){const a=e.hasOwnProperty(r),l=t.hasOwnProperty(r);if(a&&!l||!a&&l||!ht(e[r],t[r]))return!1}}return String(e)===String(t)}function hn(e,t){return e.findIndex(s=>ht(s,t))}const ki=e=>!!(e&&e.__v_isRef===!0),m=e=>de(e)?e:e==null?"":F(e)||te(e)&&(e.toString===vi||!W(e.toString))?ki(e)?m(e.value):JSON.stringify(e,Ti,2):String(e),Ti=(e,t)=>ki(t)?Ti(e,t.value):Ct(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((s,[n,i],o)=>(s[Ls(n,o)+" =>"]=i,s),{})}:Ut(t)?{[`Set(${t.size})`]:[...t.values()].map(s=>Ls(s))}:Qe(t)?Ls(t):te(t)&&!F(t)&&!yi(t)?String(t):t,Ls=(e,t="")=>{var s;return Qe(e)?`Symbol(${(s=e.description)!=null?s:t})`:e};/**
* @vue/reactivity v3.5.39
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/let ve;class Fo{constructor(t=!1){this.detached=t,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this._warnOnRun=!0,this.__v_skip=!0,!t&&ve&&(ve.active?(this.parent=ve,this.index=(ve.scopes||(ve.scopes=[])).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let t,s;if(this.scopes)for(t=0,s=this.scopes.length;t<s;t++)this.scopes[t].pause();for(t=0,s=this.effects.length;t<s;t++)this.effects[t].pause()}}resume(){if(this._active&&this._isPaused){this._isPaused=!1;let t,s;if(this.scopes)for(t=0,s=this.scopes.length;t<s;t++)this.scopes[t].resume();for(t=0,s=this.effects.length;t<s;t++)this.effects[t].resume()}}run(t){if(this._active){const s=ve;try{return ve=this,t()}finally{ve=s}}}on(){++this._on===1&&(this.prevScope=ve,ve=this)}off(){if(this._on>0&&--this._on===0){if(ve===this)ve=this.prevScope;else{let t=ve;for(;t;){if(t.prevScope===this){t.prevScope=this.prevScope;break}t=t.prevScope}}this.prevScope=void 0}}stop(t){if(this._active){this._active=!1;let s,n;for(s=0,n=this.effects.length;s<n;s++)this.effects[s].stop();for(this.effects.length=0,s=0,n=this.cleanups.length;s<n;s++)this.cleanups[s]();if(this.cleanups.length=0,this.scopes){for(s=0,n=this.scopes.length;s<n;s++)this.scopes[s].stop(!0);this.scopes.length=0}if(!this.detached&&this.parent&&!t){const i=this.parent.scopes.pop();i&&i!==this&&(this.parent.scopes[this.index]=i,i.index=this.index)}this.parent=void 0}}}function Bo(){return ve}let oe;const Fs=new WeakSet;class Si{constructor(t){this.fn=t,this.deps=void 0,this.depsTail=void 0,this.flags=5,this.next=void 0,this.cleanup=void 0,this.scheduler=void 0,ve&&(ve.active?ve.effects.push(this):this.flags&=-2)}pause(){this.flags|=64}resume(){this.flags&64&&(this.flags&=-65,Fs.has(this)&&(Fs.delete(this),this.trigger()))}notify(){this.flags&2&&!(this.flags&32)||this.flags&8||Pi(this)}run(){if(!(this.flags&1))return this.fn();this.flags|=2,jn(this),Ci(this);const t=oe,s=Le;oe=this,Le=!0;try{return this.fn()}finally{Ai(this),oe=t,Le=s,this.flags&=-3}}stop(){if(this.flags&1){for(let t=this.deps;t;t=t.nextDep)bn(t);this.deps=this.depsTail=void 0,jn(this),this.onStop&&this.onStop(),this.flags&=-2}}trigger(){this.flags&64?Fs.add(this):this.scheduler?this.scheduler():this.runIfDirty()}runIfDirty(){Ys(this)&&this.run()}get dirty(){return Ys(this)}}let Ei=0,Kt,Wt;function Pi(e,t=!1){if(e.flags|=8,t){e.next=Wt,Wt=e;return}e.next=Kt,Kt=e}function gn(){Ei++}function mn(){if(--Ei>0)return;if(Wt){let t=Wt;for(Wt=void 0;t;){const s=t.next;t.next=void 0,t.flags&=-9,t=s}}let e;for(;Kt;){let t=Kt;for(Kt=void 0;t;){const s=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(n){e||(e=n)}t=s}}if(e)throw e}function Ci(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function Ai(e){let t,s=e.depsTail,n=s;for(;n;){const i=n.prevDep;n.version===-1?(n===s&&(s=i),bn(n),Ho(n)):t=n,n.dep.activeLink=n.prevActiveLink,n.prevActiveLink=void 0,n=i}e.deps=t,e.depsTail=s}function Ys(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&($i(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function $i(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===Xt)||(e.globalVersion=Xt,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!Ys(e))))return;e.flags|=2;const t=e.dep,s=oe,n=Le;oe=e,Le=!0;try{Ci(e);const i=e.fn(e._value);(t.version===0||Ye(i,e._value))&&(e.flags|=128,e._value=i,t.version++)}catch(i){throw t.version++,i}finally{oe=s,Le=n,Ai(e),e.flags&=-3}}function bn(e,t=!1){const{dep:s,prevSub:n,nextSub:i}=e;if(n&&(n.nextSub=i,e.prevSub=void 0),i&&(i.prevSub=n,e.nextSub=void 0),s.subs===e&&(s.subs=n,!n&&s.computed)){s.computed.flags&=-5;for(let o=s.computed.deps;o;o=o.nextDep)bn(o,!0)}!t&&!--s.sc&&s.map&&s.map.delete(s.key)}function Ho(e){const{prevDep:t,nextDep:s}=e;t&&(t.nextDep=s,e.prevDep=void 0),s&&(s.prevDep=t,e.nextDep=void 0)}let Le=!0;const Oi=[];function et(){Oi.push(Le),Le=!1}function tt(){const e=Oi.pop();Le=e===void 0?!0:e}function jn(e){const{cleanup:t}=e;if(e.cleanup=void 0,t){const s=oe;oe=void 0;try{t()}finally{oe=s}}}let Xt=0;class Vo{constructor(t,s){this.sub=t,this.dep=s,this.version=s.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class vn{constructor(t){this.computed=t,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(t){if(!oe||!Le||oe===this.computed)return;let s=this.activeLink;if(s===void 0||s.sub!==oe)s=this.activeLink=new Vo(oe,this),oe.deps?(s.prevDep=oe.depsTail,oe.depsTail.nextDep=s,oe.depsTail=s):oe.deps=oe.depsTail=s,Di(s);else if(s.version===-1&&(s.version=this.version,s.nextDep)){const n=s.nextDep;n.prevDep=s.prevDep,s.prevDep&&(s.prevDep.nextDep=n),s.prevDep=oe.depsTail,s.nextDep=void 0,oe.depsTail.nextDep=s,oe.depsTail=s,oe.deps===s&&(oe.deps=n)}return s}trigger(t){this.versiLine truncated
* @vue/runtime-core v3.5.39
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/function os(e,t,s,n){try{return n?e(...n):e()}catch(i){Rs(i,t,s)}}function Be(e,t,s,n){if(W(e)){const i=os(e,t,s,n);return i&&bi(i)&&i.catch(o=>{Rs(o,t,s)}),i}if(F(e)){const i=[];for(let o=0;o<e.length;o++)i.push(Be(e[o],t,s,n));return i}}function Rs(e,t,s,n=!0){const i=t?t.vnode:null,{errorHandler:o,throwUnhandledErrorInProduction:r}=t&&t.appContext.config||ne;if(t){let a=t.parent;const l=t.proxy,g=`https://vuejs.org/error-reference/#runtime-${s}`;for(;a;){const d=a.ec;if(d){for(let b=0;b<d.length;b++)if(d[b](e,l,g)===!1)return}a=a.parent}if(o){et(),os(o,null,10,[e,l,g]),tt();return}}gr(e,s,i,n,r)}function gr(e,t,s,n=!0,i=!1){if(i)throw e;console.error(e)}const Te=[];let qe=-1;const At=[];let ft=null,Et=0;const Li=Promise.resolve();let ys=null;function Fi(e){const t=ys||Li;return e?t.then(this?e.bind(this):e):t}function mr(e){let t=qe+1,s=Te.length;for(;t<s;){const n=t+s>>>1,i=Te[n],o=ts(i);o<e||o===e&&i.flags&2?t=n+1:s=n}return t}function xn(e){if(!(e.flags&1)){const t=ts(e),s=Te[Te.length-1];!s||!(e.flags&2)&&t>=ts(s)?Te.push(e):Te.splice(mr(t),0,e),e.flags|=1,Bi()}}function Bi(){ys||(ys=Li.then(Vi))}function br(e){F(e)?At.push(...e):ft&&e.id===-1?ft.splice(Et+1,0,e):e.flags&1||(At.push(e),e.flags|=1),Bi()}function Mn(e,t,s=qe+1){for(;s<Te.length;s++){const n=Te[s];if(n&&n.flags&2){if(e&&n.id!==e.uid)continue;Te.splice(s,1),s--,n.flags&4&&(n.flags&=-2),n(),n.flags&4||(n.flags&=-2)}}}function Hi(e){if(At.length){const t=[...new Set(At)].sort((s,n)=>ts(s)-ts(n));if(At.length=0,ft){ft.push(...t);return}for(ft=t,Et=0;Et<ft.length;Et++){const s=ft[Et];s.flags&4&&(s.flags&=-2),s.flags&8||s(),s.flags&=-2}ft=null,Et=0}}const ts=e=>e.id==null?e.flags&2?-1:1/0:e.id;function Vi(e){try{for(qe=0;qe<Te.length;qe++){const t=Te[qe];t&&!(t.flags&8)&&(t.flags&4&&(t.flags&=-2),os(t,t.i,t.i?15:14),t.flags&4||(t.flags&=-2))}}finally{for(;qe<Te.length;qe++){const t=Te[qe];t&&(t.flags&=-2)}qe=-1,Te.length=0,Hi(),ys=null,(Te.length||At.length)&&Vi()}}let je=null,Gi=null;function _s(e){const t=je;return je=e,Gi=e&&e.type.__scopeId||null,t}function vr(e,t=je,s){if(!t||e._n)return e;const n=(...i)=>{n._d&&Zn(-1);const o=_s(t);let r;try{r=e(...i)}finally{_s(o),n._d&&Zn(1)}return r};return n._n=!0,n._c=!0,n._d=!0,n}function fe(e,t){if(je===null)return e;const s=Us(je),n=e.dirs||(e.dirs=[]);for(let i=0;i<t.length;i++){let[o,r,a,l=ne]=t[i];o&&(W(o)&&(o={mounted:o,updated:o}),o.deep&&lt(r),n.push({dir:o,instance:s,value:r,oldValue:void 0,arg:a,modifiers:l}))}return e}function _t(e,t,s,n){const i=e.dirs,o=t&&t.dirs;for(let r=0;r<i.length;r++){const a=i[r];o&&(a.oldValue=o[r].value);let l=a.dir[n];l&&(et(),Be(l,s,8,[e.el,a,e,t]),tt())}}function yr(e,t){if(Se){let s=Se.provides;const n=Se.parent&&Se.parent.provides;n===s&&(s=Se.provides=Object.create(n)),s[e]=t}}function gs(e,t,s=!1){const n=ma();if(n||$t){let i=$t?$t._context.provides:n?n.parent==null||n.ce?n.vnode.appContext&&n.vnode.appContext.provides:n.parent.provides:void 0;if(i&&e in i)return i[e];if(arguments.length>1)return s&&W(t)?t.call(n&&n.proxy):t}}const _r=Symbol.for("v-scx"),wr=()=>gs(_r);function Vs(e,t,s){return Ki(e,t,s)}function Ki(e,t,s=ne){const{immediate:n,deep:i,flush:o,once:r}=s,a=xe({},s),l=t&&n||!t&&o!=="post";let g;if(ns){if(o==="sync"){const C=wr();g=C.__watcherHandles||(C.__watcherHandles=[])}else if(!l){const C=()=>{};return C.stop=Xe,C.resume=Xe,C.pause=Xe,C}}const d=Se;a.call=(C,G,k)=>Be(C,d,G,k);let b=!1;o==="post"?a.scheduler=C=>{Ce(C,d&&d.suspense)}:o!=="sync"&&(b=!0,a.scheduler=(C,G)=>{G?C():xn(C)}),a.augmentJob=C=>{t&&(C.flags|=4),b&&(C.flags|=2,d&&(C.id=d.uid,C.i=d))};const E=hr(e,t,a);return ns&&(g?g.push(E):l&&E()),E}function xr(e,t,s){const n=this.proxy,i=de(e)?e.includes(".")?Wi(n,e):()=>n[e]:e.bind(n,n);let o;W(t)?o=t:(o=t.handler,s=t);const r=rs(this),a=Ki(i,o.bind(n),s);return r(),a}function Wi(e,t){const s=t.split(".");return()=>{let n=e;for(let i=0;i<s.length&&n;i++)n=n[s[i]];return n}}const kr=Symbol("_vte"),Tr=e=>e.__isTeleport,Gs=Symbol("_leaveCb");function kn(e,t){e.shapeFlag&6&&e.component?(e.transition=t,kn(e.component.subTree,t)):e.shapeFlag&128?(e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback)):e.transition=t}function qi(e){e.ids=[e.ids[0]+e.ids[2]+++"-",0,0]}function Nn(e,t){let s;return!!((s=Object.getOwnPropertyDescriptor(e,t))&&!s.configurable)}const ws=new WeakMap;function qt(e,t,s,n,i=!1){if(F(e)){e.forEach((k,M)=>qt(k,t&&(F(t)?t[M]:t),s,n,i));return}if(Zt(n)&&!i){n.shapeFlag&512&&n.type.__asyncResolved&&n.component.subTree.component&&qt(e,t,s,n.component.subTree);return}const o=n.shapeFlag&4?Us(n.component):n.el,r=i?null:o,{i:a,r:l}=e,g=t&&t.r,d=a.refs===ne?a.refs={}:a.refs,b=a.setupState,E=Y(b),C=b===ne?mi:k=>Nn(d,k)?!1:X(E,k),G=(k,M)=>!(M&&Nn(d,M));if(g!=null&&g!==l){if(Ln(t),de(g))d[g]=null,C(g)&&(b[g]=null);else if(we(g)){const k=t;G(g,k.k)&&(g.value=null),k.k&&(d[k.k]=null)}}if(W(l)){et();try{os(l,a,12,[r,d])}finally{tt()}}else{const k=de(l),M=we(l);if(k||M){const z=()=>{if(e.f Line truncated
* @vue/runtime-dom v3.5.39
* (c) 2018-present Yuxi (Evan) You and Vue contributors
* @license MIT
**/let ln;const Xn=typeof window<"u"&&window.trustedTypes;if(Xn)try{ln=Xn.createPolicy("vue",{createHTML:e=>e})}catch{}const _o=ln?e=>ln.createHTML(e):e=>e,ka="http://www.w3.org/2000/svg",Ta="http://www.w3.org/1998/Math/MathML",ot=typeof document<"u"?document:null,Qn=ot&&ot.createElement("template"),Sa={insert:(e,t,s)=>{t.insertBefore(e,s||null)},remove:e=>{const t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,s,n)=>{const i=t==="svg"?ot.createElementNS(ka,e):t==="mathml"?ot.createElementNS(Ta,e):s?ot.createElement(e,{is:s}):ot.createElement(e);return e==="select"&&n&&n.multiple!=null&&i.setAttribute("multiple",n.multiple),i},createText:e=>ot.createTextNode(e),createComment:e=>ot.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>ot.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},insertStaticContent(e,t,s,n,i,o){const r=s?s.previousSibling:t.lastChild;if(i&&(i===o||i.nextSibling))for(;t.insertBefore(i.cloneNode(!0),s),!(i===o||!(i=i.nextSibling)););else{Qn.innerHTML=_o(n==="svg"?`<svg>${e}</svg>`:n==="mathml"?`<math>${e}</math>`:e);const a=Qn.content;if(n==="svg"||n==="mathml"){const l=a.firstChild;for(;l.firstChild;)a.appendChild(l.firstChild);a.removeChild(l)}t.insertBefore(a,s)}return[r?r.nextSibling:t.firstChild,s?s.previousSibling:t.lastChild]}},Ea=Symbol("_vtc");function Pa(e,t,s){const n=e[Ea];n&&(t=(t?[t,...n]:[...n]).join(" ")),t==null?e.removeAttribute("class"):s?e.setAttribute("class",t):e.className=t}const ei=Symbol("_vod"),Ca=Symbol("_vsh"),Aa=Symbol(""),$a=/(?:^|;)\s*display\s*:/;function Oa(e,t,s){const n=e.style,i=de(s);let o=!1;if(s&&!i){if(t)if(de(t))for(const r of t.split(";")){const a=r.slice(0,r.indexOf(":")).trim();s[a]==null&&Vt(n,a,"")}else for(const r in t)s[r]==null&&Vt(n,r,"");for(const r in s){r==="display"&&(o=!0);const a=s[r];a!=null?Ra(e,r,!de(t)&&t?t[r]:void 0,a)||Vt(n,r,a):Vt(n,r,"")}}else if(i){if(t!==s){const r=n[Aa];r&&(s+=";"+r),n.cssText=s,o=$a.test(s)}}else t&&e.removeAttribute("style");ei in e&&(e[ei]=o?n.display:"",e[Ca]&&(n.display="none"))}const ti=/\s*!important$/;function Vt(e,t,s){if(F(s))s.forEach(n=>Vt(e,t,n));else if(s==null&&(s=""),t.startsWith("--"))e.setProperty(t,s);else{const n=Da(e,t);ti.test(s)?e.setProperty(bt(n),s.replace(ti,""),"important"):e[n]=s}}const si=["Webkit","Moz","ms"],Zs={};function Da(e,t){const s=Zs[t];if(s)return s;let n=Ne(t);if(n!=="filter"&&n in e)return Zs[t]=n;n=_i(n);for(let i=0;i<si.length;i++){const o=si[i]+n;if(o in e)return Zs[t]=o}return t}function Ra(e,t,s,n){return e.tagName==="TEXTAREA"&&(t==="width"||t==="height")&&de(n)&&s===n}const ni="http://www.w3.org/1999/xlink";function ii(e,t,s,n,i,o=No(t)){n&&t.startsWith("xlink:")?s==null?e.removeAttributeNS(ni,t.slice(6,t.length)):e.setAttributeNS(ni,t,s):s==null||o&&!xi(s)?e.removeAttribute(t):e.setAttribute(t,o?"":Qe(s)?String(s):s)}function oi(e,t,s,n,i){if(t==="innerHTML"||t==="textContent"){s!=null&&(e[t]=t==="innerHTML"?_o(s):s);return}const o=e.tagName;if(t==="value"&&o!=="PROGRESS"&&!o.includes("-")){const a=o==="OPTION"?e.getAttribute("value")||"":e.value,l=s==null?e.type==="checkbox"?"on":"":String(s);(a!==l||!("_value"in e))&&(e.value=l),s==null&&e.removeAttribute(t),e._value=s;return}let r=!1;if(s===""||s==null){const a=typeof e[t];a==="boolean"?s=xi(s):s==null&&a==="string"?(s="",r=!0):a==="number"&&(s=0,r=!0)}try{e[t]=s}catch{}r&&e.removeAttribute(i||t)}function ct(e,t,s,n){e.addEventListener(t,s,n)}function za(e,t,s,n){e.removeEventListener(t,s,n)}const ri=Symbol("_vei");function Ia(e,t,s,n,i=null){const o=e[ri]||(e[ri]={}),r=o[t];if(n&&r)r.value=n;else{const[a,l]=Ma(t);if(n){const g=o[t]=Fa(n,i);ct(e,a,g,l)}else r&&(za(e,a,r,l),o[t]=void 0)}}const ja=/(Once|Passive|Capture)$/,Ua=/^on:?(?:Once|Passive|Capture)$/;function Ma(e){let t,s;for(;(s=e.match(ja))&&!Ua.test(e);)t||(t={}),e=e.slice(0,e.length-s[1].length),t[s[1].toLowerCase()]=!0;return[e[2]===":"?e.slice(3):bt(e.slice(2)),t]}let Js=0;const Na=Promise.resolve(),La=()=>Js||(Na.then(()=>Js=0),Js=Date.now());function Fa(e,t){const s=n=>{if(!n._vts)n._vts=Date.now();else if(n._vts<=s.attached)return;const i=s.value;if(F(i)){const o=n.stopImmediatePropagation;n.stopImmediatePropagation=()=>{o.call(n),n._stopped=!0};const r=i.slice(),a=[n];for(let l=0;l<r.length&&!n._stopped;l++){const g=r[l];g&&Be(g,t,5,a)}}else Be(i,t,5,[n])};return s.value=e,s.attached=La(),s}const ai=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,Ba=(e,t,s,n,i,o)=>{const r=i==="svg";t==="class"?Pa(e,n,r):t==="style"?Oa(e,s,n):Ps(t)?Cs(t)||Ia(e,t,s,n,o):(t[0]==="."?(t=t.slice(1),!0):t[0]==="^"?(t=t.slice(1),!1):Ha(e,t,n,r))?(oi(e,t,n),!e.tagName.includes("-")&&(t==="value"||t==="checked"||t==="selected")&&ii(e,t,n,r,o,t!=="value")):e._isVueCE&&(Va(e,t)||e._def.__asyncLoader&&(/[A-Z]/.test(t)||!de(n)))?oi(e,Ne(t),n,o,t):(t==="true-value"?e._trueValue=n:t==="false-value"&&(e._fals Line truncated
@@ -1 +1 @@
@import"https://fonts.googleapis.com/css2?family=Archivo:ital,wght@0,400;0,500;0,600;0,700;0,800;1,700;1,800&family=DM+Mono:ital,wght@0,400;0,500&display=swap";/*! tailwindcss v4.3.2 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial}}}@layer theme{:root,:host{--font-sans:var(--font-sans);--font-mono:var(--font-mono);--color-white:#fff;--spacing:.25rem;--container-sm:24rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--font-weight-extrabold:800;--shadow-xs:var(--shadow-xs);--shadow-sm:var(--shadow-sm);--shadow-md:0 4px 6px -1px #0000001a, 0 2px 4px -2px #0000001a;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--radius-control:12px;--radius-card:18px;--radius-pill:999px}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:nLine truncated @import"https://fonts.googleapis.com/css2?family=Archivo:ital,wght@0,400;0,500;0,600;0,700;0,800;1,700;1,800&family=DM+Mono:ital,wght@0,400;0,500&display=swap";/*! tailwindcss v4.3.2 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial}}}@layer theme{:root,:host{--font-sans:var(--font-sans);--font-mono:var(--font-mono);--color-white:#fff;--spacing:.25rem;--container-sm:24rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--font-weight-extrabold:800;--shadow-xs:var(--shadow-xs);--shadow-sm:var(--shadow-sm);--shadow-md:0 4px 6px -1px #0000001a, 0 2px 4px -2px #0000001a;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--radius-control:12px;--radius-card:18px;--radius-pill:999px}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:nLine truncated
+2 -2
View File
@@ -6,8 +6,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#2563eb" /> <meta name="theme-color" content="#2563eb" />
<title>DriverVault · API Server</title> <title>DriverVault · API Server</title>
<script type="module" crossorigin src="/assets/index-BBZfstAT.js"></script> <script type="module" crossorigin src="/assets/index-CUgU2Fxs.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-_8IdQ1wh.css"> <link rel="stylesheet" crossorigin href="/assets/index-Cd85xDqG.css">
</head> </head>
<body> <body>
<div id="app"></div> <div id="app"></div>
+172 -84
View File
@@ -6,6 +6,8 @@ import (
"net/http" "net/http"
"net/url" "net/url"
"strings" "strings"
"drivervault/apiserver/internal/plugins/builtin/toyota"
) )
// Integrations exposes the Toyota Connected Europe plugin to end users under a // Integrations exposes the Toyota Connected Europe plugin to end users under a
@@ -13,14 +15,20 @@ import (
// account, while a superadmin (and, in an organization, an org admin) can impose // account, while a superadmin (and, in an organization, an org admin) can impose
// settings from above. // settings from above.
// //
// The one connector serves three brands — Toyota, Lexus and Subaru — and each is
// a plugin of its own to the user (toyota.Brands): its own panel entry, its own
// settings card, its own credentials and enable flag under its own
// pluginSettings key, and its own /api/integrations/{brand} routes. Everything
// below is written once and parameterized by the brand.
//
// Resolution is a cascade: the top layer wins, and a lower layer only fills a // Resolution is a cascade: the top layer wins, and a lower layer only fills a
// field the layers above left blank. // field the layers above left blank.
// //
// - global (L1): pluginSettings on the app_settings singleton, set in the API // - global (L1): pluginSettings on the app_settings singleton, set in the API
// Server panel by a superadmin. This is the top of the cascade for everyone. // Server panel by a superadmin. This is the top of the cascade for everyone.
// - org (L2): pluginSettings.toyota on the caller's organization record, // - org (L2): pluginSettings.{brand} on the caller's organization record,
// editable by an org admin. Present only for users who belong to an org. // editable by an org admin. Present only for users who belong to an org.
// - user (L3): pluginSettings.toyota on the caller's own user record. // - user (L3): pluginSettings.{brand} on the caller's own user record.
// //
// So the effective cascade is: // So the effective cascade is:
// - org user: global → org → user // - org user: global → org → user
@@ -28,7 +36,7 @@ import (
// //
// The MyToyota username + password resolve together as a *pair* from the highest // The MyToyota username + password resolve together as a *pair* from the highest
// layer that supplies a username, so credential halves are never mixed across // layer that supplies a username, so credential halves are never mixed across
// layers. The brand resolves on its own. Enablement is strictly per-user (L3), // layers. Enablement is strictly per-user (L3),
// gated by the global master switch (the plugin being enabled in the panel) and, // gated by the global master switch (the plugin being enabled in the panel) and,
// for org users, by the org gate. // for org users, by the org gate.
// //
@@ -36,19 +44,34 @@ import (
// client: the effective config is resolved server-side and only masked values // client: the effective config is resolved server-side and only masked values
// leave the API. The live probe runs server-side against the resolved config. // leave the API. The live probe runs server-side against the resolved config.
const ( const toyotaSecretMask = "••••••••"
toyotaPlugin = "toyota"
toyotaSecretMask = "••••••••"
)
// toyotaConfig is one layer's Toyota settings. // vehicleBrand is one face of the Toyota Connected Europe connector.
type vehicleBrand = toyota.Brand
// toyotaBrand is the MyToyota face, the one that predates the split.
var toyotaBrand = toyota.Brands[0]
// brandByName finds a registered brand by its plugin name.
func brandByName(name string) (vehicleBrand, bool) {
for _, b := range toyota.Brands {
if b.Name == name {
return b, true
}
}
return vehicleBrand{}, false
}
// toyotaConfig is one layer's settings for one brand.
type toyotaConfig struct { type toyotaConfig struct {
Username string `json:"username"` Username string `json:"username"`
Password string `json:"password"` Password string `json:"password"`
Brand string `json:"brand"` // Brand is read only from settings saved before the brands were split, to
// move them onto their own key (see splitLegacyBrand); nothing writes it.
Brand string `json:"brand,omitempty"`
} }
// toyotaStored is what we persist per user/org under pluginSettings.toyota. // toyotaStored is what we persist per user/org under pluginSettings.{brand}.
type toyotaStored struct { type toyotaStored struct {
Config toyotaConfig `json:"config"` Config toyotaConfig `json:"config"`
// Enabled is the personal per-user opt-in (user layer). Default false. // Enabled is the personal per-user opt-in (user layer). Default false.
@@ -58,9 +81,62 @@ type toyotaStored struct {
Disabled bool `json:"disabled,omitempty"` Disabled bool `json:"disabled,omitempty"`
} }
// toyotaSettingsDoc is the pluginSettings JSON shape (only toyota today). // decodePluginSettings reads a pluginSettings blob into its per-plugin entries,
type toyotaSettingsDoc struct { // with any pre-split brand entry already moved onto its own key. Never nil.
Toyota toyotaStored `json:"toyota"` func decodePluginSettings(raw json.RawMessage) map[string]json.RawMessage {
doc := map[string]json.RawMessage{}
if len(raw) > 0 {
_ = json.Unmarshal(raw, &doc)
}
if doc == nil {
doc = map[string]json.RawMessage{} // raw was JSON null
}
splitLegacyBrand(doc)
return doc
}
// splitLegacyBrand moves a pre-split entry onto its brand. Before Lexus and
// Subaru were plugins of their own, all three brands lived under
// pluginSettings.toyota with a brand field picking the login; an entry there
// that names L or S is that brand's account, so it belongs under that brand's
// key — left under toyota it would show a Lexus login on the Toyota card. The
// move happens on every read, so it needs no migration step, and is written
// back the first time the record is saved for any brand.
func splitLegacyBrand(doc map[string]json.RawMessage) {
raw, ok := doc[toyotaBrand.Name]
if !ok {
return
}
var ts toyotaStored
if json.Unmarshal(raw, &ts) != nil {
return
}
code := strings.ToUpper(strings.TrimSpace(ts.Config.Brand))
var target vehicleBrand
for _, b := range toyota.Brands {
if b.Code == code && b.Name != toyotaBrand.Name {
target = b
}
}
if target.Name == "" {
return // a Toyota entry, or one from before the brand field existed
}
if _, taken := doc[target.Name]; !taken {
ts.Config.Brand = ""
moved, _ := json.Marshal(ts)
doc[target.Name] = moved
}
delete(doc, toyotaBrand.Name)
}
// storedFor is one brand's entry in a pluginSettings blob.
func storedFor(raw json.RawMessage, b vehicleBrand) toyotaStored {
var ts toyotaStored
if entry, ok := decodePluginSettings(raw)[b.Name]; ok {
_ = json.Unmarshal(entry, &ts)
}
ts.Config.Brand = ""
return ts
} }
// toyotaFieldView is one field's resolved state for the UI. // toyotaFieldView is one field's resolved state for the UI.
@@ -71,7 +147,7 @@ type toyotaFieldView struct {
Locked bool `json:"locked"` // set above the caller's editable layer Locked bool `json:"locked"` // set above the caller's editable layer
} }
// toyotaResolution is the fully-resolved Toyota state for one caller. It captures // toyotaResolution is the fully-resolved state of one brand for one caller. It captures
// the effective cascade plus both editable layers (personal + organization), so // the effective cascade plus both editable layers (personal + organization), so
// an org admin can manage each independently. // an org admin can manage each independently.
type toyotaResolution struct { type toyotaResolution struct {
@@ -89,24 +165,19 @@ type toyotaResolution struct {
// toyotaLayerRank orders the cascade layers; a higher number is lower priority. // toyotaLayerRank orders the cascade layers; a higher number is lower priority.
var toyotaLayerRank = map[string]int{"global": 1, "org": 2, "user": 3} var toyotaLayerRank = map[string]int{"global": 1, "org": 2, "user": 3}
// resolveToyota computes the cascade for a caller. userRaw is the caller's // resolveToyota computes one brand's cascade for a caller. userRaw is the
// pluginSettings blob (read from their user record). // caller's pluginSettings blob (read from their user record).
func (s *Server) resolveToyota(ctx context.Context, who *callerIdentity, userRaw json.RawMessage) toyotaResolution { func (s *Server) resolveToyota(ctx context.Context, who *callerIdentity, userRaw json.RawMessage, b vehicleBrand) toyotaResolution {
g, masterEnabled, _ := s.plugins.RawConfig(toyotaPlugin) g, masterEnabled, _ := s.plugins.RawConfig(b.Name)
gc := toyotaConfig{Username: g["username"], Password: g["password"], Brand: g["brand"]} gc := toyotaConfig{Username: g["username"], Password: g["password"]}
var oStored toyotaStored var oStored toyotaStored
if who.OrgID != "" { if who.OrgID != "" {
oStored, _ = s.orgToyota(ctx, who.OrgID) oStored, _ = s.orgToyota(ctx, who.OrgID, b)
} }
oc := oStored.Config oc := oStored.Config
var uStored toyotaStored uStored := storedFor(userRaw, b)
if len(userRaw) > 0 {
var d toyotaSettingsDoc
_ = json.Unmarshal(userRaw, &d)
uStored = d.Toyota
}
uc := uStored.Config uc := uStored.Config
res := toyotaResolution{ res := toyotaResolution{
@@ -133,15 +204,6 @@ func (s *Server) resolveToyota(ctx context.Context, who *callerIdentity, userRaw
} }
layers = append(layers, layer{"user", uc}) layers = append(layers, layer{"user", uc})
// Brand resolves independently: the highest layer that sets it wins.
res.source["brand"] = "unset"
for _, l := range layers {
if v := strings.TrimSpace(l.c.Brand); v != "" {
res.eff.Brand, res.source["brand"] = v, l.name
break
}
}
// Credentials resolve as a pair from the highest layer with a username, so // Credentials resolve as a pair from the highest layer with a username, so
// the username and password never come from different layers. // the username and password never come from different layers.
credSrc := "unset" credSrc := "unset"
@@ -177,10 +239,11 @@ func toyotaMaskPresent(v string) string {
return "" return ""
} }
// orgToyota reads an organization's stored Toyota settings (config + the org // orgToyota reads an organization's stored settings for one brand (config + the
// gate) and its raw pluginSettings blob via the service account. Best effort: // org gate) and its raw pluginSettings blob via the service account. Best
// zero values on any miss so callers proceed as if the org layer were empty. // effort: zero values on any miss so callers proceed as if the org layer were
func (s *Server) orgToyota(ctx context.Context, orgID string) (toyotaStored, json.RawMessage) { // empty.
func (s *Server) orgToyota(ctx context.Context, orgID string, b vehicleBrand) (toyotaStored, json.RawMessage) {
if orgID == "" || !s.pb.Configured() { if orgID == "" || !s.pb.Configured() {
return toyotaStored{}, nil return toyotaStored{}, nil
} }
@@ -193,11 +256,7 @@ func (s *Server) orgToyota(ctx context.Context, orgID string) (toyotaStored, jso
PluginSettings json.RawMessage `json:"pluginSettings"` PluginSettings json.RawMessage `json:"pluginSettings"`
} }
_ = json.Unmarshal(data, &rec) _ = json.Unmarshal(data, &rec)
var doc toyotaSettingsDoc return storedFor(rec.PluginSettings, b), rec.PluginSettings
if len(rec.PluginSettings) > 0 {
_ = json.Unmarshal(rec.PluginSettings, &doc)
}
return doc.Toyota, rec.PluginSettings
} }
// userPluginSettings reads a user's raw pluginSettings blob via the service // userPluginSettings reads a user's raw pluginSettings blob via the service
@@ -215,23 +274,19 @@ func (s *Server) userPluginSettings(ctx context.Context, id string) json.RawMess
return rec.PluginSettings return rec.PluginSettings
} }
// mergeToyota applies a mutation to the toyota entry of a pluginSettings blob, // mergeToyota applies a mutation to one brand's entry of a pluginSettings blob,
// preserving any other plugin keys, and returns the new blob. // preserving any other plugin keys, and returns the new blob. A pre-split entry
func mergeToyota(existing json.RawMessage, apply func(*toyotaStored)) json.RawMessage { // is moved onto its brand on the way through, so the save also migrates it.
doc := map[string]json.RawMessage{} func mergeToyota(existing json.RawMessage, b vehicleBrand, apply func(*toyotaStored)) json.RawMessage {
if len(existing) > 0 { doc := decodePluginSettings(existing)
_ = json.Unmarshal(existing, &doc)
}
if doc == nil {
doc = map[string]json.RawMessage{} // existing was JSON null
}
var ts toyotaStored var ts toyotaStored
if raw, ok := doc["toyota"]; ok { if raw, ok := doc[b.Name]; ok {
_ = json.Unmarshal(raw, &ts) _ = json.Unmarshal(raw, &ts)
} }
apply(&ts) apply(&ts)
b, _ := json.Marshal(ts) ts.Config.Brand = ""
doc["toyota"] = b entry, _ := json.Marshal(ts)
doc[b.Name] = entry
out, _ := json.Marshal(doc) out, _ := json.Marshal(doc)
return out return out
} }
@@ -265,7 +320,6 @@ func (s *Server) toyotaScopeView(res toyotaResolution, editable string) map[stri
"fields": map[string]toyotaFieldView{ "fields": map[string]toyotaFieldView{
"username": field("username", res.eff.Username, own.Username, false), "username": field("username", res.eff.Username, own.Username, false),
"password": field("password", res.eff.Password, own.Password, true), "password": field("password", res.eff.Password, own.Password, true),
"brand": field("brand", res.eff.Brand, own.Brand, false),
}, },
} }
} }
@@ -273,8 +327,11 @@ func (s *Server) toyotaScopeView(res toyotaResolution, editable string) map[stri
// toyotaView builds the masked, client-safe response body from a resolution. It // toyotaView builds the masked, client-safe response body from a resolution. It
// exposes a "user" scope for everyone plus, for org admins, an "org" scope — each // exposes a "user" scope for everyone plus, for org admins, an "org" scope — each
// with its own locked-field state — so the UI can present the two independently. // with its own locked-field state — so the UI can present the two independently.
func (s *Server) toyotaView(who *callerIdentity, res toyotaResolution) map[string]any { func (s *Server) toyotaView(who *callerIdentity, res toyotaResolution, b vehicleBrand) map[string]any {
out := map[string]any{ out := map[string]any{
"brand": b.Name,
"make": b.Make,
"app": b.App,
"available": res.available, "available": res.available,
"orgEnabled": res.orgEnabled, "orgEnabled": res.orgEnabled,
"enabled": res.enabled, "enabled": res.enabled,
@@ -297,28 +354,52 @@ func (s *Server) toyotaView(who *callerIdentity, res toyotaResolution) map[strin
return out return out
} }
// GET /api/integrations/toyota — resolved Toyota view for the caller. // integrationBrand reads the brand segment of /api/integrations/{brand}. The
// routes are registered once per brand, so a miss is a wiring mistake; it still
// answers 404 rather than falling back to Toyota.
func integrationBrand(w http.ResponseWriter, r *http.Request) (vehicleBrand, bool) {
name := strings.TrimPrefix(r.URL.Path, "/api/integrations/")
if i := strings.IndexByte(name, '/'); i >= 0 {
name = name[:i]
}
b, ok := brandByName(name)
if !ok {
writeError(w, http.StatusNotFound, "unknown integration")
}
return b, ok
}
// GET /api/integrations/{toyota|lexus|subaru} — resolved view of one brand for
// the caller.
func (s *Server) handleGetToyota(w http.ResponseWriter, r *http.Request) { func (s *Server) handleGetToyota(w http.ResponseWriter, r *http.Request) {
who := caller(r) who := caller(r)
if who == nil { if who == nil {
writeError(w, http.StatusUnauthorized, "not authenticated") writeError(w, http.StatusUnauthorized, "not authenticated")
return return
} }
b, ok := integrationBrand(w, r)
if !ok {
return
}
userRaw := s.userPluginSettings(r.Context(), who.ID) userRaw := s.userPluginSettings(r.Context(), who.ID)
res := s.resolveToyota(r.Context(), who, userRaw) res := s.resolveToyota(r.Context(), who, userRaw, b)
writeJSON(w, http.StatusOK, s.toyotaView(who, res)) writeJSON(w, http.StatusOK, s.toyotaView(who, res, b))
} }
// PUT /api/integrations/toyota — save the caller's editable layer. Body: // PUT /api/integrations/{toyota|lexus|subaru} — save the caller's editable layer
// {enabled?: bool, scope?: "user"|"org", config?: {username, password, brand}}. // of one brand. Body: {enabled?: bool, scope?: "user"|"org", config?: {username,
// Fields locked above the caller are ignored; a password left at the mask is // password}}. Fields locked above the caller are ignored; a password left at the
// preserved. // mask is preserved.
func (s *Server) handlePutToyota(w http.ResponseWriter, r *http.Request) { func (s *Server) handlePutToyota(w http.ResponseWriter, r *http.Request) {
who := caller(r) who := caller(r)
if who == nil { if who == nil {
writeError(w, http.StatusUnauthorized, "not authenticated") writeError(w, http.StatusUnauthorized, "not authenticated")
return return
} }
b, ok := integrationBrand(w, r)
if !ok {
return
}
if !s.pb.Configured() { if !s.pb.Configured() {
writeError(w, http.StatusServiceUnavailable, "integration settings not configured on the server") writeError(w, http.StatusServiceUnavailable, "integration settings not configured on the server")
return return
@@ -334,7 +415,7 @@ func (s *Server) handlePutToyota(w http.ResponseWriter, r *http.Request) {
} }
userRaw := s.userPluginSettings(r.Context(), who.ID) userRaw := s.userPluginSettings(r.Context(), who.ID)
res := s.resolveToyota(r.Context(), who, userRaw) res := s.resolveToyota(r.Context(), who, userRaw, b)
// Resolve which layer this write targets. Everyone edits their own personal // Resolve which layer this write targets. Everyone edits their own personal
// (user) layer by default; an org admin may target the organization layer by // (user) layer by default; an org admin may target the organization layer by
@@ -370,12 +451,11 @@ func (s *Server) handlePutToyota(w http.ResponseWriter, r *http.Request) {
} }
applyField("username", func(c *toyotaConfig, v string) { c.Username = v }) applyField("username", func(c *toyotaConfig, v string) { c.Username = v })
applyField("password", func(c *toyotaConfig, v string) { c.Password = v }) applyField("password", func(c *toyotaConfig, v string) { c.Password = v })
applyField("brand", func(c *toyotaConfig, v string) { c.Brand = v })
// Persist the organization layer (admins) via the service account. // Persist the organization layer (admins) via the service account.
if editable == "org" { if editable == "org" {
_, orgRaw := s.orgToyota(r.Context(), who.OrgID) _, orgRaw := s.orgToyota(r.Context(), who.OrgID, b)
newDoc := mergeToyota(orgRaw, func(ts *toyotaStored) { newDoc := mergeToyota(orgRaw, b, func(ts *toyotaStored) {
ts.Config = newOwn ts.Config = newOwn
// In the org scope the enable flag is the org master switch, stored // In the org scope the enable flag is the org master switch, stored
// inverted (disabled) so absent means enabled. // inverted (disabled) so absent means enabled.
@@ -401,7 +481,7 @@ func (s *Server) handlePutToyota(w http.ResponseWriter, r *http.Request) {
// so does the personal config layer when this write targets the user scope. // so does the personal config layer when this write targets the user scope.
personalEnable := body.Enabled != nil && editable != "org" personalEnable := body.Enabled != nil && editable != "org"
if personalEnable || editable == "user" { if personalEnable || editable == "user" {
newDoc := mergeToyota(userRaw, func(ts *toyotaStored) { newDoc := mergeToyota(userRaw, b, func(ts *toyotaStored) {
if personalEnable { if personalEnable {
ts.Enabled = *body.Enabled ts.Enabled = *body.Enabled
} }
@@ -418,42 +498,45 @@ func (s *Server) handlePutToyota(w http.ResponseWriter, r *http.Request) {
// Re-resolve and return the fresh view. // Re-resolve and return the fresh view.
fresh := s.userPluginSettings(r.Context(), who.ID) fresh := s.userPluginSettings(r.Context(), who.ID)
res2 := s.resolveToyota(r.Context(), who, fresh) res2 := s.resolveToyota(r.Context(), who, fresh, b)
writeJSON(w, http.StatusOK, s.toyotaView(who, res2)) writeJSON(w, http.StatusOK, s.toyotaView(who, res2, b))
} }
// POST /api/integrations/toyota/health — live probe using the caller's resolved // POST /api/integrations/{toyota|lexus|subaru}/health — live probe using the
// config. Never returns secrets. // caller's resolved config for that brand. Never returns secrets.
func (s *Server) handleToyotaHealth(w http.ResponseWriter, r *http.Request) { func (s *Server) handleToyotaHealth(w http.ResponseWriter, r *http.Request) {
who := caller(r) who := caller(r)
if who == nil { if who == nil {
writeError(w, http.StatusUnauthorized, "not authenticated") writeError(w, http.StatusUnauthorized, "not authenticated")
return return
} }
b, ok := integrationBrand(w, r)
if !ok {
return
}
userRaw := s.userPluginSettings(r.Context(), who.ID) userRaw := s.userPluginSettings(r.Context(), who.ID)
res := s.resolveToyota(r.Context(), who, userRaw) res := s.resolveToyota(r.Context(), who, userRaw, b)
down := func(detail string) { down := func(detail string) {
writeJSON(w, http.StatusOK, map[string]any{"health": map[string]any{"status": "down", "detail": detail}}) writeJSON(w, http.StatusOK, map[string]any{"health": map[string]any{"status": "down", "detail": detail}})
} }
switch { switch {
case !res.available: case !res.available:
down("The Toyota integration is disabled by the administrator") down("The " + b.Make + " integration is disabled by the administrator")
return return
case !res.orgEnabled: case !res.orgEnabled:
down("The Toyota integration is disabled for your organization") down("The " + b.Make + " integration is disabled for your organization")
return return
case strings.TrimSpace(res.eff.Username) == "" || strings.TrimSpace(res.eff.Password) == "": case strings.TrimSpace(res.eff.Username) == "" || strings.TrimSpace(res.eff.Password) == "":
down("Enter your MyToyota email and password to connect") down("Enter your " + b.App + " email and password to connect")
return return
} }
cfg := map[string]string{ cfg := map[string]string{
"username": res.eff.Username, "username": res.eff.Username,
"password": res.eff.Password, "password": res.eff.Password,
"brand": res.eff.Brand,
} }
h, err := s.plugins.HealthCheckWith(r.Context(), toyotaPlugin, cfg) h, err := s.plugins.HealthCheckWith(r.Context(), b.Name, cfg)
if err != nil { if err != nil {
writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()}) writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()})
return return
@@ -461,7 +544,8 @@ func (s *Server) handleToyotaHealth(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"health": h}) writeJSON(w, http.StatusOK, map[string]any{"health": h})
} }
// GET /api/integrations/toyota/vehicles — the caller's Toyota vehicles as the // GET /api/integrations/{toyota|lexus|subaru}/vehicles — the caller's vehicles
// on that brand's account as the
// upstream returned them, fetched server-side under their resolved credentials. // upstream returned them, fetched server-side under their resolved credentials.
// Gated by the same switches as the settings view (global master, org gate, // Gated by the same switches as the settings view (global master, org gate,
// personal opt-in, credentials present); when any gate is off it returns 200 with // personal opt-in, credentials present); when any gate is off it returns 200 with
@@ -477,14 +561,18 @@ func (s *Server) handleToyotaVehicles(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusUnauthorized, "not authenticated") writeError(w, http.StatusUnauthorized, "not authenticated")
return return
} }
b, found := integrationBrand(w, r)
if !found {
return
}
userRaw := s.userPluginSettings(r.Context(), who.ID) userRaw := s.userPluginSettings(r.Context(), who.ID)
cfg, ok, detail := toyotaSource{}.gate(r.Context(), s, who, userRaw) cfg, ok, detail := toyotaSource{b}.gate(r.Context(), s, who, userRaw)
if !ok { if !ok {
writeJSON(w, http.StatusOK, map[string]any{"vehicles": []any{}, "unavailable": true, "detail": detail}) writeJSON(w, http.StatusOK, map[string]any{"vehicles": []any{}, "unavailable": true, "detail": detail})
return return
} }
raw, err := s.plugins.InvokeWith(r.Context(), toyotaPlugin, cfg, "vehicles", nil) raw, err := s.plugins.InvokeWith(r.Context(), b.Name, cfg, "vehicles", nil)
if err != nil { if err != nil {
writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()}) writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()})
return return
@@ -62,6 +62,52 @@ func normalizeControlMode(v string) string {
} }
} }
// ankerControlModesAll lists every control mode, in the order the clients offer
// them. off leads because it is the default and the fallback.
var ankerControlModesAll = []string{ankerControlOff, ankerControlMqtt, ankerControlModbus, ankerControlOwn, ankerControlProxy}
// parseControlModes reads a stored comma-separated mode list into a set,
// dropping anything unrecognized. off is never in it: monitoring-only is what a
// charger falls back to, so no layer may take it away from the layers below.
func parseControlModes(v string) map[string]bool {
out := map[string]bool{}
for _, part := range strings.Split(v, ",") {
if m := normalizeControlMode(part); m != "" && m != ankerControlOff {
out[m] = true
}
}
return out
}
// joinControlModes renders a mode set back to its stored form, in the canonical
// order, so what a client sends round-trips to a predictable string.
func joinControlModes(set map[string]bool) string {
return strings.Join(controlModeList(set), ",")
}
// controlModeList sorts a mode set into the canonical order.
func controlModeList(set map[string]bool) []string {
out := []string{}
for _, m := range ankerControlModesAll {
if set[m] {
out = append(out, m)
}
}
return out
}
// controlModesOffered lists the modes a layer may still choose once the layers
// above it have hidden theirs.
func controlModesOffered(hidden map[string]bool) []string {
out := []string{}
for _, m := range ankerControlModesAll {
if !hidden[m] {
out = append(out, m)
}
}
return out
}
// ankerConfig is one layer's Anker Solix settings. // ankerConfig is one layer's Anker Solix settings.
type ankerConfig struct { type ankerConfig struct {
Email string `json:"email"` Email string `json:"email"`
@@ -70,6 +116,12 @@ type ankerConfig struct {
// ControlMode is the control path: off | mqtt | modbus | own | proxy. // ControlMode is the control path: off | mqtt | modbus | own | proxy.
// It resolves independently of the credentials, like Country. // It resolves independently of the credentials, like Country.
ControlMode string `json:"controlMode"` ControlMode string `json:"controlMode"`
// ControlModesDisabled is a comma-separated list of modes this layer hides
// from the layers below it — a mode a deployment (or an organization) does
// not want offered at all. It does not constrain this layer's own choice, and
// it never hides off. Meaningful on the global and organization layers only:
// a user has nobody below them.
ControlModesDisabled string `json:"controlModesDisabled,omitempty"`
} }
// ankerChargerBinding is what we know about one charger the caller controls: // ankerChargerBinding is what we know about one charger the caller controls:
@@ -128,6 +180,18 @@ type ankerResolution struct {
available bool // global master switch (plugin enabled in the panel) available bool // global master switch (plugin enabled in the panel)
orgEnabled bool // org gate (default true; gates the org's users) orgEnabled bool // org gate (default true; gates the org's users)
enabled bool // caller's personal enable flag enabled bool // caller's personal enable flag
// payloadEncryption is the global layer's switch for the plugin's REST
// transport (off | on), copied into every cloud config as-is.
payloadEncryption string
// hiddenForOrg is what the global layer hides from everyone below it;
// hiddenForUser adds what the caller's organization hides from its own users.
// They gate both the pickers the clients draw and which layer's stored mode
// is allowed to take effect.
hiddenForOrg map[string]bool
hiddenForUser map[string]bool
orgHidden map[string]bool // the organization layer's own list, for its editor
} }
// ankerLayerRank orders the cascade layers; a higher number is lower priority. // ankerLayerRank orders the cascade layers; a higher number is lower priority.
@@ -137,7 +201,8 @@ var ankerLayerRank = map[string]int{"global": 1, "org": 2, "user": 3}
// pluginSettings blob (read from their user record). // pluginSettings blob (read from their user record).
func (s *Server) resolveAnker(ctx context.Context, who *callerIdentity, userRaw json.RawMessage) ankerResolution { func (s *Server) resolveAnker(ctx context.Context, who *callerIdentity, userRaw json.RawMessage) ankerResolution {
g, masterEnabled, _ := s.plugins.RawConfig(ankerPlugin) g, masterEnabled, _ := s.plugins.RawConfig(ankerPlugin)
gc := ankerConfig{Email: g["email"], Password: g["password"], Country: g["country"], ControlMode: g["controlMode"]} gc := ankerConfig{Email: g["email"], Password: g["password"], Country: g["country"],
ControlMode: g["controlMode"], ControlModesDisabled: g["controlModesDisabled"]}
var oStored ankerStored var oStored ankerStored
if who.OrgID != "" { if who.OrgID != "" {
@@ -164,6 +229,23 @@ func (s *Server) resolveAnker(ctx context.Context, who *callerIdentity, userRaw
available: masterEnabled, available: masterEnabled,
orgEnabled: !oStored.Disabled, // default true; off only when the org disabled it orgEnabled: !oStored.Disabled, // default true; off only when the org disabled it
enabled: uStored.Enabled, enabled: uStored.Enabled,
payloadEncryption: g["payloadEncryption"],
}
// What each layer below may still be offered. The global list reaches
// everyone; an organization's own list reaches only its users, so it narrows
// the set once more on the way down.
res.hiddenForOrg = parseControlModes(gc.ControlModesDisabled)
res.orgHidden = parseControlModes(oc.ControlModesDisabled)
res.hiddenForUser = map[string]bool{}
for m := range res.hiddenForOrg {
res.hiddenForUser[m] = true
}
if who.OrgID != "" {
for m := range res.orgHidden {
res.hiddenForUser[m] = true
}
} }
// Ordered layers, top (highest priority) first. // Ordered layers, top (highest priority) first.
@@ -189,13 +271,18 @@ func (s *Server) resolveAnker(ctx context.Context, who *callerIdentity, userRaw
// Control mode resolves independently too, defaulting to off (monitoring // Control mode resolves independently too, defaulting to off (monitoring
// only). The highest layer that sets a recognized value wins; an explicit // only). The highest layer that sets a recognized value wins; an explicit
// "off" set above still wins (and locks lower layers to monitoring). // "off" set above still wins (and locks lower layers to monitoring).
// A mode hidden by a layer above is not merely absent from the picker: a value
// stored below before it was hidden stops taking effect too, so switching a
// mode off really does switch it off everywhere underneath.
res.eff.ControlMode = ankerControlOff res.eff.ControlMode = ankerControlOff
res.source["controlMode"] = "unset" res.source["controlMode"] = "unset"
for _, l := range layers { for _, l := range layers {
if v := normalizeControlMode(l.c.ControlMode); v != "" { v := normalizeControlMode(l.c.ControlMode)
res.eff.ControlMode, res.source["controlMode"] = v, l.name if v == "" || res.hiddenAt(l.name)[v] {
break continue
} }
res.eff.ControlMode, res.source["controlMode"] = v, l.name
break
} }
// Credentials resolve as a pair from the highest layer with an email, so the // Credentials resolve as a pair from the highest layer with an email, so the
@@ -212,6 +299,19 @@ func (s *Server) resolveAnker(ctx context.Context, who *callerIdentity, userRaw
return res return res
} }
// hiddenAt is the set of modes hidden from one cascade layer by the layers above
// it. The global layer answers to nobody, so nothing is hidden from it.
func (r ankerResolution) hiddenAt(layer string) map[string]bool {
switch layer {
case "org":
return r.hiddenForOrg
case "user":
return r.hiddenForUser
default:
return map[string]bool{}
}
}
// ankerLockedFor reports whether a field whose value comes from source is locked // ankerLockedFor reports whether a field whose value comes from source is locked
// for a caller whose editable layer is editable (i.e. the value is set above them). // for a caller whose editable layer is editable (i.e. the value is set above them).
func ankerLockedFor(source, editable string) bool { func ankerLockedFor(source, editable string) bool {
@@ -301,7 +401,13 @@ func (s *Server) ankerScopeView(res ankerResolution, editable string) map[string
} }
return fv return fv
} }
return map[string]any{ // The modes this scope may pick from: everything the layers above it left
// standing. A superadmin's read-only view answers as the user layer they are.
hidden := res.hiddenForUser
if editable == "org" {
hidden = res.hiddenForOrg
}
out := map[string]any{
"editableLayer": editable, "editableLayer": editable,
"fields": map[string]ankerFieldView{ "fields": map[string]ankerFieldView{
"email": field("email", res.eff.Email, own.Email, false), "email": field("email", res.eff.Email, own.Email, false),
@@ -309,7 +415,15 @@ func (s *Server) ankerScopeView(res ankerResolution, editable string) map[string
"country": field("country", res.eff.Country, own.Country, false), "country": field("country", res.eff.Country, own.Country, false),
"controlMode": field("controlMode", res.eff.ControlMode, own.ControlMode, false), "controlMode": field("controlMode", res.eff.ControlMode, own.ControlMode, false),
}, },
"controlModes": controlModesOffered(hidden),
} }
if editable == "org" {
// The organization's own hide-list, which its admin edits here. Modes the
// global layer already hid are not in controlModes above, so they simply
// never come up.
out["controlModesDisabled"] = controlModeList(res.orgHidden)
}
return out
} }
// ankerView builds the masked, client-safe response body from a resolution. // ankerView builds the masked, client-safe response body from a resolution.
@@ -319,6 +433,7 @@ func (s *Server) ankerView(who *callerIdentity, res ankerResolution) map[string]
"orgEnabled": res.orgEnabled, "orgEnabled": res.orgEnabled,
"enabled": res.enabled, "enabled": res.enabled,
"controlMode": res.eff.ControlMode, // effective control mode (off|mqtt|modbus|own|proxy) "controlMode": res.eff.ControlMode, // effective control mode (off|mqtt|modbus|own|proxy)
"controlModes": controlModesOffered(res.hiddenForUser), // modes still offered to this caller
"role": who.Role, "role": who.Role,
"orgId": who.OrgID, "orgId": who.OrgID,
"canEditOrg": res.canOrg, "canEditOrg": res.canOrg,
@@ -430,7 +545,21 @@ func (s *Server) handlePutAnker(w http.ResponseWriter, r *http.Request) {
applyField("email", func(c *ankerConfig, v string) { c.Email = v }) applyField("email", func(c *ankerConfig, v string) { c.Email = v })
applyField("password", func(c *ankerConfig, v string) { c.Password = v }) applyField("password", func(c *ankerConfig, v string) { c.Password = v })
applyField("country", func(c *ankerConfig, v string) { c.Country = strings.ToUpper(v) }) applyField("country", func(c *ankerConfig, v string) { c.Country = strings.ToUpper(v) })
applyField("controlMode", func(c *ankerConfig, v string) { c.ControlMode = normalizeControlMode(v) }) applyField("controlMode", func(c *ankerConfig, v string) {
m := normalizeControlMode(v)
// A mode hidden above is not a choice this layer can make; keep whatever it
// had rather than storing something that would never take effect.
if m != "" && res.hiddenAt(editable)[m] {
return
}
c.ControlMode = m
})
if editable == "org" {
// Only a layer with users under it has anything to hide from them.
applyField("controlModesDisabled", func(c *ankerConfig, v string) {
c.ControlModesDisabled = joinControlModes(parseControlModes(v))
})
}
// Persist the organization layer (admins) via the service account. // Persist the organization layer (admins) via the service account.
if editable == "org" { if editable == "org" {
@@ -498,11 +627,7 @@ func (s *Server) handleAnkerHealth(w http.ResponseWriter, r *http.Request) {
return return
} }
cfg := map[string]string{ cfg := ankerCloudConfig(res)
"email": res.eff.Email,
"password": res.eff.Password,
"country": res.eff.Country,
}
h, err := s.plugins.HealthCheckWith(r.Context(), ankerPlugin, cfg) h, err := s.plugins.HealthCheckWith(r.Context(), ankerPlugin, cfg)
if err != nil { if err != nil {
writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()}) writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()})
@@ -530,11 +655,7 @@ func (s *Server) handleAnkerChargers(w http.ResponseWriter, r *http.Request) {
return return
} }
cfg := map[string]string{ cfg := ankerCloudConfig(res)
"email": res.eff.Email,
"password": res.eff.Password,
"country": res.eff.Country,
}
raw, err := s.plugins.InvokeWith(r.Context(), ankerPlugin, cfg, "chargers", nil) raw, err := s.plugins.InvokeWith(r.Context(), ankerPlugin, cfg, "chargers", nil)
if err != nil { if err != nil {
writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()}) writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()})
@@ -545,9 +666,11 @@ func (s *Server) handleAnkerChargers(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, json.RawMessage(raw)) writeJSON(w, http.StatusOK, json.RawMessage(raw))
} }
// GET /api/integrations/anker-solix/chargers/{sn}/details — every per-charger // GET /api/integrations/anker-solix/chargers/{sn}/details — every view the
// view the account holds: the station record, the charging totals, the OCPP // account holds about one charger: the station record, the totals, the history,
// backend and the RFID cards. Gated exactly like the charger list, and answered // the sessions, the OCPP backend, the cards, the sharing, the binding, the
// firmware and the rest, plus the site's own views when the charger belongs to
// one. Gated exactly like the charger list, and answered
// the same way when a gate is off: 200 with nothing and the reason, because a // the same way when a gate is off: 200 with nothing and the reason, because a
// disconnected integration is a normal state with an answer. // disconnected integration is a normal state with an answer.
func (s *Server) handleAnkerChargerDetails(w http.ResponseWriter, r *http.Request) { func (s *Server) handleAnkerChargerDetails(w http.ResponseWriter, r *http.Request) {
@@ -569,11 +692,7 @@ func (s *Server) handleAnkerChargerDetails(w http.ResponseWriter, r *http.Reques
return return
} }
cfg := map[string]string{ cfg := ankerCloudConfig(res)
"email": res.eff.Email,
"password": res.eff.Password,
"country": res.eff.Country,
}
raw, err := s.plugins.InvokeWith(r.Context(), ankerPlugin, cfg, "charger-details", raw, err := s.plugins.InvokeWith(r.Context(), ankerPlugin, cfg, "charger-details",
mustJSON(map[string]any{"sn": sn})) mustJSON(map[string]any{"sn": sn}))
if err != nil { if err != nil {
@@ -582,3 +701,125 @@ func (s *Server) handleAnkerChargerDetails(w http.ResponseWriter, r *http.Reques
} }
writeJSON(w, http.StatusOK, json.RawMessage(raw)) writeJSON(w, http.StatusOK, json.RawMessage(raw))
} }
// The two card writes. They are the only calls in the Anker connector that
// change anything on the account, so both are gated exactly like the reads,
// rate-limited beside the control commands — a card is who may start a charge,
// which is the same actuator asked a slower question — and audited by serial and
// card, with the number kept out of the log line: it is the credential itself.
// Both answer with the card list as it stands after the write, so the caller
// sees what the account holds rather than what an undocumented endpoint claimed.
// ankerCardBody is what a card write is asked for.
type ankerCardBody struct {
CardNumber string `json:"cardNumber"`
CardName string `json:"cardName"`
}
// POST /api/integrations/anker-solix/chargers/{sn}/rfid-cards — add a card to
// the charger, or rename one already on it.
func (s *Server) handleAnkerCardSave(w http.ResponseWriter, r *http.Request) {
who, sn, cfg, ok := s.ankerCardGate(w, r)
if !ok {
return
}
var body ankerCardBody
if r.Body != nil {
_ = json.NewDecoder(r.Body).Decode(&body)
}
if strings.TrimSpace(body.CardNumber) == "" {
writeError(w, http.StatusBadRequest, "card number required")
return
}
s.ankerCardWrite(w, r, who, cfg, "rfid-card-save", sn, map[string]any{
"sn": sn, "cardNumber": body.CardNumber, "cardName": body.CardName,
})
}
// DELETE /api/integrations/anker-solix/chargers/{sn}/rfid-cards/{number} —
// remove one card, named in full.
func (s *Server) handleAnkerCardDelete(w http.ResponseWriter, r *http.Request) {
who, sn, cfg, ok := s.ankerCardGate(w, r)
if !ok {
return
}
number := strings.TrimSpace(r.PathValue("number"))
if number == "" {
writeError(w, http.StatusBadRequest, "card number required")
return
}
s.ankerCardWrite(w, r, who, cfg, "rfid-card-delete", sn, map[string]any{
"sn": sn, "cardNumber": number,
})
}
// POST /api/integrations/anker-solix/chargers/{sn}/rfid-cards/scan — open the
// charger's card reader and answer with the card someone taps on it. Takes as
// long as the window does, about twenty seconds, and answers either way: a
// window that closed with nothing tapped is an answer, not a timeout.
func (s *Server) handleAnkerCardScan(w http.ResponseWriter, r *http.Request) {
who, sn, cfg, ok := s.ankerCardGate(w, r)
if !ok {
return
}
s.ankerCardWrite(w, r, who, cfg, "rfid-card-scan", sn, map[string]any{"sn": sn})
}
// GET /api/integrations/anker-solix/chargers/{sn}/rfid-cards/charger — the list
// of cards the charger itself holds, asked of the device with 0104 rather than
// of the account.
//
// The two lists are written together and can still come apart: a card the
// account has forgotten still opens the charger until the device is told
// otherwise, and the account's copy is the only one every other view here
// draws. Asking the device is the only way to see the difference. It answers
// with UIDs and nothing else — the charger has no field for a card's name.
func (s *Server) handleAnkerChargerCards(w http.ResponseWriter, r *http.Request) {
who, sn, cfg, ok := s.ankerCardGate(w, r)
if !ok {
return
}
s.ankerCardWrite(w, r, who, cfg, "rfid-cards-charger", sn, map[string]any{"sn": sn})
}
// ankerCardGate is everything a card call needs before it may run: a caller, a
// serial, an integration that is on and has credentials, and a rate limit. A
// gate that is off answers 409 rather than the reads' 200-with-a-reason: a write
// that did not happen is not a state to render, it is a request that failed.
func (s *Server) ankerCardGate(w http.ResponseWriter, r *http.Request) (*callerIdentity, string, map[string]string, bool) {
who := caller(r)
if who == nil {
writeError(w, http.StatusUnauthorized, "not authenticated")
return nil, "", nil, false
}
sn := strings.TrimSpace(r.PathValue("sn"))
if sn == "" {
writeError(w, http.StatusBadRequest, "charger serial required")
return nil, "", nil, false
}
userRaw := s.userPluginSettings(r.Context(), who.ID)
res := s.resolveAnker(r.Context(), who, userRaw)
if reason := ankerGate(res, true); reason != "" {
writeError(w, http.StatusConflict, reason)
return nil, "", nil, false
}
if !s.ctlRL.allow(who.ID + "|" + sn) {
writeError(w, http.StatusTooManyRequests, "too many card requests; please slow down")
return nil, "", nil, false
}
return who, sn, ankerCloudConfig(res), true
}
// ankerCardWrite runs one card capability and relays its document. The audit
// line names the charger and how the write went, never the card number.
func (s *Server) ankerCardWrite(w http.ResponseWriter, r *http.Request, who *callerIdentity,
cfg map[string]string, action, sn string, params map[string]any) {
raw, err := s.plugins.InvokeWith(r.Context(), ankerPlugin, cfg, action, mustJSON(params))
if err != nil {
s.auditControl(who, sn, action, nil, "failed", err)
writeJSON(w, http.StatusBadGateway, map[string]any{"error": err.Error()})
return
}
s.auditControl(who, sn, action, nil, "ok", nil)
writeJSON(w, http.StatusOK, json.RawMessage(raw))
}
@@ -338,7 +338,7 @@ func (s *Server) ankerProxyUpstream(ctx context.Context, res ankerResolution, se
if strings.TrimSpace(res.eff.Email) == "" || strings.TrimSpace(res.eff.Password) == "" { if strings.TrimSpace(res.eff.Email) == "" || strings.TrimSpace(res.eff.Password) == "" {
return "", "", errors.New("Anker account credentials are required for proxy mode") return "", "", errors.New("Anker account credentials are required for proxy mode")
} }
cfg := map[string]string{"email": res.eff.Email, "password": res.eff.Password, "country": res.eff.Country} cfg := ankerCloudConfig(res)
payload, _ := json.Marshal(map[string]string{"sn": serial}) payload, _ := json.Marshal(map[string]string{"sn": serial})
raw, err := s.plugins.InvokeWith(ctx, ankerPlugin, cfg, "ocpp-info", payload) raw, err := s.plugins.InvokeWith(ctx, ankerPlugin, cfg, "ocpp-info", payload)
if err != nil { if err != nil {
@@ -604,7 +604,7 @@ func (s *Server) handleAnkerControlAction(w http.ResponseWriter, r *http.Request
operative = *body.Operative operative = *body.Operative
} }
status, err = sess.ChangeAvailability(ctx, body.ConnectorID, operative) status, err = sess.ChangeAvailability(ctx, body.ConnectorID, operative)
case "reset": case "reset", "restart":
status, err = sess.Reset(ctx, body.Hard) status, err = sess.Reset(ctx, body.Hard)
case "unlock": case "unlock":
status, err = sess.UnlockConnector(ctx, body.ConnectorID) status, err = sess.UnlockConnector(ctx, body.ConnectorID)
@@ -649,7 +649,10 @@ func (s *Server) handleAnkerControlAction(w http.ResponseWriter, r *http.Request
// releases the cable lock — actions that require an explicit confirm:true and a // releases the cable lock — actions that require an explicit confirm:true and a
// password re-authentication. // password re-authentication.
func isDestructiveAction(action string) bool { func isDestructiveAction(action string) bool {
return action == "reset" || action == "unlock" // "restart" is the cloud's name for the same act as OCPP's "reset": both
// reboot the charger, so both pass through the confirmation and the password
// step-up rather than one slipping past because it is spelled differently.
return action == "reset" || action == "restart" || action == "unlock"
} }
// reauthenticate verifies the caller's password against PocketBase (a sudo-style // reauthenticate verifies the caller's password against PocketBase (a sudo-style
@@ -43,7 +43,13 @@ func (s *Server) ankerModbusAction(w http.ResponseWriter, r *http.Request, who *
// Actions the register map has no equivalent for. Saying which transport is // Actions the register map has no equivalent for. Saying which transport is
// missing them beats a bare "unknown action" the caller cannot act on. // missing them beats a bare "unknown action" the caller cannot act on.
switch action { switch action {
case "reset", "unlock", "availability", "trigger", "config": case "reset", "restart":
// No register reboots the charger. Both of the other transports can, so
// the refusal names them rather than only the CSMS.
writeError(w, http.StatusBadRequest,
"no register reboots the charger; the local Modbus connection cannot restart it. Switch the control mode to Anker cloud (MQTT) or a CSMS mode to use it.")
return
case "unlock", "availability", "trigger", "config":
writeError(w, http.StatusBadRequest, writeError(w, http.StatusBadRequest,
"\""+action+"\" is an OCPP command; the local Modbus connection cannot send it. Switch the control mode to a CSMS mode to use it.") "\""+action+"\" is an OCPP command; the local Modbus connection cannot send it. Switch the control mode to a CSMS mode to use it.")
return return
@@ -18,11 +18,11 @@ package api
// or certificated on the customer's side; what it costs instead is a dependency // or certificated on the customer's side; what it costs instead is a dependency
// on Anker's cloud being up, and on an unofficial protocol. // on Anker's cloud being up, and on an unofficial protocol.
// //
// The command set is the charger's, not OCPP's: start, stop, boost, skip-delay // The command set is the charger's, not OCPP's: start, stop, boost, skip-delay,
// and a current limit, plus the one thing neither other transport can do at all // a current limit and a restart, plus the one thing neither other transport can
// — writing the charger's own configuration, which is what "settings" is for. // do at all — writing the charger's own configuration, which is what "settings"
// Everything the register map or the CSMS can do that this cannot is refused by // is for. Everything the register map or the CSMS can do that this cannot is
// name rather than as an unknown action. // refused by name rather than as an unknown action.
import ( import (
"context" "context"
@@ -40,13 +40,18 @@ import (
// waits are shorter, so this only catches a request that is going nowhere. // waits are shorter, so this only catches a request that is going nowhere.
const ankerMqttTimeout = 45 * time.Second const ankerMqttTimeout = 45 * time.Second
// ankerCloudConfig is the plugin config one caller's resolved credentials make. // ankerCloudConfig is the plugin config one caller's resolved credentials make —
// The cloud transport signs in as the account, so unlike Modbus it needs them. // every transient instance the api package builds for the cloud goes through
// here. The cloud transport signs in as the account, so unlike Modbus it needs
// them. Payload encryption rides along from the global layer: it is how the
// connector talks to Anker, not whose account it talks as, so it is not part of
// the cascade and no lower layer can set it.
func ankerCloudConfig(res ankerResolution) map[string]string { func ankerCloudConfig(res ankerResolution) map[string]string {
return map[string]string{ return map[string]string{
"email": res.eff.Email, "email": res.eff.Email,
"password": res.eff.Password, "password": res.eff.Password,
"country": res.eff.Country, "country": res.eff.Country,
"payloadEncryption": res.payloadEncryption,
} }
} }
@@ -59,7 +64,7 @@ func (s *Server) ankerMqttAction(w http.ResponseWriter, r *http.Request, who *ca
// Actions this transport has no equivalent for. Naming the transport that // Actions this transport has no equivalent for. Naming the transport that
// does have them beats a bare "unknown action" the caller cannot act on. // does have them beats a bare "unknown action" the caller cannot act on.
switch action { switch action {
case "reset", "unlock", "availability", "trigger", "config": case "unlock", "availability", "trigger", "config":
writeError(w, http.StatusBadRequest, writeError(w, http.StatusBadRequest,
"\""+action+"\" is an OCPP command; the Anker cloud connection cannot send it. Switch the control mode to a CSMS mode to use it.") "\""+action+"\" is an OCPP command; the Anker cloud connection cannot send it. Switch the control mode to a CSMS mode to use it.")
return return
@@ -96,6 +101,11 @@ func (s *Server) ankerMqttAction(w http.ResponseWriter, r *http.Request, who *ca
case "limit": case "limit":
params["amps"] = body.Amps params["amps"] = body.Amps
payload["command"], payload["amps"] = "limit", body.Amps payload["command"], payload["amps"] = "limit", body.Amps
case "reset", "restart":
// The charger's own restart, the cloud's answer to the OCPP reset. It has
// already been through the confirmation and the password step-up upstairs,
// like any other reboot.
payload["command"] = "restart"
case "settings": case "settings":
// The values themselves are audited, not just the fact of a write: a // The values themselves are audited, not just the fact of a write: a
// setting that changes what the charger will draw, or whether it answers on // setting that changes what the charger will draw, or whether it answers on
@@ -24,7 +24,6 @@ func refuse(t *testing.T, action string, body ankerControlBody) *httptest.Respon
// unknown. // unknown.
func TestAnkerMqttActionNamesTheTransportThatCan(t *testing.T) { func TestAnkerMqttActionNamesTheTransportThatCan(t *testing.T) {
for _, tc := range []struct{ action, want string }{ for _, tc := range []struct{ action, want string }{
{"reset", "CSMS"},
{"unlock", "CSMS"}, {"unlock", "CSMS"},
{"availability", "CSMS"}, {"availability", "CSMS"},
{"config", "CSMS"}, {"config", "CSMS"},
@@ -43,6 +42,21 @@ func TestAnkerMqttActionNamesTheTransportThatCan(t *testing.T) {
} }
} }
// A reboot is a reboot under either name and over any transport: both go through
// the confirmation and the password step-up, and nothing else does.
func TestBothNamesForARebootAreGated(t *testing.T) {
for _, action := range []string{"reset", "restart", "unlock"} {
if !isDestructiveAction(action) {
t.Errorf("%s should need a confirmation and a password", action)
}
}
for _, action := range []string{"start", "stop", "limit", "boost", "settings", "status"} {
if isDestructiveAction(action) {
t.Errorf("%s should not demand a password", action)
}
}
}
func TestAnkerMqttActionRejectsUnknownActions(t *testing.T) { func TestAnkerMqttActionRejectsUnknownActions(t *testing.T) {
rec := refuse(t, "explode", ankerControlBody{}) rec := refuse(t, "explode", ankerControlBody{})
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "unknown control action") { if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "unknown control action") {
@@ -3,10 +3,12 @@ package api
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
"time" "time"
"drivervault/apiserver/internal/config"
"drivervault/apiserver/internal/pb" "drivervault/apiserver/internal/pb"
) )
@@ -217,3 +219,105 @@ func TestOCPPEndpoint(t *testing.T) {
t.Errorf("tls endpoint = %q", got) t.Errorf("tls endpoint = %q", got)
} }
} }
// The four card routes are reachable at all. A capability the plugin implements
// and the action catalogue advertises is still unusable if nothing routes to it,
// and that is not a failure any other test here would notice: the plugin's own
// tests pass, and the panel simply has no button. Each route is asked for
// without a token, so what is being checked is that the request reached the
// authentication middleware rather than a 404.
func TestAnkerCardRoutesAreRegistered(t *testing.T) {
h := New(config.Config{}, nil).Handler()
for _, tc := range []struct{ method, path string }{
{"POST", "/api/integrations/anker-solix/chargers/SN1/rfid-cards"},
{"POST", "/api/integrations/anker-solix/chargers/SN1/rfid-cards/scan"},
{"GET", "/api/integrations/anker-solix/chargers/SN1/rfid-cards/charger"},
{"DELETE", "/api/integrations/anker-solix/chargers/SN1/rfid-cards/AABBCCDD"},
} {
rr := httptest.NewRecorder()
h.ServeHTTP(rr, httptest.NewRequest(tc.method, tc.path, nil))
if rr.Code == http.StatusNotFound {
t.Errorf("%s %s is not routed", tc.method, tc.path)
}
}
}
func TestParseControlModes(t *testing.T) {
got := parseControlModes(" Proxy , own ,bogus,, off ")
// off is never hideable: monitoring only is what a charger falls back to.
want := map[string]bool{"proxy": true, "own": true}
if len(got) != len(want) {
t.Fatalf("parseControlModes = %v, want %v", got, want)
}
for m := range want {
if !got[m] {
t.Errorf("parseControlModes is missing %q", m)
}
}
if s := joinControlModes(got); s != "own,proxy" {
t.Errorf("joinControlModes = %q, want own,proxy (canonical order)", s)
}
}
func TestControlModesOffered(t *testing.T) {
got := controlModesOffered(map[string]bool{"own": true, "proxy": true})
want := []string{"off", "mqtt", "modbus"}
if len(got) != len(want) {
t.Fatalf("controlModesOffered = %v, want %v", got, want)
}
for i, m := range want {
if got[i] != m {
t.Errorf("controlModesOffered[%d] = %q, want %q", i, got[i], m)
}
}
}
// A mode the global layer hides is not merely absent from a lower picker: a
// value stored below before it was hidden stops taking effect too.
func TestHiddenControlModeDoesNotTakeEffect(t *testing.T) {
res := ankerResolution{
hiddenForOrg: map[string]bool{"own": true, "proxy": true},
hiddenForUser: map[string]bool{"own": true, "proxy": true},
}
if !res.hiddenAt("user")["proxy"] {
t.Error("proxy should be hidden from the user layer")
}
if res.hiddenAt("global")["proxy"] {
t.Error("nothing is hidden from the global layer — it is the one hiding")
}
view := (&Server{}).ankerScopeView(res, "user")
for _, m := range view["controlModes"].([]string) {
if m == "own" || m == "proxy" {
t.Errorf("hidden mode %q is still offered to the user scope", m)
}
}
if _, ok := view["controlModesDisabled"]; ok {
t.Error("the user scope has nobody below it and must carry no hide-list")
}
}
// An organization narrows the set once more for its own users, and its admin
// edits that list in the org scope.
func TestOrgScopeCarriesItsOwnHideList(t *testing.T) {
res := ankerResolution{
hiddenForOrg: map[string]bool{"proxy": true},
hiddenForUser: map[string]bool{"proxy": true, "own": true},
orgHidden: map[string]bool{"own": true},
}
org := (&Server{}).ankerScopeView(res, "org")
offered := org["controlModes"].([]string)
var sawOwn, sawProxy bool
for _, m := range offered {
sawOwn = sawOwn || m == "own"
sawProxy = sawProxy || m == "proxy"
}
if !sawOwn {
t.Error("an org may still choose a mode it only hides from its users")
}
if sawProxy {
t.Error("a mode the global layer hid must not reach the org picker")
}
if got := org["controlModesDisabled"].([]string); len(got) != 1 || got[0] != "own" {
t.Errorf("org hide-list = %v, want [own]", got)
}
}
@@ -0,0 +1,131 @@
package api
import (
"encoding/json"
"net/http"
"strings"
"testing"
)
// Toyota, Lexus and Subaru are one connector shown as three integrations, so
// each brand must be a vehicle provider of its own, labelled with its app.
func TestEveryBrandIsAVehicleProvider(t *testing.T) {
want := map[string]string{"toyota": "MyToyota", "lexus": "Lexus Link+", "subaru": "MySubaru"}
for id, label := range want {
src, ok := vehicleSourceByID(id)
if !ok {
t.Errorf("%q is not a vehicle provider", id)
continue
}
if src.label() != label {
t.Errorf("%q label = %q, want %q", id, src.label(), label)
}
}
if n := len(vehicleSources()); n != len(want) {
t.Errorf("vehicle providers = %d, want %d", n, len(want))
}
}
// Before the split every brand lived under pluginSettings.toyota with a brand
// field. A Lexus or Subaru entry there belongs to that brand now, and must leave
// the Toyota card empty rather than show the other brand's login.
func TestLegacyBrandEntryMovesToItsBrand(t *testing.T) {
lexus, _ := brandByName("lexus")
subaru, _ := brandByName("subaru")
raw := json.RawMessage(`{"toyota":{"config":{"username":"me@x","password":"pw","brand":"L"},"enabled":true},"anker-solix":{"enabled":true}}`)
if got := storedFor(raw, lexus); got.Config.Username != "me@x" || got.Config.Password != "pw" || !got.Enabled {
t.Errorf("lexus entry = %+v, want the legacy login, enabled", got)
}
if got := storedFor(raw, toyotaBrand); got.Config.Username != "" || got.Enabled {
t.Errorf("toyota entry = %+v, want empty — the legacy login was a Lexus one", got)
}
if got := storedFor(raw, subaru); got.Config.Username != "" {
t.Errorf("subaru entry = %+v, want empty", got)
}
// Saving any brand writes the move back and keeps unrelated plugins.
out := mergeToyota(raw, toyotaBrand, func(ts *toyotaStored) { ts.Config.Username = "t@x" })
var doc map[string]map[string]any
_ = json.Unmarshal(out, &doc)
if doc["lexus"] == nil || doc["anker-solix"] == nil {
t.Fatalf("merged doc lost an entry: %s", out)
}
if cfg, _ := doc["toyota"]["config"].(map[string]any); cfg["username"] != "t@x" || cfg["brand"] != nil {
t.Errorf("toyota entry after save = %v", doc["toyota"])
}
// A plain Toyota entry, with or without the old field, stays where it is.
for _, plain := range []string{
`{"toyota":{"config":{"username":"t@x","brand":"T"}}}`,
`{"toyota":{"config":{"username":"t@x"}}}`,
} {
if got := storedFor(json.RawMessage(plain), toyotaBrand); got.Config.Username != "t@x" {
t.Errorf("%s: toyota entry = %+v", plain, got)
}
}
// A brand that already has its own entry keeps it; the legacy one is dropped.
both := json.RawMessage(`{"toyota":{"config":{"username":"old","brand":"S"}},"subaru":{"config":{"username":"new"}}}`)
if got := storedFor(both, subaru); got.Config.Username != "new" {
t.Errorf("subaru entry = %+v, want its own", got)
}
}
// A car linked before the split says provider "toyota" whatever its make; it
// must read through its own brand's account.
func TestLegacyCarLinkFollowsItsMake(t *testing.T) {
cases := []struct{ provider, make, want string }{
{"toyota", "Lexus", "lexus"},
{"toyota", "SUBARU", "subaru"},
{"toyota", "Toyota", "toyota"},
{"toyota", "", "toyota"},
{"lexus", "Lexus", "lexus"},
}
for _, c := range cases {
src, ok := carVehicleSource(c.provider, c.make)
if !ok || src.id() != c.want {
t.Errorf("carVehicleSource(%q, %q) = %v, want %q", c.provider, c.make, src, c.want)
}
}
}
// Each brand answers on its own route with its own identity, and the provider
// listing offers all three — the server end of "three plugins in the apps".
func TestEveryBrandHasItsOwnIntegrationRoutes(t *testing.T) {
srv := newProviderTestServer(t, &fakeProviderPB{})
for _, c := range []struct{ brand, make, app string }{
{"toyota", "Toyota", "MyToyota"},
{"lexus", "Lexus", "Lexus Link+"},
{"subaru", "Subaru", "MySubaru"},
} {
status, body := call(t, srv, http.MethodGet, "/api/integrations/"+c.brand, "")
if status != http.StatusOK {
t.Errorf("GET %s: status %d", c.brand, status)
continue
}
if body["brand"] != c.brand || body["make"] != c.make || body["app"] != c.app {
t.Errorf("GET %s: identity = %v/%v/%v", c.brand, body["brand"], body["make"], body["app"])
}
scopes, _ := body["scopes"].(map[string]any)
user, _ := scopes["user"].(map[string]any)
fields, _ := user["fields"].(map[string]any)
if _, hasBrand := fields["brand"]; hasBrand || fields["username"] == nil {
t.Errorf("GET %s: fields = %v, want username/password and no brand picker", c.brand, fields)
}
// Plugin not enabled for lexus/subaru in this store: the probe says so,
// naming the brand rather than Toyota.
status, body = call(t, srv, http.MethodPost, "/api/integrations/"+c.brand+"/health", "")
h, _ := body["health"].(map[string]any)
if status != http.StatusOK || h["status"] != "down" || !strings.Contains(h["detail"].(string), c.make) {
t.Errorf("POST %s/health: %d %v", c.brand, status, body)
}
}
_, body := call(t, srv, http.MethodGet, "/api/vehicle-providers", "")
if list, _ := body["providers"].([]any); len(list) != 3 {
t.Errorf("providers = %v, want three", body["providers"])
}
}
+31
View File
@@ -29,6 +29,8 @@ type userRecord struct {
Theme string `json:"theme"` Theme string `json:"theme"`
Locale string `json:"locale"` Locale string `json:"locale"`
DateFormat string `json:"date_format"` DateFormat string `json:"date_format"`
TimeFormat string `json:"time_format"`
WeekStart string `json:"week_start"`
Currency string `json:"currency"` Currency string `json:"currency"`
FontSize string `json:"font_size"` FontSize string `json:"font_size"`
DragLocked bool `json:"drag_locked"` DragLocked bool `json:"drag_locked"`
@@ -97,6 +99,8 @@ func (rec userRecord) toModel() models.User {
Theme: orDefault(rec.Theme, "system"), Theme: orDefault(rec.Theme, "system"),
Locale: orDefault(rec.Locale, "en-US"), Locale: orDefault(rec.Locale, "en-US"),
DateFormat: orDefault(rec.DateFormat, "YMD"), DateFormat: orDefault(rec.DateFormat, "YMD"),
TimeFormat: orDefault(rec.TimeFormat, "auto"),
WeekStart: orDefault(rec.WeekStart, "auto"),
Currency: orDefault(rec.Currency, "USD"), Currency: orDefault(rec.Currency, "USD"),
FontSize: orDefault(rec.FontSize, "medium"), FontSize: orDefault(rec.FontSize, "medium"),
DragLocked: rec.DragLocked, DragLocked: rec.DragLocked,
@@ -161,6 +165,8 @@ type updateMeRequest struct {
Theme *string `json:"theme"` Theme *string `json:"theme"`
Locale *string `json:"locale"` Locale *string `json:"locale"`
DateFormat *string `json:"dateFormat"` DateFormat *string `json:"dateFormat"`
TimeFormat *string `json:"timeFormat"`
WeekStart *string `json:"weekStart"`
Currency *string `json:"currency"` Currency *string `json:"currency"`
FontSize *string `json:"fontSize"` FontSize *string `json:"fontSize"`
DragLocked *bool `json:"dragLocked"` DragLocked *bool `json:"dragLocked"`
@@ -256,6 +262,17 @@ func normalizeOrder(field string, in []string, max int) ([]string, error) {
var validThemes = map[string]bool{"light": true, "dark": true, "system": true} var validThemes = map[string]bool{"light": true, "dark": true, "system": true}
var validDateFormats = map[string]bool{"YMD": true, "DMY_NUM": true, "DMY": true, "MDY": true} var validDateFormats = map[string]bool{"YMD": true, "DMY_NUM": true, "DMY": true, "MDY": true}
// "auto" reads the clock the way the chosen region writes it, which is what
// the app did before there was a setting; the other two say it outright, for
// the people whose region and habit disagree.
var validTimeFormats = map[string]bool{"auto": true, "24": true, "12": true}
// Which day a week is drawn as starting on. "auto" is the chosen region's own
// convention — Monday across most of Europe, Sunday in the US — and is what
// every weekday row read before there was a setting; the other two say it
// outright, for the people whose region and habit disagree.
var validWeekStarts = map[string]bool{"auto": true, "monday": true, "sunday": true}
var validFontSizes = map[string]bool{"small": true, "medium": true, "large": true} var validFontSizes = map[string]bool{"small": true, "medium": true, "large": true}
// Kept in step with the users.currency select options in setup-pocketbase.mjs: // Kept in step with the users.currency select options in setup-pocketbase.mjs:
@@ -318,6 +335,20 @@ func (s *Server) handleUpdateMe(w http.ResponseWriter, r *http.Request) {
} }
payload["date_format"] = *in.DateFormat payload["date_format"] = *in.DateFormat
} }
if in.TimeFormat != nil {
if !validTimeFormats[*in.TimeFormat] {
writeError(w, http.StatusBadRequest, "timeFormat must be auto, 24, or 12")
return
}
payload["time_format"] = *in.TimeFormat
}
if in.WeekStart != nil {
if !validWeekStarts[*in.WeekStart] {
writeError(w, http.StatusBadRequest, "weekStart must be auto, monday, or sunday")
return
}
payload["week_start"] = *in.WeekStart
}
if in.Currency != nil { if in.Currency != nil {
if !validCurrencies[*in.Currency] { if !validCurrencies[*in.Currency] {
writeError(w, http.StatusBadRequest, "currency must be a supported ISO 4217 code") writeError(w, http.StatusBadRequest, "currency must be a supported ISO 4217 code")
+237
View File
@@ -0,0 +1,237 @@
package api
// Automatic odometer updates from a car's connected service.
//
// The MyToyota tab already offers the provider's odometer when it is ahead of
// the stored one; this is that same write done on a timer, so a car that is
// driven every day does not need somebody to open its page and press the
// button. It runs on the server's own ticker rather than in the browser for the
// same reason the charging scheduler does: an update that needs the page open
// is a reminder, not an update.
//
// Provider calls always run under a person's account, so the car remembers who
// switched updates on and reads under theirs. That person must still have write
// access when a sweep comes round — a share that was revoked stops the updates
// rather than letting them write on a car the user no longer may edit.
import (
"context"
"encoding/json"
"errors"
"log"
"net/http"
"net/url"
"time"
)
// The intervals offered, in minutes. A fixed set rather than any number: the
// provider's servers are somebody else's, and every update is a login plus a
// batch of calls, so nothing more often than every half hour.
var odometerSyncIntervals = map[int]bool{
30: true, 60: true, 180: true, 360: true, 720: true, 1440: true, 10080: true,
}
// defaultOdometerSyncMinutes is what a car gets when updates are switched on
// without an interval: once a day, enough for service reminders.
const defaultOdometerSyncMinutes = 1440
// How often the sweep looks for cars that are due. The shortest interval is 30
// minutes, so a five-minute look lands every update within five of its time.
const odometerSyncTick = 5 * time.Minute
// How long one sweep may take, across every due car.
const odometerSyncSweepTimeout = 4 * time.Minute
// PUT /api/cars/{id}/provider/auto-sync — switch automatic odometer updates on
// or off, and choose how often. Body: {enabled: bool, intervalMinutes?: int}.
// Needs write access, since the updates write to the car, and a linked car.
// Switching on records the caller as the account the readings come from, and
// runs one update straight away so the choice shows its effect.
func (s *Server) handleCarOdometerAutoSync(w http.ResponseWriter, r *http.Request) {
who := caller(r)
if who == nil {
writeError(w, http.StatusUnauthorized, "not authenticated")
return
}
var body struct {
Enabled bool `json:"enabled"`
IntervalMinutes int `json:"intervalMinutes"`
}
if err := decodeJSON(r, &body); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
carID := r.PathValue("id")
level, rec, err := s.carAccessLevel(r.Context(), who.ID, carID)
if err != nil {
writePBError(w, err)
return
}
if !canWrite(level) {
writeError(w, http.StatusForbidden, "you cannot edit this car")
return
}
if rec.Provider == "" {
writeError(w, http.StatusBadRequest, "this car is not linked to a connected service")
return
}
minutes := body.IntervalMinutes
if minutes == 0 {
minutes = rec.OdometerSyncMinutes
}
if minutes == 0 {
minutes = defaultOdometerSyncMinutes
}
if !odometerSyncIntervals[minutes] {
writeError(w, http.StatusBadRequest, "unsupported interval")
return
}
payload := map[string]any{
"odometer_auto_sync": body.Enabled,
"odometer_sync_minutes": minutes,
}
if body.Enabled {
payload["odometer_sync_by"] = who.ID
} else {
payload["odometer_sync_error"] = ""
}
var updated carRecord
if err := s.pb.Update(r.Context(), colCars, carID, payload, &updated); err != nil {
writePBError(w, err)
return
}
// Switching on (or changing the interval while on) updates once now, so the
// panel can show "last checked" and the odometer moves without waiting a day.
if body.Enabled {
s.syncCarOdometer(r.Context(), updated)
_ = s.pb.GetOne(r.Context(), colCars, carID, &updated)
}
m := updated.toModel()
m.Access = level
writeJSON(w, http.StatusOK, m)
}
// startOdometerSync starts the ticker that updates due cars. Called from
// StartScheduler and stopped by the same cancel.
func (s *Server) startOdometerSync(ctx context.Context) {
go func() {
t := time.NewTicker(odometerSyncTick)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
s.sweepOdometerSync(ctx)
}
}
}()
}
// sweepOdometerSync updates every car whose interval has run out.
func (s *Server) sweepOdometerSync(ctx context.Context) {
if !s.pb.Configured() {
return
}
ctx, cancel := context.WithTimeout(ctx, odometerSyncSweepTimeout)
defer cancel()
res, err := s.pb.List(ctx, colCars, url.Values{
"filter": {`odometer_auto_sync=true && provider!=""`},
"perPage": {"500"},
})
if err != nil {
return // the database not answering is retried next tick, silently
}
var recs []carRecord
if err := json.Unmarshal(res.Items, &recs); err != nil {
return
}
now := time.Now()
for _, rec := range recs {
if !odometerSyncDue(rec, now) {
continue
}
s.syncCarOdometer(ctx, rec)
}
}
// odometerSyncDue says whether a car's interval has run out. A car never
// attempted, or whose timestamp is unreadable, is due.
func odometerSyncDue(rec carRecord, now time.Time) bool {
minutes := rec.OdometerSyncMinutes
if minutes <= 0 {
minutes = defaultOdometerSyncMinutes
}
last, err := time.Parse(time.RFC3339, rec.OdometerSyncedAt)
if err != nil {
return true
}
return !now.Before(last.Add(time.Duration(minutes) * time.Minute))
}
// syncCarOdometer fetches the provider's odometer for one car and stores it
// when it is ahead of the car's, then records the attempt. Failures are stored
// on the car (and so shown on its page) rather than returned: there is nobody
// waiting on a background update to tell.
func (s *Server) syncCarOdometer(ctx context.Context, rec carRecord) {
km, err := s.fetchCarOdometer(ctx, rec)
payload := map[string]any{
"odometer_synced_at": time.Now().UTC().Format(time.RFC3339),
"odometer_sync_error": "",
}
if err != nil {
payload["odometer_sync_error"] = err.Error()
log.Printf("odometer sync: car %s (%s): %v", rec.ID, rec.Name, err)
} else if km > rec.CurrentKm {
// Only ever forward, as with the button: a reading behind the stored one
// is the provider being stale, not the car running backwards.
payload["current_km"] = km
}
if err := s.pb.Update(ctx, colCars, rec.ID, payload, nil); err != nil {
log.Printf("odometer sync: car %s: saving: %v", rec.ID, err)
}
}
// fetchCarOdometer reads the provider's odometer for a car under the account of
// the user who switched updates on, checking they may still write to it.
func (s *Server) fetchCarOdometer(ctx context.Context, rec carRecord) (int, error) {
if rec.OdometerSyncBy == "" {
return 0, errors.New("nobody is set to read this car's odometer; switch automatic updates off and on again")
}
level, _, err := s.carAccessLevel(ctx, rec.OdometerSyncBy, rec.ID)
if err != nil {
return 0, err
}
if !canWrite(level) {
return 0, errors.New("the user who switched automatic updates on can no longer edit this car")
}
who, userRaw, err := s.callerForUser(ctx, rec.OdometerSyncBy)
if err != nil {
return 0, err
}
src, found := carVehicleSource(rec.Provider, rec.Make)
if !found {
return 0, errors.New("unknown vehicle provider")
}
cfg, ok, detail := src.gate(ctx, s, who, userRaw)
if !ok {
return 0, errors.New(detail)
}
vehicles, err := s.fetchProviderVehicles(ctx, src, cfg)
if err != nil {
return 0, err
}
vehicle, found := findVehicle(vehicles, rec.ProviderVehicleID)
if !found {
return 0, errors.New("this vehicle is not on the " + src.label() + " account")
}
km, ok := s.providerOdometer(ctx, src, cfg, vehicle.ID)
if !ok {
return 0, errors.New(src.label() + " did not report an odometer")
}
return km, nil
}
@@ -0,0 +1,65 @@
package api
import (
"net/http"
"strings"
"testing"
"time"
)
func TestOdometerSyncDue(t *testing.T) {
now := time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)
at := func(d time.Duration) string { return now.Add(-d).Format(time.RFC3339) }
cases := []struct {
name string
rec carRecord
want bool
}{
{"never attempted", carRecord{OdometerSyncMinutes: 60}, true},
{"unreadable timestamp", carRecord{OdometerSyncMinutes: 60, OdometerSyncedAt: "yesterday"}, true},
{"inside the interval", carRecord{OdometerSyncMinutes: 60, OdometerSyncedAt: at(59 * time.Minute)}, false},
{"exactly at the interval", carRecord{OdometerSyncMinutes: 60, OdometerSyncedAt: at(time.Hour)}, true},
{"no interval falls back to daily", carRecord{OdometerSyncedAt: at(23 * time.Hour)}, false},
{"daily default runs out", carRecord{OdometerSyncedAt: at(24 * time.Hour)}, true},
}
for _, c := range cases {
if got := odometerSyncDue(c.rec, now); got != c.want {
t.Errorf("%s: due = %v, want %v", c.name, got, c.want)
}
}
}
func TestOdometerAutoSyncNeedsLinkedCar(t *testing.T) {
srv := newProviderTestServer(t, &fakeProviderPB{})
status, body := call(t, srv, http.MethodPut, "/api/cars/"+provCarID+"/provider/auto-sync", `{"enabled":true}`)
if status != http.StatusBadRequest || !strings.Contains(toStr(body["error"]), "not linked") {
t.Errorf("status = %d (%v), want 400 not linked", status, body["error"])
}
}
func TestOdometerAutoSyncRejectsOddInterval(t *testing.T) {
srv := newProviderTestServer(t, &fakeProviderPB{carProvider: "toyota", carVehicleID: "VIN1"})
status, body := call(t, srv, http.MethodPut, "/api/cars/"+provCarID+"/provider/auto-sync",
`{"enabled":true,"intervalMinutes":7}`)
if status != http.StatusBadRequest || !strings.Contains(toStr(body["error"]), "interval") {
t.Errorf("status = %d (%v), want 400 unsupported interval", status, body["error"])
}
}
func TestOdometerAutoSyncSwitchOff(t *testing.T) {
fake := &fakeProviderPB{carProvider: "toyota", carVehicleID: "VIN1"}
srv := newProviderTestServer(t, fake)
status, body := call(t, srv, http.MethodPut, "/api/cars/"+provCarID+"/provider/auto-sync",
`{"enabled":false,"intervalMinutes":360}`)
if status != http.StatusOK {
t.Fatalf("status = %d (%v), want 200", status, body["error"])
}
patch := fake.patch()
if patch["odometer_auto_sync"] != false || patch["odometer_sync_minutes"] != float64(360) {
t.Errorf("patch = %+v, want updates off at 360 minutes", patch)
}
if _, set := patch["odometer_sync_by"]; set {
t.Error("switching off must not record whose account to read under")
}
}
+12 -1
View File
@@ -64,6 +64,11 @@ type carRecord struct {
FirstRegistrationDate string `json:"first_registration_date"` FirstRegistrationDate string `json:"first_registration_date"`
Provider string `json:"provider"` Provider string `json:"provider"`
ProviderVehicleID string `json:"provider_vehicle_id"` ProviderVehicleID string `json:"provider_vehicle_id"`
OdometerAutoSync bool `json:"odometer_auto_sync"`
OdometerSyncMinutes int `json:"odometer_sync_minutes"`
OdometerSyncBy string `json:"odometer_sync_by"`
OdometerSyncedAt string `json:"odometer_synced_at"`
OdometerSyncError string `json:"odometer_sync_error"`
Owner string `json:"owner"` Owner string `json:"owner"`
Created string `json:"created"` Created string `json:"created"`
Updated string `json:"updated"` Updated string `json:"updated"`
@@ -108,7 +113,11 @@ func (rec carRecord) toModel() models.Car {
FirstRegistrationDate: rec.FirstRegistrationDate, FirstRegistrationDate: rec.FirstRegistrationDate,
Provider: rec.Provider, Provider: rec.Provider,
ProviderVehicleID: rec.ProviderVehicleID, ProviderVehicleID: rec.ProviderVehicleID,
HiddenTabs: decodeStringList(rec.HiddenTabs), OdometerAutoSync: rec.OdometerAutoSync,
OdometerSyncMinutes: rec.OdometerSyncMinutes,
OdometerSyncedAt: rec.OdometerSyncedAt,
OdometerSyncError: rec.OdometerSyncError,
HiddenTabs: decodeStringList(rec.HiddenTabs),
HiddenFields: decodeStringList(rec.HiddenFields), HiddenFields: decodeStringList(rec.HiddenFields),
HiddenServiceColumns: decodeStringList(rec.HiddenServiceColumns), HiddenServiceColumns: decodeStringList(rec.HiddenServiceColumns),
HiddenServiceParts: decodeStringList(rec.HiddenServiceParts), HiddenServiceParts: decodeStringList(rec.HiddenServiceParts),
@@ -155,6 +164,8 @@ func carPayload(c models.Car) map[string]any {
// provider clears both fields (unlink). // provider clears both fields (unlink).
func carProviderPayload(provider, vehicleID string) map[string]any { func carProviderPayload(provider, vehicleID string) map[string]any {
if provider == "" { if provider == "" {
// Automatic odometer updates are left as they are: the sweep only looks
// at linked cars, so an unlinked one is simply never updated.
return map[string]any{"provider": "", "provider_vehicle_id": ""} return map[string]any{"provider": "", "provider_vehicle_id": ""}
} }
return map[string]any{"provider": provider, "provider_vehicle_id": vehicleID} return map[string]any{"provider": provider, "provider_vehicle_id": vehicleID}
+39 -7
View File
@@ -45,13 +45,17 @@
// DELETE /api/admin/plugins/{name} POST /api/admin/plugins/{name}/health // DELETE /api/admin/plugins/{name} POST /api/admin/plugins/{name}/health
// //
// # integrations (per-user plugin settings; superadmin → org admin → user cascade) // # integrations (per-user plugin settings; superadmin → org admin → user cascade)
// GET /api/integrations/toyota PUT /api/integrations/toyota // GET /api/integrations/{toyota|lexus|subaru} PUT (same)
// POST /api/integrations/toyota/health // POST /api/integrations/{toyota|lexus|subaru}/health
// GET /api/integrations/toyota/vehicles // GET /api/integrations/{toyota|lexus|subaru}/vehicles
// GET /api/integrations/anker-solix PUT /api/integrations/anker-solix // GET /api/integrations/anker-solix PUT /api/integrations/anker-solix
// POST /api/integrations/anker-solix/health // POST /api/integrations/anker-solix/health
// GET /api/integrations/anker-solix/chargers // GET /api/integrations/anker-solix/chargers
// GET /api/integrations/anker-solix/chargers/{sn}/details // GET /api/integrations/anker-solix/chargers/{sn}/details
// POST /api/integrations/anker-solix/chargers/{sn}/rfid-cards
// POST /api/integrations/anker-solix/chargers/{sn}/rfid-cards/scan
// DELETE /api/integrations/anker-solix/chargers/{sn}/rfid-cards/{number}
// GET /api/integrations/anker-solix/chargers/{sn}/rfid-cards/charger
// GET /api/integrations/greencell PUT /api/integrations/greencell // GET /api/integrations/greencell PUT /api/integrations/greencell
// POST /api/integrations/greencell/health // POST /api/integrations/greencell/health
// GET /api/integrations/greencell/chargers // GET /api/integrations/greencell/chargers
@@ -68,6 +72,7 @@
// PUT /api/cars/{id}/view // PUT /api/cars/{id}/view
// GET /api/cars/{id}/provider POST /api/cars/{id}/provider // GET /api/cars/{id}/provider POST /api/cars/{id}/provider
// POST /api/cars/{id}/provider/sync // POST /api/cars/{id}/provider/sync
// PUT /api/cars/{id}/provider/auto-sync
// GET /api/cars/{id}/service-records // GET /api/cars/{id}/service-records
// GET /api/cars/{id}/parts // GET /api/cars/{id}/parts
// GET /api/cars/{id}/shares POST /api/cars/{id}/shares // GET /api/cars/{id}/shares POST /api/cars/{id}/shares
@@ -138,6 +143,7 @@ import (
"drivervault/apiserver/internal/ocpp" "drivervault/apiserver/internal/ocpp"
"drivervault/apiserver/internal/pb" "drivervault/apiserver/internal/pb"
"drivervault/apiserver/internal/plugins" "drivervault/apiserver/internal/plugins"
"drivervault/apiserver/internal/plugins/builtin/toyota"
_ "drivervault/apiserver/internal/plugins/builtin" // register built-in plugins _ "drivervault/apiserver/internal/plugins/builtin" // register built-in plugins
) )
@@ -155,6 +161,7 @@ const (
colDocuments = "car_documents" colDocuments = "car_documents"
colReminders = "reminders" colReminders = "reminders"
colHomeChargers = "home_chargers" colHomeChargers = "home_chargers"
colChargingTasks = "charging_tasks"
colControlAudit = "control_audit" colControlAudit = "control_audit"
colAppSettings = "app_settings" colAppSettings = "app_settings"
) )
@@ -178,6 +185,10 @@ type Server struct {
ocpp *ocpp.CSMS ocpp *ocpp.CSMS
control *controlIndex // token -> owning user/charger for the /ocpp endpoint control *controlIndex // token -> owning user/charger for the /ocpp endpoint
ctlRL *rateLimiter // per user+charger control-command rate limit ctlRL *rateLimiter // per user+charger control-command rate limit
// schedulerStop ends the ticker that fires the home-charger scheduler's
// tasks, started by StartScheduler (see chargingtasks_run.go).
schedulerStop context.CancelFunc
} }
// New constructs a Server around an already-built PocketBase client. // New constructs a Server around an already-built PocketBase client.
@@ -281,6 +292,9 @@ func (s *Server) Stop(ctx context.Context) {
if s.pluginsStop != nil { if s.pluginsStop != nil {
s.pluginsStop() s.pluginsStop()
} }
if s.schedulerStop != nil {
s.schedulerStop()
}
s.ocpp.Shutdown(ctx) s.ocpp.Shutdown(ctx)
s.plugins.Shutdown(ctx) s.plugins.Shutdown(ctx)
} }
@@ -432,15 +446,24 @@ func (s *Server) Handler() http.Handler {
// Integrations — per-user plugin settings under the superadmin → org admin → // Integrations — per-user plugin settings under the superadmin → org admin →
// user cascade (see integrations.go). Any authenticated user manages their // user cascade (see integrations.go). Any authenticated user manages their
// own layer; an org admin may also target their organization's layer. // own layer; an org admin may also target their organization's layer.
mux.HandleFunc("GET /api/integrations/toyota", s.handleGetToyota) // Toyota, Lexus and Subaru are one connector registered once per brand; each
mux.HandleFunc("PUT /api/integrations/toyota", s.handlePutToyota) // gets its own routes, so the apps can show them as three integrations.
mux.HandleFunc("POST /api/integrations/toyota/health", s.handleToyotaHealth) for _, b := range toyota.Brands {
mux.HandleFunc("GET /api/integrations/toyota/vehicles", s.handleToyotaVehicles) base := "/api/integrations/" + b.Name
mux.HandleFunc("GET "+base, s.handleGetToyota)
mux.HandleFunc("PUT "+base, s.handlePutToyota)
mux.HandleFunc("POST "+base+"/health", s.handleToyotaHealth)
mux.HandleFunc("GET "+base+"/vehicles", s.handleToyotaVehicles)
}
mux.HandleFunc("GET /api/integrations/anker-solix", s.handleGetAnker) mux.HandleFunc("GET /api/integrations/anker-solix", s.handleGetAnker)
mux.HandleFunc("PUT /api/integrations/anker-solix", s.handlePutAnker) mux.HandleFunc("PUT /api/integrations/anker-solix", s.handlePutAnker)
mux.HandleFunc("POST /api/integrations/anker-solix/health", s.handleAnkerHealth) mux.HandleFunc("POST /api/integrations/anker-solix/health", s.handleAnkerHealth)
mux.HandleFunc("GET /api/integrations/anker-solix/chargers", s.handleAnkerChargers) mux.HandleFunc("GET /api/integrations/anker-solix/chargers", s.handleAnkerChargers)
mux.HandleFunc("GET /api/integrations/anker-solix/chargers/{sn}/details", s.handleAnkerChargerDetails) mux.HandleFunc("GET /api/integrations/anker-solix/chargers/{sn}/details", s.handleAnkerChargerDetails)
mux.HandleFunc("POST /api/integrations/anker-solix/chargers/{sn}/rfid-cards", s.handleAnkerCardSave)
mux.HandleFunc("POST /api/integrations/anker-solix/chargers/{sn}/rfid-cards/scan", s.handleAnkerCardScan)
mux.HandleFunc("DELETE /api/integrations/anker-solix/chargers/{sn}/rfid-cards/{number}", s.handleAnkerCardDelete)
mux.HandleFunc("GET /api/integrations/anker-solix/chargers/{sn}/rfid-cards/charger", s.handleAnkerChargerCards)
mux.HandleFunc("GET /api/integrations/greencell", s.handleGetGreencell) mux.HandleFunc("GET /api/integrations/greencell", s.handleGetGreencell)
mux.HandleFunc("PUT /api/integrations/greencell", s.handlePutGreencell) mux.HandleFunc("PUT /api/integrations/greencell", s.handlePutGreencell)
mux.HandleFunc("POST /api/integrations/greencell/health", s.handleGreencellHealth) mux.HandleFunc("POST /api/integrations/greencell/health", s.handleGreencellHealth)
@@ -480,6 +503,14 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("PATCH /api/home-chargers/{id}", s.updateHomeCharger) mux.HandleFunc("PATCH /api/home-chargers/{id}", s.updateHomeCharger)
mux.HandleFunc("DELETE /api/home-chargers/{id}", s.deleteHomeCharger) mux.HandleFunc("DELETE /api/home-chargers/{id}", s.deleteHomeCharger)
// The home-charger scheduler: one list of charging tasks per user, covering
// every charger they own. See chargingtasks.go.
mux.HandleFunc("GET /api/charging-tasks", s.listChargingTasks)
mux.HandleFunc("POST /api/charging-tasks", s.createChargingTask)
mux.HandleFunc("PATCH /api/charging-tasks/{id}", s.updateChargingTask)
mux.HandleFunc("DELETE /api/charging-tasks/{id}", s.deleteChargingTask)
mux.HandleFunc("POST /api/charging-tasks/{id}/steps/{step}/run", s.runChargingStepNow)
// Cars + sharing. // Cars + sharing.
mux.HandleFunc("GET /api/cars", s.listCars) mux.HandleFunc("GET /api/cars", s.listCars)
mux.HandleFunc("POST /api/cars", s.createCar) mux.HandleFunc("POST /api/cars", s.createCar)
@@ -500,6 +531,7 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("GET /api/cars/{id}/provider", s.handleCarProvider) mux.HandleFunc("GET /api/cars/{id}/provider", s.handleCarProvider)
mux.HandleFunc("POST /api/cars/{id}/provider", s.handleLinkCarProvider) mux.HandleFunc("POST /api/cars/{id}/provider", s.handleLinkCarProvider)
mux.HandleFunc("POST /api/cars/{id}/provider/sync", s.handleSyncCarProvider) mux.HandleFunc("POST /api/cars/{id}/provider/sync", s.handleSyncCarProvider)
mux.HandleFunc("PUT /api/cars/{id}/provider/auto-sync", s.handleCarOdometerAutoSync)
mux.HandleFunc("GET /api/cars/{id}/shares", s.handleListShares) mux.HandleFunc("GET /api/cars/{id}/shares", s.handleListShares)
mux.HandleFunc("POST /api/cars/{id}/shares", s.handleUpsertShare) mux.HandleFunc("POST /api/cars/{id}/shares", s.handleUpsertShare)
mux.HandleFunc("DELETE /api/cars/{id}/shares/{userId}", s.handleDeleteShare) mux.HandleFunc("DELETE /api/cars/{id}/shares/{userId}", s.handleDeleteShare)
+32 -5
View File
@@ -49,6 +49,7 @@ import (
"drivervault/apiserver/internal/models" "drivervault/apiserver/internal/models"
"drivervault/apiserver/internal/plugins" "drivervault/apiserver/internal/plugins"
"drivervault/apiserver/internal/plugins/builtin/toyota"
) )
// vehicleSource adapts one plugin that can enumerate the caller's vehicles and // vehicleSource adapts one plugin that can enumerate the caller's vehicles and
@@ -73,9 +74,30 @@ type vehicleSource interface {
sections() []providerSection sections() []providerSection
} }
// vehicleSources are the registered providers, in menu order. // vehicleSources are the registered providers, in menu order: one per brand of
// the Toyota Connected Europe connector.
func vehicleSources() []vehicleSource { func vehicleSources() []vehicleSource {
return []vehicleSource{toyotaSource{}} out := make([]vehicleSource, 0, len(toyota.Brands))
for _, b := range toyota.Brands {
out = append(out, toyotaSource{b})
}
return out
}
// carVehicleSource is the provider a linked car reads from. A Lexus or a Subaru
// linked before the brands were split carries provider "toyota" — there was only
// the one — so its make picks the brand it now belongs to; reading it through
// the Toyota account would log in to the wrong app.
func carVehicleSource(provider, carMake string) (vehicleSource, bool) {
if provider == toyotaBrand.Name && strings.TrimSpace(carMake) != "" {
mk := toyotaMake(carMake)
for _, b := range toyota.Brands {
if b.Make == mk {
return toyotaSource{b}, true
}
}
}
return vehicleSourceByID(provider)
} }
func vehicleSourceByID(id string) (vehicleSource, bool) { func vehicleSourceByID(id string) (vehicleSource, bool) {
@@ -282,8 +304,13 @@ func (s *Server) linkedVehicles(ctx context.Context, userID, provider string) ma
if userID == "" || provider == "" { if userID == "" || provider == "" {
return out return out
} }
filter := fmt.Sprintf("provider='%s'", provider)
if b, ok := brandByName(provider); ok && b.Name != toyotaBrand.Name {
// Cars of this brand linked before the split are under "toyota".
filter = fmt.Sprintf("(%s || (provider='%s' && make='%s'))", filter, toyotaBrand.Name, b.Make)
}
res, err := s.pb.List(ctx, colCars, url.Values{ res, err := s.pb.List(ctx, colCars, url.Values{
"filter": {fmt.Sprintf("owner='%s' && provider='%s'", userID, provider)}, "filter": {fmt.Sprintf("owner='%s' && %s", userID, filter)},
"perPage": {"200"}, "perPage": {"200"},
}) })
if err != nil { if err != nil {
@@ -531,7 +558,7 @@ func (s *Server) handleCarProvider(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "this car is not linked to a connected service") writeError(w, http.StatusNotFound, "this car is not linked to a connected service")
return return
} }
src, found := vehicleSourceByID(rec.Provider) src, found := carVehicleSource(rec.Provider, rec.Make)
if !found { if !found {
writeError(w, http.StatusNotFound, "unknown vehicle provider") writeError(w, http.StatusNotFound, "unknown vehicle provider")
return return
@@ -822,7 +849,7 @@ func (s *Server) handleSyncCarProvider(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "this car is not linked to a connected service") writeError(w, http.StatusBadRequest, "this car is not linked to a connected service")
return return
} }
src, found := vehicleSourceByID(rec.Provider) src, found := carVehicleSource(rec.Provider, rec.Make)
if !found { if !found {
writeError(w, http.StatusNotFound, "unknown vehicle provider") writeError(w, http.StatusNotFound, "unknown vehicle provider")
return return
@@ -269,6 +269,21 @@ func TestHeadlineMetricsRoundsConvertedReadings(t *testing.T) {
} }
} }
func TestToyotaFuelType(t *testing.T) {
cases := map[string]string{
"E": "electric", // battery EV
"I": "hybrid", // plug-in hybrid
"HV": "hybrid", // spelled out: falls through to the normalizer
"G": "", // a letter nobody has pinned down stays unset
"": "",
}
for in, want := range cases {
if got := toyotaFuelType(in); got != want {
t.Errorf("toyotaFuelType(%q) = %q, want %q", in, got, want)
}
}
}
func TestNormalizeProviderFuelType(t *testing.T) { func TestNormalizeProviderFuelType(t *testing.T) {
cases := map[string]string{ cases := map[string]string{
"HV": "hybrid", "HV": "hybrid",
@@ -362,6 +377,10 @@ func TestToyotaVehiclesFallbacks(t *testing.T) {
if got[0].Name != "Lexus IS 300h" { if got[0].Name != "Lexus IS 300h" {
t.Errorf("name = %q, want Lexus IS 300h", got[0].Name) t.Errorf("name = %q, want Lexus IS 300h", got[0].Name)
} }
// The third brand on the wire: a Solterra reports itself as "S".
if m := toyotaMake("S"); m != "Subaru" {
t.Errorf(`toyotaMake("S") = %q, want Subaru`, m)
}
// A vehicle with nothing to address it by is skipped, not imported blind. // A vehicle with nothing to address it by is skipped, not imported blind.
anonymous := toyotaSource{}.vehicles(json.RawMessage(`{"payload": [{"colour": "blue"}]}`)) anonymous := toyotaSource{}.vehicles(json.RawMessage(`{"payload": [{"colour": "blue"}]}`))
@@ -1,7 +1,9 @@
package api package api
// toyotaSource is the first vehicleSource: Toyota Connected Europe, the backend // toyotaSource is the first vehicleSource: Toyota Connected Europe, the backend
// behind the MyToyota app (see internal/plugins/builtin/toyota). It contributes // behind the MyToyota app (see internal/plugins/builtin/toyota), and behind the
// Lexus and Subaru apps too. There is one source per brand, so each shows up as
// a provider of its own, labelled with the app its owner knows. It contributes
// nothing but wiring — credentials come from the cascade already in // nothing but wiring — credentials come from the cascade already in
// integrations.go, and the payload walking lives in vehicleproviders.go — which // integrations.go, and the payload walking lives in vehicleproviders.go — which
// is the shape the next manufacturer's adapter should copy. // is the shape the next manufacturer's adapter should copy.
@@ -12,14 +14,13 @@ import (
"strings" "strings"
) )
// toyotaLabel is what the user sees: the app they know the account by, not the // toyotaSource serves one brand. Its label is what the user sees: the app they
// corporate service name behind it. It titles the car's provider tab. // know the account by ("MyToyota", "Lexus Link+"), not the corporate service
const toyotaLabel = "MyToyota" // name behind it. It titles the car's provider tab.
type toyotaSource struct{ brand vehicleBrand }
type toyotaSource struct{} func (t toyotaSource) id() string { return t.brand.Name }
func (t toyotaSource) label() string { return t.brand.App }
func (toyotaSource) id() string { return toyotaPlugin }
func (toyotaSource) label() string { return toyotaLabel }
func (toyotaSource) service() string { return "Toyota Connected Europe" } func (toyotaSource) service() string { return "Toyota Connected Europe" }
func (toyotaSource) listAction() string { return "vehicles" } func (toyotaSource) listAction() string { return "vehicles" }
@@ -40,25 +41,25 @@ func (toyotaSource) sections() []providerSection {
} }
} }
// gate resolves the caller's MyToyota credentials through the global → org → user // gate resolves the caller's credentials for this brand through the global → org
// cascade and reports what is missing when they cannot be used. It is the single // → user cascade and reports what is missing when they cannot be used. It is the
// place those messages are written: handleToyotaVehicles calls it too. // single place those messages are written: handleToyotaVehicles calls it too.
func (toyotaSource) gate(ctx context.Context, s *Server, who *callerIdentity, userRaw json.RawMessage) (map[string]string, bool, string) { func (t toyotaSource) gate(ctx context.Context, s *Server, who *callerIdentity, userRaw json.RawMessage) (map[string]string, bool, string) {
res := s.resolveToyota(ctx, who, userRaw) b := t.brand
res := s.resolveToyota(ctx, who, userRaw, b)
switch { switch {
case !res.available: case !res.available:
return nil, false, "The Toyota integration is disabled by the administrator" return nil, false, "The " + b.Make + " integration is disabled by the administrator"
case !res.orgEnabled: case !res.orgEnabled:
return nil, false, "The Toyota integration is disabled for your organization" return nil, false, "The " + b.Make + " integration is disabled for your organization"
case !res.enabled: case !res.enabled:
return nil, false, "Enable the Toyota integration in Settings to load your vehicles" return nil, false, "Enable the " + b.Make + " integration in Settings to load your vehicles"
case strings.TrimSpace(res.eff.Username) == "" || strings.TrimSpace(res.eff.Password) == "": case strings.TrimSpace(res.eff.Username) == "" || strings.TrimSpace(res.eff.Password) == "":
return nil, false, "Enter your MyToyota email and password to connect" return nil, false, "Enter your " + b.App + " email and password to connect"
} }
return map[string]string{ return map[string]string{
"username": res.eff.Username, "username": res.eff.Username,
"password": res.eff.Password, "password": res.eff.Password,
"brand": res.eff.Brand,
}, true, "" }, true, ""
} }
@@ -86,7 +87,7 @@ func (toyotaSource) vehicles(raw json.RawMessage) []providerVehicle {
Make: toyotaMake(findString(obj, "brand", "brandName", "make")), Make: toyotaMake(findString(obj, "brand", "brandName", "make")),
Model: findString(obj, "modelName", "modelDescription", "carModelName", "carLineName", "model"), Model: findString(obj, "modelName", "modelDescription", "carModelName", "carLineName", "model"),
Registration: findString(obj, "licensePlate", "registrationNumber", "plateNumber", "licencePlate"), Registration: findString(obj, "licensePlate", "registrationNumber", "plateNumber", "licencePlate"),
FuelType: normalizeProviderFuelType(findString(obj, "fuelType", "fuel", "engineType", "powerTrain", "drivetrain")), FuelType: toyotaFuelType(findString(obj, "fuelType", "fuel", "engineType", "powerTrain", "drivetrain")),
BuildDate: isoDateOnly(findString(obj, "productionDate", "manufacturingDate", "buildDate")), BuildDate: isoDateOnly(findString(obj, "productionDate", "manufacturingDate", "buildDate")),
FirstRegistrationDate: isoDateOnly(findString(obj, "firstRegistrationDate", "initialRegistrationDate", "registrationDate")), FirstRegistrationDate: isoDateOnly(findString(obj, "firstRegistrationDate", "initialRegistrationDate", "registrationDate")),
ImageURL: findString(obj, "imageUrl", "carImageUrl", "image", "picture"), ImageURL: findString(obj, "imageUrl", "carImageUrl", "image", "picture"),
@@ -105,19 +106,35 @@ func (toyotaSource) vehicles(raw json.RawMessage) []providerVehicle {
return out return out
} }
// toyotaMake expands the one-letter brand code the app uses on the wire ("T"/"L") // toyotaMake expands the one-letter brand code the app uses on the wire
// and otherwise passes the reported brand through in title case. // ("T"/"L"/"S") and otherwise passes the reported brand through in title case.
func toyotaMake(brand string) string { func toyotaMake(brand string) string {
switch strings.ToUpper(strings.TrimSpace(brand)) { switch strings.ToUpper(strings.TrimSpace(brand)) {
case "T", "TOYOTA", "": case "T", "TOYOTA", "":
return "Toyota" return "Toyota"
case "L", "LEXUS": case "L", "LEXUS":
return "Lexus" return "Lexus"
case "S", "SUBARU":
return "Subaru"
} }
b := strings.TrimSpace(brand) b := strings.TrimSpace(brand)
return strings.ToUpper(b[:1]) + strings.ToLower(b[1:]) return strings.ToUpper(b[:1]) + strings.ToLower(b[1:])
} }
// toyotaFuelType reads the one-letter powertrain code the vehicle list sends in
// fuelType: "E" is a battery EV and "I" a plug-in hybrid (pytoyoda gates the
// electric read on exactly these two). Other letters are not pinned down, so
// they and any spelled-out value go through the generic normalizer.
func toyotaFuelType(v string) string {
switch strings.ToUpper(strings.TrimSpace(v)) {
case "E":
return "electric"
case "I":
return "hybrid"
}
return normalizeProviderFuelType(v)
}
// vehicleDisplayName is the name the car gets by default: the nickname the owner // vehicleDisplayName is the name the car gets by default: the nickname the owner
// already gave the vehicle in the app, else make + model, else the VIN. // already gave the vehicle in the app, else make + model, else the VIN.
func vehicleDisplayName(obj map[string]any, v providerVehicle) string { func vehicleDisplayName(obj map[string]any, v providerVehicle) string {
+118
View File
@@ -29,6 +29,24 @@ type Options struct {
SuperAdminEmail string SuperAdminEmail string
SuperAdminPassword string SuperAdminPassword string
SuperAdminName string SuperAdminName string
// S3, when non-nil and Enabled, points PocketBase's record-file storage at
// a bucket. Nil is the normal case — a stack started without one of the
// SeaweedFS compose overlays keeps its uploads on the pb_data volume.
S3 *S3Options
}
// S3Options describes the bucket PocketBase should keep record files in. It
// mirrors PocketBase's own settings block one field at a time, so there is
// nothing to translate at the wire.
type S3Options struct {
Enabled bool
Bucket string
Region string
Endpoint string
AccessKey string
Secret string
ForcePathStyle bool
} }
// fieldDef is a schema field normalized to a single shape; it is rendered into // fieldDef is a schema field normalized to a single shape; it is rendered into
@@ -190,6 +208,10 @@ func Run(ctx context.Context, client *pb.Client, opts Options) error {
if err := ensureSuperAdmin(ctx, client, opts); err != nil { if err := ensureSuperAdmin(ctx, client, opts); err != nil {
return fmt.Errorf("super-admin: %w", err) return fmt.Errorf("super-admin: %w", err)
} }
if err := ensureFileStorage(ctx, client, opts.S3); err != nil {
return fmt.Errorf("file storage: %w", err)
}
return nil return nil
} }
@@ -433,6 +455,102 @@ func ensureSuperAdmin(ctx context.Context, client *pb.Client, opts Options) erro
return nil return nil
} }
// --- file storage ----------------------------------------------------------
// storageSettings is the slice of PocketBase's settings this step owns. The
// json names are PocketBase's own (core.S3Config), so the PATCH body is just
// this type marshalled back out.
type storageSettings struct {
Enabled bool `json:"enabled"`
Bucket string `json:"bucket"`
Region string `json:"region"`
Endpoint string `json:"endpoint"`
AccessKey string `json:"accessKey"`
Secret string `json:"secret,omitempty"`
ForcePathStyle bool `json:"forcePathStyle"`
}
// sameExceptSecret compares everything a read of the settings can be trusted
// on. PocketBase masks the stored secret, so a rotation of the secret alone is
// invisible from here — changing any other PB_S3_* value forces the write, and
// so does editing it in the admin UI.
func (s storageSettings) sameExceptSecret(other storageSettings) bool {
s.Secret, other.Secret = "", ""
return s == other
}
// ensureFileStorage points PocketBase's record-file storage at the configured
// bucket, and does nothing at all when no bucket was asked for.
//
// It never turns S3 *off*: files already written to a bucket are only reachable
// while PocketBase is still pointed at it, so dropping the overlay leaves the
// setting where it is rather than stranding every existing attachment. Moving
// back to local storage is a deliberate act in the admin UI.
func ensureFileStorage(ctx context.Context, client *pb.Client, opts *S3Options) error {
if opts == nil || !opts.Enabled {
return nil // not requested
}
want := storageSettings{
Enabled: true,
Bucket: opts.Bucket,
Region: opts.Region,
Endpoint: opts.Endpoint,
AccessKey: opts.AccessKey,
Secret: opts.Secret,
ForcePathStyle: opts.ForcePathStyle,
}
raw, status, err := client.Raw(ctx, http.MethodGet, "/api/settings", nil)
if err != nil {
return err
}
if status < 200 || status >= 300 {
return fmt.Errorf("read settings: status %d: %s", status, raw)
}
var current struct {
S3 storageSettings `json:"s3"`
}
if err := json.Unmarshal(raw, &current); err != nil {
return err
}
if current.S3.sameExceptSecret(want) {
log.Printf("bootstrap: • file storage already on S3 (%s)", want.Bucket)
} else {
// Only the s3 block is sent: everything else in the settings — mail,
// backups, rate limits — belongs to whoever set it.
raw, status, err = client.Raw(ctx, http.MethodPatch, "/api/settings",
map[string]any{"s3": want})
if err != nil {
return err
}
if status < 200 || status >= 300 {
return fmt.Errorf("apply settings: status %d: %s", status, raw)
}
log.Printf("bootstrap: ✓ file storage → S3 (%s at %s)", want.Bucket, want.Endpoint)
}
testFileStorage(ctx, client)
return nil
}
// testFileStorage asks PocketBase to prove it can actually reach the bucket,
// and only says so in the log. A failure here means uploads will fail, but the
// server still has to come up — the endpoint is fixable from the panel, and a
// stack that refuses to boot cannot be fixed from anywhere.
func testFileStorage(ctx context.Context, client *pb.Client) {
raw, status, err := client.Raw(ctx, http.MethodPost, "/api/settings/test/s3",
map[string]any{"filesystem": "storage"})
switch {
case err != nil:
log.Printf("bootstrap: WARNING: S3 storage test failed: %v", err)
case status < 200 || status >= 300:
log.Printf("bootstrap: WARNING: S3 storage unreachable (status %d): %s", status, raw)
default:
log.Printf("bootstrap: ✓ S3 storage reachable")
}
}
// --- helpers --------------------------------------------------------------- // --- helpers ---------------------------------------------------------------
func asBool(v any) bool { func asBool(v any) bool {
@@ -94,3 +94,39 @@ func TestSchemaConsistency(t *testing.T) {
} }
} }
} }
// TestSameExceptSecret covers the decision ensureFileStorage makes on every
// boot: write the settings, or leave them alone. The secret is excluded because
// PocketBase masks it on read — comparing it would make every boot a write.
func TestSameExceptSecret(t *testing.T) {
want := storageSettings{
Enabled: true,
Bucket: "drivervault",
Region: "us-east-1",
Endpoint: "http://seaweedfs:8333",
AccessKey: "key",
Secret: "secret",
ForcePathStyle: true,
}
cases := []struct {
name string
current storageSettings
same bool
}{
{"identical", want, true},
{"masked secret", func() storageSettings { s := want; s.Secret = ""; return s }(), true},
{"rotated secret only", func() storageSettings { s := want; s.Secret = "other"; return s }(), true},
{"changed endpoint", func() storageSettings { s := want; s.Endpoint = "http://elsewhere:8333"; return s }(), false},
{"changed bucket", func() storageSettings { s := want; s.Bucket = "other"; return s }(), false},
{"changed access key", func() storageSettings { s := want; s.AccessKey = "other"; return s }(), false},
{"still disabled", func() storageSettings { s := want; s.Enabled = false; return s }(), false},
{"path style off", func() storageSettings { s := want; s.ForcePathStyle = false; return s }(), false},
{"untouched settings", storageSettings{}, false},
}
for _, tc := range cases {
if got := tc.current.sameExceptSecret(want); got != tc.same {
t.Errorf("%s: sameExceptSecret = %v, want %v", tc.name, got, tc.same)
}
}
}
+50
View File
@@ -41,6 +41,15 @@ var collectionsSchema = map[string][]fieldDef{
// internal/api/vehicleproviders.go. Blank for a hand-entered car. // internal/api/vehicleproviders.go. Blank for a hand-entered car.
fText("provider", false), fText("provider", false),
fText("provider_vehicle_id", false), fText("provider_vehicle_id", false),
// Automatic odometer updates from that service: on/off, how often (in
// minutes), whose account the reading is fetched under (the user who
// switched it on — provider calls always run as a person), and the last
// attempt with its error, if any. See internal/api/odometersync.go.
fBool("odometer_auto_sync"),
fNumber("odometer_sync_minutes"),
fText("odometer_sync_by", false),
fText("odometer_synced_at", false),
fText("odometer_sync_error", false),
// What this car's page shows: the tabs switched off (["fuel"] on an EV) // What this car's page shows: the tabs switched off (["fuel"] on an EV)
// and the Information fields switched off (["differentialOil"] on a car // and the Information fields switched off (["differentialOil"] on a car
// without one). Properties of the car, so everyone it is shared with sees // without one). Properties of the car, so everyone it is shared with sees
@@ -225,12 +234,48 @@ var collectionsSchema = map[string][]fieldDef{
// audit trail's. // audit trail's.
fAutodate("created", true, false), fAutodate("created", true, false),
}, },
// The home-charger scheduler: the user's own list of charging tasks, one list
// covering every charger they own. The charger's own cloud schedule holds one
// window per box; this holds as many tasks as they like, each naming its own
// chargers, days and action. Run by the ticker in internal/api/chargingtasks_run.go.
"charging_tasks": {
fText("name", true),
// The home_chargers rows this task acts on. Stored as a list of ids rather
// than a relation because empty has to mean "every charger I own" — a
// standing wish that keeps covering chargers imported later — and a
// multi-relation would have to be rewritten on every import to say it.
fJSON("chargers", 2000),
// The flow: [{action, amps, time}, …] in the order it runs. A whole
// charging window is one task rather than the two that would otherwise
// open and close it, so it is named once and switched off once. Times are
// 24-hour "HH:MM" read in the zone below — the server's clock is not the
// one the user set 23:00 by. Validated in internal/api/chargingtasks.go.
fJSON("steps", 4000),
fText("zone", false),
fJSON("days", 200), // 0=Sunday … 6=Saturday; empty means every day
fBool("enabled"),
// The outcome of the last firing, so a task that has been failing quietly
// says so in the list. last_run is also the guard against firing twice in
// the same minute.
fText("last_run", false), // RFC3339, UTC
fText("last_result", false),
// Owner. Non-cascading, like a charger's.
fRelation("owner", "users", false, false),
fAutodate("created", true, false),
},
// Custom fields layered onto the built-in "users" auth collection. // Custom fields layered onto the built-in "users" auth collection.
"users": { "users": {
fText("bio", false), fText("bio", false),
fSelect("theme", []string{"light", "dark", "system"}, false), fSelect("theme", []string{"light", "dark", "system"}, false),
fText("locale", false), fText("locale", false),
fSelect("date_format", []string{"YMD", "DMY_NUM", "DMY", "MDY"}, false), fSelect("date_format", []string{"YMD", "DMY_NUM", "DMY", "MDY"}, false),
// "auto" is the region's own convention, which is what every clock in the
// app read before this field existed.
fSelect("time_format", []string{"auto", "24", "12"}, false),
// The day a week is drawn as starting on, wherever weekdays are laid out
// in a row. "auto" is the region's own convention, which is what the
// scheduler's day picker read before this field existed.
fSelect("week_start", []string{"auto", "monday", "sunday"}, false),
fSelect("currency", []string{ fSelect("currency", []string{
"EUR", "GBP", "CHF", "PLN", "CZK", "HUF", "RON", "BGN", "DKK", "SEK", "NOK", "EUR", "GBP", "CHF", "PLN", "CZK", "HUF", "RON", "BGN", "DKK", "SEK", "NOK",
"ISK", "ALL", "AMD", "AZN", "BAM", "BYN", "GEL", "MDL", "MKD", "RSD", "RUB", "ISK", "ALL", "AMD", "AZN", "BAM", "BYN", "GEL", "MDL", "MKD", "RSD", "RUB",
@@ -277,6 +322,7 @@ var createOrder = []string{
"reminders", "reminders",
"control_audit", "control_audit",
"home_chargers", "home_chargers",
"charging_tasks",
} }
// reconcileOrder additionally includes "users" so its custom fields (role, // reconcileOrder additionally includes "users" so its custom fields (role,
@@ -297,6 +343,7 @@ var reconcileOrder = []string{
"reminders", "reminders",
"control_audit", "control_audit",
"home_chargers", "home_chargers",
"charging_tasks",
} }
// indexes are extra SQL indexes applied at collection-create time. // indexes are extra SQL indexes applied at collection-create time.
@@ -313,6 +360,9 @@ var indexes = map[string][]string{
// A charger is looked up by its owner, and by serial when checking whether // A charger is looked up by its owner, and by serial when checking whether
// the account it came from has already been imported. // the account it came from has already been imported.
"home_chargers": {"CREATE INDEX `idx_home_chargers_owner_serial` ON `home_chargers` (`owner`, `serial`)"}, "home_chargers": {"CREATE INDEX `idx_home_chargers_owner_serial` ON `home_chargers` (`owner`, `serial`)"},
// The runner sweeps every enabled task on every tick, and the page reads one
// owner's; both go through these two columns.
"charging_tasks": {"CREATE INDEX `idx_charging_tasks_owner_enabled` ON `charging_tasks` (`owner`, `enabled`)"},
"control_audit": { "control_audit": {
"CREATE INDEX `idx_control_audit_serial_created` ON `control_audit` (`serial`, `created`)", "CREATE INDEX `idx_control_audit_serial_created` ON `control_audit` (`serial`, `created`)",
"CREATE INDEX `idx_control_audit_user_created` ON `control_audit` (`user_id`, `created`)", "CREATE INDEX `idx_control_audit_user_created` ON `control_audit` (`user_id`, `created`)",
+36
View File
@@ -51,6 +51,26 @@ type Config struct {
SuperAdminEmail string SuperAdminEmail string
SuperAdminPassword string SuperAdminPassword string
SuperAdminName string SuperAdminName string
// PocketBase file storage. With S3Enabled set, bootstrap points PocketBase's
// "Files storage" at this bucket instead of the pb_data volume; left unset,
// uploads stay on disk exactly as they always have. Only *record files* move
// — backups are deliberately not touched.
//
// Nothing here reaches a container unless one of the SeaweedFS compose
// overlays is layered on, so an existing stack is unaffected by an upgrade.
// S3Endpoint has no default: an in-stack SeaweedFS and one outside it are
// different addresses, and guessing either would be worse than not starting.
S3Enabled bool
S3Bucket string
S3Region string
S3Endpoint string
S3AccessKey string
S3Secret string
// S3ForcePathStyle keeps bucket names in the path rather than the hostname.
// True by default because that is what a self-hosted gateway serves —
// virtual-host style would need a DNS entry per bucket.
S3ForcePathStyle bool
} }
// EnvFile is the .env path (relative to the working directory) that Load reads // EnvFile is the .env path (relative to the working directory) that Load reads
@@ -66,6 +86,15 @@ func (c Config) AdminConfigured() bool {
return c.PocketBaseAdminEmail != "" && c.PocketBaseAdminPassword != "" return c.PocketBaseAdminEmail != "" && c.PocketBaseAdminPassword != ""
} }
// StorageConfigured reports whether S3 file storage has been fully specified.
// Anything less than all of it counts as "not asked for": a half-filled .env
// leaves uploads on the local volume rather than pointing PocketBase at a
// bucket it has no way to reach.
func (c Config) StorageConfigured() bool {
return c.S3Enabled && c.S3Bucket != "" && c.S3Endpoint != "" &&
c.S3AccessKey != "" && c.S3Secret != ""
}
// Load reads configuration from environment variables, applying sensible // Load reads configuration from environment variables, applying sensible
// defaults. A .env file, if present in the working directory, is loaded first. // defaults. A .env file, if present in the working directory, is loaded first.
func Load() Config { func Load() Config {
@@ -86,6 +115,13 @@ func Load() Config {
SuperAdminEmail: firstEnv("DRIVERVAULT_SUPERADMIN_EMAIL", "SUPERADMIN_EMAIL"), SuperAdminEmail: firstEnv("DRIVERVAULT_SUPERADMIN_EMAIL", "SUPERADMIN_EMAIL"),
SuperAdminPassword: firstEnv("DRIVERVAULT_SUPERADMIN_PASSWORD", "SUPERADMIN_PASSWORD"), SuperAdminPassword: firstEnv("DRIVERVAULT_SUPERADMIN_PASSWORD", "SUPERADMIN_PASSWORD"),
SuperAdminName: getenv("DRIVERVAULT_SUPERADMIN_NAME", "Administrator"), SuperAdminName: getenv("DRIVERVAULT_SUPERADMIN_NAME", "Administrator"),
S3Enabled: boolEnv("PB_S3_ENABLED", false),
S3Bucket: getenv("PB_S3_BUCKET", "drivervault"),
S3Region: getenv("PB_S3_REGION", "us-east-1"),
S3Endpoint: strings.TrimRight(getenv("PB_S3_ENDPOINT", ""), "/"),
S3AccessKey: getenv("PB_S3_ACCESS_KEY", ""),
S3Secret: getenv("PB_S3_SECRET", ""),
S3ForcePathStyle: boolEnv("PB_S3_FORCE_PATH_STYLE", true),
} }
} }
+69 -3
View File
@@ -66,6 +66,15 @@ type Car struct {
Provider string `json:"provider,omitempty"` Provider string `json:"provider,omitempty"`
ProviderVehicleID string `json:"providerVehicleId,omitempty"` ProviderVehicleID string `json:"providerVehicleId,omitempty"`
// OdometerAutoSync keeps CurrentKm in step with the provider's odometer in
// the background, every OdometerSyncMinutes. OdometerSyncedAt is the last
// attempt (RFC 3339) and OdometerSyncError what went wrong with it, if
// anything. Set through PUT /api/cars/{id}/provider/auto-sync only.
OdometerAutoSync bool `json:"odometerAutoSync"`
OdometerSyncMinutes int `json:"odometerSyncMinutes,omitempty"`
OdometerSyncedAt string `json:"odometerSyncedAt,omitempty"`
OdometerSyncError string `json:"odometerSyncError,omitempty"`
// HiddenTabs and HiddenFields are what this car's page does not show: tabs // HiddenTabs and HiddenFields are what this car's page does not show: tabs
// (["fuel"] on an EV) and Information fields (["differentialOil"] on a car // (["fuel"] on an EV) and Information fields (["differentialOil"] on a car
// without one). Properties of the car, so everyone it is shared with sees the // without one). Properties of the car, so everyone it is shared with sees the
@@ -152,6 +161,59 @@ type HomeCharger struct {
Created string `json:"created,omitempty"` Created string `json:"created,omitempty"`
} }
// ChargingStep is one command in a task's flow: what to do, and at what time
// of day. A step is the smallest thing the scheduler sends.
type ChargingStep struct {
// start, stop, limit (to Amps) or boost.
Action string `json:"action"`
Amps float64 `json:"amps,omitempty"`
// A 24-hour "HH:MM", read in the task's zone.
Time string `json:"time"`
}
// ChargingTask is one entry in the home-charger scheduler: a flow of steps, the
// days it repeats on, and the chargers it acts on. It belongs to the person,
// like the chargers themselves — one list covering every charger they own,
// rather than a separate schedule inside each one.
//
// The charger's own cloud schedule can only say "charge between these hours,
// every day, on this one box". This says "start at 23:00, cap to 10 A at 01:00,
// stop at 06:30 — on weeknights, on these two chargers", as one named thing that
// is switched on and off as one.
type ChargingTask struct {
ID string `json:"id"`
Name string `json:"name"`
// The home-charger records this task acts on. Empty means every charger the
// owner has, including ones imported after the task was written — "all of
// them" is a standing wish, not the list that happened to exist that day.
Chargers []string `json:"chargers"`
// The flow, in the order it runs. A whole charging window lives in one task
// rather than in the two that used to open and close it: it is named once,
// switched off once, and reads as the one intention it is.
Steps []ChargingStep `json:"steps"`
// The IANA zone the steps' times are read in — the one the browser was in
// when the task was written. The server's own clock is not the one the user
// set 23:00 by, and a laptop that travels must not move the schedule.
Zone string `json:"zone,omitempty"`
// The weekdays it repeats on, 0=Sunday … 6=Saturday. Empty means every day.
Days []int `json:"days"`
Enabled bool `json:"enabled"`
// What happened the last time a step of it fired, so a task that has been
// failing quietly for a week says so in the list rather than in a log nobody
// reads.
LastRun string `json:"lastRun,omitempty"` // RFC3339, UTC
LastResult string `json:"lastResult,omitempty"`
Created string `json:"created,omitempty"`
}
// ServiceRecord is one row of the Service log for a car. // ServiceRecord is one row of the Service log for a car.
type ServiceRecord struct { type ServiceRecord struct {
ID string `json:"id"` ID string `json:"id"`
@@ -476,9 +538,13 @@ type User struct {
Theme string `json:"theme"` // light | dark | system Theme string `json:"theme"` // light | dark | system
Locale string `json:"locale"` // e.g. "en-US" Locale string `json:"locale"` // e.g. "en-US"
DateFormat string `json:"dateFormat"` // YMD | DMY | MDY DateFormat string `json:"dateFormat"` // YMD | DMY | MDY
Currency string `json:"currency"` // ISO 4217 code, e.g. "EUR" TimeFormat string `json:"timeFormat"` // auto (the region's own) | 24 | 12
FontSize string `json:"fontSize"` // small | medium | large // The day a week is drawn as starting on, wherever a client lays weekdays
Role string `json:"role"` // user | admin // out in a row — the scheduler's day picker today.
WeekStart string `json:"weekStart"` // auto (the region's own) | monday | sunday
Currency string `json:"currency"` // ISO 4217 code, e.g. "EUR"
FontSize string `json:"fontSize"` // small | medium | large
Role string `json:"role"` // user | admin
// DragLocked holds every arrangement on this account's pages still: the // DragLocked holds every arrangement on this account's pages still: the
// garage, a car's tabs, its Information rows, the provider's readings. A // garage, a car's tabs, its Information rows, the provider's readings. A
+56 -3
View File
@@ -6,12 +6,14 @@ package pb
import ( import (
"bytes" "bytes"
"context" "context"
"encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"mime/multipart" "mime/multipart"
"net/http" "net/http"
"net/url" "net/url"
"strings"
"sync" "sync"
"time" "time"
) )
@@ -29,6 +31,7 @@ type Client struct {
email string email string
password string password string
token string token string
tokenExp time.Time
} }
func New(baseURL, email, password string) *Client { func New(baseURL, email, password string) *Client {
@@ -69,6 +72,7 @@ func (c *Client) Reconfigure(baseURL, email, password string) {
c.email = email c.email = email
c.password = password c.password = password
c.token = "" c.token = ""
c.tokenExp = time.Time{}
c.mu.Unlock() c.mu.Unlock()
} }
@@ -120,6 +124,7 @@ func (c *Client) Authenticate(ctx context.Context) error {
} }
c.mu.Lock() c.mu.Lock()
c.token = out.Token c.token = out.Token
c.tokenExp = jwtExpiry(out.Token)
c.mu.Unlock() c.mu.Unlock()
return nil return nil
} }
@@ -134,8 +139,46 @@ func (c *Client) currentToken() string {
return c.token return c.token
} }
// ensureToken acquires a superuser token when none is cached yet, so that a // tokenSkew is how long before its stated expiry a cached token is treated as
// superuser call never goes out unauthenticated. // spent. It covers clock drift between this server and PocketBase, and the
// flight time of a request that passes the check and then arrives just late.
const tokenSkew = 60 * time.Second
// tokenLive reports whether the cached token can still be used. A token with no
// readable expiry is taken at face value — the 401 retry remains the backstop.
func (c *Client) tokenLive() bool {
c.mu.RLock()
defer c.mu.RUnlock()
if c.token == "" {
return false
}
return c.tokenExp.IsZero() || time.Now().Add(tokenSkew).Before(c.tokenExp)
}
// jwtExpiry reads the exp claim out of a PocketBase auth token. The signature is
// PocketBase's business — this only needs the expiry the server itself stamped,
// so the payload is decoded without verification. Anything unreadable comes back
// as the zero time, which tokenLive treats as "no expiry known".
func jwtExpiry(token string) time.Time {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return time.Time{}
}
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return time.Time{}
}
var claims struct {
Exp int64 `json:"exp"`
}
if err := json.Unmarshal(raw, &claims); err != nil || claims.Exp == 0 {
return time.Time{}
}
return time.Unix(claims.Exp, 0)
}
// ensureToken acquires a superuser token when the cached one is missing or
// spent, so that a superuser call never goes out unauthenticated.
// //
// It matters because PocketBase answers a record read it will not allow with // It matters because PocketBase answers a record read it will not allow with
// 404, not 401 — it hides the record rather than refusing the credentials. So a // 404, not 401 — it hides the record rather than refusing the credentials. So a
@@ -149,8 +192,18 @@ func (c *Client) currentToken() string {
// With no service account configured there is nothing to acquire, so the call // With no service account configured there is nothing to acquire, so the call
// proceeds as before — the endpoints that need superuser access answer 503 on // proceeds as before — the endpoints that need superuser access answer 503 on
// their own. // their own.
//
// Expiry is checked here rather than left to the 401 retry below, because that
// retry never fires for this client: PocketBase does not reject a stale token on
// a record call, it ignores the header and serves the request as a guest. The
// collection rules then answer instead of the transport — a superuser-only
// collection 403s, a rule-guarded record 404s, and a rule-filtered list comes
// back 200 with nothing in it. None of those are a 401, so a server whose token
// has lapsed keeps sending it and keeps being treated as a stranger to its own
// database until it is restarted. Superuser tokens are long-lived, which only
// means the failure waits weeks and then arrives as "the app forgot my account".
func (c *Client) ensureToken(ctx context.Context) error { func (c *Client) ensureToken(ctx context.Context) error {
if c.currentToken() != "" || !c.Configured() { if c.tokenLive() || !c.Configured() {
return nil return nil
} }
return c.Authenticate(ctx) return c.Authenticate(ctx)
+118 -3
View File
@@ -2,11 +2,13 @@ package pb
import ( import (
"context" "context"
"encoding/base64"
"encoding/json" "encoding/json"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"sync" "sync"
"testing" "testing"
"time"
) )
// PocketBase hides a record it will not let you read behind a 404 rather than a // PocketBase hides a record it will not let you read behind a 404 rather than a
@@ -31,9 +33,14 @@ type fakePB struct {
email string email string
password string password string
// When set, tokens are minted as JWTs carrying this lifetime in their exp
// claim, the way PocketBase issues them. Zero keeps the opaque test token.
jwtTTL time.Duration
authCalls int authCalls int
lastIdentity string lastIdentity string
guestAttempts int // record reads that arrived without the superuser token issued string // the token most recently handed out
guestAttempts int // record reads that arrived without the superuser token
} }
func (f *fakePB) handler() http.Handler { func (f *fakePB) handler() http.Handler {
@@ -51,11 +58,21 @@ func (f *fakePB) handler() http.Handler {
writeTestJSON(w, 400, map[string]any{"message": "Failed to authenticate."}) writeTestJSON(w, 400, map[string]any{"message": "Failed to authenticate."})
return return
} }
writeTestJSON(w, 200, map[string]any{"token": fakeSvcToken}) token := fakeSvcToken
if f.jwtTTL > 0 {
token = testJWT(time.Now().Add(f.jwtTTL))
}
f.mu.Lock()
f.issued = token
f.mu.Unlock()
writeTestJSON(w, 200, map[string]any{"token": token})
}) })
mux.HandleFunc("GET /api/collections/users/records/{id}", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("GET /api/collections/users/records/{id}", func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != fakeSvcToken { f.mu.Lock()
live := f.issued
f.mu.Unlock()
if got := r.Header.Get("Authorization"); got == "" || got != live {
f.mu.Lock() f.mu.Lock()
f.guestAttempts++ f.guestAttempts++
f.mu.Unlock() f.mu.Unlock()
@@ -190,3 +207,101 @@ func TestNoServiceAccountSkipsAuthentication(t *testing.T) {
t.Errorf("attempted %d sign-in(s) with no credentials, want 0", auth) t.Errorf("attempted %d sign-in(s) with no credentials, want 0", auth)
} }
} }
// testJWT builds a token shaped like PocketBase's: three base64url segments,
// the middle one carrying the exp claim. Only that claim is ever read, so the
// header and signature are filler.
func testJWT(exp time.Time) string {
enc := func(v any) string {
b, _ := json.Marshal(v)
return base64.RawURLEncoding.EncodeToString(b)
}
return enc(map[string]string{"alg": "HS256", "typ": "JWT"}) + "." +
enc(map[string]int64{"exp": exp.Unix()}) + ".sig"
}
func TestJWTExpiry(t *testing.T) {
want := time.Now().Add(time.Hour).Truncate(time.Second)
if got := jwtExpiry(testJWT(want)); !got.Equal(want) {
t.Errorf("jwtExpiry = %v, want %v", got, want)
}
// An opaque (non-JWT) token has no readable expiry, and must not be mistaken
// for one that expired at the zero time — tokenLive takes it at face value.
for _, tok := range []string{"", "opaque", "a.b", "a.!!.c", "a." + base64.RawURLEncoding.EncodeToString([]byte("{}")) + ".c"} {
if got := jwtExpiry(tok); !got.IsZero() {
t.Errorf("jwtExpiry(%q) = %v, want zero", tok, got)
}
}
}
// The failure this whole mechanism exists for: a superuser token that has run
// out. PocketBase does not answer 401 for one — it ignores the header and serves
// the request as a guest, so the 401 retry never fires and the client would go
// on presenting a dead token forever. The expiry check has to catch it first.
func TestExpiredTokenIsRenewedBeforeUse(t *testing.T) {
f := &fakePB{email: "admin@test.local", password: "pw", jwtTTL: time.Hour}
c := New(newFakePB(t, f), f.email, f.password)
if err := c.GetOne(context.Background(), "users", fakeRecordID, new(struct{})); err != nil {
t.Fatalf("GetOne: %v", err)
}
// Age the cached token past its expiry, as an uptime longer than the token's
// lifetime would.
c.mu.Lock()
c.tokenExp = time.Now().Add(-time.Minute)
c.mu.Unlock()
var rec struct{ ID string }
if err := c.GetOne(context.Background(), "users", fakeRecordID, &rec); err != nil {
t.Fatalf("GetOne with an expired token: %v", err)
}
if rec.ID != fakeRecordID {
t.Fatalf("record id = %q, want %q", rec.ID, fakeRecordID)
}
auth, guest := f.counts()
if guest != 0 {
t.Errorf("%d record read(s) went out on a dead token, want 0", guest)
}
if auth != 2 {
t.Errorf("authenticated %d time(s), want 2 (startup + renewal)", auth)
}
}
// A token close enough to its expiry that it could lapse mid-flight is renewed
// rather than spent, so a call cannot land just after the token dies.
func TestTokenNearingExpiryIsRenewed(t *testing.T) {
f := &fakePB{email: "admin@test.local", password: "pw", jwtTTL: time.Hour}
c := New(newFakePB(t, f), f.email, f.password)
if err := c.GetOne(context.Background(), "users", fakeRecordID, new(struct{})); err != nil {
t.Fatalf("GetOne: %v", err)
}
c.mu.Lock()
c.tokenExp = time.Now().Add(tokenSkew / 2)
c.mu.Unlock()
if err := c.GetOne(context.Background(), "users", fakeRecordID, new(struct{})); err != nil {
t.Fatalf("GetOne near expiry: %v", err)
}
if auth, _ := f.counts(); auth != 2 {
t.Errorf("authenticated %d time(s), want 2 (startup + renewal)", auth)
}
}
// A token with a real lifetime still ahead of it is reused — the expiry check
// must not turn every call into a fresh sign-in.
func TestLiveJWTIsReused(t *testing.T) {
f := &fakePB{email: "admin@test.local", password: "pw", jwtTTL: time.Hour}
c := New(newFakePB(t, f), f.email, f.password)
for i := 0; i < 3; i++ {
if err := c.GetOne(context.Background(), "users", fakeRecordID, new(struct{})); err != nil {
t.Fatalf("GetOne #%d: %v", i, err)
}
}
if auth, _ := f.counts(); auth != 1 {
t.Errorf("authenticated %d time(s), want 1", auth)
}
}
+2 -1
View File
@@ -177,7 +177,8 @@ Restart the server. The plugin appears in the panel's **Plugins** card,
**disabled** by default. **disabled** by default.
> DriverVault ships four built-in connectors today — `toyota` (Toyota Connected / > DriverVault ships four built-in connectors today — `toyota` (Toyota Connected /
> MyToyota, read-only vehicle data), `anker-solix` (Anker Solix V1 EV charger), > MyToyota, read-only vehicle data; registered three times, as `toyota`, `lexus`
> and `subaru`, so each brand shows up as a plugin of its own), `anker-solix` (Anker Solix V1 EV charger),
> `greencell` (Greencell HabuDen EV charger, read over the owner's MQTT broker > `greencell` (Greencell HabuDen EV charger, read over the owner's MQTT broker
> rather than a cloud API) and `apprise` (notifications, through an apprise-api > rather than a cloud API) and `apprise` (notifications, through an apprise-api
> gateway the operator runs) — all blank-imported from `builtin/builtin.go`. The > gateway the operator runs) — all blank-imported from `builtin/builtin.go`. The
@@ -2,9 +2,16 @@
// scoped to the Anker Solix V1 Smart EV Charger (product A5191). It is a Go // scoped to the Anker Solix V1 Smart EV Charger (product A5191). It is a Go
// re-implementation of the authentication and read-only data flow from the // re-implementation of the authentication and read-only data flow from the
// anker-solix-api project (https://github.com/thomluther/anker-solix-api), // anker-solix-api project (https://github.com/thomluther/anker-solix-api),
// adapted to DriverVault's plugin contract. It tracks upstream v3.8.1 // adapted to DriverVault's plugin contract. It tracks upstream v3.9.0
// (ha-anker-solix 3.8.1); the login exchange and every endpoint used here are // (ha-anker-solix 3.9.0); the login exchange and every endpoint used here are
// unchanged since v3.7.0. // unchanged since v3.7.0. v3.8.2 added the app's REST payload encryption,
// ported in payloadcrypto.go and off by default as upstream leaves it. v3.9.0
// reaches a charger in three small places: Singapore accounts log in on the
// EU server, Start is offered while a finished session still shows completed,
// and a failed login drops the payload handshake with the token. The rest of
// v3.9.0 (PPS time-of-use plans, device energy queries, the condensed V2
// command map) touches devices this connector does not address, and the A5191
// MQTT map is byte-for-byte the one v3.8.1 had.
// //
// Scope & limitations: // Scope & limitations:
// - The REST half is read-only. Every endpoint below retrieves EV-charger // - The REST half is read-only. Every endpoint below retrieves EV-charger
@@ -47,6 +54,7 @@ import (
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
neturl "net/url"
"sort" "sort"
"strings" "strings"
"sync" "sync"
@@ -88,6 +96,69 @@ const (
epUserVehicles = "power_service/v1/app/vehicle/get_vehicle_list" // vehicles registered for smart charging epUserVehicles = "power_service/v1/app/vehicle/get_vehicle_list" // vehicles registered for smart charging
epVehicleDetail = "power_service/v1/app/vehicle/get_vehicle_detail" // details for one registered vehicle epVehicleDetail = "power_service/v1/app/vehicle/get_vehicle_detail" // details for one registered vehicle
// The rest of the read surface an EV charger can reach, from the same source
// as the endpoints above (anker-solix-api's apitypes.py, filtered to what a
// charger touches) and catalogued in anker-api-map.html. Every one of these
// reads; the account-level writes the app makes — vehicles, site prices,
// sharing invites, quiet hours, auto-upgrade — are deliberately not here, and
// neither is any endpoint whose payload was only ever read out of the app
// package rather than called ("unmapped" in the map).
// Finding and identifying a charger.
epSiteDetailBySN = "power_service/v1/site/get_site_detail_by_sn" // the site a charger belongs to, from its serial alone
epSiteDetail = "power_service/v1/site/get_site_detail" // site detail; answers for shared accounts too
epSiteHomepage = "power_service/v1/site/get_site_homepage" // the app home screen's own view of every site
epUserDevices = "power_service/v1/site/list_user_devices" // owned devices, lighter than the bound-device view
epDeviceBindDetails = "power_service/v1/app/get_device_bind_details" // binding details for a list of serials
epGroupDevices = "power_service/v1/app/group/get_group_devices" // whether a charger is grouped with sub-devices
epSiteWifiList = "power_service/v1/site/get_wifi_info_list" // networks the site can see
epDeviceProductInfo = "charging_hes_svc/get_device_product_info" // product info for HES-family devices
epInstallInfo = "charging_hes_svc/get_install_info" // where the system was installed
epChargerWifiInfo = "charging_hes_svc/get_wifi_info" // the charger's own Wi-Fi details
// Charging sessions — where the completed history lives.
epChargingOrders = "power_service/v1/app/order/get_charging_order_list" // every session in a date range
epChargingOrder = "power_service/v1/app/order/get_charging_order_detail" // one session, with its chart points and vehicle
epOrderSecDetail = "power_service/v1/app/order/get_charging_order_sec_detail" // second-resolution detail for a session
epOrderSecPreview = "power_service/v1/app/order/get_charging_order_sec_preview" // preview of the same
// Energy, price and what it cost.
epEnergyStatistics = "charging_hes_svc/get_energy_statistics" // energy stats with the EV charger as its own source
epDeviceIncome = "power_service/v1/app/device/get_device_income" // income / savings figures per device
epSitePrice = "power_service/v1/site/get_site_price" // the site's power price and CO2 factor
epCurrencyList = "power_service/v1/currency/get_list" // supported currencies
epSiteDataExport = "power_service/v1/site/site_data_exported" // filename and URL for a CSV export
epDynPriceCheck = "power_service/v1/dynamic_price/check_available" // which sites have dynamic pricing at all
epDynPriceOptions = "power_service/v1/dynamic_price/support_option" // price providers for a product code
epDynPriceDetail = "power_service/v1/dynamic_price/price_detail" // the actual price curve
// The vehicle catalogue behind smart charging.
epVehicleBrands = "power_service/v1/app/get_brand_list" // vehicle brands
epVehicleModels = "power_service/v1/app/get_models" // models for a brand
epVehicleYears = "power_service/v1/app/get_model_years" // production years for a model
epVehicleSpecs = "power_service/v1/app/get_model_list" // what Anker knows about that exact car
// Sharing.
epSharedDevice = "app/devicerelation/get_shared_device" // who a charger is currently shared with
// Firmware.
epOtaBatchCheck = "app/ota/batch/check_update" // latest available version per serial
epOtaInfo = "power_service/v1/app/compatible/get_ota_info" // current OTA status
epOtaUpdate = "power_service/v1/app/compatible/get_ota_update" // details of an available update
epUpgradeRecords = "power_service/v1/app/get_upgrade_record" // firmware update history
epUpgradeRecord = "power_service/v1/app/check_upgrade_record" // one update record, three views of it
epAutoUpgrade = "power_service/v1/app/get_auto_upgrade" // which devices auto-update
// Notifications, and the charging events behind them. The first two are the
// only endpoints in this connector Anker serves over GET.
epMessageUnread = "power_service/v1/get_message_unread" // whether anything is waiting (GET)
epMessages = "power_service/v1/get_message" // the messages themselves (GET, last_time)
epMessageNotDisturb = "power_service/v1/get_message_not_disturb" // current quiet-hours settings
epMessageSNList = "power_service/v1/get_message_sn_list" // which devices produce messages at all
// Health and faults.
epTamperRecords = "power_service/v1/device/get_tamper_records" // tamper records for a device
// The cloud MQTT broker's own credentials endpoint is epMqttInfo, declared in // The cloud MQTT broker's own credentials endpoint is epMqttInfo, declared in
// cloudmqtt.go next to the transport that uses it. // cloudmqtt.go next to the transport that uses it.
) )
@@ -134,12 +205,14 @@ var ocppConnStatus = map[int]string{0: "disconnected", 1: "connecting", 2: "conn
const tokenExpiryMargin = 5 * time.Minute const tokenExpiryMargin = 5 * time.Minute
// comCountries are the ISO country IDs served by the global (".com") server. // comCountries are the ISO country IDs served by the global (".com") server.
// Any country not listed here is served by the EU server. // Any country not listed here is served by the EU server — Singapore among
// them since upstream v3.9.0 (ha-anker-solix #593), where SG accounts turned
// out to live.
var comCountries = map[string]bool{ var comCountries = map[string]bool{
"DZ": true, "LB": true, "SY": true, "EG": true, "LY": true, "TN": true, "DZ": true, "LB": true, "SY": true, "EG": true, "LY": true, "TN": true,
"MA": true, "JO": true, "PS": true, "AR": true, "AU": true, "BR": true, "MA": true, "JO": true, "PS": true, "AR": true, "AU": true, "BR": true,
"HK": true, "IN": true, "MX": true, "NG": true, "NZ": true, "RU": true, "HK": true, "IN": true, "MX": true, "NG": true, "NZ": true, "RU": true,
"SG": true, "ZA": true, "KR": true, "TW": true, "US": true, "CA": true, "ZA": true, "KR": true, "TW": true, "US": true, "CA": true,
} }
func init() { func init() {
@@ -152,6 +225,7 @@ type tokenInfo struct {
gtoken string // md5(user_id) gtoken string // md5(user_id)
nickname string nickname string
expiration time.Time expiration time.Time
issued time.Time // when the login that returned it answered
} }
// Plugin is the Anker Solix EV-charger connector. // Plugin is the Anker Solix EV-charger connector.
@@ -159,6 +233,9 @@ type Plugin struct {
email string email string
password string password string
countryId string countryId string
// encrypt turns on the app's payload encryption for every request after
// login (payloadcrypto.go). Off unless payloadEncryption is "on".
encrypt bool
mu sync.Mutex // guards the fields above and the client mu sync.Mutex // guards the fields above and the client
apiBase string apiBase string
@@ -181,7 +258,7 @@ func (p *Plugin) Descriptor() plugins.Descriptor {
AuthType: plugins.AuthBasic, AuthType: plugins.AuthBasic,
Capabilities: []plugins.Capability{ Capabilities: []plugins.Capability{
{ID: "chargers", Method: "POST", Endpoint: epStandaloneChargers, Description: "Every EV charger on the account, merged from the standalone, per-site, bound-device and per-charger station views, each charger carrying every field those views reported (see chargers.go)."}, {ID: "chargers", Method: "POST", Endpoint: epStandaloneChargers, Description: "Every EV charger on the account, merged from the standalone, per-site, bound-device and per-charger station views, each charger carrying every field those views reported (see chargers.go)."},
{ID: "charger-details", Method: "POST", Endpoint: epStationInfo, Description: "Every per-charger view the account holds — the station record, the charging totals, the OCPP backend and the RFID cards — each relayed as the fields it sent (needs sn)."}, {ID: "charger-details", Method: "POST", Endpoint: epStationInfo, Description: "Every view the account holds about one charger — the station record, the totals, the history and sessions, the savings, the OCPP backend and the endpoints that name its source, the cards, the sharing, the binding, the group, the Wi-Fi, the firmware, the tamper log, and the site's own views when it belongs to one — each relayed as the fields it sent (needs sn)."},
{ID: "charger-status", Method: "POST", Endpoint: epStationInfo, Description: "Live station/status info for one charger (needs sn; optional featuretype 1 or 2)."}, {ID: "charger-status", Method: "POST", Endpoint: epStationInfo, Description: "Live station/status info for one charger (needs sn; optional featuretype 1 or 2)."},
{ID: "charger-state", Method: "POST", Endpoint: epSceneInfo, Description: "Normalized live state of a site's EV chargers: status, operational mode and the modes it can be switched to (needs siteId; optional sn)."}, {ID: "charger-state", Method: "POST", Endpoint: epSceneInfo, Description: "Normalized live state of a site's EV chargers: status, operational mode and the modes it can be switched to (needs siteId; optional sn)."},
{ID: "site-status", Method: "POST", Endpoint: epSceneInfo, Description: "Live site view; EV chargers appear under charging_pile_info (needs siteId)."}, {ID: "site-status", Method: "POST", Endpoint: epSceneInfo, Description: "Live site view; EV chargers appear under charging_pile_info (needs siteId)."},
@@ -189,14 +266,61 @@ func (p *Plugin) Descriptor() plugins.Descriptor {
{ID: "charge-orders", Method: "POST", Endpoint: epChargeStatsList, Description: "Per-session charging history for one charger (needs sn)."}, {ID: "charge-orders", Method: "POST", Endpoint: epChargeStatsList, Description: "Per-session charging history for one charger (needs sn)."},
{ID: "charge-energy", Method: "POST", Endpoint: epEnergyAnalysis, Description: "Interval charging energy for a site's EV charger (needs siteId; optional sn, range, startDate, endDate)."}, {ID: "charge-energy", Method: "POST", Endpoint: epEnergyAnalysis, Description: "Interval charging energy for a site's EV charger (needs siteId; optional sn, range, startDate, endDate)."},
{ID: "rfid-cards", Method: "POST", Endpoint: epRfidCards, Description: "RFID cards authorised on one charger (needs sn)."}, {ID: "rfid-cards", Method: "POST", Endpoint: epRfidCards, Description: "RFID cards authorised on one charger (needs sn)."},
{ID: "rfid-card-save", Method: "POST", Endpoint: epRfidSaveCard, Description: "Add a card, at the charger over MQTT and on the account over REST, and answer with the list as it stands afterwards (needs sn, cardNumber; optional cardName). WRITES; the charger's half is the app's own message, the account's is inferred (see rfidcards.go, mqttcards.go)."},
{ID: "rfid-card-delete", Method: "POST", Endpoint: epRfidDeleteCard, Description: "Remove one card, both places it is held, and answer with the list afterwards (needs sn, cardNumber). WRITES; same two halves."},
{ID: "rfid-card-scan", Method: "MQTT", Endpoint: "0108 a2=7", Description: "Open the charger's card reader for twenty seconds and answer with the card tapped, or with the fact that none was (needs sn). This is what \"add through the charger\" in the Anker app does."},
{ID: "rfid-cards-charger", Method: "MQTT", Endpoint: "0104", Description: "The cards the charger itself holds, asked of the device rather than of the account (needs sn)."},
{ID: "ocpp-info", Method: "POST", Endpoint: epOcppInfo, Description: "OCPP endpoint source info for one charger (needs sn)."}, {ID: "ocpp-info", Method: "POST", Endpoint: epOcppInfo, Description: "OCPP endpoint source info for one charger (needs sn)."},
{ID: "ocpp-endpoints", Method: "POST", Endpoint: epOcppEndpoints, Description: "The OCPP endpoints Anker itself uses, with their source numbers."}, {ID: "ocpp-endpoints", Method: "POST", Endpoint: epOcppEndpoints, Description: "The OCPP endpoints Anker itself uses, with their source numbers."},
{ID: "devices", Method: "POST", Endpoint: epBindDevices, Description: "Bound devices on the account, incl. firmware version."}, {ID: "devices", Method: "POST", Endpoint: epBindDevices, Description: "Bound devices on the account, incl. firmware version."},
{ID: "sites", Method: "POST", Endpoint: epSiteList, Description: "Sites (systems) registered to the account."}, {ID: "sites", Method: "POST", Endpoint: epSiteList, Description: "Sites (systems) registered to the account."},
{ID: "vehicles", Method: "POST", Endpoint: epUserVehicles, Description: "Vehicles registered for smart charging."}, {ID: "vehicles", Method: "POST", Endpoint: epUserVehicles, Description: "Vehicles registered for smart charging."},
{ID: "vehicle", Method: "POST", Endpoint: epVehicleDetail, Description: "Details for one registered vehicle (needs vehicleId)."}, {ID: "vehicle", Method: "POST", Endpoint: epVehicleDetail, Description: "Details for one registered vehicle (needs vehicleId)."},
// The rest of the read surface an EV charger can reach, one action per
// endpoint, so anything the account will say can be asked for without
// a new capability being invented for it first. The account-level
// writes the app makes and the endpoints nobody has ever called stay
// out (see the endpoint block above).
{ID: "site-by-sn", Method: "POST", Endpoint: epSiteDetailBySN, Description: "The site a charger belongs to, from its serial alone (needs sn)."},
{ID: "site-detail", Method: "POST", Endpoint: epSiteDetail, Description: "Site detail; answers for shared accounts too (needs siteId)."},
{ID: "site-homepage", Method: "POST", Endpoint: epSiteHomepage, Description: "The app home screen's own view of every site."},
{ID: "user-devices", Method: "POST", Endpoint: epUserDevices, Description: "Owned devices, a lighter list than the bound-device view."},
{ID: "bind-details", Method: "POST", Endpoint: epDeviceBindDetails, Description: "Binding details for one or more serials (needs sn, or sns)."},
{ID: "group-devices", Method: "POST", Endpoint: epGroupDevices, Description: "Whether a charger is grouped with sub-devices (needs sn)."},
{ID: "site-wifi", Method: "POST", Endpoint: epSiteWifiList, Description: "The networks a site can see (needs siteId)."},
{ID: "charger-wifi", Method: "POST", Endpoint: epChargerWifiInfo, Description: "The charger's own Wi-Fi details (needs sn)."},
{ID: "product-info", Method: "POST", Endpoint: epDeviceProductInfo, Description: "Product info for HES-family devices (optional sn)."},
{ID: "install-info", Method: "POST", Endpoint: epInstallInfo, Description: "Where the system was installed (optional sn, siteId)."},
{ID: "charging-orders", Method: "POST", Endpoint: epChargingOrders, Description: "Every charging session in a date range - a plainer list than the paged stats one (needs sn; optional startTime)."},
{ID: "charging-order", Method: "POST", Endpoint: epChargingOrder, Description: "One session with its chart points and the vehicle it charged (needs sn and orderId)."},
{ID: "order-seconds", Method: "POST", Endpoint: epOrderSecDetail, Description: "Second-resolution detail for one session (needs orderId; optional startTime)."},
{ID: "order-seconds-preview", Method: "POST", Endpoint: epOrderSecPreview, Description: "Preview of the second-resolution session detail (needs orderId)."},
{ID: "energy-statistics", Method: "POST", Endpoint: epEnergyStatistics, Description: "Energy statistics with the EV charger as its own source (optional sn, siteId)."},
{ID: "device-income", Method: "POST", Endpoint: epDeviceIncome, Description: "Income / savings figures for one charger (needs sn; optional startTime)."},
{ID: "site-price", Method: "POST", Endpoint: epSitePrice, Description: "A site's power price and CO2 factor (needs siteId)."},
{ID: "currencies", Method: "POST", Endpoint: epCurrencyList, Description: "The currencies the cloud supports."},
{ID: "site-export", Method: "POST", Endpoint: epSiteDataExport, Description: "Filename and URL for a site's CSV export, where the system supports one (needs siteId; optional startTime, endTime)."},
{ID: "dynamic-price-available", Method: "POST", Endpoint: epDynPriceCheck, Description: "Which sites have dynamic pricing at all."},
{ID: "dynamic-price-options", Method: "POST", Endpoint: epDynPriceOptions, Description: "Price providers for a product code and the login country (needs devicePn)."},
{ID: "dynamic-price", Method: "POST", Endpoint: epDynPriceDetail, Description: "The dynamic price curve smart charging would schedule against (needs area and company; optional date, sn)."},
{ID: "vehicle-brands", Method: "POST", Endpoint: epVehicleBrands, Description: "Vehicle brands - the first picker behind adding a car."},
{ID: "vehicle-models", Method: "POST", Endpoint: epVehicleModels, Description: "Models for a brand (needs brand)."},
{ID: "vehicle-years", Method: "POST", Endpoint: epVehicleYears, Description: "Production years for a model (needs brand and model)."},
{ID: "vehicle-specs", Method: "POST", Endpoint: epVehicleSpecs, Description: "What Anker knows about one exact car (needs brand, model and year)."},
{ID: "shared-with", Method: "POST", Endpoint: epSharedDevice, Description: "Who a charger is currently shared with (needs sn)."},
{ID: "ota-check", Method: "POST", Endpoint: epOtaBatchCheck, Description: "The latest firmware available per serial (needs sn, or sns)."},
{ID: "ota-info", Method: "POST", Endpoint: epOtaInfo, Description: "Current OTA status for one or more serials (needs sn, or sns)."},
{ID: "ota-update", Method: "POST", Endpoint: epOtaUpdate, Description: "Details of an available update (needs sn, or sns)."},
{ID: "upgrade-records", Method: "POST", Endpoint: epUpgradeRecords, Description: "Firmware update history (optional sn)."},
{ID: "upgrade-record", Method: "POST", Endpoint: epUpgradeRecord, Description: "One update record, in one of three views (needs sn; optional type 1-3)."},
{ID: "auto-upgrade", Method: "POST", Endpoint: epAutoUpgrade, Description: "Which devices update themselves."},
{ID: "messages-unread", Method: "GET", Endpoint: epMessageUnread, Description: "Whether any notification is waiting."},
{ID: "messages", Method: "GET", Endpoint: epMessages, Description: "The notifications themselves (optional lastTime cursor)."},
{ID: "quiet-hours", Method: "POST", Endpoint: epMessageNotDisturb, Description: "The account's quiet-hours settings, and the charging events they cover."},
{ID: "message-devices", Method: "POST", Endpoint: epMessageSNList, Description: "Which devices produce notifications at all."},
{ID: "tamper-records", Method: "POST", Endpoint: epTamperRecords, Description: "Tamper records for one device (needs sn; optional page, pageSize)."},
{ID: "mqtt-status", Method: "POST", Endpoint: epMqttInfo, Description: "Live state of one charger over Anker's cloud MQTT broker — the path to a charger the server cannot reach (needs sn)."}, {ID: "mqtt-status", Method: "POST", Endpoint: epMqttInfo, Description: "Live state of one charger over Anker's cloud MQTT broker — the path to a charger the server cannot reach (needs sn)."},
{ID: "mqtt-command", Method: "POST", Endpoint: epMqttInfo, Description: "Control one charger over Anker's cloud MQTT broker: start, stop, boost, skip-delay, limit (with amps) or trigger (needs sn and command)."}, {ID: "mqtt-command", Method: "POST", Endpoint: epMqttInfo, Description: "Control one charger over Anker's cloud MQTT broker: start, stop, boost, skip-delay, limit (with amps), trigger or restart (needs sn and command)."},
{ID: "mqtt-settings", Method: "POST", Endpoint: epMqttInfo, Description: "Write one charger's settings over Anker's cloud MQTT broker — current ceiling, switches, schedules, load balancing and solar charging (needs sn and settings)."}, {ID: "mqtt-settings", Method: "POST", Endpoint: epMqttInfo, Description: "Write one charger's settings over Anker's cloud MQTT broker — current ceiling, switches, schedules, load balancing and solar charging (needs sn and settings)."},
}, },
ConfigFields: []plugins.ConfigField{ ConfigFields: []plugins.ConfigField{
@@ -210,6 +334,16 @@ func (p *Plugin) Descriptor() plugins.Descriptor {
Help: "Your Anker account password. Stored locally, sent only (encrypted) to Anker's login endpoint."}, Help: "Your Anker account password. Stored locally, sent only (encrypted) to Anker's login endpoint."},
{Key: "country", Label: "Country", Type: "text", Default: "DE", {Key: "country", Label: "Country", Type: "text", Default: "DE",
Help: "ISO country code of your Anker account (e.g. DE, GB, US). Determines which Anker server the account lives on; a wrong value logs in but shows no devices."}, Help: "ISO country code of your Anker account (e.g. DE, GB, US). Determines which Anker server the account lives on; a wrong value logs in but shows no devices."},
// payloadEncryption is a transport property of the connector as a whole,
// so it lives on the global layer only: the api package copies it into
// every per-user config it builds (ankerCloudConfig) rather than
// cascading it. Off by default, as the reference implementation ships it.
{Key: "payloadEncryption", Label: "Payload encryption", Type: "select", Default: "off",
Help: "Whether requests to Anker's cloud carry their bodies encrypted the way the mobile app does (ECDH key exchange after login, then AES on every request and response). Anker's servers accept plain bodies today, so Off is safe; switch it On if they stop accepting them. A server that refuses the key exchange fails every request until this is switched back off.",
Options: []plugins.SelectOption{
{Value: "off", Label: "Off (plain JSON, as today)"},
{Value: "on", Label: "On (encrypt like the app)"},
}},
// controlMode selects the OCPP control path. It does not affect this // controlMode selects the OCPP control path. It does not affect this
// (read-only) cloud plugin — the CSMS that acts on it lives in the api // (read-only) cloud plugin — the CSMS that acts on it lives in the api
// package (internal/ocpp) — but it is advertised here so a superadmin can // package (internal/ocpp) — but it is advertised here so a superadmin can
@@ -223,6 +357,19 @@ func (p *Plugin) Descriptor() plugins.Descriptor {
{Value: "own", Label: "Own CSMS (full control)"}, {Value: "own", Label: "Own CSMS (full control)"},
{Value: "proxy", Label: "Proxy CSMS (relay + control)"}, {Value: "proxy", Label: "Proxy CSMS (relay + control)"},
}}, }},
// controlModesDisabled hides modes from the layers *below* this one. It
// is how a superadmin takes a mode that is broken or unwanted in this
// deployment (OCPP, say) out of every organization's and user's picker
// without touching the mode this layer itself runs. Organizations carry
// the same field for their own users; see integrations_ankersolix.go.
{Key: "controlModesDisabled", Label: "Hidden control modes", Type: "multiselect",
Help: "Control modes to hide from organizations and users. A hidden mode disappears from their picker and stops taking effect for them; the mode chosen above, which is this layer's own, is unaffected. Off (monitoring only) can never be hidden — it is what a charger falls back to.",
Options: []plugins.SelectOption{
{Value: "mqtt", Label: "Anker cloud (works anywhere)"},
{Value: "modbus", Label: "Modbus TCP (local network)"},
{Value: "own", Label: "Own CSMS (full control)"},
{Value: "proxy", Label: "Proxy CSMS (relay + control)"},
}},
}, },
} }
} }
@@ -239,6 +386,7 @@ func (p *Plugin) Init(_ context.Context, config map[string]string) error {
if p.countryId == "" { if p.countryId == "" {
p.countryId = "DE" p.countryId = "DE"
} }
p.encrypt = payloadEncryptionOn(config["payloadEncryption"])
if comCountries[p.countryId] { if comCountries[p.countryId] {
p.apiBase = serverCOM p.apiBase = serverCOM
} else { } else {
@@ -294,6 +442,30 @@ type invokeParams struct {
StartDate string `json:"startDate"` // YYYY-MM-DD, or YYYY-MM / YYYY for month / year StartDate string `json:"startDate"` // YYYY-MM-DD, or YYYY-MM / YYYY for month / year
EndDate string `json:"endDate"` EndDate string `json:"endDate"`
// The wider read surface. Session history addresses a session by id, the
// vehicle catalogue walks brand -> model -> year, dynamic pricing is asked
// per area and provider, and a few views take several serials at once. Each
// field is read only by the actions that name it.
SNs []string `json:"sns"` // several serials at once (binding details, OTA)
OrderID string `json:"orderId"` // one charging session
StartTime string `json:"startTime"` // upstream's own epoch/date field, passed through
EndTime string `json:"endTime"`
Page int `json:"page"`
PageSize int `json:"pageSize"`
Type int `json:"type"` // upgrade-record view, 1-3
LastTime string `json:"lastTime"` // message cursor, format undocumented upstream
Brand string `json:"brand"`
Model string `json:"model"`
Year string `json:"year"`
DevicePN string `json:"devicePn"` // product code, for dynamic-price providers
Area string `json:"area"`
Company string `json:"company"`
Date string `json:"date"`
// The two RFID card writes: which card, and what to call it.
CardNumber string `json:"cardNumber"`
CardName string `json:"cardName"`
// The cloud MQTT actions: which command to send, the current ceiling "limit" // The cloud MQTT actions: which command to send, the current ceiling "limit"
// carries, and the settings "mqtt-settings" writes, by the names the snapshot // carries, and the settings "mqtt-settings" writes, by the names the snapshot
// reports them under. // reports them under.
@@ -302,9 +474,11 @@ type invokeParams struct {
Settings map[string]any `json:"settings"` Settings map[string]any `json:"settings"`
} }
// Invoke runs a named read-only capability. The upstream response body is // Invoke runs a named capability. Every one of them reads, bar the two RFID
// returned verbatim, except for "charger-state", which is derived (see // card writes, which are the only calls in this connector that change anything
// chargerState). // on the account (see rfidcards.go). The upstream response body is returned
// verbatim, except for "charger-state" and those two, which are derived (see
// chargerState, rfidAfterWrite).
func (p *Plugin) Invoke(ctx context.Context, action string, params json.RawMessage) (json.RawMessage, error) { func (p *Plugin) Invoke(ctx context.Context, action string, params json.RawMessage) (json.RawMessage, error) {
var pp invokeParams var pp invokeParams
if len(params) > 0 { if len(params) > 0 {
@@ -333,6 +507,28 @@ func (p *Plugin) Invoke(ctx context.Context, action string, params json.RawMessa
} }
return p.chargerState(ctx, pp.SiteID, pp.SN) return p.chargerState(ctx, pp.SiteID, pp.SN)
} }
// Reading a card at the charger and asking the charger for its list are the
// device's own messages, not endpoints (see mqttcards.go).
if action == "rfid-card-scan" || action == "rfid-cards-charger" {
if pp.SN == "" {
return nil, fmt.Errorf("anker-solix: action %q requires an sn (EV charger serial)", action)
}
if action == "rfid-card-scan" {
return p.mqttReadCard(ctx, pp.SN)
}
return p.mqttChargerCards(ctx, pp.SN)
}
// The two card writes are a write followed by the read that checks it, so
// neither fits the single-endpoint dispatch below either.
if action == "rfid-card-save" || action == "rfid-card-delete" {
if pp.SN == "" {
return nil, fmt.Errorf("anker-solix: action %q requires an sn (EV charger serial)", action)
}
if action == "rfid-card-save" {
return p.rfidSaveCard(ctx, pp.SN, pp.CardNumber, pp.CardName)
}
return p.rfidDeleteCard(ctx, pp.SN, pp.CardNumber)
}
// The cloud MQTT actions address the charger itself over the account's broker // The cloud MQTT actions address the charger itself over the account's broker
// rather than a REST endpoint, so they route to that transport instead of the // rather than a REST endpoint, so they route to that transport instead of the
// single-endpoint dispatch below. // single-endpoint dispatch below.
@@ -352,6 +548,7 @@ func (p *Plugin) Invoke(ctx context.Context, action string, params json.RawMessa
var ( var (
endpoint string endpoint string
payload map[string]any payload map[string]any
query map[string]string // set instead of payload for the two GET views
needSN bool needSN bool
needSite bool needSite bool
) )
@@ -403,6 +600,147 @@ func (p *Plugin) Invoke(ctx context.Context, action string, params json.RawMessa
} }
endpoint = epVehicleDetail endpoint = epVehicleDetail
payload = map[string]any{"vehicle_id": pp.VehicleID} payload = map[string]any{"vehicle_id": pp.VehicleID}
// --- the rest of the read surface ---------------------------------------
// Bodies are upstream's own field names, taken from the endpoint map; a
// field the caller left empty is still sent, because the cloud treats an
// empty string as "no filter" on every one of these.
case "site-by-sn":
endpoint, needSN = epSiteDetailBySN, true
payload = map[string]any{"device_sn": pp.SN}
case "site-detail":
endpoint, needSite = epSiteDetail, true
payload = map[string]any{"site_id": pp.SiteID}
case "site-homepage":
endpoint, payload = epSiteHomepage, map[string]any{}
case "user-devices":
endpoint, payload = epUserDevices, map[string]any{}
case "bind-details", "ota-check", "ota-info", "ota-update":
// The four views that ask about a list of serials rather than one. Both
// spellings are accepted: sns for several, sn for the usual one.
sns := serialList(pp)
if len(sns) == 0 {
return nil, fmt.Errorf("anker-solix: action %q requires an sn (or sns)", action)
}
switch action {
case "bind-details":
endpoint = epDeviceBindDetails
case "ota-check":
endpoint = epOtaBatchCheck
case "ota-info":
endpoint = epOtaInfo
default:
endpoint = epOtaUpdate
}
payload = map[string]any{"device_sn_list": sns}
case "group-devices":
endpoint, needSN = epGroupDevices, true
payload = map[string]any{"device_sn": pp.SN}
case "site-wifi":
endpoint, needSite = epSiteWifiList, true
payload = map[string]any{"site_id": pp.SiteID}
case "charger-wifi":
endpoint, needSN = epChargerWifiInfo, true
payload = map[string]any{"evChargerSn": pp.SN}
case "product-info":
endpoint = epDeviceProductInfo
payload = map[string]any{"evChargerSn": pp.SN}
case "install-info":
endpoint = epInstallInfo
payload = map[string]any{"evChargerSn": pp.SN, "siteId": pp.SiteID}
case "charging-orders":
endpoint, needSN = epChargingOrders, true
payload = map[string]any{"device_sn": pp.SN, "start_time": pp.StartTime}
case "charging-order":
if pp.OrderID == "" {
return nil, fmt.Errorf("anker-solix: action %q requires an orderId", action)
}
endpoint, needSN = epChargingOrder, true
payload = map[string]any{"device_sn": pp.SN, "order_id": pp.OrderID}
case "order-seconds", "order-seconds-preview":
if pp.OrderID == "" {
return nil, fmt.Errorf("anker-solix: action %q requires an orderId", action)
}
if action == "order-seconds" {
endpoint = epOrderSecDetail
payload = map[string]any{"order_id": pp.OrderID, "start_time": pp.StartTime}
} else {
endpoint = epOrderSecPreview
payload = map[string]any{"order_id": pp.OrderID}
}
case "energy-statistics":
endpoint = epEnergyStatistics
payload = map[string]any{"sourceType": "evCharger", "evChargerSn": pp.SN, "siteId": pp.SiteID}
case "device-income":
endpoint, needSN = epDeviceIncome, true
payload = map[string]any{"device_sn": pp.SN, "start_time": pp.StartTime}
case "site-price":
endpoint, needSite = epSitePrice, true
payload = map[string]any{"site_id": pp.SiteID}
case "currencies":
endpoint, payload = epCurrencyList, map[string]any{}
case "site-export":
endpoint, needSite = epSiteDataExport, true
payload = map[string]any{"site_id": pp.SiteID, "start_time": pp.StartTime, "end_time": pp.EndTime}
case "dynamic-price-available":
endpoint, payload = epDynPriceCheck, map[string]any{}
case "dynamic-price-options":
if pp.DevicePN == "" {
return nil, fmt.Errorf("anker-solix: action %q requires a devicePn (the charger's product code)", action)
}
endpoint = epDynPriceOptions
payload = map[string]any{"device_pn": pp.DevicePN}
case "dynamic-price":
if pp.Area == "" || pp.Company == "" {
return nil, fmt.Errorf("anker-solix: action %q requires an area and a company (from dynamic-price-options)", action)
}
endpoint = epDynPriceDetail
payload = map[string]any{"area": pp.Area, "company": pp.Company, "date": pp.Date, "device_sn": pp.SN}
case "vehicle-brands":
endpoint, payload = epVehicleBrands, map[string]any{}
case "vehicle-models":
if pp.Brand == "" {
return nil, fmt.Errorf("anker-solix: action %q requires a brand", action)
}
endpoint = epVehicleModels
payload = map[string]any{"brand_name": pp.Brand}
case "vehicle-years":
if pp.Brand == "" || pp.Model == "" {
return nil, fmt.Errorf("anker-solix: action %q requires a brand and a model", action)
}
endpoint = epVehicleYears
payload = map[string]any{"brand_name": pp.Brand, "model_name": pp.Model}
case "vehicle-specs":
if pp.Brand == "" || pp.Model == "" || pp.Year == "" {
return nil, fmt.Errorf("anker-solix: action %q requires a brand, a model and a year", action)
}
endpoint = epVehicleSpecs
payload = map[string]any{"brand_name": pp.Brand, "model_name": pp.Model, "productive_year": pp.Year}
case "shared-with":
endpoint, needSN = epSharedDevice, true
payload = map[string]any{"device_sn": pp.SN}
case "upgrade-records":
endpoint = epUpgradeRecords
payload = map[string]any{"device_sn": pp.SN}
case "upgrade-record":
endpoint, needSN = epUpgradeRecord, true
payload = map[string]any{"device_sn": pp.SN, "type": upgradeRecordView(pp.Type)}
case "auto-upgrade":
endpoint, payload = epAutoUpgrade, map[string]any{}
case "messages-unread":
endpoint, query = epMessageUnread, map[string]string{}
case "messages":
endpoint, query = epMessages, map[string]string{}
if pp.LastTime != "" {
query["last_time"] = pp.LastTime
}
case "quiet-hours":
endpoint, payload = epMessageNotDisturb, map[string]any{}
case "message-devices":
endpoint, payload = epMessageSNList, map[string]any{}
case "tamper-records":
endpoint, needSN = epTamperRecords, true
payload = map[string]any{"device_sn": pp.SN, "page_num": pageNum(pp.Page), "page_size": pageSize(pp.PageSize)}
default: default:
return nil, fmt.Errorf("anker-solix: unknown action %q", action) return nil, fmt.Errorf("anker-solix: unknown action %q", action)
} }
@@ -413,6 +751,14 @@ func (p *Plugin) Invoke(ctx context.Context, action string, params json.RawMessa
return nil, fmt.Errorf("anker-solix: action %q requires a siteId", action) return nil, fmt.Errorf("anker-solix: action %q requires a siteId", action)
} }
// Two of these are GET views; everything else is a POST with a JSON body.
if query != nil {
body, err := p.apiGet(ctx, endpoint, query)
if err != nil {
return nil, err
}
return json.RawMessage(body), nil
}
body, err := p.apiRequest(ctx, endpoint, payload) body, err := p.apiRequest(ctx, endpoint, payload)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -420,6 +766,48 @@ func (p *Plugin) Invoke(ctx context.Context, action string, params json.RawMessa
return json.RawMessage(body), nil return json.RawMessage(body), nil
} }
// serialList is the serials a multi-serial view is asked about: the several it
// was given, or the single one every other action takes, so a caller never has
// to know which spelling an endpoint wanted.
func serialList(pp invokeParams) []string {
out := make([]string, 0, len(pp.SNs)+1)
for _, sn := range pp.SNs {
if sn = strings.TrimSpace(sn); sn != "" {
out = append(out, sn)
}
}
if len(out) == 0 && pp.SN != "" {
out = append(out, pp.SN)
}
return out
}
// upgradeRecordView clamps check_upgrade_record's view selector, which upstream
// documents as 1-3 and nothing more; 1 is what the app asks for.
func upgradeRecordView(t int) int {
if t < 1 || t > 3 {
return 1
}
return t
}
// pageNum and pageSize give the paged views a first page and a readable page
// when the caller does not care, rather than sending a zero the cloud reads as
// "no page at all".
func pageNum(n int) int {
if n < 1 {
return 1
}
return n
}
func pageSize(n int) int {
if n < 1 || n > 100 {
return 20
}
return n
}
// energyRange normalizes the energy_analysis period, defaulting to a week like // energyRange normalizes the energy_analysis period, defaulting to a week like
// the reference implementation's EV-charger poll. // the reference implementation's EV-charger poll.
func energyRange(r string) string { func energyRange(r string) string {
@@ -651,8 +1039,10 @@ func chargerModeOptions(mode, statusDesc string) []string {
case modeBoostCharge: case modeBoostCharge:
set[modeStopCharge] = true set[modeStopCharge] = true
default: default:
// Only a charger sitting in standby can be told to start. // A charger sitting in standby can be told to start, and so can one still
if statusDesc == stateStandby { // showing a finished session: completed can last until the cable is pulled,
// and the app offers Start throughout (upstream v3.9.0, ha-anker-solix #629).
if statusDesc == stateStandby || statusDesc == stateCompleted {
set[modeStartCharge] = true set[modeStartCharge] = true
} }
} }
@@ -678,6 +1068,13 @@ const (
// penalty out rather than spending attempts against a door that is shut. // penalty out rather than spending attempts against a door that is shut.
codeSignInLocked = 10019 codeSignInLocked = 10019
loginLockoutWait = 10 * time.Minute loginLockoutWait = 10 * time.Minute
// codeLoginBanned is "Hit max login error limit": Anker has banned the
// client's IP for 24 hours after too many logins (ha-anker-solix #659).
// Nothing but a new public IP lifts it early, so try once an hour rather
// than adding attempts to the count.
codeLoginBanned = 100041
loginBanWait = time.Hour
) )
// loginRejected is the login endpoint answering with a non-zero API code. The // loginRejected is the login endpoint answering with a non-zero API code. The
@@ -788,7 +1185,7 @@ func (p *Plugin) login(ctx context.Context) error {
"transaction": fmt.Sprintf("%d", time.Now().UnixMilli()), "transaction": fmt.Sprintf("%d", time.Now().UnixMilli()),
} }
body, status, err := p.doRequest(ctx, epLogin, reqBody, "", "", gmt) body, status, err := p.doRequest(ctx, epLogin, reqBody, nil, "", "", gmt)
if err != nil { if err != nil {
return err return err
} }
@@ -834,44 +1231,166 @@ func (p *Plugin) storeToken(body []byte) error {
gtoken: md5hex(env.Data.UserID), gtoken: md5hex(env.Data.UserID),
nickname: env.Data.NickName, nickname: env.Data.NickName,
expiration: exp, expiration: exp,
issued: time.Now(),
}
// A handshake belongs to the login it was run under; the next encrypted
// request runs a fresh one.
p.sess.enc = nil
return nil
}
// ensureCipher returns the payload cipher for the token held, running the key
// exchange if this token has not had one yet. Serialised by p.sess.mu like the
// login, so concurrent requests share one handshake. Only called when the
// connector is configured to encrypt.
func (p *Plugin) ensureCipher(ctx context.Context, tok tokenInfo) (*payloadCipher, error) {
s := p.sess
s.mu.Lock()
defer s.mu.Unlock()
if s.tok == nil || s.tok.authToken != tok.authToken {
// The token was replaced under us; the caller will fetch the new one and
// come back.
return nil, errors.New("anker-solix: token changed during request")
}
if s.enc.ready() {
return s.enc, nil
}
enc, err := newPayloadCipher()
if err != nil {
return nil, err
}
if err := p.keyExchange(ctx, tok, enc); err != nil {
return nil, err
}
s.enc = enc
return enc, nil
}
// keyExchange runs the handshake described in payloadcrypto.go: the wrapped
// client key goes up as plain JSON under the presetKey's signature, the wrapped
// server key comes back, and enc ends up holding the shared secret.
func (p *Plugin) keyExchange(ctx context.Context, tok tokenInfo, enc *payloadCipher) error {
clientKey, err := enc.clientPublicKey()
if err != nil {
return fmt.Errorf("anker-solix: key exchange: %w", err)
}
buf, err := json.Marshal(map[string]string{"client_public_key": clientKey})
if err != nil {
return fmt.Errorf("anker-solix: key exchange: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.apiBase+"/"+epKeyExchange, bytes.NewReader(buf))
if err != nil {
return err
}
gmt, _ := timezone()
ankerHeaders(req, p.countryId, tok.authToken, tok.gtoken, gmt)
enc.signRequest(req, fmt.Sprintf("%d", time.Now().Unix()), clientKey, true)
resp, err := p.client.Do(req)
if err != nil {
return fmt.Errorf("anker-solix: key exchange: %w", err)
}
defer drain(resp)
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("anker-solix: key exchange failed (HTTP %d): %s", resp.StatusCode, shorten(string(body)))
}
if code, msg, bad := apiError(body); bad {
return fmt.Errorf("anker-solix: key exchange failed (code %d): %s", code, shorten(msg))
}
var env struct {
Data struct {
ServerPublicKey string `json:"server_public_key"`
} `json:"data"`
}
if err := json.Unmarshal(body, &env); err != nil {
return fmt.Errorf("anker-solix: decode key exchange: %w", err)
}
if env.Data.ServerPublicKey == "" {
return errors.New("anker-solix: key exchange answered without a server key")
}
if err := enc.acceptServerKey(env.Data.ServerPublicKey); err != nil {
return fmt.Errorf("anker-solix: key exchange: %w", err)
} }
return nil return nil
} }
// payloadEncryptionOn reads the payloadEncryption config value.
func payloadEncryptionOn(v string) bool {
switch strings.ToLower(strings.TrimSpace(v)) {
case "on", "true", "1", "yes":
return true
}
return false
}
// ---- data requests ----------------------------------------------------------- // ---- data requests -----------------------------------------------------------
// apiRequest performs an authenticated POST, re-authenticating once if the token // apiRequest performs an authenticated POST, re-authenticating once if the token
// is rejected. It returns the raw response body; a non-zero API code or non-2xx // is rejected. It returns the raw response body; a non-zero API code or non-2xx
// status is returned as an error. // status is returned as an error.
func (p *Plugin) apiRequest(ctx context.Context, endpoint string, payload map[string]any) ([]byte, error) { func (p *Plugin) apiRequest(ctx context.Context, endpoint string, payload map[string]any) ([]byte, error) {
return p.apiCall(ctx, endpoint, func(tok tokenInfo, enc *payloadCipher, gmt string) ([]byte, int, error) {
return p.doRequest(ctx, endpoint, payload, enc, tok.authToken, tok.gtoken, gmt)
})
}
// apiGet is apiRequest for the two message views, the only endpoints in this
// connector Anker serves over GET: same headers, same credential, same one
// retry after a fresh login — a query string instead of a body.
func (p *Plugin) apiGet(ctx context.Context, endpoint string, query map[string]string) ([]byte, error) {
return p.apiCall(ctx, endpoint, func(tok tokenInfo, enc *payloadCipher, gmt string) ([]byte, int, error) {
return p.doGet(ctx, endpoint, query, enc, tok.authToken, tok.gtoken, gmt)
})
}
// apiCall is what both of those share: a token, one attempt, and — when the
// cloud rejects the token — a fresh login and exactly one more. There is no
// refresh token, so a rejected token can only be answered with a new login.
// With payload encryption on, the token comes with its handshake (run once per
// login), and a new login means a new handshake before the retry.
func (p *Plugin) apiCall(ctx context.Context, endpoint string, send func(tokenInfo, *payloadCipher, string) ([]byte, int, error)) ([]byte, error) {
tok, err := p.ensureToken(ctx) tok, err := p.ensureToken(ctx)
if err != nil { if err != nil {
return nil, err return nil, err
} }
var enc *payloadCipher
if p.encrypt {
if enc, err = p.ensureCipher(ctx, tok); err != nil {
return nil, err
}
}
gmt, _ := timezone() gmt, _ := timezone()
body, status, err := p.doRequest(ctx, endpoint, payload, tok.authToken, tok.gtoken, gmt) body, status, err := send(tok, enc, gmt)
if err != nil { if err != nil {
return nil, err return nil, err
} }
// A rejected token surfaces as 401/403 or an auth error code; log in afresh // A rejected token surfaces as 401/403 or an auth error code; log in afresh
// and retry once. // and retry once — unless the rejection cannot be about the token. Anker
if status == http.StatusUnauthorized || status == http.StatusForbidden || isAuthCode(body) { // also answers 403 for an endpoint it has retired (ha-anker-solix #658,
p.sess.mu.Lock() // #659), and a fresh login per poll for one of those ends in a 24-hour IP
p.sess.tok = nil // ban. relogin decides; see there.
lerr := p.attemptLogin(ctx) if rejected(status, body) {
var newTok tokenInfo newTok, again, lerr := p.relogin(ctx, endpoint, tok)
if lerr == nil {
newTok = *p.sess.tok
}
p.sess.mu.Unlock()
if lerr != nil { if lerr != nil {
return nil, lerr return nil, lerr
} }
body, status, err = p.doRequest(ctx, endpoint, payload, newTok.authToken, newTok.gtoken, gmt) if again {
if err != nil { if p.encrypt {
return nil, err if enc, err = p.ensureCipher(ctx, newTok); err != nil {
return nil, err
}
}
body, status, err = send(newTok, enc, gmt)
if err != nil {
return nil, err
}
if rejected(status, body) {
// A token minutes old was refused too: the endpoint is saying no.
p.sess.noteRefused(endpoint)
}
} }
} }
@@ -884,27 +1403,93 @@ func (p *Plugin) apiRequest(ctx context.Context, endpoint string, payload map[st
return body, nil return body, nil
} }
// rejected reports whether a reply is the cloud refusing the token.
func rejected(status int, body []byte) bool {
return status == http.StatusUnauthorized || status == http.StatusForbidden || isAuthCode(body)
}
// freshToken is how young a token is when a refusal of it is taken to be about
// the endpoint rather than the token: the mobile app evicting it, the one
// reason a valid token stops working, does not happen seconds after a login.
const freshToken = 2 * time.Minute
// relogin answers a refused token. It returns the token to retry with and
// whether to retry at all. Three cases spend no login: the endpoint already
// refused a fresh token within the hour, the token used is itself fresh (so a
// new one would be refused the same way), and another request has already
// replaced the token meanwhile (so retry with that one). Otherwise the token
// is dropped, with the handshake run under it, and a new login is made.
func (p *Plugin) relogin(ctx context.Context, endpoint string, used tokenInfo) (tokenInfo, bool, error) {
s := p.sess
s.mu.Lock()
defer s.mu.Unlock()
if s.refusing(endpoint) {
return tokenInfo{}, false, nil
}
if s.tok != nil && s.tok.authToken != used.authToken && time.Now().Before(s.tok.expiration) {
return *s.tok, true, nil
}
if !used.issued.IsZero() && time.Since(used.issued) < freshToken {
s.noteRefusedLocked(endpoint)
return tokenInfo{}, false, nil
}
s.tok = nil
s.enc = nil // the handshake goes with the token it was run under
if err := p.attemptLogin(ctx); err != nil {
return tokenInfo{}, false, err
}
return *s.tok, true, nil
}
// doRequest issues a single POST to an endpoint with the common Anker headers. // doRequest issues a single POST to an endpoint with the common Anker headers.
// When authToken is empty the auth headers are omitted (login request). // When authToken is empty the auth headers are omitted (login request). A
func (p *Plugin) doRequest(ctx context.Context, endpoint string, payload map[string]any, authToken, gtoken, gmt string) ([]byte, int, error) { // non-nil enc sends the body sealed and signed, and opens the reply.
func (p *Plugin) doRequest(ctx context.Context, endpoint string, payload map[string]any, enc *payloadCipher, authToken, gtoken, gmt string) ([]byte, int, error) {
buf, err := json.Marshal(payload) buf, err := json.Marshal(payload)
if err != nil { if err != nil {
return nil, 0, fmt.Errorf("anker-solix: encode request: %w", err) return nil, 0, fmt.Errorf("anker-solix: encode request: %w", err)
} }
return p.send(ctx, http.MethodPost, endpoint, p.apiBase+"/"+endpoint, buf, payload, enc, authToken, gtoken, gmt)
}
// doGet issues a single GET with the same headers a POST carries. Only the two
// message views are served this way. Under encryption a GET still carries a
// sealed body — an empty object — because that is what the reference
// implementation sends and the signature has to cover something.
func (p *Plugin) doGet(ctx context.Context, endpoint string, query map[string]string, enc *payloadCipher, authToken, gtoken, gmt string) ([]byte, int, error) {
url := p.apiBase + "/" + endpoint url := p.apiBase + "/" + endpoint
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(buf)) if len(query) > 0 {
vals := neturl.Values{}
for k, v := range query {
vals.Set(k, v)
}
url += "?" + vals.Encode()
}
return p.send(ctx, http.MethodGet, endpoint, url, nil, nil, enc, authToken, gtoken, gmt)
}
// send is the one HTTP exchange behind doRequest and doGet. plain is the JSON
// body a plain request carries (nil for a GET); payload is the same body as the
// map enc seals when the request is encrypted.
func (p *Plugin) send(ctx context.Context, method, endpoint, url string, plain []byte, payload map[string]any, enc *payloadCipher, authToken, gtoken, gmt string) ([]byte, int, error) {
var body io.Reader
var wire string
if enc != nil {
sealed, err := enc.sealBody(payload)
if err != nil {
return nil, 0, err
}
wire, body = sealed, strings.NewReader(sealed)
} else if plain != nil {
body = bytes.NewReader(plain)
}
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
req.Header.Set("content-type", "application/json") ankerHeaders(req, p.countryId, authToken, gtoken, gmt)
req.Header.Set("model-type", "DESKTOP") if enc != nil {
req.Header.Set("app-name", "anker_power") enc.signRequest(req, fmt.Sprintf("%d", time.Now().Unix()), wire, false)
req.Header.Set("os-type", "android")
req.Header.Set("country", p.countryId)
req.Header.Set("timezone", gmt)
if authToken != "" {
req.Header.Set("x-auth-token", authToken)
req.Header.Set("gtoken", gtoken)
} }
resp, err := p.client.Do(req) resp, err := p.client.Do(req)
@@ -913,9 +1498,29 @@ func (p *Plugin) doRequest(ctx context.Context, endpoint string, payload map[str
} }
defer drain(resp) defer drain(resp)
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20)) respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
if enc != nil {
if respBody, err = enc.unsealEnvelope(respBody); err != nil {
return nil, resp.StatusCode, err
}
}
return respBody, resp.StatusCode, nil return respBody, resp.StatusCode, nil
} }
// ankerHeaders sets the identity every request carries. When authToken is empty
// the credential headers are omitted (the login request).
func ankerHeaders(req *http.Request, countryId, authToken, gtoken, gmt string) {
req.Header.Set("content-type", "application/json")
req.Header.Set("model-type", "DESKTOP")
req.Header.Set("app-name", "anker_power")
req.Header.Set("os-type", "android")
req.Header.Set("country", countryId)
req.Header.Set("timezone", gmt)
if authToken != "" {
req.Header.Set("x-auth-token", authToken)
req.Header.Set("gtoken", gtoken)
}
}
// ---- crypto & small helpers -------------------------------------------------- // ---- crypto & small helpers --------------------------------------------------
// encryptPassword AES-256-CBC encrypts the password under the ECDH shared secret // encryptPassword AES-256-CBC encrypts the password under the ECDH shared secret
@@ -66,6 +66,31 @@ func TestDescriptor(t *testing.T) {
t.Errorf("controlMode is missing option %q", v) t.Errorf("controlMode is missing option %q", v)
} }
} }
// controlModesDisabled is the superadmin's hide-list: which of the modes the
// organizations and users below are offered at all. off is not among them —
// monitoring only is the fallback, so no layer may take it away.
hide, ok := fields["controlModesDisabled"]
if !ok {
t.Fatal("controlModesDisabled config field should be present")
}
if hide.Type != "multiselect" {
t.Errorf("controlModesDisabled type = %q, want multiselect", hide.Type)
}
hideable := map[string]bool{"mqtt": false, "modbus": false, "own": false, "proxy": false}
for _, o := range hide.Options {
if o.Value == "off" {
t.Error("off must not be hideable — it is what a charger falls back to")
}
if _, known := hideable[o.Value]; known {
hideable[o.Value] = true
}
}
for v, seen := range hideable {
if !seen {
t.Errorf("controlModesDisabled is missing option %q", v)
}
}
} }
func TestRegistered(t *testing.T) { func TestRegistered(t *testing.T) {
@@ -86,6 +111,7 @@ func TestServerSelection(t *testing.T) {
"GB": serverEU, // not in the COM list → EU default "GB": serverEU, // not in the COM list → EU default
"US": serverCOM, "US": serverCOM,
"AU": serverCOM, "AU": serverCOM,
"SG": serverEU, // moved off the COM list in upstream v3.9.0
"": serverEU, // empty → defaults to DE → EU "": serverEU, // empty → defaults to DE → EU
} }
for country, want := range cases { for country, want := range cases {
@@ -323,9 +349,9 @@ func TestChargerModeOptions(t *testing.T) {
{modeWaitStart, statePreparing, []string{modeSkipDelay, modeStopCharge, modeWaitStart}}, {modeWaitStart, statePreparing, []string{modeSkipDelay, modeStopCharge, modeWaitStart}},
{modeWaitPlug, statePreparing, []string{modeStopCharge, modeWaitPlug}}, {modeWaitPlug, statePreparing, []string{modeStopCharge, modeWaitPlug}},
{modeBoostCharge, stateCharging, []string{modeBoostCharge, modeStopCharge}}, {modeBoostCharge, stateCharging, []string{modeBoostCharge, modeStopCharge}},
// Stopped: startable only from standby. // Stopped: startable from standby, and from completed since v3.9.0.
{modeStopCharge, stateStandby, []string{modeStartCharge, modeStopCharge}}, {modeStopCharge, stateStandby, []string{modeStartCharge, modeStopCharge}},
{modeStopCharge, stateCompleted, []string{modeStopCharge}}, {modeStopCharge, stateCompleted, []string{modeStartCharge, modeStopCharge}},
{modeStopCharge, stateError, []string{modeStopCharge}}, {modeStopCharge, stateError, []string{modeStopCharge}},
{"", stateUnknown, []string{}}, {"", stateUnknown, []string{}},
} }
@@ -3,11 +3,18 @@ package ankersolix
// The account's other views of one charger. // The account's other views of one charger.
// //
// The merged inventory (chargers.go) answers "what chargers are there", and it // The merged inventory (chargers.go) answers "what chargers are there", and it
// asks the views that list them. Four more endpoints answer only when a serial // asks the views that list them. Everything else the cloud will say about one
// is named: the station record the app opens on a charger, its cumulative // charger answers only when a serial is named — the station record, the
// charging totals, which OCPP backend it is pointed at, and the RFID cards // charging totals and the completed sessions, the OCPP backend, the RFID cards,
// authorised on it. None of them lists a charger, so none belongs in the merge — // the binding, the sharing, the firmware, the Wi-Fi, the tamper log — so none of
// and none of them was reachable from the app at all until this capability. // them can be part of the merge, and none of them was reachable from the app at
// all until this capability.
//
// Every read the endpoint map lists for one charger is asked here, rather than a
// chosen few: which of them an account can answer is itself the finding, and a
// view nobody asks for is a field nobody can see. A charger that belongs to a
// site brings four more with it — the site is only known once the first pass has
// asked for it, so the site's own views are a second pass.
// //
// What they answer with is not documented, by Anker or by the reference: the // What they answer with is not documented, by Anker or by the reference: the
// endpoints are known, their payloads are not. So each view is relayed as the // endpoints are known, their payloads are not. So each view is relayed as the
@@ -19,15 +26,24 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"strings"
"sync"
) )
// chargerDetailView is one endpoint's answer about one charger. A view that // chargerDetailView is one endpoint's answer about one charger. A view that
// fails carries its reason instead of its fields: an account that is not the // fails carries its reason instead of its fields: an account that is not the
// owner cannot read the cards, which is a fact about the account rather than an // owner cannot read the cards, which is a fact about the account rather than an
// error in the read. // error in the read. A view that answers with nothing carries neither, and says
// so by being empty — a standalone charger has no station record, and that is
// worth seeing too.
//
// Note is the one thing said in DriverVault's own words rather than the cloud's:
// a number the account elsewhere gives a meaning to, resolved. It never replaces
// a field, so the cloud's own keys stay exactly as they arrived.
type chargerDetailView struct { type chargerDetailView struct {
ID string `json:"id"` ID string `json:"id"`
Attrs map[string]string `json:"attrs,omitempty"` Attrs map[string]string `json:"attrs,omitempty"`
Note string `json:"note,omitempty"`
Error string `json:"error,omitempty"` Error string `json:"error,omitempty"`
} }
@@ -36,6 +52,20 @@ type chargerDetailsDoc struct {
Views []chargerDetailView `json:"views"` Views []chargerDetailView `json:"views"`
} }
// detailRequest is one view to ask for: the id it is reported under, the
// endpoint, and the body it takes.
type detailRequest struct {
id string
endpoint string
payload map[string]any
}
// detailFanout is how many of these are in flight at once. The cloud is a
// stranger's API being asked twenty questions about one charger; a handful at a
// time keeps the whole card under a couple of seconds without arriving as a
// burst that looks like something to rate-limit.
const detailFanout = 6
// chargerDetails asks every per-charger endpoint and returns what each answered. // chargerDetails asks every per-charger endpoint and returns what each answered.
// One failing view is reported in place; only losing all of them is an error, // One failing view is reported in place; only losing all of them is an error,
// for the same reason the inventory works that way — a charger the cloud will // for the same reason the inventory works that way — a charger the cloud will
@@ -45,35 +75,162 @@ func (p *Plugin) chargerDetails(ctx context.Context, sn string) (json.RawMessage
return nil, err return nil, err
} }
views := []struct { // Everything that needs only the serial. Ordered as the card reads them:
id string // what it is doing, what it has done, who may use it, what it is, and the
endpoint string // housekeeping the account keeps about it.
payload map[string]any views := []detailRequest{
}{
{"station", epStationInfo, map[string]any{"evChargerSn": sn, "featuretype": 1}}, {"station", epStationInfo, map[string]any{"evChargerSn": sn, "featuretype": 1}},
{"stationFeature", epStationInfo, map[string]any{"evChargerSn": sn, "featuretype": 2}},
{"totals", epChargeStats, map[string]any{ {"totals", epChargeStats, map[string]any{
"device_sn": sn, "date_type": "all", "start_date": "", "end_date": ""}}, "device_sn": sn, "date_type": "all", "start_date": "", "end_date": ""}},
{"orders", epChargeStatsList, map[string]any{
"device_sn": sn, "order_status": 1, "date_type": "all",
"start_date": "", "end_date": "", "page": 0, "page_size": 10}},
{"sessions", epChargingOrders, map[string]any{"device_sn": sn, "start_time": ""}},
{"income", epDeviceIncome, map[string]any{"device_sn": sn, "start_time": ""}},
{"ocpp", epOcppInfo, map[string]any{"device_sn": sn}}, {"ocpp", epOcppInfo, map[string]any{"device_sn": sn}},
{"ocppEndpoints", epOcppEndpoints, map[string]any{}},
{"rfid", epRfidCards, map[string]any{"device_sn": sn}}, {"rfid", epRfidCards, map[string]any{"device_sn": sn}},
{"shared", epSharedDevice, map[string]any{"device_sn": sn}},
{"binding", epDeviceBindDetails, map[string]any{"device_sn_list": []string{sn}}},
{"group", epGroupDevices, map[string]any{"device_sn": sn}},
{"wifi", epChargerWifiInfo, map[string]any{"evChargerSn": sn}},
{"ota", epOtaInfo, map[string]any{"device_sn_list": []string{sn}}},
{"upgrades", epUpgradeRecords, map[string]any{"device_sn": sn}},
{"tamper", epTamperRecords, map[string]any{"device_sn": sn, "page_num": 1, "page_size": 20}},
{"siteBySn", epSiteDetailBySN, map[string]any{"device_sn": sn}},
} }
doc := chargerDetailsDoc{SN: sn, Views: make([]chargerDetailView, 0, len(views))} out := p.askViews(ctx, views)
failed := 0
for _, v := range views { // The site's own views, once the first pass has found which site this is.
out := chargerDetailView{ID: v.id} // A standalone charger has none, and asking anyway would be four errors
body, err := p.apiRequest(ctx, v.endpoint, v.payload) // about a site that does not exist.
if err != nil { if siteID := siteIDFrom(out); siteID != "" {
out.Error, failed = shorten(err.Error()), failed+1 out = append(out, p.askViews(ctx, []detailRequest{
} else { {"site", epSiteDetail, map[string]any{"site_id": siteID}},
out.Attrs = map[string]string{} {"sitePrice", epSitePrice, map[string]any{"site_id": siteID}},
flattenInto(out.Attrs, "", dataValue(body)) {"siteWifi", epSiteWifiList, map[string]any{"site_id": siteID}},
} {"energy", epEnergyAnalysis, map[string]any{
doc.Views = append(doc.Views, out) "site_id": siteID, "device_sn": sn, "device_type": "ev_charger",
"type": energyRange(""), "start_time": "", "end_time": ""}},
})...)
} }
if failed == len(views) {
// Which OCPP backend "source 0" actually is, from the list the account
// publishes for exactly that purpose.
noteOcppSource(out)
failed := 0
for _, v := range out {
if v.Error != "" {
failed++
}
}
if failed == len(out) {
return nil, fmt.Errorf("anker-solix: charger %s: no per-charger view answered", sn) return nil, fmt.Errorf("anker-solix: charger %s: no per-charger view answered", sn)
} }
return json.Marshal(doc) return json.Marshal(chargerDetailsDoc{SN: sn, Views: out})
}
// askViews asks a batch of views at once and returns them in the order given —
// concurrency is for the waiting, not for the reading, and a card whose boxes
// reorder between refreshes is a card nobody can read against itself.
func (p *Plugin) askViews(ctx context.Context, reqs []detailRequest) []chargerDetailView {
out := make([]chargerDetailView, len(reqs))
sem := make(chan struct{}, detailFanout)
var wg sync.WaitGroup
for i, req := range reqs {
wg.Add(1)
go func(i int, req detailRequest) {
defer wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
view := chargerDetailView{ID: req.id}
body, err := p.apiRequest(ctx, req.endpoint, req.payload)
if err != nil {
view.Error = shorten(err.Error())
} else {
attrs := map[string]string{}
flattenInto(attrs, "", dataValue(body))
if len(attrs) > 0 {
view.Attrs = attrs
}
}
out[i] = view
}(i, req)
}
wg.Wait()
return out
}
// siteIDFrom reads the site this charger belongs to out of the by-serial lookup,
// under whichever key that view used for it.
func siteIDFrom(views []chargerDetailView) string {
for _, v := range views {
if v.ID != "siteBySn" {
continue
}
for _, key := range []string{"site_id", "siteId", "station_id", "site_info.site_id"} {
if id := strings.TrimSpace(v.Attrs[key]); id != "" {
return id
}
}
}
return ""
}
// noteOcppSource names the OCPP backend the charger is pointed at. The per-
// charger view reports it as a bare number ("source 0"); the account's endpoint
// list is where those numbers have addresses, so the two are read together and
// the answer is said once, as the view's note. When the list does not carry the
// number, nothing is said — a guessed backend is worse than a plain number.
func noteOcppSource(views []chargerDetailView) {
var ocpp *chargerDetailView
var endpoints map[string]string
for i := range views {
switch views[i].ID {
case "ocpp":
ocpp = &views[i]
case "ocppEndpoints":
endpoints = views[i].Attrs
}
}
if ocpp == nil || len(ocpp.Attrs) == 0 || len(endpoints) == 0 {
return
}
source := strings.TrimSpace(ocpp.Attrs["source"])
if source == "" {
return
}
if url := endpointForSource(endpoints, source); url != "" {
ocpp.Note = "source " + source + " = " + url
}
}
// endpointForSource finds the address listed under a source number. The list
// arrives flattened — list[0].source, list[0].url and whatever else it carries —
// so the entry whose source matches is found first, and its address taken from
// that same entry.
func endpointForSource(endpoints map[string]string, source string) string {
prefix := ""
for key, val := range endpoints {
if !strings.HasSuffix(key, ".source") || strings.TrimSpace(val) != source {
continue
}
prefix = strings.TrimSuffix(key, ".source")
break
}
if prefix == "" {
return ""
}
for _, field := range []string{".url", ".endpoint", ".address", ".ocpp_url", ".server_url", ".name"} {
if v := strings.TrimSpace(endpoints[prefix+field]); v != "" {
return v
}
}
return ""
} }
// dataValue returns a response's "data", whatever shape it came in: these views // dataValue returns a response's "data", whatever shape it came in: these views
@@ -0,0 +1,97 @@
package ankersolix
import "testing"
// The site views are only worth asking for once the by-serial lookup has found a
// site, and that lookup names it differently depending on which shape answered.
func TestSiteIDFromReadsWhicheverKeyTheLookupUsed(t *testing.T) {
cases := []struct {
name string
attrs map[string]string
want string
}{
{"snake case", map[string]string{"site_id": "s-1"}, "s-1"},
{"camel case", map[string]string{"siteId": "s-2"}, "s-2"},
{"nested", map[string]string{"site_info.site_id": "s-3"}, "s-3"},
{"standalone charger", map[string]string{"device_sn": "AT1"}, ""},
{"blank is not an answer", map[string]string{"site_id": " "}, ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
views := []chargerDetailView{{ID: "ocpp", Attrs: map[string]string{"site_id": "wrong"}}, {ID: "siteBySn", Attrs: tc.attrs}}
if got := siteIDFrom(views); got != tc.want {
t.Fatalf("siteIDFrom = %q, want %q", got, tc.want)
}
})
}
}
// "source 0" is a number until the account's endpoint list gives it an address.
func TestNoteOcppSourceNamesTheBackend(t *testing.T) {
views := []chargerDetailView{
{ID: "ocpp", Attrs: map[string]string{"source": "1"}},
{ID: "ocppEndpoints", Attrs: map[string]string{
"list[0].source": "0", "list[0].url": "wss://ocpp.anker.example/0",
"list[1].source": "1", "list[1].url": "wss://ocpp.anker.example/1",
}},
}
noteOcppSource(views)
if want := "source 1 = wss://ocpp.anker.example/1"; views[0].Note != want {
t.Fatalf("note = %q, want %q", views[0].Note, want)
}
}
// A number the list does not carry stays a number: a guessed backend would be
// worse than saying nothing.
func TestNoteOcppSourceSaysNothingWhenTheListCannotAnswer(t *testing.T) {
views := []chargerDetailView{
{ID: "ocpp", Attrs: map[string]string{"source": "7"}},
{ID: "ocppEndpoints", Attrs: map[string]string{"list[0].source": "0", "list[0].url": "wss://x/0"}},
}
noteOcppSource(views)
if views[0].Note != "" {
t.Fatalf("note = %q, want none", views[0].Note)
}
}
// The entry's own address, not a neighbour's.
func TestEndpointForSourceStaysWithinItsEntry(t *testing.T) {
endpoints := map[string]string{
"list[0].source": "0", "list[0].endpoint": "wss://a",
"list[1].source": "2", "list[1].endpoint": "wss://b",
}
if got := endpointForSource(endpoints, "2"); got != "wss://b" {
t.Fatalf("endpointForSource = %q, want wss://b", got)
}
if got := endpointForSource(endpoints, "3"); got != "" {
t.Fatalf("endpointForSource = %q, want empty", got)
}
}
// The multi-serial views accept either spelling, and reject neither silently.
func TestSerialList(t *testing.T) {
if got := serialList(invokeParams{SN: "AT1"}); len(got) != 1 || got[0] != "AT1" {
t.Fatalf("single serial = %v", got)
}
got := serialList(invokeParams{SN: "AT1", SNs: []string{"AT2", " ", "AT3"}})
if len(got) != 2 || got[0] != "AT2" || got[1] != "AT3" {
t.Fatalf("several serials = %v", got)
}
if got := serialList(invokeParams{}); len(got) != 0 {
t.Fatalf("nothing given = %v", got)
}
}
// The paged and multi-view endpoints get a sane ask when the caller does not
// care, rather than a zero the cloud reads as "no page at all".
func TestPagingAndViewDefaults(t *testing.T) {
if pageNum(0) != 1 || pageNum(3) != 3 {
t.Fatalf("pageNum: %d %d", pageNum(0), pageNum(3))
}
if pageSize(0) != 20 || pageSize(500) != 20 || pageSize(50) != 50 {
t.Fatalf("pageSize: %d %d %d", pageSize(0), pageSize(500), pageSize(50))
}
if upgradeRecordView(0) != 1 || upgradeRecordView(4) != 1 || upgradeRecordView(2) != 2 {
t.Fatalf("upgradeRecordView: %d %d %d", upgradeRecordView(0), upgradeRecordView(4), upgradeRecordView(2))
}
}
@@ -44,11 +44,14 @@ import (
"crypto/x509" "crypto/x509"
"encoding/base64" "encoding/base64"
"encoding/binary" "encoding/binary"
"encoding/hex"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"log"
"math/big" "math/big"
"net" "net"
"os"
"strings" "strings"
"sync" "sync"
"time" "time"
@@ -90,6 +93,17 @@ const (
// having to reach it first. // having to reach it first.
statusWait = 12 * time.Second statusWait = 12 * time.Second
// settingsMaxAge is how old the settings half may be before a status read
// asks for it again; settingsWait is how long that read then waits for the
// answer, and statusReqTries how many unanswered requests it takes before a
// charger is treated as one whose firmware ignores the message — after which
// the request still goes out, but no read pays the wait for it. That verdict
// is undone by the charger answering (see ingest): it describes a spell of
// silence, not a permanent property of the firmware.
settingsMaxAge = 10 * time.Minute
settingsWait = 4 * time.Second
statusReqTries = 3
// commandWait is how long a command waits for the charger's confirmation // commandWait is how long a command waits for the charger's confirmation
// message. A command is fire-and-forget on the wire, so this only decides // message. A command is fire-and-forget on the wire, so this only decides
// whether we can say the charger answered — not whether it was sent. // whether we can say the charger answered — not whether it was sent.
@@ -262,6 +276,22 @@ type deviceState struct {
telemetryAt time.Time telemetryAt time.Time
settingsAt time.Time settingsAt time.Time
triggeredUntil time.Time triggeredUntil time.Time
// The card half, kept beside the readings rather than in them: when the
// reader last reported a card and which, and when the charger last published
// its card list and what was in it. Each carries its own time because both
// are waited on — a value that was already there before the question was
// asked is not an answer to it.
cardReadAt time.Time
cardRead string
cardsAt time.Time
cards []string
// How many status requests this charger has been asked and not answered.
// The request is cheap to send and is sent regardless; what it buys is the
// right to wait a few seconds for the reply, and a charger whose firmware
// ignores the message should not cost every later read that wait.
statusReqMisses int
} }
// mqttClient returns the account's broker connection, opening one if there is // mqttClient returns the account's broker connection, opening one if there is
@@ -454,15 +484,46 @@ func (c *mqttConn) idleLoop() {
} }
} }
// mqttFrameLog writes a line for every inbound frame — the ones this package can
// read and, the whole point, the ones it cannot. Off unless ANKER_MQTT_FRAME_LOG
// is set on the server: it exists to put a name to a frame nobody has named yet
// (a card held against the reader, say, or one of the two types the map lists as
// unnamed), not to write a line per telemetry message on a running server.
var mqttFrameLog = os.Getenv("ANKER_MQTT_FRAME_LOG") != ""
// frameLogLine is that line. The bytes are the part that matters — a frame this
// package drops is unreadable here but perfectly readable afterwards — so they
// are always in it, capped so one long frame cannot fill a log.
func frameLogLine(sn, topic string, data []byte, msgType string, values map[string]any, err error) string {
hexed := hex.EncodeToString(data)
if len(hexed) > 1024 {
hexed = hexed[:1024] + "..."
}
if err != nil {
return fmt.Sprintf("ANKER-MQTT FRAME sn=%s topic=%s len=%d unreadable=%q hex=%s",
sn, topic, len(data), err.Error(), hexed)
}
return fmt.Sprintf("ANKER-MQTT FRAME sn=%s topic=%s len=%d type=%s fields=%d hex=%s values=%v",
sn, topic, len(data), msgType, len(values), hexed, values)
}
// ingest decodes one inbound message and folds it into the sending charger's // ingest decodes one inbound message and folds it into the sending charger's
// state. Anything it cannot read is dropped: these frames come from a cloud // state. Anything it cannot read is dropped: these frames come from a cloud
// connection, and a malformed one must not be recorded as a reading. // connection, and a malformed one must not be recorded as a reading.
func (c *mqttConn) ingest(msg mqtt.Message) { func (c *mqttConn) ingest(msg mqtt.Message) {
sn, data, ok := parseEnvelope(msg) sn, data, ok := parseEnvelope(msg)
if !ok { if !ok {
if mqttFrameLog {
log.Printf("ANKER-MQTT ENVELOPE topic=%s unreadable payload=%s", msg.Topic, msg.Payload)
}
return return
} }
msgType, values, err := decodeFrame(data) msgType, values, err := decodeFrame(data)
// Logged before the drop below, because the frames worth naming are exactly
// the ones this package throws away.
if mqttFrameLog {
log.Print(frameLogLine(sn, msg.Topic, data, msgType, values, err))
}
if err != nil || len(values) == 0 { if err != nil || len(values) == 0 {
return return
} }
@@ -478,6 +539,18 @@ func (c *mqttConn) ingest(msg mqtt.Message) {
st.values[k] = v st.values[k] = v
} }
now := time.Now() now := time.Now()
// The card frames are stamped separately: a tap and a card list are answers
// to questions this package asks one at a time, and each waits for its own.
if s, ok := values["rfidCardRead"].(string); ok && s != "" {
st.cardRead, st.cardReadAt = s, now
} else if msgType == msgEVCardRead {
// The window closed with nothing tapped. That is an answer too, and the
// wait must end on it rather than run to its own timeout.
st.cardRead, st.cardReadAt = "", now
}
if cards, ok := values["rfidCards"].([]string); ok {
st.cards, st.cardsAt = cards, now
}
// Only a message this package can name counts as a report. An unnamed one // Only a message this package can name counts as a report. An unnamed one
// still leaves its fields behind, but it must not stamp settingsAt: that // still leaves its fields behind, but it must not stamp settingsAt: that
// timestamp is what a control command waits on to say the charger // timestamp is what a control command waits on to say the charger
@@ -487,6 +560,12 @@ func (c *mqttConn) ingest(msg mqtt.Message) {
st.telemetryAt = now st.telemetryAt = now
case evMessages[msgType] != nil: case evMessages[msgType] != nil:
st.settingsAt = now st.settingsAt = now
// It does report its settings after all, so whatever made it look like a
// firmware that ignores the request has passed. Without this the verdict
// was permanent — the counter only ever went up — and a charger that
// missed three requests early on was never waited for again, however
// freely it answered afterwards.
st.statusReqMisses = 0
} }
c.wakeLocked() c.wakeLocked()
} }
@@ -569,6 +648,27 @@ func (c *mqttConn) listen(ctx context.Context, model, sn string) error {
c.mu.Lock() c.mu.Lock()
c.subs[topic] = true c.subs[topic] = true
c.mu.Unlock() c.mu.Unlock()
// With the frame log on, listen to the charger's command topic as well. The
// data topic carries only what the charger says; the commands the Anker app
// sends it — the half no capture here has ever seen — go to this one, and a
// command nobody has a name for cannot be named without reading it first.
// Off by default: it is a diagnostic subscription, not part of control.
if mqttFrameLog {
cmd := commandTopic(c.creds, model, sn)
c.mu.Lock()
seen := c.subs[cmd]
c.mu.Unlock()
if !seen {
if err := c.client.Subscribe(ctx, cmd); err == nil {
c.mu.Lock()
c.subs[cmd] = true
c.mu.Unlock()
log.Printf("ANKER-MQTT listening to the command topic %s (frame log)", cmd)
} else {
log.Printf("ANKER-MQTT cannot listen to the command topic %s: %v", cmd, err)
}
}
}
return nil return nil
} }
@@ -671,6 +771,28 @@ func (c *mqttConn) snapshotOf(sn string) (map[string]any, time.Time, time.Time,
return out, st.telemetryAt, st.settingsAt, st.triggeredUntil return out, st.telemetryAt, st.settingsAt, st.triggeredUntil
} }
// noteStatusMiss records that a status request went unanswered, and reports how
// many have now in a row.
func (c *mqttConn) noteStatusMiss(sn string) int {
c.mu.Lock()
defer c.mu.Unlock()
st := c.devices[sn]
if st == nil {
return 0
}
st.statusReqMisses++
return st.statusReqMisses
}
// statusReqAnswered reports whether this charger has answered a status request
// recently enough to be worth waiting for again.
func (c *mqttConn) statusReqAnswered(sn string) bool {
c.mu.Lock()
defer c.mu.Unlock()
st := c.devices[sn]
return st == nil || st.statusReqMisses < statusReqTries
}
// noteTrigger records how long the charger has been asked to keep streaming. // noteTrigger records how long the charger has been asked to keep streaming.
func (c *mqttConn) noteTrigger(sn string, until time.Time) { func (c *mqttConn) noteTrigger(sn string, until time.Time) {
c.mu.Lock() c.mu.Lock()
@@ -704,6 +826,20 @@ func (p *Plugin) mqttTrigger(ctx context.Context, c *mqttConn, model, sn string,
return nil return nil
} }
// mqttStatusRequest asks the charger to publish what it is set to. The trigger
// above buys telemetry and nothing else: the settings half arrives on its own
// message, and otherwise only after a command, which is why a charger that has
// been read but never commanded reports live amps and knows nothing about its
// own schedule, its Modbus server or its firmware. This is the message the app
// uses for that — a status request the charger answers with 0840.
func (p *Plugin) mqttStatusRequest(ctx context.Context, c *mqttConn, model, sn string) error {
frame, err := encodeFrame(msgEVStatusReq, []cmdField{bareTimestampField(time.Now())})
if err != nil {
return err
}
return c.publishFrame(ctx, model, sn, frame, 0)
}
// mqttSetMode sends the start / stop / skip-delay / boost command. // mqttSetMode sends the start / stop / skip-delay / boost command.
func (p *Plugin) mqttSetMode(ctx context.Context, c *mqttConn, model, sn, mode string) error { func (p *Plugin) mqttSetMode(ctx context.Context, c *mqttConn, model, sn, mode string) error {
v, ok := mqttModeValues[mode] v, ok := mqttModeValues[mode]
@@ -722,6 +858,25 @@ func (p *Plugin) mqttSetMode(ctx context.Context, c *mqttConn, model, sn, mode s
return c.publishFrame(ctx, model, sn, frame, mqttEncodingMode) return c.publishFrame(ctx, model, sn, frame, mqttEncodingMode)
} }
// mqttRestart reboots the charger. It is the cloud's answer to the OCPP reset —
// the one thing the phone can do to a charger that no register holds and no CSMS
// reaches when the charger is not on one. The charger goes away and comes back,
// so nothing confirms it: the acknowledgement would have to arrive from a device
// that is rebooting.
func (p *Plugin) mqttRestart(ctx context.Context, c *mqttConn, model, sn string) error {
frame, err := encodeFrame(msgEVPowerMode, []cmdField{
rawField(0xa1, 0x22),
uintField(0xa2, powerModeRestart),
timestampField(time.Now()),
})
if err != nil {
return err
}
// The same encoding_type the mode command carries: the charger expects the
// field on these two messages and on no others.
return c.publishFrame(ctx, model, sn, frame, mqttEncodingMode)
}
// mqttSetMaxCurrent sets the charging current ceiling, in amps. The limit is // mqttSetMaxCurrent sets the charging current ceiling, in amps. The limit is
// checked by the same rule the Modbus path uses, because the rule is the // checked by the same rule the Modbus path uses, because the rule is the
// charger's: the transport differs, the charger does not. // charger's: the transport differs, the charger does not.
@@ -265,3 +265,27 @@ func TestClientIDDoesNotCollideWithTheApp(t *testing.T) {
t.Errorf("client id %q does not fall back to the user id", got) t.Errorf("client id %q does not fall back to the user id", got)
} }
} }
// A charger that goes quiet long enough to be written off is not written off for
// good. The miss counter decides whether a status read waits for the settings
// frame at all, so a counter that only ever rose meant one early patch of
// silence cost every later read its settings — which is the half the settings
// card is drawn from.
func TestAnsweringClearsTheStatusRequestMisses(t *testing.T) {
c := &mqttConn{subs: map[string]bool{}, devices: map[string]*deviceState{}, shutdown: make(chan struct{})}
// Three unanswered requests: the reads stop paying the wait.
c.ingest(envelope(t, "SN1", buildInbound(t, msgEVTelemetry, field(0xbb, typeUint8, 0x02))))
for i := 0; i < statusReqTries; i++ {
c.noteStatusMiss("SN1")
}
if c.statusReqAnswered("SN1") {
t.Fatalf("after %d misses the charger should not be waited for", statusReqTries)
}
// Then it answers one.
c.ingest(envelope(t, "SN1", buildInbound(t, msgEVParams, field(0xa8, typeInt16LE, 0x40, 0x01))))
if !c.statusReqAnswered("SN1") {
t.Error("a charger that reported its settings is still being written off")
}
}
@@ -0,0 +1,36 @@
package ankersolix
import (
"errors"
"strings"
"testing"
)
// The frame nobody can read is the one worth logging, so its bytes have to be in
// the line — that is the whole of what a capture is.
func TestFrameLogLineCarriesTheBytes(t *testing.T) {
data := []byte{0xff, 0x09, 0x01, 0x02}
line := frameLogLine("EVSN1", "dt/app/A5191/EVSN1/x", data, "", nil, errors.New("bad marker"))
if !strings.Contains(line, "hex=ff090102") {
t.Errorf("unreadable frame: %q, want the bytes in it", line)
}
if !strings.Contains(line, "unreadable=") || !strings.Contains(line, "EVSN1") {
t.Errorf("unreadable frame: %q, want the reason and the serial", line)
}
line = frameLogLine("EVSN1", "t", data, "0857", map[string]any{"a": 1}, nil)
if !strings.Contains(line, "type=0857") || !strings.Contains(line, "fields=1") {
t.Errorf("readable frame: %q, want its type and field count", line)
}
}
// One long frame must not fill a log file.
func TestFrameLogLineCapsTheHex(t *testing.T) {
line := frameLogLine("EVSN1", "t", make([]byte, 4096), "0410", nil, nil)
if len(line) > 1400 {
t.Errorf("line is %d chars, want it capped", len(line))
}
if !strings.Contains(line, "...") {
t.Error("a truncated frame should say so")
}
}
@@ -168,3 +168,90 @@ func TestPruneSessionsDropsIdle(t *testing.T) {
t.Error("a session in use must not be pruned") t.Error("a session in use must not be pruned")
} }
} }
// TestRetiredEndpointSpendsNoLoginLoop is the ha-anker-solix #659 regression:
// Anker retired an endpoint by answering it 403, and a client that took every
// 403 for an evicted token logged in afresh on each poll until the IP was banned
// for 24 hours. A token that is days old earns one fresh login; once a fresh
// token is refused too, the endpoint is left alone, and the polls that follow
// spend nothing on it.
func TestRetiredEndpointSpendsNoLoginLoop(t *testing.T) {
logins, gone := 0, 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, epLogin):
logins++
_, _ = w.Write([]byte(`{"code":0,"msg":"success!","data":{"auth_token":"t` + strconv.Itoa(logins) +
`","user_id":"u","token_expires_at":` + strconv.FormatInt(time.Now().Add(24*time.Hour).Unix(), 10) + `}}`))
case strings.HasSuffix(r.URL.Path, "/retired"):
gone++
w.WriteHeader(http.StatusForbidden)
default:
_, _ = w.Write([]byte(`{"code":0,"msg":"success!","data":{}}`))
}
}))
defer srv.Close()
p := &Plugin{}
if err := p.Init(context.Background(), map[string]string{"email": "retired@example.com", "password": "pw"}); err != nil {
t.Fatal(err)
}
p.apiBase = srv.URL
p.sess = sessionFor(srv.URL, "retired@example.com", "pw")
// A token from days ago, as a long-running server holds.
p.sess.tok = &tokenInfo{authToken: "old", gtoken: "g", expiration: time.Now().Add(time.Hour), issued: time.Now().Add(-72 * time.Hour)}
for i := 0; i < 5; i++ {
if _, err := p.apiRequest(context.Background(), "retired", map[string]any{}); err == nil {
t.Fatal("a refused endpoint must still fail")
}
}
if logins != 1 {
t.Errorf("logins over five polls = %d, want 1", logins)
}
if gone != 6 {
t.Errorf("requests to the endpoint = %d, want 6 (one retry, then one per poll)", gone)
}
// Other endpoints keep working on the token that login bought.
if _, err := p.apiRequest(context.Background(), "alive", map[string]any{}); err != nil {
t.Errorf("a working endpoint failed: %v", err)
}
}
// TestFreshTokenRefusalIsTheEndpoint: a token a minute old was not evicted, so a
// 403 for it spends no login at all.
func TestFreshTokenRefusalIsTheEndpoint(t *testing.T) {
logins := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, epLogin) {
logins++
}
w.WriteHeader(http.StatusForbidden)
}))
defer srv.Close()
p := &Plugin{}
if err := p.Init(context.Background(), map[string]string{"email": "fresh@example.com", "password": "pw"}); err != nil {
t.Fatal(err)
}
p.apiBase = srv.URL
p.sess = sessionFor(srv.URL, "fresh@example.com", "pw")
p.sess.tok = &tokenInfo{authToken: "new", gtoken: "g", expiration: time.Now().Add(time.Hour), issued: time.Now().Add(-time.Minute)}
if _, err := p.apiRequest(context.Background(), "anything", map[string]any{}); err == nil {
t.Fatal("expected the 403 to fail the request")
}
if logins != 0 {
t.Errorf("logins = %d, want 0", logins)
}
}
// TestLoginBanWaitsAnHour: code 100041 is a 24-hour IP ban, and every attempt
// inside it is one more against the count.
func TestLoginBanWaitsAnHour(t *testing.T) {
s := &session{}
s.noteLogin(&loginRejected{code: codeLoginBanned, msg: "Hit max login error limit"})
if wait := time.Until(s.loginRetryAt); wait < loginBanWait-time.Second {
t.Errorf("banned login waits %s, want at least %s", wait, loginBanWait)
}
}
@@ -0,0 +1,270 @@
package ankersolix
// Cards, at the charger rather than at the account.
//
// The Anker app offers two ways to add an RFID card: type its number, which is
// the account write in rfidcards.go, or hold the card against the reader inside
// a twenty-second window. The second one never touches the REST API. It is three
// messages on the charger's own MQTT topics, captured from the app's traffic:
//
// 0108 a2=7 open the reader -> 0908, with the UID when a card is
// tapped and without one when the
// window closes empty
// 0103 a2=1 write the card -> 0903, then 0904
// 0103 a2=2 remove it -> the same pair
// 0104 ask for the card list -> 0904
//
// Nothing here is inferred: every frame above is one this connector watched the
// app send and the charger answer. What is inferred is the account write those
// three replace, which is why a card written here is checked by reading the
// charger's own list back rather than by trusting the write.
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"time"
)
const (
// cardReadWindow is how long the reader stays open. The app counts twenty
// seconds down; a couple more allow for the answer's trip back through the
// cloud, and the charger closes the window on its own either way.
cardReadWindow = 24 * time.Second
// cardWriteWait is how long a write waits for the charger to republish its
// list. The answer arrived within a second in every capture.
cardWriteWait = 8 * time.Second
// cardWriteAdd and cardWriteRemove are the two values the write takes.
cardWriteAdd uint8 = 1
cardWriteRemove uint8 = 2
)
// cardReadResult is what a scan answers with: the card that was tapped, or the
// plain fact that nothing was.
type cardReadResult struct {
SN string `json:"sn"`
Card string `json:"card,omitempty"`
Tapped bool `json:"tapped"`
Seconds int `json:"windowSeconds"`
}
// mqttReadCard opens the charger's card reader and waits for a card. The
// charger answers either way — with a UID when one is tapped, without when the
// window closes — so a scan that finds nothing is an answer rather than a
// timeout, and says so.
func (p *Plugin) mqttReadCard(ctx context.Context, sn string) (json.RawMessage, error) {
model, err := p.chargerModel(ctx, sn)
if err != nil {
return nil, err
}
conn, err := p.mqttClient(ctx)
if err != nil {
return nil, err
}
// Listen before asking: the charger answers in under a second, and a
// subscription made afterwards would miss it.
if err := conn.listen(ctx, model, sn); err != nil {
return nil, err
}
since := conn.cardReadAt(sn)
// Field for field what the app sends, timestamp included — which is to say
// not included: the app's own reader-open frame carries none, and this
// command is copied rather than composed.
frame, err := encodeFrame(msgEVPowerMode, []cmdField{
rawField(0xa1, 0x22),
uintField(0xa2, powerModeReadCard),
})
if err != nil {
return nil, err
}
// The same encoding the other power-mode command carries; this is that
// command with a different value, and the charger expects the field on it.
if err := conn.publishFrame(ctx, model, sn, frame, mqttEncodingMode); err != nil {
return nil, fmt.Errorf("anker-solix: opening the card reader on %s: %w", sn, err)
}
ok, err := conn.waitFor(ctx, sn, func(st *deviceState) bool {
return st.cardReadAt.After(since)
}, cardReadWindow)
if err != nil {
return nil, err
}
out := cardReadResult{SN: sn, Seconds: int(cardReadWindow / time.Second)}
if ok {
out.Card = conn.cardRead(sn)
out.Tapped = out.Card != ""
}
return json.Marshal(out)
}
// cardWriteResult is what a device write answers with: what was asked, and the
// charger's own list afterwards. Present is read from that list — the charger
// says 0903 to everything, and a write is judged by what it changed.
type cardWriteResult struct {
SN string `json:"sn"`
Action string `json:"action"` // save | delete
Number string `json:"cardNumber"`
Present bool `json:"present"`
Cards []string `json:"cards"`
Via string `json:"via"` // charger
Detail string `json:"detail,omitempty"`
}
// mqttWriteCard adds a card to the charger or removes one, and then reads the
// charger's list back. Both halves are the app's own messages.
func (p *Plugin) mqttWriteCard(ctx context.Context, sn, number string, add bool) (*cardWriteResult, error) {
number = normalizeCardNumber(number)
uid, err := hex.DecodeString(number)
if err != nil || len(uid) == 0 {
return nil, fmt.Errorf("anker-solix: %q is not a card number: the charger takes the UID as hex", number)
}
model, err := p.chargerModel(ctx, sn)
if err != nil {
return nil, err
}
conn, err := p.mqttClient(ctx)
if err != nil {
return nil, err
}
if err := conn.listen(ctx, model, sn); err != nil {
return nil, err
}
since := conn.cardsAt(sn)
action := cardWriteAdd
name := "save"
if !add {
action, name = cardWriteRemove, "delete"
}
frame, err := encodeFrame(msgEVCardWrite, []cmdField{
rawField(0xa1, 0x22),
uintField(0xa2, action),
uintField(0xa3, 1),
bytesField(0xa4, uid),
})
if err != nil {
return nil, err
}
if err := conn.publishFrame(ctx, model, sn, frame, 0); err != nil {
return nil, fmt.Errorf("anker-solix: writing card %s to %s: %w", number, sn, err)
}
out := &cardWriteResult{SN: sn, Action: name, Number: number, Via: "charger"}
cards, err := p.mqttCardList(ctx, conn, model, sn, since)
if err != nil {
// The write went out; what it did is simply unknown, which is not the
// same as it having failed and must not be reported as either.
out.Detail = err.Error()
return out, nil
}
out.Cards = cards
for _, c := range cards {
if normalizeCardNumber(c) == number {
out.Present = true
break
}
}
return out, nil
}
// mqttCardList is the charger's own list of the cards it will open for. A write
// republishes it unasked; when it does not, it is asked for.
func (p *Plugin) mqttCardList(ctx context.Context, conn *mqttConn, model, sn string, since time.Time) ([]string, error) {
ok, err := conn.waitFor(ctx, sn, func(st *deviceState) bool {
return st.cardsAt.After(since)
}, cardWriteWait)
if err != nil {
return nil, err
}
if !ok {
// Nothing came unasked, so ask.
frame, err := encodeFrame(msgEVCardListReq, []cmdField{rawField(0xa1, 0x22)})
if err != nil {
return nil, err
}
if err := conn.publishFrame(ctx, model, sn, frame, 0); err != nil {
return nil, err
}
ok, err = conn.waitFor(ctx, sn, func(st *deviceState) bool {
return st.cardsAt.After(since)
}, cardWriteWait)
if err != nil {
return nil, err
}
}
if !ok {
return nil, fmt.Errorf("anker-solix: charger %s did not answer with its card list", sn)
}
return conn.cards(sn), nil
}
// mqttChargerCards asks the charger for its list on its own, for a caller that
// wants to know what the device holds rather than what the account does.
func (p *Plugin) mqttChargerCards(ctx context.Context, sn string) (json.RawMessage, error) {
model, err := p.chargerModel(ctx, sn)
if err != nil {
return nil, err
}
conn, err := p.mqttClient(ctx)
if err != nil {
return nil, err
}
if err := conn.listen(ctx, model, sn); err != nil {
return nil, err
}
since := conn.cardsAt(sn)
frame, err := encodeFrame(msgEVCardListReq, []cmdField{rawField(0xa1, 0x22)})
if err != nil {
return nil, err
}
if err := conn.publishFrame(ctx, model, sn, frame, 0); err != nil {
return nil, err
}
cards, err := p.mqttCardList(ctx, conn, model, sn, since)
if err != nil {
return nil, err
}
return json.Marshal(map[string]any{"sn": sn, "cards": cards, "via": "charger"})
}
// ---- the card half of a device's state, read out from under the lock --------
func (c *mqttConn) cardReadAt(sn string) time.Time {
c.mu.Lock()
defer c.mu.Unlock()
if st := c.devices[sn]; st != nil {
return st.cardReadAt
}
return time.Time{}
}
func (c *mqttConn) cardRead(sn string) string {
c.mu.Lock()
defer c.mu.Unlock()
if st := c.devices[sn]; st != nil {
return st.cardRead
}
return ""
}
func (c *mqttConn) cardsAt(sn string) time.Time {
c.mu.Lock()
defer c.mu.Unlock()
if st := c.devices[sn]; st != nil {
return st.cardsAt
}
return time.Time{}
}
func (c *mqttConn) cards(sn string) []string {
c.mu.Lock()
defer c.mu.Unlock()
if st := c.devices[sn]; st != nil {
return append([]string(nil), st.cards...)
}
return nil
}
@@ -0,0 +1,202 @@
package ankersolix
import (
"encoding/hex"
"testing"
)
// The card-list frame, captured from a live A5191 on firmware 1.0.6.1. The nine
// UIDs in it are the nine the account's own card list answered with, which is
// what named this frame in the first place.
const capturedCardFrame = "ff09540003010f090400a10132a2020109a3080404dfe672151a90a4050457c4df2a" +
"a505046745bb4ea6050477dfd24ea70504d7b1c44ea80504778acd4ea905048a3cbc3f" +
"aa0504da7cb93fab05044754dc2a00"
func TestDecodeCardListFrame(t *testing.T) {
data, err := hex.DecodeString(capturedCardFrame)
if err != nil {
t.Fatal(err)
}
msgType, values, err := decodeFrame(data)
if err != nil {
t.Fatalf("decodeFrame: %v", err)
}
if msgType != msgEVCards {
t.Fatalf("msgType = %q, want %q", msgType, msgEVCards)
}
if n, _ := values["rfidCardCount"].(float64); n != 9 {
t.Errorf("rfidCardCount = %v, want 9", values["rfidCardCount"])
}
cards, ok := values["rfidCards"].([]string)
if !ok {
t.Fatalf("rfidCards = %T, want []string", values["rfidCards"])
}
// In the charger's own order: newest first, which is the reverse of the way
// the account lists them.
want := []string{
"04DFE672151A90", "57C4DF2A", "6745BB4E", "77DFD24E", "D7B1C44E",
"778ACD4E", "8A3CBC3F", "DA7CB93F", "4754DC2A",
}
if len(cards) != len(want) {
t.Fatalf("got %d cards, want %d: %v", len(cards), len(want), cards)
}
for i, w := range want {
if cards[i] != w {
t.Errorf("card %d = %q, want %q", i, cards[i], w)
}
}
}
// A UID is an identifier, not a quantity: read as a big-endian number, 57C4DF2A
// becomes 1472519978 and matches nothing the account ever prints.
func TestCardUIDsAreHexNotNumbers(t *testing.T) {
v, ok := decodeValue(typeBytes, []byte{0x57, 0xc4, 0xdf, 0x2a}, mqttField{})
if !ok || v != "57C4DF2A" {
t.Fatalf("decodeValue = %v (%T), want \"57C4DF2A\"", v, v)
}
}
// The charger's own view of its OCPP backend, from the same capture.
func TestDecodeOcppInfoFrame(t *testing.T) {
data, err := hex.DecodeString("ff096a0003010f091100a10132a20600416e6b6572a331007773733a2f2f" +
"6368617267696e672d6f63707070726f78792d65752d70726f642e616e6b65722e636f6d2f6f6370706a" +
"a4020100a51200415432444b325a31463438333030313134a60100a70100a80100a7")
if err != nil {
t.Fatal(err)
}
msgType, values, err := decodeFrame(data)
if err != nil {
t.Fatalf("decodeFrame: %v", err)
}
if msgType != msgEVOcppInfo {
t.Fatalf("msgType = %q, want %q", msgType, msgEVOcppInfo)
}
if got := values["ocppBackendName"]; got != "Anker" {
t.Errorf("ocppBackendName = %v, want Anker", got)
}
if got := values["ocppBackendUrl"]; got != "wss://charging-ocppproxy-eu-prod.anker.com/ocppj" {
t.Errorf("ocppBackendUrl = %v", got)
}
if got, _ := values["ocppSource"].(float64); got != 0 {
t.Errorf("ocppSource = %v, want 0 — the number the account's OCPP view leaves bare", values["ocppSource"])
}
if got := values["ocppChargePointId"]; got != "AT2DK2Z1F48300114" {
t.Errorf("ocppChargePointId = %v", got)
}
}
// The tap itself, captured while a card was enrolled at the charger: the reader
// reports the UID the moment the card touches it.
func TestDecodeCardReadFrame(t *testing.T) {
data, err := hex.DecodeString("ff091b0003010f090800a10132a20107a3080404dfe672151a90a8")
if err != nil {
t.Fatal(err)
}
msgType, values, err := decodeFrame(data)
if err != nil {
t.Fatalf("decodeFrame: %v", err)
}
if msgType != msgEVCardRead {
t.Fatalf("msgType = %q, want %q", msgType, msgEVCardRead)
}
if got := values["rfidCardRead"]; got != "04DFE672151A90" {
t.Errorf("rfidCardRead = %v, want 04DFE672151A90", got)
}
}
// The same frame when the window closed with nothing tapped: no UID, and the
// absence is the answer.
func TestCardReadWithoutACard(t *testing.T) {
data, err := hex.DecodeString("ff09110003010f090801a10132a20107dc")
if err != nil {
t.Fatal(err)
}
msgType, values, err := decodeFrame(data)
if err != nil {
t.Fatalf("decodeFrame: %v", err)
}
if msgType != msgEVCardRead {
t.Fatalf("msgType = %q, want %q", msgType, msgEVCardRead)
}
if _, ok := values["rfidCardRead"]; ok {
t.Errorf("rfidCardRead = %v, want it absent", values["rfidCardRead"])
}
}
// The two writes the Anker app sent, caught on the charger's own command topic:
// the same card removed and then added back, the action the only difference.
func TestDecodeCardWriteCommands(t *testing.T) {
for _, tc := range []struct {
name, hex string
action float64
}{
{"delete", "ff091f0003000f0103a10122a2020102a3020101a4080404dfe672151a901f", 2},
{"add", "ff091f0003000f0103a10122a2020101a3020101a4080404dfe672151a901c", 1},
} {
data, err := hex.DecodeString(tc.hex)
if err != nil {
t.Fatal(err)
}
msgType, values, err := decodeFrame(data)
if err != nil {
t.Fatalf("%s: decodeFrame: %v", tc.name, err)
}
if msgType != msgEVCardWrite {
t.Fatalf("%s: msgType = %q, want %q", tc.name, msgType, msgEVCardWrite)
}
if got, _ := values["cardWriteAction"].(float64); got != tc.action {
t.Errorf("%s: cardWriteAction = %v, want %v", tc.name, values["cardWriteAction"], tc.action)
}
if got := values["cardWritten"]; got != "04DFE672151A90" {
t.Errorf("%s: cardWritten = %v, want the UID", tc.name, got)
}
}
}
// The frames this connector sends to enrol a card, against the ones the Anker
// app was captured sending. They are compared byte for byte: neither carries a
// timestamp, so there is nothing in them that can differ between two senders,
// and anything that does differ is a difference the charger would see.
func TestCardCommandsMatchTheApp(t *testing.T) {
open, err := encodeFrame(msgEVPowerMode, []cmdField{
rawField(0xa1, 0x22),
uintField(0xa2, powerModeReadCard),
})
if err != nil {
t.Fatal(err)
}
if got, want := hex.EncodeToString(open), "ff09110003000f0108a10122a2020107c6"; got != want {
t.Errorf("reader-open frame:\n got %s\nwant %s (the app's own)", got, want)
}
list, err := encodeFrame(msgEVCardListReq, []cmdField{rawField(0xa1, 0x22)})
if err != nil {
t.Fatal(err)
}
if got, want := hex.EncodeToString(list), "ff090d0003000f0104a1012270"; got != want {
t.Errorf("list-request frame:\n got %s\nwant %s (the app's own)", got, want)
}
uid, _ := hex.DecodeString("04DFE672151A90")
for _, tc := range []struct {
name string
action uint8
want string
}{
{"add", cardWriteAdd, "ff091f0003000f0103a10122a2020101a3020101a4080404dfe672151a901c"},
{"delete", cardWriteRemove, "ff091f0003000f0103a10122a2020102a3020101a4080404dfe672151a901f"},
} {
frame, err := encodeFrame(msgEVCardWrite, []cmdField{
rawField(0xa1, 0x22),
uintField(0xa2, tc.action),
uintField(0xa3, 1),
bytesField(0xa4, uid),
})
if err != nil {
t.Fatalf("%s: %v", tc.name, err)
}
if got := hex.EncodeToString(frame); got != tc.want {
t.Errorf("%s frame:\n got %s\nwant %s (the app's own)", tc.name, got, tc.want)
}
}
}
@@ -7,7 +7,7 @@ package ankersolix
// That frame is the same one the app sends, so a command is not a documented API // That frame is the same one the app sends, so a command is not a documented API
// call but a byte layout, reproduced here from the message maps in // call but a byte layout, reproduced here from the message maps in
// anker-solix-api (src/anker_solix_api/mqtttypes.py, mqttmap.py, mqttcmdmap.py at // anker-solix-api (src/anker_solix_api/mqtttypes.py, mqttmap.py, mqttcmdmap.py at
// v3.8.1) and checked against a live A5191. // v3.8.1, unchanged for the A5191 through v3.9.0) and checked against a live A5191.
// //
// ff 09 2-byte marker on every Anker Solix frame // ff 09 2-byte marker on every Anker Solix frame
// xx xx total length in bytes, little endian, counting the checksum // xx xx total length in bytes, little endian, counting the checksum
@@ -55,6 +55,7 @@ const (
typeUint8 byte = 0x01 typeUint8 byte = 0x01
typeInt16LE byte = 0x02 typeInt16LE byte = 0x02
typeInt32LE byte = 0x03 // "var": four bytes, though not always one value typeInt32LE byte = 0x03 // "var": four bytes, though not always one value
typeBytes byte = 0x04 // bytes that are an identifier, not a number — an RFID UID
typeFloat32 byte = 0x05 typeFloat32 byte = 0x05
typeNone byte = 0xff // this package's marker for "no type byte" typeNone byte = 0xff // this package's marker for "no type byte"
) )
@@ -68,17 +69,60 @@ const typeByteMax byte = 0x31
// Message types this package speaks, for the A5191 (V1 Smart EV Charger). // Message types this package speaks, for the A5191 (V1 Smart EV Charger).
// Outbound ones are commands, inbound ones are what the charger publishes back. // Outbound ones are commands, inbound ones are what the charger publishes back.
const ( const (
msgEVStatusReq = "0040" // ask the charger to report its parameters
msgRealtimeTrigger = "0057" // ask for the fast telemetry stream msgRealtimeTrigger = "0057" // ask for the fast telemetry stream
msgEVSettings = "0100" // the settings group: current limit, brightness, … msgEVSettings = "0100" // the settings group: current limit, brightness, …
msgEVMode = "0105" // start / stop / skip delay / boost msgEVMode = "0105" // start / stop / skip delay / boost
msgEVSchedule = "0106" // the charging schedule: switch, mode and times msgEVSchedule = "0106" // the charging schedule: switch, mode and times
msgEVBalancing = "010c" // load balancing and the main breaker limit msgEVBalancing = "010c" // load balancing and the main breaker limit
msgEVSolar = "010e" // solar charging msgEVSolar = "010e" // solar charging
msgEVPowerMode = "0108" // the device power mode: the one value restarts it
msgEVTelemetry = "0410" // fast telemetry, only while a trigger is live msgEVTelemetry = "0410" // fast telemetry, only while a trigger is live
msgEVParams = "0405" // settings and identity, sent after a command msgEVParams = "0405" // settings and identity, sent after a command
msgEVParamsAlt = "0840" // the same fields, in answer to a status request msgEVParamsAlt = "0840" // the same fields, in answer to a status request
msgEVConfirm = "0900" // the same fields again, confirming a control change msgEVConfirm = "0900" // the same fields again, confirming a control change
msgEVCharging = "0403" // a couple of charging parameters msgEVCharging = "0403" // a couple of charging parameters
// The charger's own copy of the RFID card list, published when the account
// asks it for one. Named from a live capture: nine UIDs in one frame, the
// same nine the cloud's get_device_cards answered with, in reverse order —
// newest first. The count is a field; the cards are one field each, so they
// are collected rather than mapped (see decodeFrame).
msgEVCards = "0904"
// Which OCPP backend the charger is pointed at, from the charger rather than
// from the account: the same address get_ocpp_info reports, and the source
// number that view leaves as a bare integer.
msgEVOcppInfo = "0911"
// The three commands the app sends about cards, all captured from its own
// traffic on the charger's command topic. The pattern is the connector's
// everywhere: a command 01xx is answered by the data frame 09xx.
//
// 0103 write one card: a2 = 1 add, 2 delete; a4 = the UID -> 0903, then 0904
// 0104 ask for the list -> 0904
// 0111 ask which OCPP backend -> 0911
//
// The fourth is not its own message: opening the reader is the power-mode
// command with powerModeReadCard, which is answered by 0908.
msgEVCardWrite = "0103"
msgEVCardListReq = "0104"
msgEVOcppInfoReq = "0111"
// The reader, reporting a card held against it. Captured during an
// enrol-at-the-charger: the frame arrives the moment the card is tapped,
// carrying the UID, and the charger publishes its updated card list a second
// later. The same frame arrives without a UID when the twenty-second window
// closes with nothing tapped, which is what makes the UID field the event.
msgEVCardRead = "0908"
// powerModeReadCard opens the card reader for a tap: the app sends the
// power-mode command with this value and the charger answers 0908 — with the
// UID if a card was held against it inside the twenty seconds, and without one
// if the window closed empty. Captured from the app on an A5191; the same 7
// comes back in the answer.
powerModeReadCard uint8 = 7
// powerModeRestart is the only other value the power-mode command is known to take.
// The map documents 5 and nothing else, so nothing else is sent.
powerModeRestart uint8 = 5
) )
// mqttField is one named value inside a device message. factor scales the raw // mqttField is one named value inside a device message. factor scales the raw
@@ -196,6 +240,44 @@ var evCharging = map[byte]mqttField{
0xa6: {name: "solarMinCurrentA"}, 0xa6: {name: "solarMinCurrentA"},
} }
// evCards names what is not a card in the card-list frame. The cards themselves
// start at 0xa3 and run one per field for as many as the charger holds, so they
// cannot be a map — decodeFrame collects them.
var evCards = map[byte]mqttField{
0xa2: {name: "rfidCardCount"},
}
// evCardRead names the reader's own event. a2 was 7 in every capture, with and
// without a card, so it is relayed under its own key rather than guessed at.
var evCardRead = map[byte]mqttField{
0xa3: {name: "rfidCardRead"},
}
// evCardWrite names the write the app sends. a3 was 1 on both the add and the
// delete, so it keeps its own key rather than a guessed name.
var evCardWrite = map[byte]mqttField{
0xa2: {name: "cardWriteAction"}, // 1 add, 2 delete
0xa4: {name: "cardWritten"},
}
// evOcppInfo names the charger's own view of its OCPP backend.
var evOcppInfo = map[byte]mqttField{
0xa2: {name: "ocppBackendName"},
0xa3: {name: "ocppBackendUrl"},
0xa4: {name: "ocppSource"},
0xa5: {name: "ocppChargePointId"},
}
// evInfoMessages are messages this package can name but must not treat as a
// settings report: evMessages is what stamps the timestamp a control command
// waits on, and a card list is not an acknowledgement of anything.
var evInfoMessages = map[string]map[byte]mqttField{
msgEVCards: evCards,
msgEVOcppInfo: evOcppInfo,
msgEVCardRead: evCardRead,
msgEVCardWrite: evCardWrite,
}
// evMessages selects a field map by message type. A type absent from here is one // evMessages selects a field map by message type. A type absent from here is one
// we have no map for; its frame is still parsed, but nothing is named. // we have no map for; its frame is still parsed, but nothing is named.
var evMessages = map[string]map[byte]mqttField{ var evMessages = map[string]map[byte]mqttField{
@@ -241,12 +323,29 @@ func varField(name byte, v uint32) cmdField {
return cmdField{name: name, typ: typeInt32LE, value: b} return cmdField{name: name, typ: typeInt32LE, value: b}
} }
// bytesField builds a field holding bytes that are an identifier rather than a
// number — an RFID UID, four bytes or seven, exactly as the reader reported it.
func bytesField(name byte, b []byte) cmdField {
return cmdField{name: name, typ: typeBytes, value: append([]byte(nil), b...)}
}
// timestampField is the `fe` field every command ends with: the sender's clock, // timestampField is the `fe` field every command ends with: the sender's clock,
// in whole seconds. // in whole seconds.
func timestampField(now time.Time) cmdField { func timestampField(now time.Time) cmdField {
return varField(0xfe, uint32(now.Unix())) return varField(0xfe, uint32(now.Unix()))
} }
// bareTimestampField is the timestamp the status request carries: the same
// clock as every other command, sent without its value type. The app sends it
// that way — the reference reads it as an Anker bug and keeps the whole command
// commented out because of it — and the charger answers what the app sends, so
// the oddity is reproduced rather than corrected.
func bareTimestampField(now time.Time) cmdField {
b := make([]byte, 4)
binary.LittleEndian.PutUint32(b, uint32(now.Unix()))
return cmdField{name: 0xfe, typ: typeNone, value: b}
}
// clockField builds the two-byte field the charger carries a time of day in: // clockField builds the two-byte field the charger carries a time of day in:
// the hour and the minute, least significant byte first, which is the same // the hour and the minute, least significant byte first, which is the same
// layout the decoder reads back as "HH:MM". // layout the decoder reads back as "HH:MM".
@@ -348,6 +447,9 @@ func decodeFrame(data []byte) (string, map[string]any, error) {
} }
fields := evMessages[msgType] fields := evMessages[msgType]
if fields == nil {
fields = evInfoMessages[msgType]
}
values := map[string]any{} values := map[string]any{}
for _, r := range raw { for _, r := range raw {
f, known := fields[r.name] f, known := fields[r.name]
@@ -363,9 +465,28 @@ func decodeFrame(data []byte) (string, map[string]any, error) {
values[f.name] = v values[f.name] = v
} }
} }
if msgType == msgEVCards {
values["rfidCards"] = cardsFromFields(raw)
}
return msgType, values, nil return msgType, values, nil
} }
// cardsFromFields reads the card UIDs out of a card-list frame. Every field from
// 0xa3 up is one card, in the order the charger sent them, and a UID is however
// many bytes the card has — four for the older tags, seven for the newer ones —
// so the bytes are taken as they are and read as hex, which is how the account
// prints them and how a person reads one off a card.
func cardsFromFields(raw []rawFieldBytes) []string {
out := []string{}
for _, r := range raw {
if r.name < 0xa3 || len(r.value) == 0 {
continue
}
out = append(out, strings.ToUpper(encodeHex(r.value)))
}
return out
}
// rawFieldName keys a field no map names, by the message it arrived in and the // rawFieldName keys a field no map names, by the message it arrived in and the
// name byte the charger gave it — "0410.b6". The message type belongs in the key // name byte the charger gave it — "0410.b6". The message type belongs in the key
// because a name byte means whatever its message says it means: the same b6 is a // because a name byte means whatever its message says it means: the same b6 is a
@@ -457,6 +578,11 @@ func decodeValue(typ byte, b []byte, f mqttField) (any, bool) {
return scale(int64(binary.LittleEndian.Uint32(b))), true return scale(int64(binary.LittleEndian.Uint32(b))), true
} }
return scale(int64(int32(binary.LittleEndian.Uint32(b)))), true return scale(int64(int32(binary.LittleEndian.Uint32(b)))), true
case typeBytes:
// An identifier rather than a quantity: a 4- or 7-byte card UID, which is
// the same hex the account prints on the card list. Read as a number it
// would be a different string on every screen it reached.
return strings.ToUpper(encodeHex(b)), true
case typeFloat32: case typeFloat32:
if len(b) < 4 { if len(b) < 4 {
return nil, false return nil, false
@@ -42,6 +42,76 @@ func TestEncodeFrameMatchesTheDocumentedTrigger(t *testing.T) {
} }
} }
// The status request is the one command whose timestamp travels without a value
// type — the app sends it that way, and the charger answers what the app sends.
func TestStatusRequestSendsItsClockWithoutAValueType(t *testing.T) {
got, err := encodeFrame(msgEVStatusReq, []cmdField{bareTimestampField(time.Unix(1756813256, 0))})
if err != nil {
t.Fatalf("encodeFrame: %v", err)
}
want := "ff09100003000f0040" + // header: marker, length 16, send pattern, type 0040
"fe04c8d7b668" // fe: four clock bytes, no value type between the length and them
if h := encodeHex(got); h[:len(want)] != want {
t.Fatalf("frame = %s\nwant %s + checksum", h, want)
}
if len(got) != 16 {
t.Errorf("frame is %d bytes, want 16", len(got))
}
// The field's length byte counts the value alone, since there is no type byte
// to count — the whole point of the oddity.
if got[10] != 4 {
t.Errorf("fe length byte is %d, want 4", got[10])
}
var sum byte
for _, b := range got {
sum ^= b
}
if sum != 0 {
t.Errorf("checksum does not close the frame: %02x", sum)
}
}
// The restart carries the one value the map documents for the power-mode
// command, opened and closed like every other command.
func TestRestartFrameCarriesThePowerModeValue(t *testing.T) {
got, err := encodeFrame(msgEVPowerMode, []cmdField{
rawField(0xa1, 0x22),
uintField(0xa2, powerModeRestart),
timestampField(time.Unix(1756813256, 0)),
})
if err != nil {
t.Fatalf("encodeFrame: %v", err)
}
want := "ff09180003000f0108" + // header: marker, length 24, send pattern, type 0108
"a10122" + // a1: the opener, no value type
"a2020105" + // a2: ui 5 — restart
"fe0503c8d7b668" // fe: var — the sender's clock
if h := encodeHex(got); h[:len(want)] != want {
t.Fatalf("frame = %s / want %s + checksum", h, want)
}
var sum byte
for _, b := range got {
sum ^= b
}
if sum != 0 {
t.Errorf("checksum does not close the frame: %02x", sum)
}
}
// Both spellings reach the restart; nothing else does.
func TestIsRestartTakesEitherName(t *testing.T) {
for _, name := range []string{"restart", "reset"} {
if !isRestart(name) {
t.Errorf("%q should ask for a restart", name)
}
}
for _, name := range []string{"reboot", "start", "stop", "trigger", ""} {
if isRestart(name) {
t.Errorf("%q should not ask for a restart", name)
}
}
}
// A frame is only self-consistent if XORing every byte, checksum included, // A frame is only self-consistent if XORing every byte, checksum included,
// comes to zero — which is exactly what the decoder checks. // comes to zero — which is exactly what the decoder checks.
func TestEncodeFrameChecksumClosesToZero(t *testing.T) { func TestEncodeFrameChecksumClosesToZero(t *testing.T) {
@@ -103,6 +103,18 @@ var settingCmds = []settingCmd{
// mode: the charger stops serving the register map on the LAN. // mode: the charger stops serving the register map on the LAN.
{wire: 0xb7, key: "modbusEnabled", state: "modbusSwitch", encode: switchOnOff(1, 0)}, {wire: 0xb7, key: "modbusEnabled", state: "modbusSwitch", encode: switchOnOff(1, 0)},
}}, }},
// The panel's own three: what a swipe up, a swipe down and a touch do. The
// charger has always reported them and the card has always shown them; they
// are settings like any other on this message, so they are writable here too.
{msgType: msgEVSettings, fields: []settingField{
{wire: 0xaf, key: "swipeUpMode", state: "swipeUpMode", encode: optionValue(0, 1, 2, 3)},
}},
{msgType: msgEVSettings, fields: []settingField{
{wire: 0xb0, key: "swipeDownMode", state: "swipeDownMode", encode: optionValue(0, 1, 2, 3)},
}},
{msgType: msgEVSettings, fields: []settingField{
{wire: 0xb2, key: "smartTouchMode", state: "smartTouchMode", encode: optionValue(0, 1)},
}},
{msgType: msgEVSchedule, fields: []settingField{ {msgType: msgEVSchedule, fields: []settingField{
{wire: 0xa2, key: "scheduleEnabled", state: "scheduleSwitch", encode: switchOnOff(1, 2)}, {wire: 0xa2, key: "scheduleEnabled", state: "scheduleSwitch", encode: switchOnOff(1, 2)},
{wire: 0xa8, key: "scheduleMode", state: "scheduleMode", encode: optionValue(0, 1)}, {wire: 0xa8, key: "scheduleMode", state: "scheduleMode", encode: optionValue(0, 1)},
@@ -189,13 +189,27 @@ func (p *Plugin) mqttStatus(ctx context.Context, sn string) (json.RawMessage, er
// Re-arm whenever the window is spent or close to it, so a poll never lands // Re-arm whenever the window is spent or close to it, so a poll never lands
// in the gap between the last frame and the trigger expiring. // in the gap between the last frame and the trigger expiring.
_, _, _, triggered := conn.snapshotOf(sn) _, _, settingsAt, triggered := conn.snapshotOf(sn)
if time.Until(triggered) < triggerRenew { if time.Until(triggered) < triggerRenew {
if err := p.mqttTrigger(ctx, conn, model, sn, triggerWindow); err != nil { if err := p.mqttTrigger(ctx, conn, model, sn, triggerWindow); err != nil {
return nil, err return nil, err
} }
} }
// The trigger buys telemetry only. What the charger is set to — its schedule,
// its balancing, its Modbus server, its firmware — travels on its own message,
// and without asking it never comes: a charger that has been read a hundred
// times and commanded none reports amps and nothing else. So the read asks for
// that half too whenever it is missing or has gone stale.
askedSettings := false
if time.Since(settingsAt) > settingsMaxAge {
// A charger that will not answer this is not a failed read: the telemetry
// half is still the answer, and the settings half is what it was.
if err := p.mqttStatusRequest(ctx, conn, model, sn); err == nil {
askedSettings = true
}
}
// Anything older than the trigger's own interval is stale; wait for the next. // Anything older than the trigger's own interval is stale; wait for the next.
cutoff := time.Now().Add(-triggerRenew) cutoff := time.Now().Add(-triggerRenew)
live, err := conn.waitFor(ctx, sn, func(st *deviceState) bool { live, err := conn.waitFor(ctx, sn, func(st *deviceState) bool {
@@ -205,6 +219,32 @@ func (p *Plugin) mqttStatus(ctx context.Context, sn string) (json.RawMessage, er
return nil, err return nil, err
} }
// Give the parameter message a moment of its own, but only while this charger
// still looks like one that answers: the reference reads the status request as
// carrying an Anker bug, so a firmware that ignores it must not tax every read
// with the same wait forever.
if askedSettings && conn.statusReqAnswered(sn) {
// A charger that has never reported its settings is a different case from
// one whose settings have merely gone stale. Stale has something to fall
// back on — the values are still there, and a read that misses costs the
// caller nothing but their age. Never-reported has nothing: the settings
// are absent from the answer entirely, and the card that reads them draws
// almost nothing. So the first ones are given the same wait a settings
// write gives them rather than the short one that only has to catch a
// refresh. It is still bounded by statusReqTries, so a charger that truly
// never answers costs that wait three times and then stops being asked to.
wait := settingsWait
if settingsAt.IsZero() {
wait = statusWait
}
settled, werr := conn.waitFor(ctx, sn, func(st *deviceState) bool {
return st.settingsAt.After(cutoff)
}, wait)
if werr == nil && !settled {
conn.noteStatusMiss(sn)
}
}
values, telemetryAt, settingsAt, _ := conn.snapshotOf(sn) values, telemetryAt, settingsAt, _ := conn.snapshotOf(sn)
if len(values) == 0 { if len(values) == 0 {
return nil, fmt.Errorf("anker-solix: charger %s did not answer over the cloud; it may be offline", sn) return nil, fmt.Errorf("anker-solix: charger %s did not answer over the cloud; it may be offline", sn)
@@ -247,6 +287,12 @@ var mqttCommands = map[string]string{
modeSkipDelay: modeSkipDelay, modeSkipDelay: modeSkipDelay,
} }
// isRestart reports whether a command asks for a reboot. Both names answer to
// it: "restart" is what this transport calls the message, and "reset" is what
// the OCPP path has always called the same act, so a caller that knows one is
// not told the charger cannot do the other.
func isRestart(command string) bool { return command == "restart" || command == "reset" }
// mqttCommand issues one control command over the cloud. // mqttCommand issues one control command over the cloud.
func (p *Plugin) mqttCommand(ctx context.Context, sn, command string, amps float64) (json.RawMessage, error) { func (p *Plugin) mqttCommand(ctx context.Context, sn, command string, amps float64) (json.RawMessage, error) {
// Validate before touching the cloud: a mistyped command should not cost a // Validate before touching the cloud: a mistyped command should not cost a
@@ -260,8 +306,9 @@ func (p *Plugin) mqttCommand(ctx context.Context, sn, command string, amps float
return nil, err return nil, err
} }
case command == "trigger": case command == "trigger":
case isRestart(command):
default: default:
return nil, fmt.Errorf("anker-solix: %q is not a cloud command (start, stop, boost, skip-delay, limit, trigger)", command) return nil, fmt.Errorf("anker-solix: %q is not a cloud command (start, stop, boost, skip-delay, limit, trigger, restart)", command)
} }
model, err := p.chargerModel(ctx, sn) model, err := p.chargerModel(ctx, sn)
@@ -284,6 +331,8 @@ func (p *Plugin) mqttCommand(ctx context.Context, sn, command string, amps float
err = p.mqttSetMode(ctx, conn, model, sn, mode) err = p.mqttSetMode(ctx, conn, model, sn, mode)
case command == "limit": case command == "limit":
err = p.mqttSetMaxCurrent(ctx, conn, model, sn, amps) err = p.mqttSetMaxCurrent(ctx, conn, model, sn, amps)
case isRestart(command):
err = p.mqttRestart(ctx, conn, model, sn)
default: default:
err = p.mqttTrigger(ctx, conn, model, sn, triggerWindow) err = p.mqttTrigger(ctx, conn, model, sn, triggerWindow)
} }
@@ -291,6 +340,15 @@ func (p *Plugin) mqttCommand(ctx context.Context, sn, command string, amps float
return nil, err return nil, err
} }
// A restart is the one command with nothing to wait for: the charger that
// would send the confirmation is the charger that is rebooting. Saying so
// beats waiting five seconds to report an unconfirmed command as if that
// were news.
if isRestart(command) {
return json.Marshal(mqttCommandDoc{Serial: sn, Command: command, Status: "accepted",
Detail: "sent; the charger reboots rather than confirming, and drops off the cloud for about a minute"})
}
// The charger answers a control change with a settings message. Waiting for // The charger answers a control change with a settings message. Waiting for
// it turns "published" into "the charger has it". // it turns "published" into "the charger has it".
confirmed, waitErr := conn.waitFor(ctx, sn, func(st *deviceState) bool { confirmed, waitErr := conn.waitFor(ctx, sn, func(st *deviceState) bool {
@@ -0,0 +1,250 @@
package ankersolix
// Payload encryption — the mobile app's "algo_ecdh" mode for the REST API.
//
// Anker's servers currently accept plain JSON bodies, and that is what this
// connector has always sent. The app itself does not: it runs a key exchange
// once per login and then encrypts every request body and reads back every
// response body encrypted, with an HMAC over each request. anker-solix-api
// v3.8.2 worked the scheme out end to end (session.py, AnkerEncryptionHandler),
// and this file is that handler in Go, kept behind the payloadEncryption config
// switch — off by default, as upstream leaves it, because plain bodies are what
// the cloud has been answering for years and any slip in a port of the cipher
// would take every read down at once. It exists so the day Anker stops
// tolerating plain bodies is a config change, not an outage.
//
// The scheme, in the order it runs:
//
// 1. Handshake. A fresh P-256 key pair is generated; its uncompressed point
// (0x04 || X || Y) is taken as its 130-character ascii hex and wrapped —
// AES-128-CBC under the region's presetKey with a random IV prepended, then
// base64 — and POSTed as client_public_key to openapi/oauth/key/exchange with
// the usual auth headers. The x-signature on that request is
// HMAC-SHA256(key = the presetKey's ascii hex, msg = ts+once+client_public_key).
// The reply's server_public_key is wrapped the same way; unwrapping it and
// running ECDH gives the 32-byte shared secret. There is no KDF.
// 2. Requests. The body is compact JSON, AES-128-CBC under secret[:16] (the
// "securityKey"), random IV prepended, PKCS#7, base64, sent as text/plain.
// x-signature is HMAC-SHA256(key = ascii hex of secret[:16],
// msg = ts+once+body). x-key-ident is fixed for the life of the key pair
// and is how the server finds the secret again; x-request-once is fresh
// per request.
// 3. Responses come back with data as a base64 string and a signature field
// beside it; data decrypts with the same key and cipher to the JSON the
// plain mode would have received.
//
// The presetKey is an app constant, identical for both regional servers today
// (upstream's API_PRESET_KEYS), not a user secret.
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/ecdh"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
)
const (
epKeyExchange = "openapi/oauth/key/exchange"
// presetKeyHex is the region AES-128 key the app carries in its stored
// userConfig as "presetKey". It wraps the two public keys of the handshake and
// keys the handshake's signature. EU and global use the same one.
presetKeyHex = "e8ad18f61bbd3fbd52d5ed12d14d3b9c"
)
// payloadCipher is one token's encryption state: the key pair the handshake was
// run with, the identifier the server files its result under, and the secret
// the handshake produced. It lives beside the token in the session and is
// discarded with it — a new login is a new handshake.
type payloadCipher struct {
priv *ecdh.PrivateKey
keyIdent string // x-key-ident: 32 hex chars, random, constant per key pair
preset []byte // the region presetKey, raw
secret []byte // ECDH shared secret; nil until the exchange has answered
}
// newPayloadCipher generates the key pair and identifier for one handshake.
func newPayloadCipher() (*payloadCipher, error) {
priv, err := ecdh.P256().GenerateKey(rand.Reader)
if err != nil {
return nil, fmt.Errorf("anker-solix: generate key: %w", err)
}
preset, err := hex.DecodeString(presetKeyHex)
if err != nil {
return nil, fmt.Errorf("anker-solix: preset key: %w", err)
}
ident := make([]byte, 16)
if _, err := rand.Read(ident); err != nil {
return nil, fmt.Errorf("anker-solix: key ident: %w", err)
}
return &payloadCipher{priv: priv, keyIdent: hex.EncodeToString(ident), preset: preset}, nil
}
// ready reports whether the handshake has produced a secret.
func (c *payloadCipher) ready() bool { return c != nil && c.secret != nil }
// clientPublicKey is the handshake body's one field: the uncompressed point as
// ascii hex, wrapped under the presetKey.
func (c *payloadCipher) clientPublicKey() (string, error) {
return aesCBCSeal(c.preset, []byte(hex.EncodeToString(c.priv.PublicKey().Bytes())))
}
// acceptServerKey unwraps the handshake reply's server_public_key and derives
// the shared secret from it.
func (c *payloadCipher) acceptServerKey(wrapped string) error {
pointHex, err := aesCBCOpen(c.preset, wrapped)
if err != nil {
return fmt.Errorf("unwrap server key: %w", err)
}
point, err := hex.DecodeString(strings.TrimSpace(string(pointHex)))
if err != nil {
return fmt.Errorf("server key is not hex: %w", err)
}
pub, err := ecdh.P256().NewPublicKey(point)
if err != nil {
return fmt.Errorf("server key is not a P-256 point: %w", err)
}
secret, err := c.priv.ECDH(pub)
if err != nil {
return fmt.Errorf("derive shared secret: %w", err)
}
c.secret = secret
return nil
}
// bodyKey is the AES-128 key both directions use after the handshake.
func (c *payloadCipher) bodyKey() []byte { return c.secret[:16] }
// sealBody encrypts a request payload for the wire. GETs, which carry no
// payload, seal an empty object — what the reference implementation sends.
func (c *payloadCipher) sealBody(payload map[string]any) (string, error) {
if payload == nil {
payload = map[string]any{}
}
plain, err := json.Marshal(payload)
if err != nil {
return "", fmt.Errorf("anker-solix: encode request: %w", err)
}
return aesCBCSeal(c.bodyKey(), plain)
}
// signRequest sets the encryption headers on a request whose body is already
// on the wire form given. The handshake signs under the presetKey and keeps a
// JSON content type; every request after it signs under the session key and
// goes out as text/plain.
func (c *payloadCipher) signRequest(req *http.Request, ts, wire string, handshake bool) {
var signKey string
if handshake {
signKey = presetKeyHex
req.Header.Set("content-type", "application/json")
req.Header.Set("x-auth-ts", ts)
} else {
signKey = hex.EncodeToString(c.bodyKey())
req.Header.Set("content-type", "text/plain")
}
once := make([]byte, 16)
_, _ = rand.Read(once)
onceHex := hex.EncodeToString(once)
mac := hmac.New(sha256.New, []byte(signKey))
mac.Write([]byte(ts + "+" + onceHex + "+" + wire))
req.Header.Set("x-app-key", "")
req.Header.Set("x-encryption-info", "algo_ecdh")
req.Header.Set("x-replay-info", "replay")
req.Header.Set("x-key-ident", c.keyIdent)
req.Header.Set("x-request-once", onceHex)
req.Header.Set("x-request-ts", ts)
req.Header.Set("x-signature", hex.EncodeToString(mac.Sum(nil)))
}
// unsealEnvelope turns an encrypted response into the envelope the plain mode
// receives: when a signature field is present and data is a string, data is
// decrypted and put back as the JSON it holds. Anything else — an error
// envelope, a plain reply — is returned as it came.
func (c *payloadCipher) unsealEnvelope(body []byte) ([]byte, error) {
var env map[string]json.RawMessage
if err := json.Unmarshal(body, &env); err != nil {
return body, nil
}
if _, signed := env["signature"]; !signed {
return body, nil
}
var wrapped string
if err := json.Unmarshal(env["data"], &wrapped); err != nil || wrapped == "" {
return body, nil
}
plain, err := aesCBCOpen(c.bodyKey(), wrapped)
if err != nil {
return nil, fmt.Errorf("anker-solix: decrypt response: %w", err)
}
if !json.Valid(plain) {
return nil, errors.New("anker-solix: decrypted response is not JSON")
}
env["data"] = json.RawMessage(plain)
return json.Marshal(env)
}
// aesCBCSeal is the one envelope every wrapped value in the scheme uses:
// AES-CBC under key, a random IV prepended to the ciphertext, PKCS#7 padding,
// standard base64. The key's length picks AES-128 or -256.
func aesCBCSeal(key, plain []byte) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", fmt.Errorf("aes cipher: %w", err)
}
iv := make([]byte, block.BlockSize())
if _, err := rand.Read(iv); err != nil {
return "", fmt.Errorf("iv: %w", err)
}
padded := pkcs7Pad(plain, block.BlockSize())
out := make([]byte, len(iv)+len(padded))
copy(out, iv)
cipher.NewCBCEncrypter(block, iv).CryptBlocks(out[len(iv):], padded)
return base64.StdEncoding.EncodeToString(out), nil
}
// aesCBCOpen reverses aesCBCSeal.
func aesCBCOpen(key []byte, wrapped string) ([]byte, error) {
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(wrapped))
if err != nil {
return nil, fmt.Errorf("base64: %w", err)
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, fmt.Errorf("aes cipher: %w", err)
}
bs := block.BlockSize()
if len(raw) < 2*bs || len(raw)%bs != 0 {
return nil, fmt.Errorf("ciphertext length %d is not iv plus whole blocks", len(raw))
}
iv, ct := raw[:bs], raw[bs:]
plain := make([]byte, len(ct))
cipher.NewCBCDecrypter(block, iv).CryptBlocks(plain, ct)
return pkcs7Unpad(plain, bs)
}
// pkcs7Unpad strips the padding pkcs7Pad added, refusing anything malformed.
func pkcs7Unpad(data []byte, blockSize int) ([]byte, error) {
if len(data) == 0 || len(data)%blockSize != 0 {
return nil, errors.New("bad padding: length")
}
pad := int(data[len(data)-1])
if pad == 0 || pad > blockSize || pad > len(data) {
return nil, errors.New("bad padding: count")
}
if !bytes.Equal(data[len(data)-pad:], bytes.Repeat([]byte{byte(pad)}, pad)) {
return nil, errors.New("bad padding: bytes")
}
return data[:len(data)-pad], nil
}
@@ -0,0 +1,291 @@
package ankersolix
import (
"context"
"crypto/ecdh"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
)
// encryptedCloud is the server half of the scheme in payloadcrypto.go, written
// from the reference implementation's description rather than from our client,
// so a test against it checks the two halves agree on every step: the presetKey
// wrapping of both public keys, the handshake signature, the per-request
// signature under the session key, the sealed body and the sealed reply.
type encryptedCloud struct {
t *testing.T
mu sync.Mutex
secrets map[string][]byte // x-key-ident -> shared secret
logins int
exchanges int
seen []map[string]any // decrypted request bodies, in order
rejectTok string // a token the cloud answers 401 to
}
func newEncryptedCloud(t *testing.T) *encryptedCloud {
return &encryptedCloud{t: t, secrets: map[string][]byte{}}
}
func (c *encryptedCloud) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c.mu.Lock()
defer c.mu.Unlock()
body, _ := io.ReadAll(r.Body)
switch {
case strings.HasSuffix(r.URL.Path, epLogin):
c.logins++
tok := "tok-" + hex.EncodeToString([]byte{byte(c.logins)})
_, _ = w.Write([]byte(`{"code":0,"data":{"auth_token":"` + tok + `","user_id":"u1","nick_name":"n","token_expires_at":9999999999}}`))
case strings.HasSuffix(r.URL.Path, epKeyExchange):
c.exchanges++
if got := r.Header.Get("content-type"); got != "application/json" {
c.t.Errorf("handshake content-type = %q, want application/json", got)
}
if r.Header.Get("x-auth-ts") == "" || r.Header.Get("x-auth-token") == "" {
c.t.Error("handshake must carry x-auth-ts and the auth token")
}
var req struct {
ClientPublicKey string `json:"client_public_key"`
}
if err := json.Unmarshal(body, &req); err != nil || req.ClientPublicKey == "" {
c.t.Errorf("handshake body %q is not {client_public_key}", body)
}
c.checkSignature(r, presetKeyHex, req.ClientPublicKey)
preset, _ := hex.DecodeString(presetKeyHex)
pointHex, err := aesCBCOpen(preset, req.ClientPublicKey)
if err != nil {
c.t.Fatalf("unwrap client key: %v", err)
}
point, _ := hex.DecodeString(string(pointHex))
if len(point) != 65 || point[0] != 4 {
c.t.Fatalf("client key is %d bytes starting %x, want a 65-byte uncompressed point", len(point), point[:1])
}
clientPub, err := ecdh.P256().NewPublicKey(point)
if err != nil {
c.t.Fatalf("client key: %v", err)
}
serverPriv, _ := ecdh.P256().GenerateKey(rand.Reader)
secret, _ := serverPriv.ECDH(clientPub)
c.secrets[r.Header.Get("x-key-ident")] = secret
wrapped, _ := aesCBCSeal(preset, []byte(hex.EncodeToString(serverPriv.PublicKey().Bytes())))
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]string{"server_public_key": wrapped}})
default:
if r.Header.Get("x-auth-token") == c.rejectTok {
w.WriteHeader(http.StatusUnauthorized)
return
}
if got := r.Header.Get("content-type"); got != "text/plain" {
c.t.Errorf("%s content-type = %q, want text/plain", r.URL.Path, got)
}
if got := r.Header.Get("x-encryption-info"); got != "algo_ecdh" {
c.t.Errorf("x-encryption-info = %q", got)
}
secret := c.secrets[r.Header.Get("x-key-ident")]
if secret == nil {
c.t.Errorf("%s arrived under key ident %q the cloud never issued", r.URL.Path, r.Header.Get("x-key-ident"))
w.WriteHeader(http.StatusBadRequest)
return
}
c.checkSignature(r, hex.EncodeToString(secret[:16]), string(body))
plain, err := aesCBCOpen(secret[:16], string(body))
if err != nil {
c.t.Fatalf("open %s body: %v", r.URL.Path, err)
}
var payload map[string]any
if err := json.Unmarshal(plain, &payload); err != nil {
c.t.Fatalf("%s body decrypted to %q, not JSON", r.URL.Path, plain)
}
c.seen = append(c.seen, payload)
reply, _ := json.Marshal(map[string]any{"echo": payload, "path": r.URL.Path, "query": r.URL.RawQuery})
sealed, _ := aesCBCSeal(secret[:16], reply)
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "msg": "success!", "data": sealed, "signature": "sig"})
}
}
// checkSignature recomputes x-signature the way the reference documents it:
// HMAC-SHA256 keyed on the ascii hex of the key, over ts+once+wire.
func (c *encryptedCloud) checkSignature(r *http.Request, keyHex, wire string) {
ts, once := r.Header.Get("x-request-ts"), r.Header.Get("x-request-once")
if len(once) != 32 || len(r.Header.Get("x-key-ident")) != 32 {
c.t.Errorf("x-request-once %q / x-key-ident %q should be 32 hex chars", once, r.Header.Get("x-key-ident"))
}
mac := hmac.New(sha256.New, []byte(keyHex))
mac.Write([]byte(ts + "+" + once + "+" + wire))
if want := hex.EncodeToString(mac.Sum(nil)); r.Header.Get("x-signature") != want {
c.t.Errorf("%s x-signature = %q, want %q", r.URL.Path, r.Header.Get("x-signature"), want)
}
}
func encryptedPlugin(t *testing.T, srv *httptest.Server) *Plugin {
t.Helper()
p := &Plugin{}
if err := p.Init(context.Background(), map[string]string{"email": "e@example.com", "password": "pw", "payloadEncryption": "on"}); err != nil {
t.Fatal(err)
}
p.apiBase = srv.URL
p.sess = sessionFor(srv.URL, "e@example.com", "pw")
return p
}
// TestPayloadEncryptionRoundTrip drives a POST and a GET through the sealed
// path and checks the plugin sees exactly the envelope the plain mode would.
func TestPayloadEncryptionRoundTrip(t *testing.T) {
cloud := newEncryptedCloud(t)
srv := httptest.NewServer(cloud)
defer srv.Close()
p := encryptedPlugin(t, srv)
body, err := p.apiRequest(context.Background(), epStationInfo, map[string]any{"sn": "ABC", "featuretype": 1})
if err != nil {
t.Fatal(err)
}
var env struct {
Code int `json:"code"`
Data struct {
Echo map[string]any `json:"echo"`
Path string `json:"path"`
} `json:"data"`
}
if err := json.Unmarshal(body, &env); err != nil {
t.Fatalf("unsealed body %s: %v", body, err)
}
if env.Code != 0 || env.Data.Echo["sn"] != "ABC" || env.Data.Echo["featuretype"] != float64(1) {
t.Fatalf("unsealed envelope = %s", body)
}
if !strings.HasSuffix(env.Data.Path, epStationInfo) {
t.Errorf("request went to %q", env.Data.Path)
}
body, err = p.apiGet(context.Background(), epMessages, map[string]string{"last_time": "7"})
if err != nil {
t.Fatal(err)
}
var got struct {
Data struct {
Echo map[string]any `json:"echo"`
Query string `json:"query"`
} `json:"data"`
}
_ = json.Unmarshal(body, &got)
if got.Data.Query != "last_time=7" {
t.Errorf("GET query = %q, want last_time=7", got.Data.Query)
}
if len(got.Data.Echo) != 0 {
t.Errorf("a GET seals an empty object, got %v", got.Data.Echo)
}
if cloud.logins != 1 || cloud.exchanges != 1 {
t.Errorf("logins = %d, exchanges = %d; want one of each for two requests", cloud.logins, cloud.exchanges)
}
}
// TestPayloadEncryptionHandshakeFollowsLogin: a rejected token costs a login and
// a new handshake, and the retry goes out under both.
func TestPayloadEncryptionHandshakeFollowsLogin(t *testing.T) {
cloud := newEncryptedCloud(t)
srv := httptest.NewServer(cloud)
defer srv.Close()
p := encryptedPlugin(t, srv)
if _, err := p.apiRequest(context.Background(), epSiteList, map[string]any{}); err != nil {
t.Fatal(err)
}
// An evicted token is an old one: a token refused minutes after its login
// is taken to be the endpoint saying no (relogin), so age it first.
p.sess.tok.issued = time.Now().Add(-72 * time.Hour)
cloud.mu.Lock()
cloud.rejectTok = "tok-01" // the first login's token
cloud.mu.Unlock()
if _, err := p.apiRequest(context.Background(), epSiteList, map[string]any{}); err != nil {
t.Fatal(err)
}
if cloud.logins != 2 || cloud.exchanges != 2 {
t.Errorf("logins = %d, exchanges = %d; want 2 and 2 after a rejected token", cloud.logins, cloud.exchanges)
}
if p.sess.enc == nil || !p.sess.enc.ready() {
t.Error("the session should hold the new handshake")
}
}
// TestPayloadEncryptionOffStaysPlain guards the default: no switch, no
// handshake, JSON on the wire as before.
func TestPayloadEncryptionOffStaysPlain(t *testing.T) {
var sawExchange bool
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, epLogin):
_, _ = w.Write([]byte(`{"code":0,"data":{"auth_token":"t","user_id":"u1","token_expires_at":9999999999}}`))
case strings.HasSuffix(r.URL.Path, epKeyExchange):
sawExchange = true
default:
if r.Header.Get("content-type") != "application/json" || r.Header.Get("x-encryption-info") != "" {
t.Errorf("plain request carried %q / %q", r.Header.Get("content-type"), r.Header.Get("x-encryption-info"))
}
_, _ = w.Write([]byte(`{"code":0,"data":{}}`))
}
}))
defer srv.Close()
p := &Plugin{}
_ = p.Init(context.Background(), map[string]string{"email": "plain@example.com", "password": "pw"})
p.apiBase = srv.URL
p.sess = sessionFor(srv.URL, "plain@example.com", "pw")
if p.encrypt {
t.Fatal("payload encryption must be off by default")
}
if _, err := p.apiRequest(context.Background(), epSiteList, map[string]any{}); err != nil {
t.Fatal(err)
}
if sawExchange {
t.Error("no handshake should run with encryption off")
}
}
// TestUnsealEnvelopeLeavesUnsignedAlone: an error envelope, or a plain reply,
// is passed through untouched; a signed reply that fails to open is an error
// rather than garbage.
func TestUnsealEnvelopeLeavesUnsignedAlone(t *testing.T) {
enc, _ := newPayloadCipher()
enc.secret = make([]byte, 32)
for _, in := range []string{`{"code":26161,"msg":"Failed to request."}`, `{"code":0,"data":{"x":1}}`, `not json`} {
out, err := enc.unsealEnvelope([]byte(in))
if err != nil || string(out) != in {
t.Errorf("unsealEnvelope(%q) = %q, %v; want it untouched", in, out, err)
}
}
if _, err := enc.unsealEnvelope([]byte(`{"code":0,"data":"AAAA","signature":"s"}`)); err == nil {
t.Error("a signed reply that does not open should be an error")
}
}
func TestPayloadEncryptionSwitch(t *testing.T) {
for v, want := range map[string]bool{"": false, "off": false, "on": true, "ON": true, "true": true, "1": true, "no": false} {
if got := payloadEncryptionOn(v); got != want {
t.Errorf("payloadEncryptionOn(%q) = %v", v, got)
}
}
fields := map[string]bool{}
for _, f := range (&Plugin{}).Descriptor().ConfigFields {
fields[f.Key] = f.Default == "off"
}
if off, ok := fields["payloadEncryption"]; !ok || !off {
t.Error("payloadEncryption must be advertised with default off")
}
}
@@ -0,0 +1,192 @@
package ankersolix
// The cards that open the charger, and the two writes that change them.
//
// get_device_cards is well behaved: every card comes back as alias_name,
// card_number and create_time, and nothing else. There is no card id anywhere in
// that payload, which is why both writes below address a card by its number —
// it is the only handle the account ever gives out.
//
// save_device_card and delete_device_card are a different matter. Neither is
// documented, by Anker or by the reference implementation: both names were read
// out of the app package, and the bodies here are inferred from the field names
// the read view answers with. That is a guess, and it is treated as one:
//
// - a write never reports its own success. After the call the card list is
// read again and the answer says whether the card is on the charger now, so
// a caller never has to take an ack's word for what happened;
// - the cloud's own response is relayed alongside it, because an endpoint
// nobody has documented is one whose reply is worth reading;
// - nothing here deletes by pattern, by index, or in bulk. One card, named in
// full, per call.
import (
"context"
"encoding/json"
"fmt"
"strings"
)
const (
epRfidSaveCard = "power_service/v1/rfid/save_device_card" // add or rename one card — payload inferred, see above
epRfidDeleteCard = "power_service/v1/rfid/delete_device_card" // remove one card — payload inferred, see above
)
// rfidCard is one authorised card, under the names get_device_cards uses for it.
// create_time is relayed rather than parsed: it is upstream's own epoch and the
// UI already knows how to read one.
type rfidCard struct {
Name string `json:"alias_name,omitempty"`
Number string `json:"card_number,omitempty"`
Added json.RawMessage `json:"create_time,omitempty"`
}
// rfidWriteResult is what a write answers with: what was asked, what the cloud
// said, and — the part that matters — the list as it stands afterwards.
type rfidWriteResult struct {
SN string `json:"sn"`
Action string `json:"action"` // save | delete
Number string `json:"cardNumber"` // as it was sent, normalized
Present bool `json:"present"` // whether the account holds that card now
Cards []rfidCard `json:"cards"`
// What the charger itself did, when it could be reached: the write the Anker
// app makes, and the only one of the two that is not inferred.
Charger *cardWriteResult `json:"charger,omitempty"`
Response json.RawMessage `json:"response,omitempty"`
Detail string `json:"detail,omitempty"` // why the list could not be read back
}
// normalizeCardNumber puts a card number in the form the account stores it in.
// The numbers arrive as bare uppercase hex; people type them with spaces, dashes
// or colons between the bytes, and a number that differs from the stored one
// only in punctuation would delete nothing and add a duplicate.
func normalizeCardNumber(s string) string {
var b strings.Builder
for _, r := range s {
switch {
case r >= '0' && r <= '9', r >= 'A' && r <= 'Z':
b.WriteRune(r)
case r >= 'a' && r <= 'z':
b.WriteRune(r - 'a' + 'A')
}
}
return b.String()
}
// rfidCardLabel is the name a card gets when it is added without one — the same
// shape the Anker app writes, so a card added here does not stand out in it.
func rfidCardLabel(number string) string {
if len(number) > 4 {
number = number[len(number)-4:]
}
return "RFID " + number
}
// parseRfidCards reads the card list out of get_device_cards' envelope. A
// response that carries no list is an empty charger, not an error: an account
// with no cards answers exactly that way.
func parseRfidCards(body []byte) ([]rfidCard, error) {
var env struct {
Data struct {
List []rfidCard `json:"list"`
} `json:"data"`
}
if err := json.Unmarshal(body, &env); err != nil {
return nil, err
}
return env.Data.List, nil
}
// cardPresent says whether a number is among the cards, comparing them the way
// normalizeCardNumber writes them so punctuation cannot answer for the account.
func cardPresent(cards []rfidCard, number string) bool {
want := normalizeCardNumber(number)
for _, c := range cards {
if normalizeCardNumber(c.Number) == want {
return true
}
}
return false
}
// rfidList is the cards authorised on one charger, as the account holds them.
func (p *Plugin) rfidList(ctx context.Context, sn string) ([]rfidCard, error) {
body, err := p.apiRequest(ctx, epRfidCards, map[string]any{"device_sn": sn})
if err != nil {
return nil, err
}
return parseRfidCards(body)
}
// rfidSaveCard adds a card, both places it has to be added.
//
// The charger is written first, with the app's own message: it is the device
// that decides who may start a charge, and that write is the one this connector
// watched the app make rather than inferred. The account write follows because
// it is the half that carries a name — the charger's message has no name field —
// and because the list people read is the account's. Either may fail on its own
// and the answer says which; only both failing is an error.
func (p *Plugin) rfidSaveCard(ctx context.Context, sn, number, name string) (json.RawMessage, error) {
number = normalizeCardNumber(number)
if number == "" {
return nil, fmt.Errorf("anker-solix: a card number is required")
}
name = strings.TrimSpace(name)
if name == "" {
name = rfidCardLabel(number)
}
dev, devErr := p.mqttWriteCard(ctx, sn, number, true)
body, err := p.apiRequest(ctx, epRfidSaveCard, map[string]any{
"device_sn": sn,
"card_number": number,
"alias_name": name,
})
if err != nil && devErr != nil {
return nil, fmt.Errorf("anker-solix: saving card %s: charger: %v; account: %v", number, devErr, err)
}
return p.rfidAfterWrite(ctx, sn, "save", number, body, dev, devErr)
}
// rfidDeleteCard removes one card from the charger. The caller names the whole
// number: there is no "delete the third one" here, because an index into a list
// that was read a minute ago is not a card.
func (p *Plugin) rfidDeleteCard(ctx context.Context, sn, number string) (json.RawMessage, error) {
number = normalizeCardNumber(number)
if number == "" {
return nil, fmt.Errorf("anker-solix: a card number is required")
}
dev, devErr := p.mqttWriteCard(ctx, sn, number, false)
body, err := p.apiRequest(ctx, epRfidDeleteCard, map[string]any{
"device_sn": sn,
"card_number": number,
})
if err != nil && devErr != nil {
return nil, fmt.Errorf("anker-solix: deleting card %s: charger: %v; account: %v", number, devErr, err)
}
return p.rfidAfterWrite(ctx, sn, "delete", number, body, dev, devErr)
}
// rfidAfterWrite reads the list back and answers with it. A list that cannot be
// read is not a failed write — the write already happened — so it is reported as
// the detail beside an answer that says nothing about presence rather than
// guessing at one.
func (p *Plugin) rfidAfterWrite(ctx context.Context, sn, action, number string, response []byte,
dev *cardWriteResult, devErr error) (json.RawMessage, error) {
out := rfidWriteResult{SN: sn, Action: action, Number: number, Response: json.RawMessage(response)}
if dev != nil {
out.Charger = dev
} else if devErr != nil {
// The charger could not be reached or would not answer. The account write
// may still have landed, so this is said beside the answer rather than
// instead of it.
out.Charger = &cardWriteResult{SN: sn, Action: action, Number: number, Via: "charger", Detail: devErr.Error()}
}
cards, err := p.rfidList(ctx, sn)
if err != nil {
out.Detail = err.Error()
} else {
out.Cards = cards
out.Present = cardPresent(cards, number)
}
return json.Marshal(out)
}
@@ -0,0 +1,99 @@
package ankersolix
import (
"context"
"encoding/json"
"strings"
"testing"
)
// A card number typed with punctuation is the same card as the one the account
// stores bare — anything else deletes nothing and adds a duplicate.
func TestNormalizeCardNumber(t *testing.T) {
for _, tc := range []struct{ in, want string }{
{"4754DC2A", "4754DC2A"},
{"47:54:dc:2a", "4754DC2A"},
{" 47-54 dc 2a ", "4754DC2A"},
{"04dfe672151a90", "04DFE672151A90"},
{"", ""},
{" :- ", ""},
} {
if got := normalizeCardNumber(tc.in); got != tc.want {
t.Errorf("normalizeCardNumber(%q) = %q, want %q", tc.in, got, tc.want)
}
}
}
// The name a card gets when it is added without one, in the shape the Anker app
// writes so a card added here does not stand out in it.
func TestRfidCardLabel(t *testing.T) {
if got := rfidCardLabel("4754DC2A"); got != "RFID DC2A" {
t.Errorf("rfidCardLabel = %q, want %q", got, "RFID DC2A")
}
if got := rfidCardLabel("2A"); got != "RFID 2A" {
t.Errorf("short number: rfidCardLabel = %q, want %q", got, "RFID 2A")
}
}
func TestParseRfidCards(t *testing.T) {
body := []byte(`{"code":0,"data":{"list":[
{"alias_name":"RFID DC2A","card_number":"4754DC2A","create_time":1788187299},
{"alias_name":"RFID B93F","card_number":"DA7CB93F","create_time":1788187315}]}}`)
cards, err := parseRfidCards(body)
if err != nil {
t.Fatalf("parseRfidCards: %v", err)
}
if len(cards) != 2 {
t.Fatalf("got %d cards, want 2", len(cards))
}
if cards[0].Name != "RFID DC2A" || cards[0].Number != "4754DC2A" {
t.Fatalf("first card = %+v", cards[0])
}
if string(cards[0].Added) != "1788187299" {
t.Fatalf("create_time = %q, want it relayed as it arrived", cards[0].Added)
}
// A charger with no cards answers with an empty document, which is an answer
// and not a failure.
cards, err = parseRfidCards([]byte(`{"code":0,"data":{}}`))
if err != nil || len(cards) != 0 {
t.Fatalf("empty list: got %d cards, err %v", len(cards), err)
}
}
// Presence is what a write is judged by, and it is judged on the number rather
// than on how either side punctuated it.
func TestCardPresent(t *testing.T) {
cards := []rfidCard{{Number: "4754DC2A"}, {Number: "DA7CB93F"}}
if !cardPresent(cards, "47:54:dc:2a") {
t.Error("punctuated number: want present")
}
if cardPresent(cards, "DEADBEEF") {
t.Error("unknown number: want absent")
}
if cardPresent(nil, "4754DC2A") {
t.Error("empty charger: want absent")
}
}
// Neither write may reach the cloud without knowing which charger and which
// card: an endpoint nobody has documented is not one to send half a request to.
func TestCardWritesRefuseIncompleteRequests(t *testing.T) {
p := &Plugin{}
_ = p.Init(context.Background(), map[string]string{"email": "u@example.com", "password": "p"})
for _, action := range []string{"rfid-card-save", "rfid-card-delete"} {
if _, err := p.Invoke(context.Background(), action, nil); err == nil ||
!strings.Contains(err.Error(), "requires an sn") {
t.Errorf("%s without a serial: got %v, want an sn-required error", action, err)
}
// A serial but no card, and no card number to be found in punctuation
// either: both stop before anything is sent.
for _, params := range []string{`{"sn":"EVSN1"}`, `{"sn":"EVSN1","cardNumber":" :- "}`} {
_, err := p.Invoke(context.Background(), action, json.RawMessage(params))
if err == nil || !strings.Contains(err.Error(), "card number is required") {
t.Errorf("%s with %s: got %v, want a card-number-required error", action, params, err)
}
}
}
}
@@ -29,13 +29,23 @@ import (
// its login alone after a refusal, and the broker connection its chargers are // its login alone after a refusal, and the broker connection its chargers are
// commanded over. // commanded over.
type session struct { type session struct {
mu sync.Mutex // guards tok and the backoff below, and serialises the login exchange mu sync.Mutex // guards tok, enc and the backoff below, and serialises the login and key exchanges
tok *tokenInfo tok *tokenInfo
// enc is the payload-encryption handshake run under tok, when the connector
// is configured to encrypt (payloadcrypto.go). It is tied to the token — the
// server files the secret under the login — so it is dropped whenever tok is
// replaced, and stays nil while encryption is off.
enc *payloadCipher
loginErr error loginErr error
loginRetryAt time.Time loginRetryAt time.Time
loginFails int loginFails int
// refused holds endpoints that turned a token away minutes after the login
// that issued it, until when no login is spent on them again. Guarded by mu.
refused map[string]time.Time
// The cloud MQTT half (cloudmqtt.go), under its own lock: a broker connection // The cloud MQTT half (cloudmqtt.go), under its own lock: a broker connection
// takes a TLS handshake and a fetched certificate to open, so it outlives the // takes a TLS handshake and a fetched certificate to open, so it outlives the
// plugin instance for the same reason the token does. mqttMu guards all four // plugin instance for the same reason the token does. mqttMu guards all four
@@ -125,9 +135,43 @@ func (s *session) noteLogin(err error) {
wait = loginRetryMax wait = loginRetryMax
} }
var rejected *loginRejected var rejected *loginRejected
if errors.As(err, &rejected) && rejected.code == codeSignInLocked && wait < loginLockoutWait { if errors.As(err, &rejected) {
wait = loginLockoutWait switch {
case rejected.code == codeSignInLocked && wait < loginLockoutWait:
wait = loginLockoutWait
case rejected.code == codeLoginBanned && wait < loginBanWait:
wait = loginBanWait
}
} }
s.loginRetryAt = time.Now().Add(wait) s.loginRetryAt = time.Now().Add(wait)
s.loginErr = &loginFailure{err: err, retryAt: s.loginRetryAt} s.loginErr = &loginFailure{err: err, retryAt: s.loginRetryAt}
} }
// endpointRefusal is how long an endpoint that refused a fresh token is left
// without a login spent on it. Its requests still go out, and fail on their own.
const endpointRefusal = time.Hour
// noteRefused records that endpoint refused a token it had no reason to.
func (s *session) noteRefused(endpoint string) {
s.mu.Lock()
defer s.mu.Unlock()
s.noteRefusedLocked(endpoint)
}
// noteRefusedLocked is noteRefused for a caller already holding s.mu.
func (s *session) noteRefusedLocked(endpoint string) {
if s.refused == nil {
s.refused = map[string]time.Time{}
}
s.refused[endpoint] = time.Now().Add(endpointRefusal)
}
// refusing reports whether endpoint is inside its refusal window. Caller holds s.mu.
func (s *session) refusing(endpoint string) bool {
until, ok := s.refused[endpoint]
if ok && !time.Now().Before(until) {
delete(s.refused, endpoint)
return false
}
return ok
}
@@ -24,6 +24,9 @@ func TestEveryBuiltinIsRegistered(t *testing.T) {
"apprise": plugins.CategoryNotifications, "apprise": plugins.CategoryNotifications,
"greencell": plugins.CategoryChargers, "greencell": plugins.CategoryChargers,
"toyota": plugins.CategoryVehicles, "toyota": plugins.CategoryVehicles,
// One connector, three registrations: see toyota.Brands.
"lexus": plugins.CategoryVehicles,
"subaru": plugins.CategoryVehicles,
} }
for name, category := range want { for name, category := range want {
v, ok := seen[name] v, ok := seen[name]
@@ -1,6 +1,7 @@
// Package toyota is a built-in connector for Toyota Connected Europe Services — // Package toyota is a built-in connector for Toyota Connected Europe Services —
// the backend behind the MyToyota app. It is a Go re-implementation of the // the backend behind the MyToyota app, and behind the Lexus and Subaru (Solterra)
// authentication and read-only data flow from the pytoyoda project // apps that share it. It is a Go re-implementation of the authentication and
// read-only data flow from the pytoyoda project
// (https://github.com/pytoyoda/pytoyoda), adapted to DriverVault's plugin // (https://github.com/pytoyoda/pytoyoda), adapted to DriverVault's plugin
// contract. // contract.
// //
@@ -51,46 +52,127 @@ import (
// and are the values baked into the official MyToyota Android app (client // and are the values baked into the official MyToyota Android app (client
// "oneapp"); they are not user secrets. // "oneapp"); they are not user secrets.
const ( const (
apiBaseURL = "https://ctpa-oneapi.tceu-ctp-prd.toyotaconnectedeurope.io" apiBaseURL = "https://ctpa-oneapi.tceu-ctp-prd.toyotaconnectedeurope.io"
accessTokenURL = "https://b2c-login.toyota-europe.com/oauth2/realms/root/realms/tme/access_token" loginBase = "https://b2c-login.toyota-europe.com"
authenticateURL = "https://b2c-login.toyota-europe.com/json/realms/root/realms/tme/authenticate?authIndexType=service&authIndexValue=oneapp"
authorizeURL = "https://b2c-login.toyota-europe.com/oauth2/realms/root/realms/tme/authorize?client_id=oneapp&scope=openid+profile+write&response_type=code&redirect_uri=com.toyota.oneapp:/oauth2Callback&code_challenge=plain&code_challenge_method=plain"
redirectURI = "com.toyota.oneapp:/oauth2Callback"
clientVersion = "2.14.0" clientVersion = "2.14.0"
// apiKey is the app's public API-gateway key (not the user's secret). // apiKey is the app's public API-gateway key (not the user's secret).
apiKey = "tTZipv6liF74PwMfk9Ed68AQ0bISswwf3iHQdqcF" apiKey = "tTZipv6liF74PwMfk9Ed68AQ0bISswwf3iHQdqcF"
// basicAuth is base64("oneapp:oneapp") — the OAuth client's basic credentials.
basicAuth = "basic b25lYXBwOm9uZWFwcA=="
userAgent = "okhttp/4.10.0" userAgent = "okhttp/4.10.0"
) )
// brandAuth is the OAuth client an account lives under. Toyota and Lexus share
// the "tme" realm and the "oneapp" client; Subaru's Solterra is sold through the
// same European backend but logs in under its own realm and client on the same
// host. Everything past the login — the data API, the headers, the endpoints —
// is common, which is why one connector serves all three.
type brandAuth struct {
clientID string
redirectURI string
// basicAuth is base64(clientID:secret) — the OAuth client's own credentials,
// baked into the app.
basicAuth string
accessTokenURL string
authenticateURL string
authorizeURL string
}
// newBrandAuth derives a realm's three login URLs from the parts that differ.
// The shape is ForgeRock's, so it is the same for every realm on the host.
func newBrandAuth(realm, clientID, redirectURI, basicAuth string) brandAuth {
return brandAuth{
clientID: clientID,
redirectURI: redirectURI,
basicAuth: basicAuth,
accessTokenURL: loginBase + "/oauth2/realms/root/realms/" + realm + "/access_token",
authenticateURL: loginBase + "/json/realms/root/realms/" + realm + "/authenticate?authIndexType=service&authIndexValue=oneapp",
authorizeURL: loginBase + "/oauth2/realms/root/realms/" + realm + "/authorize?client_id=" + clientID +
"&scope=openid+profile+write&response_type=code&redirect_uri=" + redirectURI +
"&code_challenge=plain&code_challenge_method=plain",
}
}
var (
// toyotaAuth is base64("oneapp:oneapp").
toyotaAuth = newBrandAuth("tme", "oneapp", "com.toyota.oneapp:/oauth2Callback",
"basic b25lYXBwOm9uZWFwcA==")
subaruAuth = newBrandAuth("alliance-subaru", "8c4921b0b08901fef389ce1af49c4e10.subaru.com", "com.subaru.oneapp:/oauth2Callback",
"basic OGM0OTIxYjBiMDg5MDFmZWYzODljZTFhZjQ5YzRlMTAuc3ViYXJ1LmNvbTpJaGNkcjV4YmhIYlRSMk9aOGdRa3YyNTZicmhTYjc=")
)
// authFor picks the OAuth client for a brand code. Only Subaru has its own;
// Toyota, Lexus and anything unrecognised log in as the MyToyota app does.
func authFor(brand string) brandAuth {
if brand == "S" {
return subaruAuth
}
return toyotaAuth
}
// Read-only API endpoints exposed as capabilities. // Read-only API endpoints exposed as capabilities.
// //
// Toyota retired the /v1/global/remote/{status,climate-*} read routes in mid-2026 // Toyota retired the /v1/global/remote/{status,climate-*} read routes in mid-2026
// — they now sit behind AWS SigV4 and answer a plain Bearer token with 403 — and // — they now sit behind AWS SigV4 and answer a plain Bearer token with 403 — and
// the app reads that state from /v1/vehicle/* instead. epRemoteStatus and the two // the app reads that state from /v1/vehicle/* instead. epRemoteStatus and the two
// climate endpoints below follow pytoyoda onto the new namespace; the electric // climate endpoints below follow pytoyoda onto the new namespace. The electric
// status route was not moved and stays where it was. // status read followed in September 2026 (pytoyoda 6.0.0, from a capture of the
// app); upstream has not proven it against a live car, so epElectricStatusLegacy
// is kept as the fallback when the new route refuses.
const ( const (
epVehicleGUID = "/v2/vehicle/guid" epVehicleGUID = "/v2/vehicle/guid"
epLocation = "/v1/location" epLocation = "/v1/location"
epHealthStatus = "/v1/vehiclehealth/status" epHealthStatus = "/v1/vehiclehealth/status"
epRemoteStatus = "/v1/vehicle/status" epRemoteStatus = "/v1/vehicle/status"
epElectricStatus = "/v1/global/remote/electric/status" epElectricStatus = "/v1/vehicle/electric/status"
epClimateStatus = "/v1/vehicle/climate-status" epClimateStatus = "/v1/vehicle/climate-status"
epClimateSettings = "/v1/vehicle/climate-settings" epClimateSettings = "/v1/vehicle/climate-settings"
epTelemetry = "/v3/telemetry" epTelemetry = "/v3/telemetry"
epNotifications = "/v2/notification/history" epNotifications = "/v2/notification/history"
epServiceHistory = "/v1/servicehistory/vehicle/summary" epServiceHistory = "/v1/servicehistory/vehicle/summary"
epElectricStatusLegacy = "/v1/global/remote/electric/status"
) )
// tokenExpiryMargin is subtracted from the reported token lifetime so a request // tokenExpiryMargin is subtracted from the reported token lifetime so a request
// never fires with a token that expires mid-flight. // never fires with a token that expires mid-flight.
const tokenExpiryMargin = 30 * time.Second const tokenExpiryMargin = 30 * time.Second
// Brand is one of the three makes this connector serves. The apps show each as
// a plugin of its own — its own panel entry, its own settings card, its own
// credentials — because an owner thinks of "my Lexus account", not of the
// Toyota Connected Europe backend the three happen to share. The code is one
// connector; only the login realm and a few headers differ (see authFor).
type Brand struct {
Name string // plugin name, also the key under pluginSettings: "toyota"
Code string // the one-letter code the API uses on the wire: "T"
Make string // "Toyota"
App string // the app the owner knows the account by: "MyToyota"
Provider string // the panel's provider line
}
// Brands are the registered makes, in menu order.
var Brands = []Brand{
{Name: "toyota", Code: "T", Make: "Toyota", App: "MyToyota", Provider: "Toyota Connected Europe"},
{Name: "lexus", Code: "L", Make: "Lexus", App: "Lexus Link+", Provider: "Lexus (Toyota Connected Europe)"},
{Name: "subaru", Code: "S", Make: "Subaru", App: "MySubaru", Provider: "Subaru (Toyota Connected Europe)"},
}
// brandByCode finds a brand by its wire code; Toyota for anything unknown.
func brandByCode(code string) Brand {
for _, b := range Brands {
if b.Code == code {
return b
}
}
return Brands[0]
}
func init() { func init() {
plugins.Register("toyota", func() plugins.Plugin { return &Plugin{} }) for _, b := range Brands {
code := b.Code
plugins.Register(b.Name, func() plugins.Plugin { return &Plugin{fixedBrand: code} })
}
} }
// tokenInfo holds the currently-held OAuth tokens and the derived account UUID. // tokenInfo holds the currently-held OAuth tokens and the derived account UUID.
@@ -105,7 +187,11 @@ type tokenInfo struct {
type Plugin struct { type Plugin struct {
username string username string
password string password string
brand string // "T" (Toyota) or "L" (Lexus) // fixedBrand is the brand this registration serves, set by its factory. A
// bare &Plugin{} (tests) has none and takes the brand from config instead.
fixedBrand string
brand string // "T" (Toyota), "L" (Lexus) or "S" (Subaru)
auth brandAuth // the OAuth client for brand, fixed at Init
mu sync.Mutex // guards tok and the login flow mu sync.Mutex // guards tok and the login flow
tok *tokenInfo tok *tokenInfo
@@ -119,10 +205,11 @@ type Plugin struct {
// Descriptor returns the plugin's static metadata for the admin panel. // Descriptor returns the plugin's static metadata for the admin panel.
func (p *Plugin) Descriptor() plugins.Descriptor { func (p *Plugin) Descriptor() plugins.Descriptor {
b := brandByCode(p.fixedBrand)
return plugins.Descriptor{ return plugins.Descriptor{
Name: "toyota", Name: b.Name,
Provider: "Toyota Connected Europe", Provider: b.Provider,
Version: "0.2.0", Version: "0.4.0",
Kind: plugins.KindBuiltin, Kind: plugins.KindBuiltin,
Category: plugins.CategoryVehicles, Category: plugins.CategoryVehicles,
AuthType: plugins.AuthOAuth2, AuthType: plugins.AuthOAuth2,
@@ -140,20 +227,15 @@ func (p *Plugin) Descriptor() plugins.Descriptor {
}, },
ConfigFields: []plugins.ConfigField{ ConfigFields: []plugins.ConfigField{
// Credentials are intentionally NOT required at the global (panel) layer: // Credentials are intentionally NOT required at the global (panel) layer:
// this connector runs under each user's own MyToyota account, supplied in // this connector runs under each user's own account, supplied in the
// the Web App's per-user integration settings. A superadmin/org admin may // Web App's per-user integration settings. A superadmin/org admin may
// still set a shared (e.g. fleet) account here that users inherit. See the // still set a shared (e.g. fleet) account here that users inherit. See the
// cascade in internal/api/integrations.go. // cascade in internal/api/integrations.go. There is no brand field: each
{Key: "username", Label: "MyToyota email", Type: "text", // brand is its own registration.
Help: "The email address for your MyToyota (Toyota Connected Europe) account."}, {Key: "username", Label: b.App + " email", Type: "text",
{Key: "password", Label: "MyToyota password", Type: "password", Secret: true, Help: "The email address for your " + b.App + " account."},
Help: "Your MyToyota account password. Stored locally, sent only to Toyota's login endpoint."}, {Key: "password", Label: b.App + " password", Type: "password", Secret: true,
{Key: "brand", Label: "Brand", Type: "select", Default: "T", Help: "Your " + b.App + " account password. Stored locally, sent only to the " + b.Make + " login endpoint."},
Help: "Vehicle brand tied to the account.",
Options: []plugins.SelectOption{
{Value: "T", Label: "Toyota"},
{Value: "L", Label: "Lexus"},
}},
}, },
} }
} }
@@ -166,10 +248,14 @@ func (p *Plugin) Init(_ context.Context, config map[string]string) error {
p.username = strings.TrimSpace(config["username"]) p.username = strings.TrimSpace(config["username"])
p.password = config["password"] p.password = config["password"]
p.brand = strings.TrimSpace(config["brand"]) p.brand = p.fixedBrand
if p.brand == "" {
p.brand = strings.TrimSpace(config["brand"])
}
if p.brand == "" { if p.brand == "" {
p.brand = "T" p.brand = "T"
} }
p.auth = authFor(p.brand)
// Config change invalidates any cached token. // Config change invalidates any cached token.
p.tok = nil p.tok = nil
@@ -242,13 +328,23 @@ func (p *Plugin) Invoke(ctx context.Context, action string, params json.RawMessa
return nil, fmt.Errorf("toyota: action %q requires a vin", action) return nil, fmt.Errorf("toyota: action %q requires a vin", action)
} }
body, _, err := p.apiRequest(ctx, http.MethodGet, endpoint, pp.VIN, nil) body, status, err := p.apiRequest(ctx, http.MethodGet, endpoint, pp.VIN, nil)
if err != nil && endpoint == epElectricStatus && electricFallback(status) {
body, _, err = p.apiRequest(ctx, http.MethodGet, epElectricStatusLegacy, pp.VIN, nil)
}
if err != nil { if err != nil {
return nil, err return nil, err
} }
return json.RawMessage(body), nil return json.RawMessage(body), nil
} }
// electricFallback reports whether a failed read of the new electric route should
// be retried on the old one: a 403 is the gateway's answer for a route a token
// may not use, a 404 one it does not know. Anything else would fail there too.
func electricFallback(status int) bool {
return status == http.StatusForbidden || status == http.StatusNotFound
}
// Shutdown releases pooled connections. // Shutdown releases pooled connections.
func (p *Plugin) Shutdown(context.Context) error { func (p *Plugin) Shutdown(context.Context) error {
p.mu.Lock() p.mu.Lock()
@@ -339,7 +435,7 @@ func (p *Plugin) performAuthentication(ctx context.Context) (string, error) {
payload = b payload = b
} }
resp, err := p.postRaw(ctx, authenticateURL, "application/json", payload, false) resp, err := p.postRaw(ctx, p.auth.authenticateURL, "application/json", payload, false)
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -361,7 +457,7 @@ func (p *Plugin) performAuthentication(ctx context.Context) (string, error) {
// performAuthorization exchanges the tokenId (as an SSO cookie) for an // performAuthorization exchanges the tokenId (as an SSO cookie) for an
// authorization code carried in the 302 Location header. // authorization code carried in the 302 Location header.
func (p *Plugin) performAuthorization(ctx context.Context, tokenID string) (string, error) { func (p *Plugin) performAuthorization(ctx context.Context, tokenID string) (string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, authorizeURL, nil) req, err := http.NewRequestWithContext(ctx, http.MethodGet, p.auth.authorizeURL, nil)
if err != nil { if err != nil {
return "", err return "", err
} }
@@ -388,9 +484,9 @@ func (p *Plugin) performAuthorization(ctx context.Context, tokenID string) (stri
// it. Caller holds p.mu. // it. Caller holds p.mu.
func (p *Plugin) retrieveTokens(ctx context.Context, code string) error { func (p *Plugin) retrieveTokens(ctx context.Context, code string) error {
form := url.Values{} form := url.Values{}
form.Set("client_id", "oneapp") form.Set("client_id", p.auth.clientID)
form.Set("code", code) form.Set("code", code)
form.Set("redirect_uri", redirectURI) form.Set("redirect_uri", p.auth.redirectURI)
form.Set("grant_type", "authorization_code") form.Set("grant_type", "authorization_code")
form.Set("code_verifier", "plain") form.Set("code_verifier", "plain")
return p.tokenRequest(ctx, form) return p.tokenRequest(ctx, form)
@@ -403,8 +499,8 @@ func (p *Plugin) refreshTokens(ctx context.Context) error {
return errors.New("toyota: no refresh token") return errors.New("toyota: no refresh token")
} }
form := url.Values{} form := url.Values{}
form.Set("client_id", "oneapp") form.Set("client_id", p.auth.clientID)
form.Set("redirect_uri", redirectURI) form.Set("redirect_uri", p.auth.redirectURI)
form.Set("grant_type", "refresh_token") form.Set("grant_type", "refresh_token")
form.Set("code_verifier", "plain") form.Set("code_verifier", "plain")
form.Set("refresh_token", p.tok.refreshToken) form.Set("refresh_token", p.tok.refreshToken)
@@ -413,11 +509,11 @@ func (p *Plugin) refreshTokens(ctx context.Context) error {
// tokenRequest POSTs a form to the access-token endpoint and stores the result. // tokenRequest POSTs a form to the access-token endpoint and stores the result.
func (p *Plugin) tokenRequest(ctx context.Context, form url.Values) error { func (p *Plugin) tokenRequest(ctx context.Context, form url.Values) error {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, accessTokenURL, strings.NewReader(form.Encode())) req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.auth.accessTokenURL, strings.NewReader(form.Encode()))
if err != nil { if err != nil {
return err return err
} }
req.Header.Set("authorization", basicAuth) req.Header.Set("authorization", p.auth.basicAuth)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := p.authClient.Do(req) resp, err := p.authClient.Do(req)
@@ -547,11 +643,18 @@ func (p *Plugin) applyHeaders(h http.Header, vin string, tok tokenInfo) {
set("x-channel", "ONEAPP") set("x-channel", "ONEAPP")
set("x-brand", p.brand) set("x-brand", p.brand)
set("x-region", "EU") set("x-region", "EU")
// x-user-region mirrors x-region. The gateway only insists on it for remote
// commands on Suzuki-badged DCM24 cars (CTP-GENERIC-40017 otherwise), which
// this connector never sends, but the app sets it on every call and the
// reads are cheaper to keep identical to the app than to keep distinct.
set("x-user-region", "EU")
set("authorization", "Bearer "+tok.accessToken) set("authorization", "Bearer "+tok.accessToken)
set("user-agent", userAgent) set("user-agent", userAgent)
if p.brand == "L" { // The non-Toyota brands name themselves twice more; a Toyota account sends
set("x-appbrand", "L") // neither header.
set("brand", "L") if p.brand == "L" || p.brand == "S" {
set("x-appbrand", p.brand)
set("brand", p.brand)
} }
if vin != "" { if vin != "" {
set("vin", vin) set("vin", vin)
@@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"net/http"
"strings" "strings"
"testing" "testing"
@@ -21,18 +22,22 @@ func TestDescriptor(t *testing.T) {
if len(d.Capabilities) == 0 { if len(d.Capabilities) == 0 {
t.Fatal("expected capabilities") t.Fatal("expected capabilities")
} }
// The credential + brand fields must be advertised. They are intentionally // The credential fields must be advertised. They are intentionally NOT
// NOT required at the global layer — credentials come from the per-user // required at the global layer — credentials come from the per-user cascade —
// cascade — and the password field must be marked secret. // and the password field must be marked secret. There is no brand field: each
// brand is a registration of its own.
fields := map[string]plugins.ConfigField{} fields := map[string]plugins.ConfigField{}
for _, f := range d.ConfigFields { for _, f := range d.ConfigFields {
fields[f.Key] = f fields[f.Key] = f
} }
for _, k := range []string{"username", "password", "brand"} { for _, k := range []string{"username", "password"} {
if _, ok := fields[k]; !ok { if _, ok := fields[k]; !ok {
t.Errorf("config field %q should be present", k) t.Errorf("config field %q should be present", k)
} }
} }
if _, ok := fields["brand"]; ok {
t.Error("the brand is fixed per registration and must not be a config field")
}
if fields["username"].Required || fields["password"].Required { if fields["username"].Required || fields["password"].Required {
t.Error("credentials must not be required at the global layer (per-user cascade)") t.Error("credentials must not be required at the global layer (per-user cascade)")
} }
@@ -41,6 +46,105 @@ func TestDescriptor(t *testing.T) {
} }
} }
// TestBrandRegistrations pins the three faces of the one connector: each brand
// is its own plugin name with its brand fixed, so the panel and the apps list
// Toyota, Lexus and Subaru separately, and a config cannot move one onto
// another's login.
func TestBrandRegistrations(t *testing.T) {
want := map[string]string{"toyota": "T", "lexus": "L", "subaru": "S"}
if len(Brands) != len(want) {
t.Fatalf("Brands = %d entries, want %d", len(Brands), len(want))
}
for _, b := range Brands {
code, ok := want[b.Name]
if !ok || code != b.Code {
t.Errorf("brand %q has code %q, want %q", b.Name, b.Code, code)
}
p := &Plugin{fixedBrand: b.Code}
if d := p.Descriptor(); d.Name != b.Name || d.Category != plugins.CategoryVehicles {
t.Errorf("brand %q: descriptor name %q category %q", b.Name, d.Name, d.Category)
}
// A stray brand in config (a pre-split setting) must not win.
_ = p.Init(context.Background(), map[string]string{"username": "u", "password": "p", "brand": "T"})
if p.brand != b.Code {
t.Errorf("brand %q: Init with brand=T gave %q", b.Name, p.brand)
}
}
s := &Plugin{fixedBrand: "S"}
_ = s.Init(context.Background(), map[string]string{"username": "u", "password": "p"})
if s.auth.clientID != subaruAuth.clientID {
t.Errorf("subaru registration logs in as %q", s.auth.clientID)
}
}
// TestBrandAuth pins the per-brand login: Toyota and Lexus are the MyToyota app
// in the "tme" realm, Subaru is its own client in "alliance-subaru". A brand on
// the wrong realm authenticates against a user directory it is not in, which
// reads as a bad password.
func TestBrandAuth(t *testing.T) {
for _, brand := range []string{"", "T", "L"} {
a := authFor(brand)
if a.clientID != "oneapp" || !strings.Contains(a.authenticateURL, "/realms/tme/") {
t.Errorf("brand %q: expected the oneapp client in realm tme, got %q at %s", brand, a.clientID, a.authenticateURL)
}
}
s := authFor("S")
if !strings.HasSuffix(s.clientID, ".subaru.com") || !strings.Contains(s.accessTokenURL, "/realms/alliance-subaru/") {
t.Errorf("Subaru: expected its own client in realm alliance-subaru, got %q at %s", s.clientID, s.accessTokenURL)
}
if s.redirectURI != "com.subaru.oneapp:/oauth2Callback" {
t.Errorf("Subaru redirect = %q", s.redirectURI)
}
if !strings.Contains(s.authorizeURL, "client_id="+s.clientID+"&") || !strings.Contains(s.authorizeURL, "redirect_uri="+s.redirectURI+"&") {
t.Errorf("Subaru authorize URL does not carry its own client and redirect: %s", s.authorizeURL)
}
// The three URLs of one brand must share a realm.
if !strings.Contains(s.authorizeURL, "/realms/alliance-subaru/") || !strings.Contains(s.authenticateURL, "/realms/alliance-subaru/") {
t.Error("Subaru login URLs disagree on the realm")
}
if s.basicAuth == toyotaAuth.basicAuth {
t.Error("Subaru must present its own client credentials")
}
// Init picks the client for the configured brand.
p := &Plugin{}
_ = p.Init(context.Background(), map[string]string{"username": "u", "password": "p", "brand": "S"})
if p.auth.clientID != s.clientID {
t.Errorf("Init(brand=S) chose client %q", p.auth.clientID)
}
}
// TestHeadersFollowUpstream keeps the request headers in step with what the app
// sends: x-user-region on every call, and the brand named twice more for the
// non-Toyota brands only.
func TestHeadersFollowUpstream(t *testing.T) {
tok := tokenInfo{accessToken: "at", uuid: "uuid-1"}
headers := func(brand string) http.Header {
p := &Plugin{}
_ = p.Init(context.Background(), map[string]string{"username": "u", "password": "p", "brand": brand})
h := http.Header{}
p.applyHeaders(h, "VIN1", tok)
return h
}
for _, brand := range []string{"T", "L", "S"} {
h := headers(brand)
if got := h["x-user-region"]; len(got) != 1 || got[0] != "EU" {
t.Errorf("brand %s: x-user-region = %v, want [EU]", brand, got)
}
if got := h["x-brand"]; len(got) != 1 || got[0] != brand {
t.Errorf("brand %s: x-brand = %v", brand, got)
}
_, appbrand := h["x-appbrand"]
_, bare := h["brand"]
if brand == "T" && (appbrand || bare) {
t.Error("a Toyota account must not send x-appbrand/brand")
}
if brand != "T" && (!appbrand || !bare || h["x-appbrand"][0] != brand || h["brand"][0] != brand) {
t.Errorf("brand %s: x-appbrand=%v brand=%v, want both = %s", brand, h["x-appbrand"], h["brand"], brand)
}
}
}
// TestEndpointsFollowUpstream guards the mid-2026 migration: Toyota put the // TestEndpointsFollowUpstream guards the mid-2026 migration: Toyota put the
// /v1/global/remote read routes behind AWS SigV4, where a Bearer token is // /v1/global/remote read routes behind AWS SigV4, where a Bearer token is
// answered with 403, and the app moved to /v1/vehicle/*. Falling back to the old // answered with 403, and the app moved to /v1/vehicle/*. Falling back to the old
@@ -61,9 +165,18 @@ func TestEndpointsFollowUpstream(t *testing.T) {
if epRemoteStatus != "/v1/vehicle/status" { if epRemoteStatus != "/v1/vehicle/status" {
t.Errorf("status endpoint = %q, want /v1/vehicle/status", epRemoteStatus) t.Errorf("status endpoint = %q, want /v1/vehicle/status", epRemoteStatus)
} }
// The electric route was not part of that migration and must stay put. // The electric read moved later than the rest, and keeps its old route only
if epElectricStatus != "/v1/global/remote/electric/status" { // as the fallback for a gateway that has not caught up.
t.Errorf("electric endpoint = %q, want the unmoved global route", epElectricStatus) if epElectricStatus != "/v1/vehicle/electric/status" {
t.Errorf("electric endpoint = %q, want /v1/vehicle/electric/status", epElectricStatus)
}
if epElectricStatusLegacy != "/v1/global/remote/electric/status" {
t.Errorf("electric fallback = %q, want the old global route", epElectricStatusLegacy)
}
for status, want := range map[int]bool{403: true, 404: true, 401: false, 429: false, 500: false, 0: false} {
if got := electricFallback(status); got != want {
t.Errorf("electricFallback(%d) = %v, want %v", status, got, want)
}
} }
} }
+4 -3
View File
@@ -44,7 +44,8 @@ const (
StatusDown = "down" StatusDown = "down"
) )
// SelectOption is one choice for a ConfigField of Type "select". // SelectOption is one choice for a ConfigField of Type "select" (pick one) or
// "multiselect" (pick any number; stored as a comma-separated list of values).
type SelectOption struct { type SelectOption struct {
Value string `json:"value"` Value string `json:"value"`
Label string `json:"label"` Label string `json:"label"`
@@ -55,12 +56,12 @@ type SelectOption struct {
type ConfigField struct { type ConfigField struct {
Key string `json:"key"` Key string `json:"key"`
Label string `json:"label"` Label string `json:"label"`
Type string `json:"type"` // "text" | "password" | "number" | "select" Type string `json:"type"` // "text" | "password" | "number" | "select" | "multiselect"
Required bool `json:"required"` Required bool `json:"required"`
Secret bool `json:"secret"` // never echoed back to clients in clear Secret bool `json:"secret"` // never echoed back to clients in clear
Help string `json:"help,omitempty"` Help string `json:"help,omitempty"`
Default string `json:"default,omitempty"` // effective default when unset Default string `json:"default,omitempty"` // effective default when unset
Options []SelectOption `json:"options,omitempty"` // for Type "select" Options []SelectOption `json:"options,omitempty"` // for Type "select" and "multiselect"
} }
// Capability is one operation a plugin exposes. It maps a stable id to the // Capability is one operation a plugin exposes. It maps a stable id to the
+4 -4
View File
@@ -192,10 +192,10 @@ const providersApi = [
]; ];
const integrationsApi = [ const integrationsApi = [
{ method: "GET", path: "/api/integrations/toyota", desc: "Resolved Toyota Connected settings (secrets masked)" }, { method: "GET", path: "/api/integrations/{toyota|lexus|subaru}", desc: "Resolved settings for one brand of Toyota Connected (secrets masked)" },
{ method: "PUT", path: "/api/integrations/toyota", desc: "Save the caller's own layer (user or org scope)" }, { method: "PUT", path: "/api/integrations/{toyota|lexus|subaru}", desc: "Save the caller's own layer (user or org scope)" },
{ method: "POST", path: "/api/integrations/toyota/health", desc: "Live probe with the resolved credentials" }, { method: "POST", path: "/api/integrations/{toyota|lexus|subaru}/health", desc: "Live probe with the resolved credentials" },
{ method: "GET", path: "/api/integrations/toyota/vehicles", desc: "Raw MyToyota vehicle payload" }, { method: "GET", path: "/api/integrations/{toyota|lexus|subaru}/vehicles", desc: "Raw vehicle payload from that brand's account" },
{ method: "GET", path: "/api/integrations/anker-solix", desc: "Resolved Anker Solix settings (secrets masked)" }, { method: "GET", path: "/api/integrations/anker-solix", desc: "Resolved Anker Solix settings (secrets masked)" },
{ method: "PUT", path: "/api/integrations/anker-solix", desc: "Save the caller's own layer (user or org scope)" }, { method: "PUT", path: "/api/integrations/anker-solix", desc: "Save the caller's own layer (user or org scope)" },
{ method: "POST", path: "/api/integrations/anker-solix/health", desc: "Live probe with the resolved credentials" }, { method: "POST", path: "/api/integrations/anker-solix/health", desc: "Live probe with the resolved credentials" },
@@ -62,6 +62,31 @@ function expand(p) {
open.value = p.name; open.value = p.name;
} }
// A multiselect field is a comma-separated list of option values in the same
// flat string map every other field uses, so the PUT body stays unchanged.
function multiValues(name, key) {
return String(drafts[name]?.[key] ?? "")
.split(",")
.map((v) => v.trim())
.filter(Boolean);
}
function hasMulti(name, key, value) {
return multiValues(name, key).includes(value);
}
function toggleMulti(name, key, value, on) {
const set = new Set(multiValues(name, key));
if (on) set.add(value);
else set.delete(value);
// Keep the declared option order rather than click order, so the stored value
// is stable across edits.
const p = plugins.value.find((x) => x.name === name);
const order = (p?.configFields || []).find((f) => f.key === key)?.options || [];
drafts[name][key] = order
.map((o) => o.value)
.filter((v) => set.has(v))
.join(",");
}
async function save(p, enabled) { async function save(p, enabled) {
busy.value = true; busy.value = true;
rowNotice[p.name] = ""; rowNotice[p.name] = "";
@@ -224,7 +249,25 @@ const healthClass = (s) =>
<label class="dh-label"> <label class="dh-label">
{{ f.label || f.key }}<span v-if="f.required" class="text-danger"> *</span> {{ f.label || f.key }}<span v-if="f.required" class="text-danger"> *</span>
</label> </label>
<select v-if="f.type === 'select'" v-model="drafts[p.name][f.key]" class="dh-select"> <!-- multiselect: any number of the declared options, stored as a
comma-separated list. Nothing checked means the field imposes
nothing, which is the unset state for a select too. -->
<div v-if="f.type === 'multiselect'" class="flex flex-col gap-1.5 pt-1">
<label
v-for="o in f.options || []"
:key="o.value"
class="flex items-center gap-2 text-sm text-body"
>
<input
type="checkbox"
class="dh-checkbox"
:checked="hasMulti(p.name, f.key, o.value)"
@change="toggleMulti(p.name, f.key, o.value, $event.target.checked)"
/>
<span>{{ o.label || o.value }}</span>
</label>
</div>
<select v-else-if="f.type === 'select'" v-model="drafts[p.name][f.key]" class="dh-select">
<!-- A non-required select can be left unset (empty), so the global <!-- A non-required select can be left unset (empty), so the global
layer abstains and lower layers (org / user) may choose. --> layer abstains and lower layers (org / user) may choose. -->
<option v-if="!f.required" value="">{{ t("plugins.notSet") }}</option> <option v-if="!f.required" value="">{{ t("plugins.notSet") }}</option>
+14
View File
@@ -293,6 +293,20 @@ body {
border-color: var(--accent); border-color: var(--accent);
box-shadow: 0 0 0 3px var(--focus-ring); box-shadow: 0 0 0 3px var(--focus-ring);
} }
/* Checkbox for multiselect config fields. accent-color keeps the native control
(and its keyboard behaviour) while tinting it to the panel's accent. */
.dh-checkbox {
width: 15px;
height: 15px;
flex: none;
accent-color: var(--accent);
cursor: pointer;
}
.dh-checkbox:focus-visible {
outline: none;
box-shadow: 0 0 0 3px var(--focus-ring);
border-radius: 3px;
}
.dh-label { .dh-label {
display: block; display: block;
margin-bottom: 5px; margin-bottom: 5px;
+41 -1
View File
@@ -462,6 +462,31 @@ const DESIRED = {
// defined through the API, so it is declared here like the audit trail's. // defined through the API, so it is declared here like the audit trail's.
F.autodate("created", true, false), F.autodate("created", true, false),
], ],
// The home-charger scheduler: a user's own list of charging tasks, one list
// covering every charger they own. The charger's own cloud schedule holds one
// window per box; this holds as many tasks as they like, each naming its own
// chargers, days and action. Run by the ticker in the API Server
// (internal/api/chargingtasks_run.go).
charging_tasks: [
F.text("name", true),
// The home_chargers rows this task acts on. A list of ids rather than a
// relation because empty has to mean "every charger I own" — a standing wish
// that keeps covering chargers imported later.
F.json("chargers", 2000),
// The flow: [{action, amps, time}, …] in the order it runs. A whole charging
// window is one task rather than the two that would otherwise open and close
// it, so it is named once and switched off once. Times are 24-hour "HH:MM"
// read in the zone below.
F.json("steps", 4000),
F.text("zone"),
F.json("days", 200), // 0=Sunday … 6=Saturday; empty means every day
F.bool("enabled"),
F.text("last_run"), // RFC3339, UTC — also the guard against a double firing
F.text("last_result"),
// Owner. Non-cascading, like a charger's.
F.relation("owner", "users", false, false),
F.autodate("created", true, false),
],
// Server-wide settings as a single record, keyed "global". Today it holds // Server-wide settings as a single record, keyed "global". Today it holds
// pluginSettings: the top (L1) layer of the integration cascade — every // pluginSettings: the top (L1) layer of the integration cascade — every
// plugin's enable state, its global config, and the registration of any // plugin's enable state, its global config, and the registration of any
@@ -490,6 +515,13 @@ const DESIRED = {
F.select("theme", ["light", "dark", "system"]), F.select("theme", ["light", "dark", "system"]),
F.text("locale"), F.text("locale"),
F.select("date_format", ["YMD", "DMY_NUM", "DMY", "MDY"]), F.select("date_format", ["YMD", "DMY_NUM", "DMY", "MDY"]),
// "auto" is the region's own convention. Kept in step with
// validTimeFormats in internal/api/me.go.
F.select("time_format", ["auto", "24", "12"]),
// The day a week is drawn as starting on, wherever a client lays weekdays
// out in a row. "auto" is the region's own convention. Kept in step with
// validWeekStarts in internal/api/me.go.
F.select("week_start", ["auto", "monday", "sunday"]),
// European currencies plus the non-European ones the panel already offered. // European currencies plus the non-European ones the panel already offered.
// Kept in step with validCurrencies in internal/api/me.go and CURRENCY_CODES // Kept in step with validCurrencies in internal/api/me.go and CURRENCY_CODES
// in the web app's Settings.vue. // in the web app's Settings.vue.
@@ -546,6 +578,11 @@ const INDEXES = {
// A charger is looked up by its owner, and by serial when checking whether the // A charger is looked up by its owner, and by serial when checking whether the
// account it came from has already been imported. // account it came from has already been imported.
home_chargers: ["CREATE INDEX `idx_home_chargers_owner_serial` ON `home_chargers` (`owner`, `serial`)"], home_chargers: ["CREATE INDEX `idx_home_chargers_owner_serial` ON `home_chargers` (`owner`, `serial`)"],
// The runner sweeps every enabled task on every tick, and the page reads one
// owner's; both go through these two columns.
charging_tasks: [
"CREATE INDEX `idx_charging_tasks_owner_enabled` ON `charging_tasks` (`owner`, `enabled`)",
],
// Audit is queried "this charger's events, newest first" and "this user's events". // Audit is queried "this charger's events, newest first" and "this user's events".
control_audit: [ control_audit: [
"CREATE INDEX `idx_control_audit_serial_created` ON `control_audit` (`serial`, `created`)", "CREATE INDEX `idx_control_audit_serial_created` ON `control_audit` (`serial`, `created`)",
@@ -583,6 +620,7 @@ async function main() {
"reminders", "reminders",
"control_audit", "control_audit",
"home_chargers", "home_chargers",
"charging_tasks",
]) { ]) {
if (collections.some((c) => c.name === name)) continue; if (collections.some((c) => c.name === name)) continue;
await createCollection(token, name, DESIRED[name], format, idByName); await createCollection(token, name, DESIRED[name], format, idByName);
@@ -611,6 +649,7 @@ async function main() {
"reminders", "reminders",
"control_audit", "control_audit",
"home_chargers", "home_chargers",
"charging_tasks",
]) { ]) {
await reconcileFields(token, name, DESIRED[name], format, idByName); await reconcileFields(token, name, DESIRED[name], format, idByName);
} }
@@ -619,7 +658,8 @@ async function main() {
"\nDone. Collections ready: app_settings, organizations, users, cars,\n" + "\nDone. Collections ready: app_settings, organizations, users, cars,\n" +
"service_records,\n" + "service_records,\n" +
"technical_checks, parts, car_shares, fuel_entries, charging_sessions,\n" + "technical_checks, parts, car_shares, fuel_entries, charging_sessions,\n" +
"maintenance_entries, car_documents, reminders, control_audit, home_chargers.", "maintenance_entries, car_documents, reminders, control_audit, home_chargers,\n" +
"charging_tasks.",
); );
console.log( console.log(
"Note: the legacy `sessions` collection is no longer used (auth moved to PocketBase\n" + "Note: the legacy `sessions` collection is no longer used (auth moved to PocketBase\n" +
+85
View File
@@ -0,0 +1,85 @@
# DriverVault all-in-one — production config.
# Copy to .env and fill in, then:
# docker compose -f docker-compose.prod.s3.yml pull
# docker compose -f docker-compose.prod.s3.yml up -d
# --- Registry image ----------------------------------------------------------
AIO_IMAGE=10.2.1.10:5500/admin/drivervault-aio:latest
# --- PocketBase superuser (required) -----------------------------------------
# Created/updated on first boot. The API Server uses these to manage the database.
PB_ADMIN_EMAIL=admin@example.com
PB_ADMIN_PASSWORD=change-me-long-password
# --- DriverVault super-admin (app login) -------------------------------------
# The first application user, created by the API Server on boot with role
# "superadmin" if no user with this email exists yet. Leave blank to skip.
DRIVERVAULT_SUPERADMIN_EMAIL=owner@example.com
DRIVERVAULT_SUPERADMIN_PASSWORD=change-me-long-password
DRIVERVAULT_SUPERADMIN_NAME=Administrator
# Schema creation/reconcile on boot. Leave this true: a release can add
# collections or fields the server needs, and a stack that skips the bootstrap
# never gets them. (The API Server creates app_settings, which holds the plugin
# settings, on demand — but only that one.) Set false only for a database you
# know already matches the release.
PB_BOOTSTRAP=true
# Allowed CORS origin(s) — match your public web URL / WEB_PORT.
CORS_ALLOW_ORIGINS=http://localhost:8090
# --- EV charging control (Anker Solix, OCPP) ---------------------------------
# Only relevant when a charger is set to own/proxy control mode. The charger
# dials in to /ocpp/{serial} on the API Server port, carrying its control token
# in an OCPP Basic-auth header — which a plaintext ws:// would expose, so
# non-TLS connections are rejected by default. This image serves plain HTTP, so
# terminate TLS in a reverse proxy in front of it and set OCPP_PUBLIC_URL to the
# public wss:// base the charger should be pointed at. Turning the check off is
# for trusted networks only.
OCPP_REQUIRE_TLS=true
OCPP_PUBLIC_URL=
# --- Host port mappings (optional; defaults shown) --------------------------
WEB_PORT=8090
PB_PORT=8070
API_PORT=8080
# --- Settings the API Server panel can also change ---------------------------
# The panel's Settings screens apply these immediately, but only for the life of
# the container — the value below is re-applied on every restart and wins. Set it
# here to make a change permanent. (POCKETBASE_URL is fixed to this container's
# own PocketBase and is not meant to be repointed.)
# WEBAPP_URL the Web App address the panel status page probes; nginx
# serves it on port 80 inside this container.
# CORS_ALLOW_ORIGINS browser origins allowed to call the API Server directly.
# WEBAPP_URL=http://127.0.0.1:80
# --- Storage -----------------------------------------------------------------
# One Docker-managed named volume by default. Set it to an absolute host path
# for a bind mount, e.g. PB_DATA=/srv/drivervault/pb_data.
# PB_DATA — the PocketBase database and uploads. It is the only volume in the
# image: the API Server keeps no state on disk, so everything it owns (plugin
# settings included) is backed up by backing up this one path.
PB_DATA=pb_data
# --- File storage: external S3 -----------------------------------------------
# PocketBase keeps its record files — document scans, service and refill
# receipts, workshop invoices, part photos — in the bucket below instead of on
# PB_DATA. The database and PocketBase's own backups stay where they are.
#
# Nothing in this stack runs a gateway: both the endpoint and the bucket must
# already exist. For a gateway on this Docker host use
# http://host.docker.internal:8333 — the compose file adds the host entry that
# makes that name resolve inside the containers.
PB_S3_ENDPOINT=http://10.2.1.10:8333
PB_S3_BUCKET=drivervault
PB_S3_ACCESS_KEY=
PB_S3_SECRET=
# SeaweedFS and MinIO ignore the region; PocketBase insists on having one.
PB_S3_REGION=us-east-1
# true for SeaweedFS and MinIO, false for AWS S3 proper.
PB_S3_FORCE_PATH_STYLE=true
# Existing uploads are NOT migrated when this is switched on: PocketBase copies
# nothing, so attachments made before the switch stop resolving. Read the file
# storage section of README.md first.
+99
View File
@@ -0,0 +1,99 @@
# DriverVault all-in-one — production config, SeaweedFS built into the same
# image (Dockerfile.seaweedfs). Copy to .env and fill in, then:
# docker compose -f docker-compose.prod.seaweedfs.yml build
# docker compose -f docker-compose.prod.seaweedfs.yml up -d
# The build needs the repo checkout; to deploy elsewhere, `push` after building
# and `pull` on the deploy host.
# --- Image -------------------------------------------------------------------
# The tag the build produces and `push`/`pull` use. Its own name, not
# drivervault-aio: this image carries SeaweedFS and expects two volumes.
AIO_IMAGE=10.2.1.10:5500/admin/drivervault-aio-seaweedfs:latest
# Build args, both pinned in the Dockerfile. Set to override at build time.
# PB_VERSION=0.39.11
# SEAWEED_VERSION=4.45
# --- PocketBase superuser (required) -----------------------------------------
# Created/updated on first boot. The API Server uses these to manage the database.
PB_ADMIN_EMAIL=admin@example.com
PB_ADMIN_PASSWORD=change-me-long-password
# --- DriverVault super-admin (app login) -------------------------------------
# The first application user, created by the API Server on boot with role
# "superadmin" if no user with this email exists yet. Leave blank to skip.
DRIVERVAULT_SUPERADMIN_EMAIL=owner@example.com
DRIVERVAULT_SUPERADMIN_PASSWORD=change-me-long-password
DRIVERVAULT_SUPERADMIN_NAME=Administrator
# Schema creation/reconcile on boot. Leave this true: a release can add
# collections or fields the server needs, and a stack that skips the bootstrap
# never gets them. (The API Server creates app_settings, which holds the plugin
# settings, on demand — but only that one.) Set false only for a database you
# know already matches the release.
PB_BOOTSTRAP=true
# Allowed CORS origin(s) — match your public web URL / WEB_PORT.
CORS_ALLOW_ORIGINS=http://localhost:8090
# --- EV charging control (Anker Solix, OCPP) ---------------------------------
# Only relevant when a charger is set to own/proxy control mode. The charger
# dials in to /ocpp/{serial} on the API Server port, carrying its control token
# in an OCPP Basic-auth header — which a plaintext ws:// would expose, so
# non-TLS connections are rejected by default. This image serves plain HTTP, so
# terminate TLS in a reverse proxy in front of it and set OCPP_PUBLIC_URL to the
# public wss:// base the charger should be pointed at. Turning the check off is
# for trusted networks only.
OCPP_REQUIRE_TLS=true
OCPP_PUBLIC_URL=
# --- Host port mappings (optional; defaults shown) --------------------------
WEB_PORT=8090
PB_PORT=8070
API_PORT=8080
# --- Settings the API Server panel can also change ---------------------------
# The panel's Settings screens apply these immediately, but only for the life of
# the container — the value below is re-applied on every restart and wins. Set it
# here to make a change permanent. (POCKETBASE_URL is fixed to this container's
# own PocketBase and is not meant to be repointed.)
# WEBAPP_URL the Web App address the panel status page probes; nginx
# serves it on port 80 inside this container.
# CORS_ALLOW_ORIGINS browser origins allowed to call the API Server directly.
# WEBAPP_URL=http://127.0.0.1:80
# --- Storage -----------------------------------------------------------------
# One Docker-managed named volume by default. Set it to an absolute host path
# for a bind mount, e.g. PB_DATA=/srv/drivervault/pb_data.
# PB_DATA — the PocketBase database and its backups. The API Server keeps no
# state on disk, so everything it owns (plugin settings included) is backed up
# by backing up this one path — together with SEAWEED_DATA below.
PB_DATA=pb_data
# --- File storage: SeaweedFS -------------------------------------------------
# PocketBase keeps its record files — document scans, service and refill
# receipts, workshop invoices, part photos — in the bucket below instead of on
# PB_DATA. The database and PocketBase's own backups stay where they are.
#
# The credentials do double duty: they configure the SeaweedFS gateway's single
# identity *and* are what PocketBase authenticates with. There are no safe
# defaults, and the container refuses to start without them.
PB_S3_ACCESS_KEY=
PB_S3_SECRET=
# The bucket. Created on first boot by PocketBase's program, before it serves.
PB_S3_BUCKET=drivervault
# The endpoint, region and path style are fixed by the image — the gateway is
# inside the container at a loopback address that cannot change.
# SEAWEED_DATA — where SeaweedFS keeps the files. A Docker-managed named volume
# by default; set an absolute host path for a bind mount, the same way PB_DATA
# works above. Back it up alongside PB_DATA: from here on the attachments live
# here, not in the database volume.
# It is mounted at /seaweed/data, the layout `weed server -dir` writes — the
# same one the .split. files use, so the two are interchangeable on it.
SEAWEED_DATA=seaweed_data
# The S3 gateway publishes no host port: PocketBase reaches it inside the
# container.
# Existing uploads are NOT migrated when this is switched on: PocketBase copies
# nothing, so attachments made before the switch stop resolving. Read the file
# storage section of README.md first.
@@ -0,0 +1,131 @@
# DriverVault all-in-one — production config, SeaweedFS split into its roles and
# built into the same image (Dockerfile.seaweedfs.split). Copy to .env and fill
# in, then:
# docker compose -f docker-compose.prod.seaweedfs.split.yml build
# docker compose -f docker-compose.prod.seaweedfs.split.yml up -d
# The build needs the repo checkout; to deploy elsewhere, `push` after building
# and `pull` on the deploy host.
# --- Image -------------------------------------------------------------------
# The tag the build produces and `push`/`pull` use. Its own name, not
# drivervault-aio: this image carries SeaweedFS and expects three volumes.
AIO_IMAGE=10.2.1.10:5500/admin/drivervault-aio-seaweedfs-split:latest
# Build args, both pinned in the Dockerfile. Set to override at build time.
# PB_VERSION=0.39.11
# SEAWEED_VERSION=4.45
# --- PocketBase superuser (required) -----------------------------------------
# Created/updated on first boot. The API Server uses these to manage the database.
PB_ADMIN_EMAIL=admin@example.com
PB_ADMIN_PASSWORD=change-me-long-password
# --- DriverVault super-admin (app login) -------------------------------------
# The first application user, created by the API Server on boot with role
# "superadmin" if no user with this email exists yet. Leave blank to skip.
DRIVERVAULT_SUPERADMIN_EMAIL=owner@example.com
DRIVERVAULT_SUPERADMIN_PASSWORD=change-me-long-password
DRIVERVAULT_SUPERADMIN_NAME=Administrator
# Schema creation/reconcile on boot. Leave this true: a release can add
# collections or fields the server needs, and a stack that skips the bootstrap
# never gets them. (The API Server creates app_settings, which holds the plugin
# settings, on demand — but only that one.) Set false only for a database you
# know already matches the release.
PB_BOOTSTRAP=true
# Allowed CORS origin(s) — match your public web URL / WEB_PORT.
CORS_ALLOW_ORIGINS=http://localhost:8090
# --- EV charging control (Anker Solix, OCPP) ---------------------------------
# Only relevant when a charger is set to own/proxy control mode. The charger
# dials in to /ocpp/{serial} on the API Server port, carrying its control token
# in an OCPP Basic-auth header — which a plaintext ws:// would expose, so
# non-TLS connections are rejected by default. This image serves plain HTTP, so
# terminate TLS in a reverse proxy in front of it and set OCPP_PUBLIC_URL to the
# public wss:// base the charger should be pointed at. Turning the check off is
# for trusted networks only.
OCPP_REQUIRE_TLS=true
OCPP_PUBLIC_URL=
# --- Host port mappings (optional; defaults shown) --------------------------
WEB_PORT=8090
PB_PORT=8070
API_PORT=8080
# --- Settings the API Server panel can also change ---------------------------
# The panel's Settings screens apply these immediately, but only for the life of
# the container — the value below is re-applied on every restart and wins. Set it
# here to make a change permanent. (POCKETBASE_URL is fixed to this container's
# own PocketBase and is not meant to be repointed.)
# WEBAPP_URL the Web App address the panel status page probes; nginx
# serves it on port 80 inside this container.
# CORS_ALLOW_ORIGINS browser origins allowed to call the API Server directly.
# WEBAPP_URL=http://127.0.0.1:80
# --- Storage -----------------------------------------------------------------
# One Docker-managed named volume by default. Set it to an absolute host path
# for a bind mount, e.g. PB_DATA=/srv/drivervault/pb_data.
# PB_DATA — the PocketBase database and its backups. The API Server keeps no
# state on disk, so everything it owns (plugin settings included) is backed up
# by backing up this one path — together with SEAWEED_DATA below.
PB_DATA=pb_data
# --- File storage: SeaweedFS -------------------------------------------------
# PocketBase keeps its record files — document scans, service and refill
# receipts, workshop invoices, part photos — in the bucket below instead of on
# PB_DATA. The database and PocketBase's own backups stay where they are.
#
# The credentials do double duty: the S3 gateway's program writes them into the
# filer's IAM store as the identity named "drivervault" *and* they are what
# PocketBase authenticates with. There are no safe defaults, and the container
# refuses to start without them. Change them here and restart to rotate: the
# seed updates the identity in place rather than adding a second one.
PB_S3_ACCESS_KEY=
PB_S3_SECRET=
# The bucket. Created on first boot by the S3 gateway's program.
PB_S3_BUCKET=drivervault
# The endpoint, region and path style are fixed by the image — the gateway is
# inside the container at a loopback address that cannot change.
# SEAWEED_DATA — where SeaweedFS keeps the files. A Docker-managed named volume
# by default; set an absolute host path for a bind mount, the same way PB_DATA
# works above. Back it up alongside PB_DATA: from here on the attachments live
# here, not in the database volume.
#
# Master, volume and filer share it (mounted at /seaweed/data), which is the
# layout `weed server -dir` writes — so this file and
# docker-compose.prod.seaweedfs.yml are interchangeable on the same volume, with
# nothing to migrate either way.
SEAWEED_DATA=seaweed_data
# The S3 gateway publishes no host port: PocketBase reaches it inside the
# container. The master, volume and filer listen on the container's loopback
# and publish no host port at all. The admin UI below shows what they would: the volume
# server in particular serves file content by id with no authentication. Reach
# them with `docker compose exec drivervault wget -qO- http://127.0.0.1:9333/...`
# (volume 8081, filer 8888).
# --- SeaweedFS admin UI ------------------------------------------------------
# Cluster topology, volumes, buckets, maintenance tasks, and Object Store →
# Users, where further S3 identities are created and revoked. They land in the
# filer's IAM store, the same one seeded above, and the gateway picks them up
# without a restart.
#
# REQUIRED: weed disables authentication entirely when the password is empty,
# and this panel can mint credentials for the bucket — so the image refuses to
# start the panel at all without one, and the container stays unhealthy.
SEAWEED_ADMIN_USER=admin
SEAWEED_ADMIN_PASSWORD=
# Optional view-only login.
SEAWEED_ADMIN_READONLY_USER=
SEAWEED_ADMIN_READONLY_PASSWORD=
# Bound to localhost by default: storage
# plumbing, not one of the app's own panels. On a remote host that means
# unreachable — set 0.0.0.0 and put it behind a reverse proxy.
SEAWEED_ADMIN_BIND=127.0.0.1
SEAWEED_ADMIN_PORT=23646
# Its own small volume: session key and maintenance-task state, no object data.
SEAWEED_ADMIN_DATA=seaweed_admin
# Existing uploads are NOT migrated when this is switched on: PocketBase copies
# nothing, so attachments made before the switch stop resolving. Read the file
# storage section of README.md first.
+79
View File
@@ -0,0 +1,79 @@
# Copy to .env and fill in. Used by the Docker-AIO docker-compose.s3.yml.
# --- Required (no defaults) --------------------------------------------------
# PocketBase superuser, also used by the API Server to authenticate.
PB_ADMIN_EMAIL=admin@example.com
PB_ADMIN_PASSWORD=change-me-long-password
# --- DriverVault super-admin (app login) -------------------------------------
# The first application user, created by the API Server on boot with role
# "superadmin" if no user with this email exists yet. Leave blank to skip.
DRIVERVAULT_SUPERADMIN_EMAIL=owner@example.com
DRIVERVAULT_SUPERADMIN_PASSWORD=change-me-long-password
DRIVERVAULT_SUPERADMIN_NAME=Administrator
# Schema creation/reconcile on boot. Leave this true: a release can add
# collections or fields the server needs, and a stack that skips the bootstrap
# never gets them. (The API Server creates app_settings, which holds the plugin
# settings, on demand — but only that one.) Set false only for a database you
# know already matches the release.
PB_BOOTSTRAP=true
# Allowed CORS origin(s) — match your web origin / WEB_PORT.
CORS_ALLOW_ORIGINS=http://localhost:8090
# --- EV charging control (Anker Solix, OCPP) ---------------------------------
# Only relevant when a charger is set to own/proxy control mode. The charger
# dials in to /ocpp/{serial} on the API Server port, carrying its control token
# in an OCPP Basic-auth header — which a plaintext ws:// would expose, so
# non-TLS connections are rejected by default. This image serves plain HTTP:
# either terminate TLS in front of it and set OCPP_PUBLIC_URL to the public
# wss:// base, or set OCPP_REQUIRE_TLS=false on a trusted network.
OCPP_REQUIRE_TLS=true
OCPP_PUBLIC_URL=
# --- Host port mappings (optional; defaults shown) --------------------------
WEB_PORT=8090
PB_PORT=8070
# API Server + its embedded web panel (served at the API root, http://host:8080/).
API_PORT=8080
# --- Build args (optional) ---------------------------------------------------
# Leave empty so the browser uses same-origin /api (proxied by nginx).
VITE_API_BASE=
# PocketBase version. The Dockerfile already pins one; set this only to build a
# different version. Leaving it commented out keeps the pin (an empty value here
# is passed through as-is and would resolve the latest release at build time).
#PB_VERSION=0.39.11
# --- Settings the API Server panel can also change ---------------------------
# The panel's Settings screens apply these immediately, but only for the life of
# the container — the value below is re-applied on every restart and wins. Set it
# here to make a change permanent. (POCKETBASE_URL is fixed to this container's
# own PocketBase and is not meant to be repointed.)
# WEBAPP_URL the Web App address the panel status page probes; nginx
# serves it on port 80 inside this container.
# CORS_ALLOW_ORIGINS browser origins allowed to call the API Server directly.
# WEBAPP_URL=http://127.0.0.1:80
# --- File storage: external S3 -----------------------------------------------
# PocketBase keeps its record files — document scans, service and refill
# receipts, workshop invoices, part photos — in the bucket below instead of on
# pb_data. The database and PocketBase's own backups stay where they are.
#
# Nothing in this stack runs a gateway: both the endpoint and the bucket must
# already exist. For a gateway on this Docker host use
# http://host.docker.internal:8333 — the compose file adds the host entry that
# makes that name resolve inside the containers.
PB_S3_ENDPOINT=http://host.docker.internal:8333
PB_S3_BUCKET=drivervault
PB_S3_ACCESS_KEY=
PB_S3_SECRET=
# SeaweedFS and MinIO ignore the region; PocketBase insists on having one.
PB_S3_REGION=us-east-1
# true for SeaweedFS and MinIO, false for AWS S3 proper.
PB_S3_FORCE_PATH_STYLE=true
# Existing uploads are NOT migrated when this is switched on: PocketBase copies
# nothing, so attachments made before the switch stop resolving. Read the file
# storage section of README.md first.
+78
View File
@@ -0,0 +1,78 @@
# Copy to .env and fill in. Used by the Docker-AIO docker-compose.seaweedfs.yml.
# --- Required (no defaults) --------------------------------------------------
# PocketBase superuser, also used by the API Server to authenticate.
PB_ADMIN_EMAIL=admin@example.com
PB_ADMIN_PASSWORD=change-me-long-password
# --- DriverVault super-admin (app login) -------------------------------------
# The first application user, created by the API Server on boot with role
# "superadmin" if no user with this email exists yet. Leave blank to skip.
DRIVERVAULT_SUPERADMIN_EMAIL=owner@example.com
DRIVERVAULT_SUPERADMIN_PASSWORD=change-me-long-password
DRIVERVAULT_SUPERADMIN_NAME=Administrator
# Schema creation/reconcile on boot. Leave this true: a release can add
# collections or fields the server needs, and a stack that skips the bootstrap
# never gets them. (The API Server creates app_settings, which holds the plugin
# settings, on demand — but only that one.) Set false only for a database you
# know already matches the release.
PB_BOOTSTRAP=true
# Allowed CORS origin(s) — match your web origin / WEB_PORT.
CORS_ALLOW_ORIGINS=http://localhost:8090
# --- EV charging control (Anker Solix, OCPP) ---------------------------------
# Only relevant when a charger is set to own/proxy control mode. The charger
# dials in to /ocpp/{serial} on the API Server port, carrying its control token
# in an OCPP Basic-auth header — which a plaintext ws:// would expose, so
# non-TLS connections are rejected by default. This image serves plain HTTP:
# either terminate TLS in front of it and set OCPP_PUBLIC_URL to the public
# wss:// base, or set OCPP_REQUIRE_TLS=false on a trusted network.
OCPP_REQUIRE_TLS=true
OCPP_PUBLIC_URL=
# --- Host port mappings (optional; defaults shown) --------------------------
WEB_PORT=8090
PB_PORT=8070
# API Server + its embedded web panel (served at the API root, http://host:8080/).
API_PORT=8080
# --- Build args (optional) ---------------------------------------------------
# Leave empty so the browser uses same-origin /api (proxied by nginx).
VITE_API_BASE=
# PocketBase version. The Dockerfile already pins one; set this only to build a
# different version. Leaving it commented out keeps the pin (an empty value here
# is passed through as-is and would resolve the latest release at build time).
#PB_VERSION=0.39.11
# --- Settings the API Server panel can also change ---------------------------
# The panel's Settings screens apply these immediately, but only for the life of
# the container — the value below is re-applied on every restart and wins. Set it
# here to make a change permanent. (POCKETBASE_URL is fixed to this container's
# own PocketBase and is not meant to be repointed.)
# WEBAPP_URL the Web App address the panel status page probes; nginx
# serves it on port 80 inside this container.
# CORS_ALLOW_ORIGINS browser origins allowed to call the API Server directly.
# WEBAPP_URL=http://127.0.0.1:80
# --- File storage: SeaweedFS -------------------------------------------------
# PocketBase keeps its record files — document scans, service and refill
# receipts, workshop invoices, part photos — in the bucket below instead of on
# pb_data. The database and PocketBase's own backups stay where they are.
#
# The credentials do double duty: they configure the SeaweedFS gateway's single
# identity *and* are what PocketBase authenticates with. There are no safe
# defaults, and the stack refuses to start without them.
PB_S3_ACCESS_KEY=
PB_S3_SECRET=
# The bucket. Created on first boot by the seaweedfs-init container.
PB_S3_BUCKET=drivervault
# SeaweedFS ignores the region; PocketBase insists on having one.
PB_S3_REGION=us-east-1
# The gateway image, pinned so a rebuild months from now brings up the same one.
# SEAWEED_IMAGE=chrislusf/seaweedfs:4.45
# Existing uploads are NOT migrated when this is switched on: PocketBase copies
# nothing, so attachments made before the switch stop resolving. Read the file
# storage section of README.md first.
+107
View File
@@ -0,0 +1,107 @@
# Copy to .env and fill in. Used by the Docker-AIO
# docker-compose.seaweedfs.split.yml — the same stack as .env.seaweedfs.example,
# with SeaweedFS running as separate master / volume / filer / S3 containers
# plus the SeaweedFS admin UI.
# --- Required (no defaults) --------------------------------------------------
# PocketBase superuser, also used by the API Server to authenticate.
PB_ADMIN_EMAIL=admin@example.com
PB_ADMIN_PASSWORD=change-me-long-password
# --- DriverVault super-admin (app login) -------------------------------------
# The first application user, created by the API Server on boot with role
# "superadmin" if no user with this email exists yet. Leave blank to skip.
DRIVERVAULT_SUPERADMIN_EMAIL=owner@example.com
DRIVERVAULT_SUPERADMIN_PASSWORD=change-me-long-password
DRIVERVAULT_SUPERADMIN_NAME=Administrator
# Schema creation/reconcile on boot. Leave this true: a release can add
# collections or fields the server needs, and a stack that skips the bootstrap
# never gets them. (The API Server creates app_settings, which holds the plugin
# settings, on demand — but only that one.) Set false only for a database you
# know already matches the release.
PB_BOOTSTRAP=true
# Allowed CORS origin(s) — match your web origin / WEB_PORT.
CORS_ALLOW_ORIGINS=http://localhost:8090
# --- EV charging control (Anker Solix, OCPP) ---------------------------------
# Only relevant when a charger is set to own/proxy control mode. The charger
# dials in to /ocpp/{serial} on the API Server port, carrying its control token
# in an OCPP Basic-auth header — which a plaintext ws:// would expose, so
# non-TLS connections are rejected by default. This image serves plain HTTP:
# either terminate TLS in front of it and set OCPP_PUBLIC_URL to the public
# wss:// base, or set OCPP_REQUIRE_TLS=false on a trusted network.
OCPP_REQUIRE_TLS=true
OCPP_PUBLIC_URL=
# --- Host port mappings (optional; defaults shown) --------------------------
WEB_PORT=8090
PB_PORT=8070
# API Server + its embedded web panel (served at the API root, http://host:8080/).
API_PORT=8080
# --- Build args (optional) ---------------------------------------------------
# Leave empty so the browser uses same-origin /api (proxied by nginx).
VITE_API_BASE=
# PocketBase version. The Dockerfile already pins one; set this only to build a
# different version. Leaving it commented out keeps the pin (an empty value here
# is passed through as-is and would resolve the latest release at build time).
#PB_VERSION=0.39.11
# --- Settings the API Server panel can also change ---------------------------
# The panel's Settings screens apply these immediately, but only for the life of
# the container — the value below is re-applied on every restart and wins. Set it
# here to make a change permanent. (POCKETBASE_URL is fixed to this container's
# own PocketBase and is not meant to be repointed.)
# WEBAPP_URL the Web App address the panel status page probes; nginx
# serves it on port 80 inside this container.
# CORS_ALLOW_ORIGINS browser origins allowed to call the API Server directly.
# WEBAPP_URL=http://127.0.0.1:80
# --- File storage: SeaweedFS -------------------------------------------------
# PocketBase keeps its record files — document scans, service and refill
# receipts, workshop invoices, part photos — in the bucket below instead of on
# pb_data. The database and PocketBase's own backups stay where they are.
#
# The credentials do double duty: seaweedfs-init writes them into the filer's
# IAM store as the identity named "drivervault" *and* they are what PocketBase
# authenticates with. There are no safe defaults, and the stack refuses to start
# without them. Change them here and restart to rotate: the seed updates the
# identity in place rather than adding a second one.
PB_S3_ACCESS_KEY=
PB_S3_SECRET=
# The bucket. Created on first boot by the seaweedfs-init container.
PB_S3_BUCKET=drivervault
# SeaweedFS ignores the region; PocketBase insists on having one.
PB_S3_REGION=us-east-1
# The SeaweedFS image, pinned so a rebuild months from now brings up the same
# one. All five SeaweedFS containers run it.
# SEAWEED_IMAGE=chrislusf/seaweedfs:4.45
# --- SeaweedFS admin UI ------------------------------------------------------
# http://localhost:23646 — cluster topology, volumes, buckets, and
# Object Store → Users, where further S3 identities are created and revoked.
# They land in the filer's IAM store, the same one seeded above, and the gateway
# picks them up without a restart.
#
# REQUIRED: weed disables authentication entirely when the password is empty,
# and this panel can mint credentials for the bucket.
SEAWEED_ADMIN_USER=admin
SEAWEED_ADMIN_PASSWORD=
# SEAWEED_ADMIN_PORT=23646
# --- SeaweedFS host ports (optional; defaults shown) -------------------------
# Published for aws-cli, `weed shell` and poking around while developing. The
# stack itself reaches every one of these over the compose network, and the S3
# gateway too, which is not published so a second stack cannot clash on it.
# Note SEAWEED_VOLUME_PORT: the volume server serves file content by id with NO
# authentication, so do not carry this mapping over to a shared machine. It
# lands on 8081 because API_PORT already has 8080.
# SEAWEED_MASTER_PORT=9333
# SEAWEED_VOLUME_PORT=8081
# SEAWEED_FILER_PORT=8888
# Existing uploads are NOT migrated when this is switched on: PocketBase copies
# nothing, so attachments made before the switch stop resolving. Read the file
# storage section of README.md first.
+361
View File
@@ -0,0 +1,361 @@
# syntax=docker/dockerfile:1
#
# All-in-one image WITH the object store inside: PocketBase + API Server + Web
# App, plus SeaweedFS as one `weed server -s3` process — master, volume, filer
# and S3 gateway as goroutines — under supervisord in the same container.
#
# This is Dockerfile with the two SeaweedFS containers of
# docker-compose.prod.seaweedfs.yml folded in. That compose file kept them
# outside the image so SeaweedFS could be upgraded without a rebuild; this file
# trades that away for a single image and a single container. What it costs: a
# new SeaweedFS means a rebuild (--build-arg SEAWEED_VERSION). For per-role
# restart, metrics and the admin UI, see Dockerfile.seaweedfs.split.
#
# The build context MUST be the project root so this file can reach both
# "API Server/" and "Web App/". The root .dockerignore is an allow-list of the
# paths copied below — add to it if you add a COPY here. Build it with:
#
# docker build -f "Docker-AIO/Dockerfile.seaweedfs" -t drivervault-aio-seaweedfs .
#
# Run it (everything starts together):
#
# docker run -d --name drivervault -p 80:80 -p 8070:8070 -p 8080:8080 \
# -e PB_ADMIN_EMAIL=admin@example.com \
# -e PB_ADMIN_PASSWORD=change-me \
# -e PB_S3_ACCESS_KEY=drivervault -e PB_S3_SECRET=change-me \
# -v drivervault_pb:/pb/pb_data \
# -v drivervault_seaweed:/seaweed/data \
# drivervault-aio-seaweedfs
#
# Then: web app on http://host/ and PocketBase admin on http://host:8070/_/.
# On first boot PocketBase's program creates the bucket, and the API Server
# creates the collections, the super-admin, and points PocketBase's file
# storage at the bucket.
#
# Port map inside the container (only 80, 8070, 8080 and 8333 are meant to be
# published):
#
# 80 nginx (Web App, /api/ and /ocpp/ proxied)
# 8070 PocketBase
# 8080 API Server ← which is why the volume server is NOT on its
# 8081 SeaweedFS volume usual 8080 here
# 8333 SeaweedFS S3 gateway (PocketBase's endpoint; publish on loopback)
# 8888 SeaweedFS filer
# 9333 SeaweedFS master
# SeaweedFS release to bake in, pinned like PB_VERSION so a rebuild months from
# now brings up the same one. Same tag the compose SeaweedFS files run as
# SEAWEED_IMAGE. Override with --build-arg SEAWEED_VERSION=... to upgrade.
ARG SEAWEED_VERSION="4.45"
# --- Stage 1: build the Go API Server ---------------------------------------
FROM golang:1.26-alpine3.24 AS api-build
WORKDIR /src
COPY ["API Server/go.mod", "./"]
COPY ["API Server/go.su[m]", "./"]
RUN go mod download
# Only cmd/ + internal are needed; the panel is already built into
# internal/api/dist and embedded via //go:embed. Entry point is cmd/server.
COPY ["API Server/cmd", "./cmd"]
COPY ["API Server/internal", "./internal"]
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/api-server ./cmd/server
# --- Stage 2: build the Vue Web App -----------------------------------------
# The Vue source lives under "Web App/web/".
FROM node:22-alpine3.24 AS web-build
WORKDIR /app
COPY ["Web App/web/package.json", "Web App/web/package-lock.json", "./"]
RUN npm ci
COPY ["Web App/web/index.html", "Web App/web/vite.config.js", "./"]
COPY ["Web App/web/src", "./src"]
COPY ["Web App/web/public", "./public"]
# Empty -> bundle uses same-origin "/api", proxied to the API Server by nginx.
ARG VITE_API_BASE
# vite.config writes to ../server/dist by default; emit into ./dist here.
RUN npm run build -- --outDir dist --emptyOutDir
# --- Stage 3: SeaweedFS -----------------------------------------------------
# The one static binary from the official image. SEAWEED_VERSION is declared at
# the top of the file: an ARG used in a FROM has to be global, and one declared
# here would belong to the stage above and expand to nothing.
FROM chrislusf/seaweedfs:${SEAWEED_VERSION} AS seaweed
# --- Stage 4: runtime (all services) ----------------------------------------
FROM alpine:3.24
# Pinned so a rebuild months from now produces the same PocketBase. Override to
# upgrade (--build-arg PB_VERSION=0.40.0); set it to empty to resolve the latest
# release at build time, which needs an unauthenticated GitHub API call and is
# therefore subject to that GitHub rate limit (60/hour per IP).
ARG PB_VERSION="0.39.11"
# Provided automatically by BuildKit (amd64 / arm64).
ARG TARGETARCH="amd64"
RUN apk add --no-cache ca-certificates tzdata unzip wget nginx supervisor \
&& mkdir -p /run/nginx
# Unprivileged account for PocketBase, the API Server and SeaweedFS. Only nginx
# stays root, because it binds port 80; supervisord drops to this user for
# everything else.
RUN addgroup -S app && adduser -S -G app app
# PocketBase from the official release (pinned via PB_VERSION, else latest).
WORKDIR /pb
RUN set -eux; \
ver="${PB_VERSION}"; \
if [ -z "$ver" ]; then \
ver="$(wget -qO- https://api.github.com/repos/pocketbase/pocketbase/releases/latest \
| grep -o '"tag_name": *"v[^"]*"' | head -1 | sed -E 's/.*"v([^"]+)".*/\1/')"; \
fi; \
echo "Installing PocketBase v${ver} (${TARGETARCH})"; \
wget -q -O /tmp/pb.zip \
"https://github.com/pocketbase/pocketbase/releases/download/v${ver}/pocketbase_${ver}_linux_${TARGETARCH}.zip"; \
unzip /tmp/pb.zip -d /pb; \
rm /tmp/pb.zip
# API Server binary, built Web App static assets, and the weed binary.
COPY --from=api-build /out/api-server /usr/local/bin/api-server
COPY --from=web-build /app/dist /usr/share/nginx/html
COPY --from=seaweed /usr/bin/weed /usr/local/bin/weed
# WebSocket handshakes need Connection/Upgrade forwarded, and the map deriving
# them must sit in the http context, not inside a server block. It goes in
# http.d/ (which Alpine nginx includes from http{}; it does not read conf.d/),
# and the 00- prefix keeps it ahead of default.conf in the include order.
RUN cat > /etc/nginx/http.d/00-upgrade.conf <<'NGINXMAP'
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
NGINXMAP
# nginx: serve the SPA and proxy /api/ + /ocpp/ to the API Server on localhost.
RUN cat > /etc/nginx/http.d/default.conf <<'NGINX'
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
gzip on;
gzip_types text/plain text/css application/javascript application/json image/svg+xml;
gzip_min_length 1024;
# A real liveness route, so the SPA fallback below cannot answer a health
# probe with index.html and make a broken container look healthy.
location = /healthz {
access_log off;
add_header Content-Type text/plain;
return 200 "ok";
}
location /api/ {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
# Forward WebSocket upgrades instead of silently stripping them.
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# The chargers' door, not the browser's. The API Server tells a charger to
# dial the host it was itself asked on — this one — so without this location
# the SPA fallback would answer the WebSocket handshake with index.html.
location /ocpp/ {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# A charging session is idle between heartbeats; the default 60s would
# close it under the charger.
proxy_read_timeout 1h;
proxy_send_timeout 1h;
}
location /assets/ {
expires 1y;
add_header Cache-Control "public, immutable";
try_files $uri =404;
}
location / {
try_files $uri $uri/ /index.html;
}
}
NGINX
# supervisord runs the four processes and keeps them alive. Priorities only
# order the launches; readiness is the `until wget` loop in front of each
# program that needs another one up, the same chain the compose file spells out
# with depends_on + healthchecks: SeaweedFS → bucket → PocketBase → API Server.
RUN cat > /etc/supervisord.conf <<'SUPERVISOR'
[supervisord]
nodaemon=true
user=root
pidfile=/run/supervisord.pid
logfile=/dev/null
logfile_maxbytes=0
; SeaweedFS: one process, four roles — master, volume, filer and the S3
; gateway. -dir is the only state it keeps. -ip=127.0.0.1 is the address the
; roles advertise to each other, which is where they are; -ip.bind stays open
; so the gateway can be published (weed server has one bind flag for all four,
; and the volume server, on 8081 because 8080 is the API Server, serves file
; content by id with no authentication — so never publish 8081).
;
; SeaweedFS falls back to AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY when started
; without an -s3.config file, and configuring one identity is what takes the
; gateway out of its default allow-anyone mode. They are the PB_S3_* pair
; PocketBase authenticates with, mapped here so there is one pair to set — and
; an empty pair means no gateway rather than an open one.
[program:seaweedfs]
user=app
command=/bin/sh -c 'if [ -z "$PB_S3_ACCESS_KEY" ] || [ -z "$PB_S3_SECRET" ]; then echo "seaweedfs: PB_S3_ACCESS_KEY and PB_S3_SECRET are required; refusing to start an unauthenticated gateway" >&2; exit 1; fi; export AWS_ACCESS_KEY_ID="$PB_S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$PB_S3_SECRET"; exec /usr/local/bin/weed server -dir=/seaweed/data -ip=127.0.0.1 -ip.bind=0.0.0.0 -volume.port=8081 -s3 -master.volumeSizeLimitMB=1024'
priority=1
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
; PocketBase: wait for the S3 gateway — it is the process that reads and writes
; the objects, so the bucket has to be serving before it does, exactly as the
; compose file gates the whole container on the gateway's health. Then create
; the bucket: PocketBase never issues a CreateBucket of its own and SeaweedFS
; will not conjure one on first upload. Creating a bucket that already exists is
; a no-op, and `|| true` keeps a restart from being blocked by the shell's exit
; status — a gateway that is genuinely broken is reported by the API Server's
; own S3 check at boot, with the reason. Then upsert the superuser (idempotent)
; and serve. Runs as the unprivileged app user, which owns /pb and the pb_data
; volume.
[program:pocketbase]
directory=/pb
user=app
command=/bin/sh -c 'until wget -qO- http://127.0.0.1:8333/healthz >/dev/null 2>&1; do echo "waiting for seaweedfs..."; sleep 1; done; echo "s3.bucket.create -name $PB_S3_BUCKET" | /usr/local/bin/weed shell -master=127.0.0.1:9333 || true; /pb/pocketbase superuser upsert "$PB_ADMIN_EMAIL" "$PB_ADMIN_PASSWORD" 2>/dev/null || true; exec /pb/pocketbase serve --http=0.0.0.0:8070'
priority=10
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
; API Server: wait for PocketBase to be healthy, then start. Its bootstrap
; points PocketBase's file storage at the bucket and asks it to prove the
; gateway is reachable. It keeps no state on disk — plugin settings, like
; everything else it owns, live in PocketBase — so its working directory is
; just a place to run from.
[program:api-server]
directory=/app
user=app
command=/bin/sh -c 'until wget -qO- http://127.0.0.1:8070/api/health >/dev/null 2>&1; do echo "waiting for pocketbase..."; sleep 1; done; exec /usr/local/bin/api-server'
priority=20
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
; nginx stays root so it can bind :80; its own workers drop to the nginx user.
[program:nginx]
command=/usr/sbin/nginx -g 'daemon off;'
priority=30
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
SUPERVISOR
# The entrypoint stays root only long enough to make the data volumes writable
# by the app user, then hands off to supervisord. The chown matters for a host
# bind mount, which arrives owned by root rather than inheriting the image's
# owner.
RUN cat > /entrypoint.sh <<'ENTRY'
#!/bin/sh
set -e
for dir in /pb/pb_data /seaweed/data; do
mkdir -p "$dir"
if [ "$(stat -c %U "$dir" 2>/dev/null)" != "app" ]; then
echo "entrypoint: taking ownership of $dir"
chown -R app:app "$dir"
fi
done
exec supervisord -c /etc/supervisord.conf
ENTRY
RUN chmod +x /entrypoint.sh
# API Server config: everything is local to this container. WEBAPP_URL is what
# the panel status page probes; nginx serves the Web App on :80 in here, so the
# stock default of localhost:8090 would always report the Web App as down.
#
# File storage is on by construction: the gateway is in this image, at a fixed
# loopback address, path style because a self-hosted gateway has no per-bucket
# DNS. The region is a formality SeaweedFS ignores and PocketBase insists on.
# supervisord passes these through to the API Server, whose bootstrap writes
# them into PocketBase's settings on every boot. Only record files move — scans,
# receipts, invoices, part photos; the database and PocketBase's own backups
# stay on /pb/pb_data.
ENV API_ADDR=:8080 \
POCKETBASE_URL=http://127.0.0.1:8070 \
CORS_ALLOW_ORIGINS=http://localhost:8090 \
AUTH_USERS_COLLECTION=users \
WEBAPP_URL=http://127.0.0.1:80 \
PB_S3_ENABLED=true \
PB_S3_ENDPOINT=http://127.0.0.1:8333 \
PB_S3_BUCKET=drivervault \
PB_S3_REGION=us-east-1 \
PB_S3_FORCE_PATH_STYLE=true
# Required at runtime (no safe defaults): PB_ADMIN_EMAIL, PB_ADMIN_PASSWORD;
# PB_S3_ACCESS_KEY, PB_S3_SECRET (the gateway's single identity AND what
# PocketBase authenticates with — the gateway refuses to start without them).
# Optional: DRIVERVAULT_SUPERADMIN_EMAIL / DRIVERVAULT_SUPERADMIN_PASSWORD create
# the first app super-admin on boot. PB_BOOTSTRAP=false skips schema setup —
# leave it on: a release can add collections or fields the server needs, and a
# stack that skips the bootstrap never gets them. (app_settings, which holds the
# plugin settings, is created on demand; nothing else is.)
# For Anker Solix charger control, OCPP_REQUIRE_TLS (default true) rejects
# chargers that did not arrive over TLS — this image serves plain HTTP, so put a
# TLS-terminating proxy in front and set OCPP_PUBLIC_URL to the public wss://
# base, or set OCPP_REQUIRE_TLS=false on a trusted network.
# Pass them with `docker run -e ...`.
# Two volumes. /pb/pb_data: the database, the uploads made before S3 was on,
# PocketBase's own backups, and the server settings — the API Server keeps no
# state on disk. /seaweed/data: everything SeaweedFS keeps, in the layout
# `weed server -dir` writes — the same one the split image's master, volume and
# filer share, so a SEAWEED_DATA volume from any of the SeaweedFS compose files
# mounts here unchanged, and vice versa. Both pre-created and owned by app so a
# fresh named volume inherits that ownership.
RUN mkdir -p /pb/pb_data /seaweed/data /app \
&& chown -R app:app /pb /seaweed /app
VOLUME ["/pb/pb_data", "/seaweed/data"]
# 80 = Web App, 8070 = PocketBase admin, 8080 = API Server + embedded API panel
# (also the /ocpp/{serial} endpoint chargers dial into), 8333 = S3 gateway (for
# aws-cli and the like; loopback is enough).
EXPOSE 80 8070 8080 8333
# Every process must answer, so a wedged component shows up in `docker ps`
# instead of a container that looks up while part of it is dead. start-period
# covers SeaweedFS coming up plus the first-boot schema bootstrap on a cold
# database.
HEALTHCHECK --interval=30s --timeout=10s --start-period=90s --retries=3 \
CMD wget -qO- http://127.0.0.1:9333/cluster/status >/dev/null 2>&1 \
&& wget -qO- http://127.0.0.1:8333/healthz >/dev/null 2>&1 \
&& wget -qO- http://127.0.0.1:8070/api/health >/dev/null 2>&1 \
&& wget -qO- http://127.0.0.1:8080/healthz >/dev/null 2>&1 \
&& wget -qO- http://127.0.0.1:80/healthz >/dev/null 2>&1 \
|| exit 1
ENTRYPOINT ["/entrypoint.sh"]
+462
View File
@@ -0,0 +1,462 @@
# syntax=docker/dockerfile:1
#
# All-in-one image WITH the object store inside: PocketBase + API Server + Web
# App, plus SeaweedFS split into its roles — master, volume, filer, S3 gateway
# and the admin UI — each its own supervisord program in the same container.
#
# This is Dockerfile with the six SeaweedFS containers of
# docker-compose.prod.seaweedfs.split.yml folded in. The compose split kept
# them outside the image so SeaweedFS could be upgraded without a rebuild; this
# file trades that away for a single image and a single container. What the
# split still buys in here: per-role restart under supervisord, per-role
# metrics ports, and the admin UI, where S3 identities are minted and revoked.
# What it costs: a new SeaweedFS means a rebuild (--build-arg SEAWEED_VERSION).
#
# The build context MUST be the project root so this file can reach both
# "API Server/" and "Web App/". The root .dockerignore is an allow-list of the
# paths copied below — add to it if you add a COPY here. Build it with:
#
# docker build -f "Docker-AIO/Dockerfile.seaweedfs.split" -t drivervault-aio-seaweedfs-split .
#
# Run it (everything starts together):
#
# docker run -d --name drivervault -p 80:80 -p 8070:8070 -p 8080:8080 \
# -p 127.0.0.1:23646:23646 \
# -e PB_ADMIN_EMAIL=admin@example.com \
# -e PB_ADMIN_PASSWORD=change-me \
# -e PB_S3_ACCESS_KEY=drivervault -e PB_S3_SECRET=change-me \
# -e WEED_ADMIN_PASSWORD=change-me \
# -v drivervault_pb:/pb/pb_data \
# -v drivervault_seaweed:/seaweed/data \
# -v drivervault_seaweed_admin:/seaweed/admin \
# drivervault-aio-seaweedfs-split
#
# Then: web app on http://host/, PocketBase admin on http://host:8070/_/, and
# the SeaweedFS admin UI on http://127.0.0.1:23646/. On first boot the S3
# gateway's program creates the bucket and seeds PocketBase's identity, and the
# API Server creates the collections, the super-admin, and points PocketBase's
# file storage at the bucket.
#
# Port map inside the container (only 80, 8070, 8080, 8333 and 23646 are meant
# to be published; the rest are bound to loopback):
#
# 80 nginx (Web App, /api/ and /ocpp/ proxied)
# 8070 PocketBase
# 8080 API Server ← which is why the volume server is NOT on its
# 8081 SeaweedFS volume usual 8080 here
# 8333 SeaweedFS S3 gateway (PocketBase's endpoint; publish on loopback)
# 8888 SeaweedFS filer
# 9333 SeaweedFS master
# 23646 SeaweedFS admin UI (publish on loopback, behind a proxy if remote)
# SeaweedFS release to bake in, pinned like PB_VERSION so a rebuild months from
# now brings up the same one. Same tag the compose SeaweedFS files run as
# SEAWEED_IMAGE. Override with --build-arg SEAWEED_VERSION=... to upgrade.
ARG SEAWEED_VERSION="4.45"
# --- Stage 1: build the Go API Server ---------------------------------------
FROM golang:1.26-alpine3.24 AS api-build
WORKDIR /src
COPY ["API Server/go.mod", "./"]
COPY ["API Server/go.su[m]", "./"]
RUN go mod download
# Only cmd/ + internal are needed; the panel is already built into
# internal/api/dist and embedded via //go:embed. Entry point is cmd/server.
COPY ["API Server/cmd", "./cmd"]
COPY ["API Server/internal", "./internal"]
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/api-server ./cmd/server
# --- Stage 2: build the Vue Web App -----------------------------------------
# The Vue source lives under "Web App/web/".
FROM node:22-alpine3.24 AS web-build
WORKDIR /app
COPY ["Web App/web/package.json", "Web App/web/package-lock.json", "./"]
RUN npm ci
COPY ["Web App/web/index.html", "Web App/web/vite.config.js", "./"]
COPY ["Web App/web/src", "./src"]
COPY ["Web App/web/public", "./public"]
# Empty -> bundle uses same-origin "/api", proxied to the API Server by nginx.
ARG VITE_API_BASE
# vite.config writes to ../server/dist by default; emit into ./dist here.
RUN npm run build -- --outDir dist --emptyOutDir
# --- Stage 3: SeaweedFS -----------------------------------------------------
# The one static binary from the official image. SEAWEED_VERSION is declared at
# the top of the file: an ARG used in a FROM has to be global, and one declared
# here would belong to the stage above and expand to nothing.
FROM chrislusf/seaweedfs:${SEAWEED_VERSION} AS seaweed
# --- Stage 4: runtime (all services) ----------------------------------------
FROM alpine:3.24
# Pinned so a rebuild months from now produces the same PocketBase. Override to
# upgrade (--build-arg PB_VERSION=0.40.0); set it to empty to resolve the latest
# release at build time, which needs an unauthenticated GitHub API call and is
# therefore subject to that GitHub rate limit (60/hour per IP).
ARG PB_VERSION="0.39.11"
# Provided automatically by BuildKit (amd64 / arm64).
ARG TARGETARCH="amd64"
RUN apk add --no-cache ca-certificates tzdata unzip wget nginx supervisor \
&& mkdir -p /run/nginx
# Unprivileged account for PocketBase, the API Server and every SeaweedFS role.
# Only nginx stays root, because it binds port 80; supervisord drops to this
# user for everything else.
RUN addgroup -S app && adduser -S -G app app
# PocketBase from the official release (pinned via PB_VERSION, else latest).
WORKDIR /pb
RUN set -eux; \
ver="${PB_VERSION}"; \
if [ -z "$ver" ]; then \
ver="$(wget -qO- https://api.github.com/repos/pocketbase/pocketbase/releases/latest \
| grep -o '"tag_name": *"v[^"]*"' | head -1 | sed -E 's/.*"v([^"]+)".*/\1/')"; \
fi; \
echo "Installing PocketBase v${ver} (${TARGETARCH})"; \
wget -q -O /tmp/pb.zip \
"https://github.com/pocketbase/pocketbase/releases/download/v${ver}/pocketbase_${ver}_linux_${TARGETARCH}.zip"; \
unzip /tmp/pb.zip -d /pb; \
rm /tmp/pb.zip
# API Server binary, built Web App static assets, and the weed binary.
COPY --from=api-build /out/api-server /usr/local/bin/api-server
COPY --from=web-build /app/dist /usr/share/nginx/html
COPY --from=seaweed /usr/bin/weed /usr/local/bin/weed
# WebSocket handshakes need Connection/Upgrade forwarded, and the map deriving
# them must sit in the http context, not inside a server block. It goes in
# http.d/ (which Alpine nginx includes from http{}; it does not read conf.d/),
# and the 00- prefix keeps it ahead of default.conf in the include order.
RUN cat > /etc/nginx/http.d/00-upgrade.conf <<'NGINXMAP'
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
NGINXMAP
# nginx: serve the SPA and proxy /api/ + /ocpp/ to the API Server on localhost.
RUN cat > /etc/nginx/http.d/default.conf <<'NGINX'
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
gzip on;
gzip_types text/plain text/css application/javascript application/json image/svg+xml;
gzip_min_length 1024;
# A real liveness route, so the SPA fallback below cannot answer a health
# probe with index.html and make a broken container look healthy.
location = /healthz {
access_log off;
add_header Content-Type text/plain;
return 200 "ok";
}
location /api/ {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
# Forward WebSocket upgrades instead of silently stripping them.
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# The chargers' door, not the browser's. The API Server tells a charger to
# dial the host it was itself asked on — this one — so without this location
# the SPA fallback would answer the WebSocket handshake with index.html.
location /ocpp/ {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# A charging session is idle between heartbeats; the default 60s would
# close it under the charger.
proxy_read_timeout 1h;
proxy_send_timeout 1h;
}
location /assets/ {
expires 1y;
add_header Cache-Control "public, immutable";
try_files $uri =404;
}
location / {
try_files $uri $uri/ /index.html;
}
}
NGINX
# Bucket and identity seed, run by the S3 gateway's program before it serves.
# Two jobs, both idempotent, so every boot re-applies the values from the
# environment and changes nothing else — which is also how a rotated
# PB_S3_SECRET reaches the gateway:
#
# 1. create the bucket — PocketBase never issues a CreateBucket of its own;
# 2. write PocketBase's S3 identity into the filer's IAM store.
#
# (2) is why the gateway below runs with neither an -config file nor
# AWS_ACCESS_KEY_ID: the env vars are the lowest-priority credential source in
# SeaweedFS, read only while the filer's store is empty, so the first identity
# added in the admin UI would silently displace them and lock PocketBase out.
# Seeding the store the admin UI itself writes leaves one source of truth, and
# PocketBase's key shows under Object Store → Users like any other.
#
# The closing grep is the gate: an empty IAM store means the gateway would come
# up in its allow-anyone default, so this fails loudly instead and the gateway
# never starts (supervisord retries it, and the healthcheck stays red).
RUN cat > /usr/local/bin/seaweedfs-seed <<'SEED'
#!/bin/sh
set -e
: "${PB_S3_ACCESS_KEY:?seaweedfs-seed: PB_S3_ACCESS_KEY is required}"
: "${PB_S3_SECRET:?seaweedfs-seed: PB_S3_SECRET is required}"
bucket="${PB_S3_BUCKET:-drivervault}"
shell() { weed shell -master=127.0.0.1:9333 -filer=127.0.0.1:8888; }
printf '%s\n' \
"s3.bucket.create -name $bucket" \
"s3.configure -user drivervault -access_key $PB_S3_ACCESS_KEY -secret_key $PB_S3_SECRET -actions Admin -apply" \
| shell
if ! echo "s3.configure" | shell | grep -q "$PB_S3_ACCESS_KEY"; then
echo "seaweedfs-seed: PocketBase's identity is not in the filer's IAM store; refusing to start the gateway" >&2
exit 1
fi
SEED
RUN chmod +x /usr/local/bin/seaweedfs-seed
# supervisord runs the eight processes and keeps them alive. Priorities only
# order the launches; readiness is the `until wget` loop in front of each
# program that needs another one up, the same chain the compose split spells
# out with depends_on + healthchecks: master → volume → filer → seed + S3 →
# PocketBase → API Server.
#
# Every SeaweedFS role advertises and binds 127.0.0.1 (-ip / -ip.bind): they only
# ever talk to each other in here, and the volume server in particular serves
# file content by id with no authentication at all. The S3 gateway and the admin
# UI bind everywhere so they can be published — on loopback, by the compose
# file's default.
RUN cat > /etc/supervisord.conf <<'SUPERVISOR'
[supervisord]
nodaemon=true
user=root
pidfile=/run/supervisord.pid
logfile=/dev/null
logfile_maxbytes=0
; SeaweedFS master: volume/topology metadata and file ids.
[program:seaweedfs-master]
user=app
command=/usr/local/bin/weed master -ip=127.0.0.1 -ip.bind=127.0.0.1 -port=9333 -mdir=/seaweed/data -volumeSizeLimitMB=1024 -metricsPort=9324
priority=1
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
; SeaweedFS volume server: where the bytes land. On 8081 because 8080 is the
; API Server in this container. -max=0 sizes itself from free disk rather than
; the default cap of 8 volumes.
[program:seaweedfs-volume]
user=app
command=/bin/sh -c 'until wget -qO- http://127.0.0.1:9333/cluster/status >/dev/null 2>&1; do echo "waiting for seaweedfs master..."; sleep 1; done; exec /usr/local/bin/weed volume -master=127.0.0.1:9333 -ip=127.0.0.1 -ip.bind=127.0.0.1 -port=8081 -dir=/seaweed/data -max=0 -metricsPort=9325'
priority=2
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
; SeaweedFS filer: the directory tree over the flat volume store — buckets,
; object keys — and the IAM store the S3 identities live in. -defaultStoreDir
; keeps its embedded leveldb on the data volume so they survive a recreate.
[program:seaweedfs-filer]
user=app
command=/bin/sh -c 'until wget -qO- http://127.0.0.1:8081/healthz >/dev/null 2>&1; do echo "waiting for seaweedfs volume..."; sleep 1; done; exec /usr/local/bin/weed filer -master=127.0.0.1:9333 -ip=127.0.0.1 -ip.bind=127.0.0.1 -port=8888 -defaultStoreDir=/seaweed/data -metricsPort=9326'
priority=3
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
; SeaweedFS S3 gateway: PocketBase's endpoint. Seeds the bucket and identity
; first (see /usr/local/bin/seaweedfs-seed) and never serves if that fails. No
; -config file: with only -filer given, credentials come from the filer's IAM
; store, which is what lets the admin UI add and revoke identities without a
; restart.
[program:seaweedfs-s3]
user=app
command=/bin/sh -c 'until wget -qO- http://127.0.0.1:8888/healthz >/dev/null 2>&1; do echo "waiting for seaweedfs filer..."; sleep 1; done; /usr/local/bin/seaweedfs-seed && exec /usr/local/bin/weed s3 -filer=127.0.0.1:8888 -ip.bind=0.0.0.0 -port=8333 -metricsPort=9327'
priority=4
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
; SeaweedFS admin UI: cluster view, buckets, maintenance, and Object Store →
; Users. It can mint credentials for the bucket, and weed leaves auth off
; entirely when WEED_ADMIN_PASSWORD is empty — so an empty password means no
; panel at all rather than an open one. -dataDir persists the session key and
; the maintenance-task settings.
[program:seaweedfs-admin]
user=app
command=/bin/sh -c 'if [ -z "$WEED_ADMIN_PASSWORD" ]; then echo "seaweedfs-admin: WEED_ADMIN_PASSWORD is empty; refusing to serve an unauthenticated panel" >&2; exit 1; fi; until wget -qO- http://127.0.0.1:9333/cluster/status >/dev/null 2>&1; do echo "waiting for seaweedfs master..."; sleep 1; done; exec /usr/local/bin/weed admin -port=23646 -master=127.0.0.1:9333 -dataDir=/seaweed/admin -metricsPort=9328'
priority=5
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
; PocketBase: wait for the S3 gateway — it is the process that reads and writes
; the objects, so the bucket has to be serving before it does, exactly as the
; compose split gates the whole container on the gateway's health. Then upsert
; the superuser (idempotent) and serve. Runs as the unprivileged app user, which
; owns /pb and the pb_data volume.
[program:pocketbase]
directory=/pb
user=app
command=/bin/sh -c 'until wget -qO- http://127.0.0.1:8333/healthz >/dev/null 2>&1; do echo "waiting for seaweedfs s3..."; sleep 1; done; /pb/pocketbase superuser upsert "$PB_ADMIN_EMAIL" "$PB_ADMIN_PASSWORD" 2>/dev/null || true; exec /pb/pocketbase serve --http=0.0.0.0:8070'
priority=10
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
; API Server: wait for PocketBase to be healthy, then start. Its bootstrap
; points PocketBase's file storage at the bucket and asks it to prove the
; gateway is reachable. It keeps no state on disk — plugin settings, like
; everything else it owns, live in PocketBase — so its working directory is
; just a place to run from.
[program:api-server]
directory=/app
user=app
command=/bin/sh -c 'until wget -qO- http://127.0.0.1:8070/api/health >/dev/null 2>&1; do echo "waiting for pocketbase..."; sleep 1; done; exec /usr/local/bin/api-server'
priority=20
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
; nginx stays root so it can bind :80; its own workers drop to the nginx user.
[program:nginx]
command=/usr/sbin/nginx -g 'daemon off;'
priority=30
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
SUPERVISOR
# The entrypoint stays root only long enough to make the data volumes writable
# by the app user, then hands off to supervisord. The chown matters for a host
# bind mount, which arrives owned by root rather than inheriting the image's
# owner.
RUN cat > /entrypoint.sh <<'ENTRY'
#!/bin/sh
set -e
for dir in /pb/pb_data /seaweed/data /seaweed/admin; do
mkdir -p "$dir"
if [ "$(stat -c %U "$dir" 2>/dev/null)" != "app" ]; then
echo "entrypoint: taking ownership of $dir"
chown -R app:app "$dir"
fi
done
exec supervisord -c /etc/supervisord.conf
ENTRY
RUN chmod +x /entrypoint.sh
# API Server config: everything is local to this container. WEBAPP_URL is what
# the panel status page probes; nginx serves the Web App on :80 in here, so the
# stock default of localhost:8090 would always report the Web App as down.
#
# File storage is on by construction: the gateway is in this image, at a fixed
# loopback address, path style because a self-hosted gateway has no per-bucket
# DNS. The region is a formality SeaweedFS ignores and PocketBase insists on.
# supervisord passes these through to the API Server, whose bootstrap writes
# them into PocketBase's settings on every boot. Only record files move — scans,
# receipts, invoices, part photos; the database and PocketBase's own backups
# stay on /pb/pb_data.
ENV API_ADDR=:8080 \
POCKETBASE_URL=http://127.0.0.1:8070 \
CORS_ALLOW_ORIGINS=http://localhost:8090 \
AUTH_USERS_COLLECTION=users \
WEBAPP_URL=http://127.0.0.1:80 \
PB_S3_ENABLED=true \
PB_S3_ENDPOINT=http://127.0.0.1:8333 \
PB_S3_BUCKET=drivervault \
PB_S3_REGION=us-east-1 \
PB_S3_FORCE_PATH_STYLE=true \
WEED_ADMIN_USER=admin
# Required at runtime (no safe defaults): PB_ADMIN_EMAIL, PB_ADMIN_PASSWORD;
# PB_S3_ACCESS_KEY, PB_S3_SECRET (the identity seeded into SeaweedFS AND what
# PocketBase authenticates with — the gateway refuses to start without them);
# WEED_ADMIN_PASSWORD (the admin UI refuses to start without it).
# Optional: DRIVERVAULT_SUPERADMIN_EMAIL / DRIVERVAULT_SUPERADMIN_PASSWORD create
# the first app super-admin on boot; WEED_ADMIN_READONLY_USER / _PASSWORD add a
# view-only login to the admin UI. PB_BOOTSTRAP=false skips schema setup —
# leave it on: a release can add collections or fields the server needs, and a
# stack that skips the bootstrap never gets them. (app_settings, which holds the
# plugin settings, is created on demand; nothing else is.)
# For Anker Solix charger control, OCPP_REQUIRE_TLS (default true) rejects
# chargers that did not arrive over TLS — this image serves plain HTTP, so put a
# TLS-terminating proxy in front and set OCPP_PUBLIC_URL to the public wss://
# base, or set OCPP_REQUIRE_TLS=false on a trusted network.
# Pass them with `docker run -e ...`.
# Three volumes. /pb/pb_data: the database, the uploads made before S3 was on,
# PocketBase's own backups, and the server settings — the API Server keeps no
# state on disk. /seaweed/data: master, volume and filer share it, in exactly
# the layout `weed server -dir` writes (master raft state, volume .dat/.idx, the
# filer's filerldb2/ — no filename overlap), so a SEAWEED_DATA volume from
# either compose SeaweedFS file mounts here unchanged, and vice versa.
# /seaweed/admin: the admin UI's session key and maintenance-task state, small
# and no part of the object store. All pre-created and owned by app so a fresh
# named volume inherits that ownership.
RUN mkdir -p /pb/pb_data /seaweed/data /seaweed/admin /app \
&& chown -R app:app /pb /seaweed /app
VOLUME ["/pb/pb_data", "/seaweed/data", "/seaweed/admin"]
# 80 = Web App, 8070 = PocketBase admin, 8080 = API Server + embedded API panel
# (also the /ocpp/{serial} endpoint chargers dial into), 8333 = S3 gateway (for
# aws-cli and the like; loopback is enough), 23646 = SeaweedFS admin UI.
EXPOSE 80 8070 8080 8333 23646
# Every process must answer, so a wedged component shows up in `docker ps`
# instead of a container that looks up while part of it is dead. start-period
# covers the SeaweedFS chain plus the first-boot schema bootstrap on a cold
# database.
HEALTHCHECK --interval=30s --timeout=10s --start-period=90s --retries=3 \
CMD wget -qO- http://127.0.0.1:9333/cluster/status >/dev/null 2>&1 \
&& wget -qO- http://127.0.0.1:8081/healthz >/dev/null 2>&1 \
&& wget -qO- http://127.0.0.1:8888/healthz >/dev/null 2>&1 \
&& wget -qO- http://127.0.0.1:8333/healthz >/dev/null 2>&1 \
&& wget -qO- http://127.0.0.1:23646/health >/dev/null 2>&1 \
&& wget -qO- http://127.0.0.1:8070/api/health >/dev/null 2>&1 \
&& wget -qO- http://127.0.0.1:8080/healthz >/dev/null 2>&1 \
&& wget -qO- http://127.0.0.1:80/healthz >/dev/null 2>&1 \
|| exit 1
ENTRYPOINT ["/entrypoint.sh"]
+121
View File
@@ -15,6 +15,8 @@ scale, upgrade or restart the pieces independently.
| File | Use | | File | Use |
|---|---| |---|---|
| `Dockerfile` | the all-in-one image (build context must be the **repo root**) | | `Dockerfile` | the all-in-one image (build context must be the **repo root**) |
| `Dockerfile.seaweedfs` | the same, with SeaweedFS (`weed server -s3`) baked in — see below |
| `Dockerfile.seaweedfs.split` | the same, with SeaweedFS split into its roles baked in — see below |
| `docker-compose.yml` | **builds from source** — for development and local testing | | `docker-compose.yml` | **builds from source** — for development and local testing |
| `docker-compose.prod.yml` | **pulls the prebuilt image** from the registry | | `docker-compose.prod.yml` | **pulls the prebuilt image** from the registry |
| `.env.example` / `.env.prod.example` | copy to `.env` for the matching compose file | | `.env.example` / `.env.prod.example` | copy to `.env` for the matching compose file |
@@ -88,6 +90,125 @@ volume; set `PB_DATA` to an absolute host path in the prod file for a bind mount
> container. Set the corresponding environment variables to change them > container. Set the corresponding environment variables to change them
> permanently. > permanently.
## File storage (SeaweedFS / S3)
Uploaded files — document scans, service and refill receipts, workshop invoices,
part photos — live inside `pb_data` by default, next to the database. Two further
compose files put them in an S3 bucket instead, so the blobs and the database can
be sized, backed up and moved independently. Nothing else changes: an attachment has
always been fetched through the API Server (`GET /api/service-records/{id}/file`),
never from a storage URL, so the Web App, the phone app and the Home Assistant
plugin cannot tell the difference.
Each shape is one self-contained compose file — nothing to layer, nothing to
remember — with an `.env` example of the same name:
| Shape | From the registry | From source |
|---|---|---|
| **Local storage** — the default, unchanged | `docker-compose.prod.yml` | `docker-compose.yml` |
| **SeaweedFS beside the image** | `docker-compose.prod.seaweedfs.yml` (builds `Dockerfile.seaweedfs`) | `docker-compose.seaweedfs.yml` |
| **SeaweedFS, split into its roles** | `docker-compose.prod.seaweedfs.split.yml` (builds `Dockerfile.seaweedfs.split`) | `docker-compose.seaweedfs.split.yml` |
| **An S3 endpoint elsewhere** | `docker-compose.prod.s3.yml` | `docker-compose.s3.yml` |
So `docker-compose.prod.seaweedfs.yml` is configured from
`.env.prod.seaweedfs.example`, `docker-compose.s3.yml` from `.env.s3.example`,
and so on:
```sh
cp .env.prod.seaweedfs.example .env # then edit it — PB_S3_* have no defaults
docker compose -f docker-compose.prod.seaweedfs.yml pull
docker compose -f docker-compose.prod.seaweedfs.yml up -d
```
Set `PB_S3_ACCESS_KEY` and `PB_S3_SECRET` first — both storage files refuse to
start without them. The from-source SeaweedFS files run the gateway as a
**second container** (master, volume, filer and S3 in one process, on its own
`seaweed_data` volume) plus a one-shot `seaweedfs-init` that creates the bucket,
because PocketBase never issues a `CreateBucket` of its own. The prod SeaweedFS
files go the other way and **build it into the image**: `Dockerfile.seaweedfs`
runs `weed server -s3` as a fourth supervisord program (the `weed` binary is
copied from the official image, pinned by the `SEAWEED_VERSION` build arg), on
a `/seaweed/data` volume of its own, with PocketBase's program creating the
bucket before it serves. One container, two volumes; the cost is that a new
SeaweedFS is a rebuild rather than a tag change. Inside, the volume server sits
on **8081** since 8080 is the API Server, and nothing of SeaweedFS is
published: PocketBase reaches the gateway inside the container. The build needs the repo checkout, so either build on the
deploy host or `docker compose push` the image to `AIO_IMAGE` and `pull` it
there. The external-S3 ones add no containers at all: set `PB_S3_ENDPOINT`, and
create the bucket yourself.
### Split SeaweedFS
`weed server -s3` runs master, volume, filer and gateway as four goroutines in
one process. `docker-compose.seaweedfs.split.yml` runs them as four containers
beside the all-in-one, plus a fifth: the SeaweedFS **admin UI** on port 23646,
where the cluster can be inspected and — under *Object Store → Users* — further
S3 identities minted and revoked. Split also gets you per-role restarts and
upgrades, per-role Prometheus metrics, and room to add a second volume server
later.
The prod twin, like its non-split sibling, builds it in:
`docker-compose.prod.seaweedfs.split.yml` **builds `Dockerfile.seaweedfs.split`**,
which bakes all five roles into the all-in-one image as five more supervisord
programs. One container, three volumes (`PB_DATA`, `SEAWEED_DATA`,
`SEAWEED_ADMIN_DATA`), and the bucket-and-identity seed runs inside the
gateway's program instead of a `seaweedfs-init` container. What survives of
"split" in there is per-role restart, per-role metrics ports and the admin UI;
what does not is spreading the roles over hosts. Inside, every role listens on
loopback, and only the admin UI is published, on loopback by default.
Identities work differently there, and it matters. SeaweedFS reads credentials
from, in descending priority: an `-s3.config` file, the filer's IAM store, then
`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` — and a higher source *replaces* a
lower one rather than adding to it. The single-gateway files use the env vars,
which is why nothing else may write identities there: the first user added in a
panel would displace PocketBase's key. So in the split files `seaweedfs-init`
seeds PocketBase's identity into the filer's store instead — the same store the
admin UI writes — and the gateway runs with no config file at all. One source of
truth, PocketBase's key visible in the panel beside every other, and new keys
picked up without a restart. Rotating `PB_S3_SECRET` in `.env` and restarting
updates that identity in place.
Set `SEAWEED_ADMIN_PASSWORD`: `weed admin` serves the panel with no
authentication when it is empty, and a panel that can mint bucket credentials is
the bucket (the baked-in image refuses to start the panel at all without one).
In the prod file it is bound to loopback — it is storage
plumbing, not one of the app's own panels — so a remote host needs
`SEAWEED_ADMIN_BIND=0.0.0.0` behind a reverse proxy. Neither file publishes
anything for master, volume and filer: the volume server serves file content by
id with no authentication of any kind, and the admin UI already shows what those
ports would.
Switching between any of the SeaweedFS files needs no migration: master, volume
and filer share one data mount (`/data` in the side containers, `/seaweed/data`
in the baked-in image), which is exactly the layout `weed server -dir` writes.
On every boot the API Server's bootstrap writes PocketBase's *Files storage*
settings from those variables, then asks PocketBase to prove it can reach the
bucket. Watch for it in the log:
```
[api] bootstrap: ✓ file storage → S3 (drivervault at http://seaweedfs:8333)
[api] bootstrap: ✓ S3 storage reachable
```
A boot that finds the settings already correct logs `• file storage already on S3`
and writes nothing.
Two things to know before turning it on:
- **Existing files are not migrated.** PocketBase copies nothing when the setting
flips, so attachments uploaded before the switch stop resolving. Copy
`pb_data/storage/<collectionId>/<recordId>/<file>` into the bucket root, keeping
that layout, *before* enabling it — or start from a stack with no attachments.
- **Going back to the plain compose file is not an off switch.** It leaves
PocketBase pointed at
the bucket, deliberately: files already written there are reachable only while
it is. Move them back and turn it off in PocketBase's own admin UI. For the same
reason a rotation of `PB_S3_SECRET` alone is invisible to the bootstrap —
PocketBase masks the stored secret on read — so change another `PB_S3_*` value
alongside it, or set it in the admin UI.
## Charger control (OCPP) ## Charger control (OCPP)
Chargers in own/proxy mode dial in to `/ocpp/{serial}` on the **API Server port Chargers in own/proxy mode dial in to `/ocpp/{serial}` on the **API Server port
+101
View File
@@ -0,0 +1,101 @@
name: drivervault-aio
# Production all-in-one, with external S3 — pulls the prebuilt image from the
# registry instead of building. Self-contained: one file, no overlays.
# Everything an operator needs to set lives in .env.
#
# 1. cp .env.prod.s3.example .env (then edit it — PB_S3_* especially)
# 2. docker compose -f docker-compose.prod.s3.yml pull
# 3. docker compose -f docker-compose.prod.s3.yml up -d
#
# This is docker-compose.prod.yml pointed at an S3 endpoint that already exists
# somewhere else — its own host, another compose project, or any S3-compatible
# service. PocketBase keeps its record files — document scans, service and
# refill receipts, workshop invoices, part photos — in that bucket instead of on
# the pb_data volume. The database and PocketBase's own backups stay on PB_DATA.
# Clients cannot tell the difference: an attachment has always been fetched
# through the API Server, never from a storage URL.
#
# The bucket must already exist, and nothing here runs the gateway. For a
# SeaweedFS that comes up with the container, use
# docker-compose.prod.seaweedfs.yml.
#
# Before turning this on for a stack that already has uploads: PocketBase does
# NOT copy existing files into the bucket. See README.md.
#
# On first boot PocketBase upserts the superuser from PB_ADMIN_*, and the API
# Server creates any missing collections and the DriverVault super-admin from
# DRIVERVAULT_SUPERADMIN_*. Both steps are idempotent.
services:
drivervault:
image: "${AIO_IMAGE:-10.2.1.10:5500/admin/drivervault-aio:latest}"
container_name: drivervault-aio
restart: unless-stopped
extra_hosts:
# Lets PB_S3_ENDPOINT name the Docker host as host.docker.internal.
# Harmless when the endpoint is somewhere else entirely.
- "host.docker.internal:host-gateway"
environment:
# Superuser (also used by the API Server to authenticate to PocketBase).
PB_ADMIN_EMAIL: "${PB_ADMIN_EMAIL:?set PB_ADMIN_EMAIL in .env}"
PB_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD:?set PB_ADMIN_PASSWORD in .env}"
# Match CORS to the web origin (only used if a browser calls the API directly).
CORS_ALLOW_ORIGINS: "${CORS_ALLOW_ORIGINS:-http://localhost:8090}"
# Probed by the panel status page. nginx serves the Web App on port 80
# inside this container, so plain localhost:8090 would never answer.
# Override WEBAPP_URL in .env to make a change from the panel's Web App
# screen permanent; the panel alone only holds it for the container's life.
WEBAPP_URL: "${WEBAPP_URL:-http://127.0.0.1:80}"
# Schema + super-admin bootstrap (idempotent). Leave this ON: a release can
# add collections or fields the server needs, and a stack that skips the
# bootstrap never gets them. The API Server self-heals exactly one thing —
# app_settings, the collection holding the plugin settings, which it
# creates on demand because it cannot serve the plugin panel without it.
# Every other schema change still depends on this flag. Turn it off only
# for a database you know already matches the release.
PB_BOOTSTRAP: "${PB_BOOTSTRAP:-true}"
DRIVERVAULT_SUPERADMIN_EMAIL: "${DRIVERVAULT_SUPERADMIN_EMAIL:-}"
DRIVERVAULT_SUPERADMIN_PASSWORD: "${DRIVERVAULT_SUPERADMIN_PASSWORD:-}"
DRIVERVAULT_SUPERADMIN_NAME: "${DRIVERVAULT_SUPERADMIN_NAME:-Administrator}"
# OCPP charger control (Anker Solix). This image serves plain HTTP, so a
# charger can only connect when TLS is terminated in front of it (set
# OCPP_PUBLIC_URL to the public wss:// base) — or, on a trusted network,
# with OCPP_REQUIRE_TLS=false.
OCPP_REQUIRE_TLS: "${OCPP_REQUIRE_TLS:-true}"
OCPP_PUBLIC_URL: "${OCPP_PUBLIC_URL:-}"
# --- File storage --------------------------------------------------
# supervisord passes these through to the API Server, whose bootstrap
# writes them into PocketBase's
# settings on every boot, idempotently. Only record files move — scans,
# receipts, invoices, part photos. The database and PocketBase's own
# backups stay on PB_DATA. The bucket must already exist: nothing here
# creates it.
PB_S3_ENABLED: "true"
PB_S3_BUCKET: "${PB_S3_BUCKET:-drivervault}"
PB_S3_ENDPOINT: "${PB_S3_ENDPOINT:?set PB_S3_ENDPOINT in .env}"
PB_S3_REGION: "${PB_S3_REGION:-us-east-1}"
PB_S3_ACCESS_KEY: "${PB_S3_ACCESS_KEY:?set PB_S3_ACCESS_KEY in .env}"
PB_S3_SECRET: "${PB_S3_SECRET:?set PB_S3_SECRET in .env}"
# true for SeaweedFS and MinIO, false for AWS S3 proper.
PB_S3_FORCE_PATH_STYLE: "${PB_S3_FORCE_PATH_STYLE:-true}"
ports:
- "${WEB_PORT:-8090}:80" # Web App
- "${PB_PORT:-8070}:8070" # PocketBase admin UI / API
- "${API_PORT:-8080}:8080" # API Server + panel (root /) + /ocpp/{serial}
volumes:
# The only volume — named by default; set PB_DATA to a host path in .env
# for a bind mount. The API Server keeps no state on disk, so everything
# it owns (plugin settings included) is in here.
- "${PB_DATA:-pb_data}:/pb/pb_data"
healthcheck:
# All three processes must answer. Declared here as well as in the image so
# the check is visible, and works against an older pulled image.
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8070/api/health >/dev/null && wget -qO- http://127.0.0.1:8080/healthz >/dev/null && wget -qO- http://127.0.0.1:80/healthz >/dev/null || exit 1"]
interval: 30s
timeout: 5s
retries: 3
start_period: 60s
volumes:
pb_data:
@@ -0,0 +1,166 @@
name: drivervault-aio
# Production all-in-one with SeaweedFS split into its roles — and, unlike the
# other prod files, built into ONE image here: Dockerfile.seaweedfs.split bakes
# master, volume, filer, S3 gateway and the admin UI into the same container as
# PocketBase, the API Server and the Web App. One service, one container, three
# volumes. Self-contained: one file, no overlays. Everything an operator needs
# to set lives in .env.
#
# 1. cp .env.prod.seaweedfs.split.example .env (then edit it)
# 2. docker compose -f docker-compose.prod.seaweedfs.split.yml build
# 3. docker compose -f docker-compose.prod.seaweedfs.split.yml up -d
#
# The build context is the repo root, so this has to run on a host that has the
# checkout. To deploy elsewhere, `push` the built image to the registry named in
# AIO_IMAGE and `pull` it there — `image:` and `build:` are both set, so the
# same file does either.
#
# What the split buys inside one image: per-role restart under supervisord,
# per-role metrics ports, and the SeaweedFS admin UI (weed admin) — a cluster
# view, and Object Store → Users, where S3 identities are created and revoked
# without touching a file. What it costs against the six-container shape it
# replaces: a new SeaweedFS is a rebuild (SEAWEED_VERSION below), not a tag
# change, and the roles cannot be spread over hosts. If the object store should
# stay outside the app image, use docker-compose.prod.seaweedfs.yml — the S3
# behaviour is identical.
#
# The on-disk layout is the same as every other SeaweedFS shape here: master,
# volume and filer share one data mount, exactly as `weed server -dir` lays it
# out (master raft state, volume .dat/.idx, the filer's filerldb2/ — no filename
# overlap). So a SEAWEED_DATA volume from docker-compose.prod.seaweedfs.yml
# mounts here unchanged, and vice versa, with no migration either way.
#
# Inside the container every SeaweedFS role listens on loopback except the S3
# gateway and the admin UI. Only the admin UI is published, on loopback by
# default; PocketBase reaches the gateway inside. The volume server serves file
# content by id with no authentication at all, so it is never reachable from
# outside; the admin UI shows what its port would.
#
# Before turning this on for a stack that already has uploads: PocketBase does
# NOT copy existing files into the bucket. See README.md.
#
# On first boot the S3 gateway's program creates the bucket and seeds
# PocketBase's identity into the filer's IAM store, PocketBase upserts the
# superuser from PB_ADMIN_*, and the API Server creates any missing collections,
# the DriverVault super-admin from DRIVERVAULT_SUPERADMIN_*, and points
# PocketBase's file storage at the bucket. Every step is idempotent.
services:
drivervault:
build:
# Project root (one level up from this compose file), so the Dockerfile
# can reach both "API Server/" and "Web App/".
context: ..
dockerfile: Docker-AIO/Dockerfile.seaweedfs.split
args:
# Empty -> bundle uses same-origin "/api", proxied internally by nginx.
- VITE_API_BASE=${VITE_API_BASE:-}
# Bare names = pass through only when set in the environment, so an
# unset PB_VERSION / SEAWEED_VERSION leaves the Dockerfile pin in place
# instead of overriding it with an empty string (which for PB_VERSION
# would resolve "latest" at build time, and for SEAWEED_VERSION would
# not build at all).
- PB_VERSION
- SEAWEED_VERSION
# Tagged for the registry so `docker compose push` lands it where `pull`
# on the deploy host expects it.
image: "${AIO_IMAGE:-10.2.1.10:5500/admin/drivervault-aio-seaweedfs-split:latest}"
container_name: drivervault-aio
restart: unless-stopped
environment:
# Superuser (also used by the API Server to authenticate to PocketBase).
PB_ADMIN_EMAIL: "${PB_ADMIN_EMAIL:?set PB_ADMIN_EMAIL in .env}"
PB_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD:?set PB_ADMIN_PASSWORD in .env}"
# Match CORS to the web origin (only used if a browser calls the API directly).
CORS_ALLOW_ORIGINS: "${CORS_ALLOW_ORIGINS:-http://localhost:8090}"
# Probed by the panel status page. nginx serves the Web App on port 80
# inside this container, so plain localhost:8090 would never answer.
# Override WEBAPP_URL in .env to make a change from the panel's Web App
# screen permanent; the panel alone only holds it for the container's life.
WEBAPP_URL: "${WEBAPP_URL:-http://127.0.0.1:80}"
# Schema + super-admin bootstrap (idempotent). Leave this ON: a release can
# add collections or fields the server needs, and a stack that skips the
# bootstrap never gets them. The API Server self-heals exactly one thing —
# app_settings, the collection holding the plugin settings, which it
# creates on demand because it cannot serve the plugin panel without it.
# Every other schema change still depends on this flag. Turn it off only
# for a database you know already matches the release.
PB_BOOTSTRAP: "${PB_BOOTSTRAP:-true}"
DRIVERVAULT_SUPERADMIN_EMAIL: "${DRIVERVAULT_SUPERADMIN_EMAIL:-}"
DRIVERVAULT_SUPERADMIN_PASSWORD: "${DRIVERVAULT_SUPERADMIN_PASSWORD:-}"
DRIVERVAULT_SUPERADMIN_NAME: "${DRIVERVAULT_SUPERADMIN_NAME:-Administrator}"
# OCPP charger control (Anker Solix). This image serves plain HTTP, so a
# charger can only connect when TLS is terminated in front of it (set
# OCPP_PUBLIC_URL to the public wss:// base) — or, on a trusted network,
# with OCPP_REQUIRE_TLS=false.
OCPP_REQUIRE_TLS: "${OCPP_REQUIRE_TLS:-true}"
OCPP_PUBLIC_URL: "${OCPP_PUBLIC_URL:-}"
# --- File storage --------------------------------------------------
# The image fixes the rest (PB_S3_ENABLED, the loopback endpoint, path
# style, the region): the gateway is inside, at an address that cannot
# change. supervisord passes these through to the API Server, whose
# bootstrap writes them into PocketBase's settings on every boot,
# idempotently. Only record files move — scans, receipts, invoices, part
# photos. The database and PocketBase's own backups stay on PB_DATA.
#
# The credentials do double duty: the gateway's program seeds them into
# the filer's IAM store as the identity named "drivervault" (updating it
# in place on every boot — that is how a rotated secret lands) *and* they
# are what PocketBase authenticates with. No safe defaults; the gateway
# refuses to start without them, and with it the whole container.
PB_S3_BUCKET: "${PB_S3_BUCKET:-drivervault}"
PB_S3_ACCESS_KEY: "${PB_S3_ACCESS_KEY:?set PB_S3_ACCESS_KEY in .env}"
PB_S3_SECRET: "${PB_S3_SECRET:?set PB_S3_SECRET in .env}"
# --- SeaweedFS admin UI --------------------------------------------
# An unauthenticated panel that can mint credentials for the bucket *is*
# the bucket, so the password is required rather than defaulted — weed
# leaves auth off entirely when it is empty, and the image refuses to
# start the panel at all in that case. Read from WEED_ADMIN_* rather
# than a flag, which keeps it off the process command line.
WEED_ADMIN_USER: "${SEAWEED_ADMIN_USER:-admin}"
WEED_ADMIN_PASSWORD: "${SEAWEED_ADMIN_PASSWORD:?set SEAWEED_ADMIN_PASSWORD in .env}"
# Optional view-only login. weed ignores it unless the admin password
# above is set, which it is.
WEED_ADMIN_READONLY_USER: "${SEAWEED_ADMIN_READONLY_USER:-}"
WEED_ADMIN_READONLY_PASSWORD: "${SEAWEED_ADMIN_READONLY_PASSWORD:-}"
ports:
- "${WEB_PORT:-8090}:80" # Web App
- "${PB_PORT:-8070}:8070" # PocketBase admin UI / API
- "${API_PORT:-8080}:8080" # API Server + panel (root /) + /ocpp/{serial}
# The S3 gateway is not published: PocketBase reaches it inside the
# container. The admin UI is, on loopback: storage plumbing, not one of
# the app's own panels. On a remote host that means unreachable, so set
# SEAWEED_ADMIN_BIND=0.0.0.0 and put it behind a reverse proxy.
- "${SEAWEED_ADMIN_BIND:-127.0.0.1}:${SEAWEED_ADMIN_PORT:-23646}:23646"
volumes:
# Named volumes by default; set any of them to a host path in .env for a
# bind mount. The API Server keeps no state on disk, so everything it
# owns (plugin settings included) is in PB_DATA. Back up PB_DATA and
# SEAWEED_DATA together — from here on the attachments live in the
# second, not the first.
- "${PB_DATA:-pb_data}:/pb/pb_data"
- "${SEAWEED_DATA:-seaweed_data}:/seaweed/data"
# The admin UI's own small volume: session key and maintenance state, no
# object data.
- "${SEAWEED_ADMIN_DATA:-seaweed_admin}:/seaweed/admin"
healthcheck:
# Every process must answer — the five SeaweedFS roles and the three app
# processes. Declared here as well as in the image so the check is
# visible, and works against an older pulled image. start_period covers
# the SeaweedFS chain plus the first-boot schema bootstrap.
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:9333/cluster/status >/dev/null && wget -qO- http://127.0.0.1:8081/healthz >/dev/null && wget -qO- http://127.0.0.1:8888/healthz >/dev/null && wget -qO- http://127.0.0.1:8333/healthz >/dev/null && wget -qO- http://127.0.0.1:23646/health >/dev/null && wget -qO- http://127.0.0.1:8070/api/health >/dev/null && wget -qO- http://127.0.0.1:8080/healthz >/dev/null && wget -qO- http://127.0.0.1:80/healthz >/dev/null || exit 1"]
interval: 30s
timeout: 10s
retries: 3
start_period: 90s
volumes:
pb_data:
# Master, volume and filer share it — the same layout `weed server -dir`
# writes, so this file and docker-compose.prod.seaweedfs.yml can swap places
# on it.
seaweed_data:
# The admin UI's own session key and maintenance-task state. Small, and no
# part of the object store.
seaweed_admin:
@@ -0,0 +1,136 @@
name: drivervault-aio
# Production all-in-one with SeaweedFS — and, unlike docker-compose.prod.yml,
# built into ONE image here: Dockerfile.seaweedfs bakes `weed server -s3`
# (master, volume, filer and S3 gateway in one process) into the same container
# as PocketBase, the API Server and the Web App. One service, one container,
# two volumes. Self-contained: one file, no overlays. Everything an operator
# needs to set lives in .env.
#
# 1. cp .env.prod.seaweedfs.example .env (then edit it)
# 2. docker compose -f docker-compose.prod.seaweedfs.yml build
# 3. docker compose -f docker-compose.prod.seaweedfs.yml up -d
#
# The build context is the repo root, so this has to run on a host that has the
# checkout. To deploy elsewhere, `push` the built image to the registry named in
# AIO_IMAGE and `pull` it there — `image:` and `build:` are both set, so the
# same file does either.
#
# This is docker-compose.prod.yml plus an S3 object store: PocketBase keeps its
# record files — document scans, service and refill receipts, workshop invoices,
# part photos — in a SeaweedFS bucket instead of on the pb_data volume next to
# the database. The database and PocketBase's own backups stay on PB_DATA.
# Clients cannot tell the difference: an attachment has always been fetched
# through the API Server, never from a storage URL.
#
# What baking it in costs against the two-container shape it replaces: a new
# SeaweedFS is a rebuild (SEAWEED_VERSION below), not a tag change. For
# per-role restart, metrics and the SeaweedFS admin UI, see
# docker-compose.prod.seaweedfs.split.yml — the S3 behaviour is identical, and
# the data volume is interchangeable (both write the `weed server -dir` layout).
#
# Before turning this on for a stack that already has uploads: PocketBase does
# NOT copy existing files into the bucket. See README.md.
#
# On first boot PocketBase's program creates the bucket and upserts the
# superuser from PB_ADMIN_*, and the API Server creates any missing
# collections, the DriverVault super-admin from DRIVERVAULT_SUPERADMIN_*, and
# points PocketBase's file storage at the bucket. Every step is idempotent.
services:
drivervault:
build:
# Project root (one level up from this compose file), so the Dockerfile
# can reach both "API Server/" and "Web App/".
context: ..
dockerfile: Docker-AIO/Dockerfile.seaweedfs
args:
# Empty -> bundle uses same-origin "/api", proxied internally by nginx.
- VITE_API_BASE=${VITE_API_BASE:-}
# Bare names = pass through only when set in the environment, so an
# unset PB_VERSION / SEAWEED_VERSION leaves the Dockerfile pin in place
# instead of overriding it with an empty string (which for PB_VERSION
# would resolve "latest" at build time, and for SEAWEED_VERSION would
# not build at all).
- PB_VERSION
- SEAWEED_VERSION
# Tagged for the registry so `docker compose push` lands it where `pull`
# on the deploy host expects it.
image: "${AIO_IMAGE:-10.2.1.10:5500/admin/drivervault-aio-seaweedfs:latest}"
container_name: drivervault-aio
restart: unless-stopped
environment:
# Superuser (also used by the API Server to authenticate to PocketBase).
PB_ADMIN_EMAIL: "${PB_ADMIN_EMAIL:?set PB_ADMIN_EMAIL in .env}"
PB_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD:?set PB_ADMIN_PASSWORD in .env}"
# Match CORS to the web origin (only used if a browser calls the API directly).
CORS_ALLOW_ORIGINS: "${CORS_ALLOW_ORIGINS:-http://localhost:8090}"
# Probed by the panel status page. nginx serves the Web App on port 80
# inside this container, so plain localhost:8090 would never answer.
# Override WEBAPP_URL in .env to make a change from the panel's Web App
# screen permanent; the panel alone only holds it for the container's life.
WEBAPP_URL: "${WEBAPP_URL:-http://127.0.0.1:80}"
# Schema + super-admin bootstrap (idempotent). Leave this ON: a release can
# add collections or fields the server needs, and a stack that skips the
# bootstrap never gets them. The API Server self-heals exactly one thing —
# app_settings, the collection holding the plugin settings, which it
# creates on demand because it cannot serve the plugin panel without it.
# Every other schema change still depends on this flag. Turn it off only
# for a database you know already matches the release.
PB_BOOTSTRAP: "${PB_BOOTSTRAP:-true}"
DRIVERVAULT_SUPERADMIN_EMAIL: "${DRIVERVAULT_SUPERADMIN_EMAIL:-}"
DRIVERVAULT_SUPERADMIN_PASSWORD: "${DRIVERVAULT_SUPERADMIN_PASSWORD:-}"
DRIVERVAULT_SUPERADMIN_NAME: "${DRIVERVAULT_SUPERADMIN_NAME:-Administrator}"
# OCPP charger control (Anker Solix). This image serves plain HTTP, so a
# charger can only connect when TLS is terminated in front of it (set
# OCPP_PUBLIC_URL to the public wss:// base) — or, on a trusted network,
# with OCPP_REQUIRE_TLS=false.
OCPP_REQUIRE_TLS: "${OCPP_REQUIRE_TLS:-true}"
OCPP_PUBLIC_URL: "${OCPP_PUBLIC_URL:-}"
# --- File storage --------------------------------------------------
# The image fixes the rest (PB_S3_ENABLED, the loopback endpoint, path
# style, the region): the gateway is inside, at an address that cannot
# change. supervisord passes these through to the API Server, whose
# bootstrap writes them into PocketBase's settings on every boot,
# idempotently. Only record files move — scans, receipts, invoices, part
# photos. The database and PocketBase's own backups stay on PB_DATA.
#
# The credentials do double duty: they configure the gateway's single
# identity — which is what takes it out of its default allow-anyone mode
# — *and* they are what PocketBase authenticates with. No safe defaults;
# the gateway refuses to start without them, and with it the whole
# container.
PB_S3_BUCKET: "${PB_S3_BUCKET:-drivervault}"
PB_S3_ACCESS_KEY: "${PB_S3_ACCESS_KEY:?set PB_S3_ACCESS_KEY in .env}"
PB_S3_SECRET: "${PB_S3_SECRET:?set PB_S3_SECRET in .env}"
ports:
- "${WEB_PORT:-8090}:80" # Web App
- "${PB_PORT:-8070}:8070" # PocketBase admin UI / API
- "${API_PORT:-8080}:8080" # API Server + panel (root /) + /ocpp/{serial}
# Nothing of SeaweedFS is published: PocketBase reaches the S3 gateway
# inside the container, and the volume server (8081 inside) serves file
# content by id with no authentication at all.
volumes:
# Named volumes by default; set either to a host path in .env for a bind
# mount. The API Server keeps no state on disk, so everything it owns
# (plugin settings included) is in PB_DATA. Back up PB_DATA and
# SEAWEED_DATA together — from here on the attachments live in the
# second, not the first.
- "${PB_DATA:-pb_data}:/pb/pb_data"
- "${SEAWEED_DATA:-seaweed_data}:/seaweed/data"
healthcheck:
# Every process must answer — SeaweedFS's master and gateway and the three
# app processes. Declared here as well as in the image so the check is
# visible, and works against an older pulled image. start_period covers
# SeaweedFS coming up plus the first-boot schema bootstrap.
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:9333/cluster/status >/dev/null && wget -qO- http://127.0.0.1:8333/healthz >/dev/null && wget -qO- http://127.0.0.1:8070/api/health >/dev/null && wget -qO- http://127.0.0.1:8080/healthz >/dev/null && wget -qO- http://127.0.0.1:80/healthz >/dev/null || exit 1"]
interval: 30s
timeout: 10s
retries: 3
start_period: 90s
volumes:
pb_data:
# The `weed server -dir` layout, so this file and its .split. twin can swap
# places on it.
seaweed_data:
+107
View File
@@ -0,0 +1,107 @@
name: drivervault-aio
# Single all-in-one container, with external S3: PocketBase + API Server + Web
# App (nginx) in one image, storing files in an S3 endpoint that already exists
# somewhere else. Self-contained — one file, nothing to layer.
#
# cp .env.s3.example .env (then edit it — PB_S3_* especially)
# docker compose -f docker-compose.s3.yml up -d --build
#
# The build context is the project root so the Dockerfile can reach both
# "API Server/" and "Web App/".
#
# This is docker-compose.yml plus storage: PocketBase keeps its record files —
# document scans, service and refill receipts, workshop invoices, part photos —
# in that bucket instead of on the pb_data volume next to the database. The
# database and PocketBase's own backups stay on pb_data. Clients cannot tell the
# difference: an attachment has always been fetched through the API Server,
# never from a storage URL.
#
# The bucket must already exist, and nothing here runs the gateway. For a
# SeaweedFS that comes up with the container, use docker-compose.seaweedfs.yml.
#
# Before turning this on for a stack that already has uploads: PocketBase does
# NOT copy existing files into the bucket. See README.md.
services:
drivervault:
build:
# Project root (one level up from this compose file).
context: ..
dockerfile: Docker-AIO/Dockerfile
args:
# Empty -> bundle uses same-origin "/api", proxied internally by nginx.
- VITE_API_BASE=${VITE_API_BASE:-}
# Bare name = pass through only when set in the environment, so an unset
# PB_VERSION leaves the Dockerfile pin in place instead of overriding it
# with an empty string (which would resolve "latest" at build time).
- PB_VERSION
image: drivervault-aio
container_name: drivervault-aio
restart: unless-stopped
extra_hosts:
# Lets PB_S3_ENDPOINT name the Docker host as host.docker.internal.
# Harmless when the endpoint is somewhere else entirely.
- "host.docker.internal:host-gateway"
environment:
# Superuser (also used by the API Server to authenticate to PocketBase).
PB_ADMIN_EMAIL: "${PB_ADMIN_EMAIL:?set PB_ADMIN_EMAIL in .env}"
PB_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD:?set PB_ADMIN_PASSWORD in .env}"
# Match CORS to the web origin (only used if a browser calls the API directly).
CORS_ALLOW_ORIGINS: "${CORS_ALLOW_ORIGINS:-http://localhost:8090}"
# Probed by the panel status page. nginx serves the Web App on port 80
# inside this container, so plain localhost:8090 would never answer.
# Override WEBAPP_URL in .env to make a change from the panel's Web App
# screen permanent; the panel alone only holds it for the container's life.
WEBAPP_URL: "${WEBAPP_URL:-http://127.0.0.1:80}"
# Schema + super-admin bootstrap (idempotent). Leave this ON: a release can
# add collections or fields the server needs, and a stack that skips the
# bootstrap never gets them. The API Server self-heals exactly one thing —
# app_settings, the collection holding the plugin settings, which it
# creates on demand because it cannot serve the plugin panel without it.
# Every other schema change still depends on this flag. Turn it off only
# for a database you know already matches the release.
PB_BOOTSTRAP: "${PB_BOOTSTRAP:-true}"
DRIVERVAULT_SUPERADMIN_EMAIL: "${DRIVERVAULT_SUPERADMIN_EMAIL:-}"
DRIVERVAULT_SUPERADMIN_PASSWORD: "${DRIVERVAULT_SUPERADMIN_PASSWORD:-}"
DRIVERVAULT_SUPERADMIN_NAME: "${DRIVERVAULT_SUPERADMIN_NAME:-Administrator}"
# OCPP charger control (Anker Solix). This image serves plain HTTP, so a
# charger can only connect when TLS is terminated in front of it (set
# OCPP_PUBLIC_URL to the public wss:// base) — or, on a trusted network,
# with OCPP_REQUIRE_TLS=false.
OCPP_REQUIRE_TLS: "${OCPP_REQUIRE_TLS:-true}"
OCPP_PUBLIC_URL: "${OCPP_PUBLIC_URL:-}"
# --- File storage --------------------------------------------------
# supervisord passes these through to the API Server, whose bootstrap
# writes them into PocketBase's
# settings on every boot, idempotently. Only record files move — scans,
# receipts, invoices, part photos. The database and PocketBase's own
# backups stay on pb_data. The bucket must already exist: nothing here
# creates it.
PB_S3_ENABLED: "true"
PB_S3_BUCKET: "${PB_S3_BUCKET:-drivervault}"
PB_S3_ENDPOINT: "${PB_S3_ENDPOINT:?set PB_S3_ENDPOINT in .env}"
PB_S3_REGION: "${PB_S3_REGION:-us-east-1}"
PB_S3_ACCESS_KEY: "${PB_S3_ACCESS_KEY:?set PB_S3_ACCESS_KEY in .env}"
PB_S3_SECRET: "${PB_S3_SECRET:?set PB_S3_SECRET in .env}"
# true for SeaweedFS and MinIO, false for AWS S3 proper.
PB_S3_FORCE_PATH_STYLE: "${PB_S3_FORCE_PATH_STYLE:-true}"
ports:
- "${WEB_PORT:-8090}:80" # Web App
- "${PB_PORT:-8070}:8070" # PocketBase admin UI / API
- "${API_PORT:-8080}:8080" # API Server + panel (root /) + /ocpp/{serial}
volumes:
# The only volume: the API Server keeps no state on disk, so everything
# it owns — plugin settings included — lives in the database.
- pb_data:/pb/pb_data
healthcheck:
# All three processes must answer. Declared here as well as in the image so
# the check is visible, and works against an older pulled image.
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8070/api/health >/dev/null && wget -qO- http://127.0.0.1:8080/healthz >/dev/null && wget -qO- http://127.0.0.1:80/healthz >/dev/null || exit 1"]
interval: 30s
timeout: 5s
retries: 3
start_period: 60s
volumes:
pb_data:
@@ -0,0 +1,316 @@
name: drivervault-aio
# Single all-in-one container, with SeaweedFS split into its four roles:
# PocketBase + API Server + Web App (nginx) in one image, beside master, volume,
# filer, S3 gateway and the SeaweedFS admin UI as separate containers.
# Self-contained — one file, nothing to layer.
#
# cp .env.seaweedfs.split.example .env (then edit it)
# docker compose -f docker-compose.seaweedfs.split.yml up -d --build
#
# The build context is the project root so the Dockerfile can reach both
# "API Server/" and "Web App/".
#
# This is docker-compose.seaweedfs.yml with the storage layer taken apart.
# `weed server -s3` runs master, volume, filer and gateway as goroutines in one
# process; here each is its own container. What that buys:
#
# • the admin UI (weed admin) — a cluster view, and Object Store → Users,
# where S3 identities are created and revoked without touching a file;
# • per-role restart, upgrade and Prometheus metrics;
# • room to add a second volume server later, on this host or another.
#
# What it costs: five containers beside the all-in-one instead of one, and five
# healthchecks to keep the boot order honest. If none of the above is wanted,
# use docker-compose.seaweedfs.yml — the S3 behaviour is identical.
#
# None of them run inside the all-in-one image, for the same reason the single
# gateway does not: keeping the object store in that image, on the volume the
# files are being moved off, would defeat the point and would mean rebuilding.
#
# The on-disk layout is deliberately the same as the single-process file's:
# master, volume and filer share one /data mount, exactly as `weed server -dir`
# lays it out (master raft state, volume .dat/.idx, the filer's filerldb2/ — no
# filename overlap). So the two files are interchangeable on the same volume,
# with no migration either way. A *second* volume server would need its own.
#
# Before turning this on for a stack that already has uploads: PocketBase does
# NOT copy existing files into the bucket. See README.md.
services:
# --- SeaweedFS: master -----------------------------------------------------
# Keeps the volume/topology metadata and hands out file ids. -ip is the name
# the other roles are told to reach it by, so it must be the service name and
# not the container IP the process would otherwise detect.
seaweedfs-master:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-aio-seaweedfs-master
restart: unless-stopped
command: >
master -ip=seaweedfs-master -ip.bind=0.0.0.0 -mdir=/data
-volumeSizeLimitMB=1024 -metricsPort=9324
volumes:
- seaweed_data:/data
ports:
# Master UI / API. Useful while developing; the admin UI below covers the
# same ground with a nicer face.
- "${SEAWEED_MASTER_PORT:-9333}:9333"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:9333/cluster/status || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 15s
# --- SeaweedFS: volume server ---------------------------------------------
# Where the bytes actually land. -max=0 lets it size itself from free disk
# rather than the default cap of 8 volumes.
seaweedfs-volume:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-aio-seaweedfs-volume
restart: unless-stopped
command: >
volume -master=seaweedfs-master:9333 -ip=seaweedfs-volume -ip.bind=0.0.0.0
-port=8080 -dir=/data -max=0 -metricsPort=9325
depends_on:
seaweedfs-master:
condition: service_healthy
volumes:
- seaweed_data:/data
ports:
# This port serves file content by file id with NO authentication — the S3
# credentials do not apply to it. Publish it only where you would be
# willing to publish the bucket itself.
- "${SEAWEED_VOLUME_PORT:-8081}:8080"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 15s
# --- SeaweedFS: filer ------------------------------------------------------
# Gives the flat volume store a directory tree — buckets, object keys — and
# holds the S3 identities the admin UI writes. -defaultStoreDir is where its
# embedded leveldb goes; without it that would be the container's working
# directory, and the identities would not survive a recreate.
seaweedfs-filer:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-aio-seaweedfs-filer
restart: unless-stopped
command: >
filer -master=seaweedfs-master:9333 -ip=seaweedfs-filer -ip.bind=0.0.0.0
-port=8888 -defaultStoreDir=/data -metricsPort=9326
depends_on:
seaweedfs-volume:
condition: service_healthy
volumes:
- seaweed_data:/data
ports:
- "${SEAWEED_FILER_PORT:-8888}:8888"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8888/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 15s
# --- SeaweedFS: bucket and identity seed ----------------------------------
# Runs once and exits, before the gateway starts. Two jobs:
#
# 1. create the bucket — PocketBase never issues a CreateBucket of its own;
# 2. write PocketBase's S3 identity into the filer's IAM store.
#
# (2) is why this stack does not set AWS_ACCESS_KEY_ID on the gateway, the way
# docker-compose.seaweedfs.yml does. Those env vars are the *lowest* priority
# credential source in SeaweedFS: they are read only while the filer's store is
# empty, so the first identity added in the admin UI would silently displace
# them and lock PocketBase out. Seeding the store the admin UI itself writes
# leaves one source of truth, and the key PocketBase uses appears under
# Object Store → Users like any other.
#
# Both commands update in place, so every later boot re-applies the values from
# .env and changes nothing else — which is also how a rotated PB_S3_SECRET
# reaches the gateway.
#
# The closing grep is the gate: an empty IAM store means the gateway would come
# up in its allow-anyone default, so this fails loudly instead and the gateway
# below never starts. No `|| true` here, deliberately.
seaweedfs-init:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-aio-seaweedfs-init
restart: "no"
depends_on:
seaweedfs-filer:
condition: service_healthy
environment:
# Passed as env and expanded by the shell inside the container, so the
# secret stays out of the container's argv.
PB_S3_BUCKET: "${PB_S3_BUCKET:-drivervault}"
PB_S3_ACCESS_KEY: "${PB_S3_ACCESS_KEY:?set PB_S3_ACCESS_KEY in .env}"
PB_S3_SECRET: "${PB_S3_SECRET:?set PB_S3_SECRET in .env}"
entrypoint: ["/bin/sh", "-c"]
command:
- |
set -e
printf '%s\n' \
"s3.bucket.create -name $$PB_S3_BUCKET" \
"s3.configure -user drivervault -access_key $$PB_S3_ACCESS_KEY -secret_key $$PB_S3_SECRET -actions Admin -apply" \
| weed shell -master=seaweedfs-master:9333 -filer=seaweedfs-filer:8888
echo "s3.configure" \
| weed shell -master=seaweedfs-master:9333 -filer=seaweedfs-filer:8888 \
| grep -q "$$PB_S3_ACCESS_KEY"
# --- SeaweedFS: S3 gateway -------------------------------------------------
# The endpoint PocketBase talks to. No -config file: with only -filer given,
# credentials come from the filer's IAM store, which is what lets the admin UI
# add and revoke identities without a restart. A config file would take
# priority over that store and make the admin UI's users inert.
seaweedfs-s3:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-aio-seaweedfs-s3
restart: unless-stopped
command: >
s3 -filer=seaweedfs-filer:8888 -ip.bind=0.0.0.0 -port=8333
-metricsPort=9327
depends_on:
seaweedfs-filer:
condition: service_healthy
# Never serve before an identity exists — see seaweedfs-init above.
seaweedfs-init:
condition: service_completed_successfully
# No published port: the stack reaches the gateway over the compose network.
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8333/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 15s
# --- SeaweedFS: admin UI ---------------------------------------------------
# http://localhost:23646 — cluster topology, volumes, buckets, maintenance
# tasks, and Object Store → Users, where S3 access keys are minted and revoked.
# It finds the filer through the master, so -master is all it needs.
#
# An unauthenticated panel that can mint credentials for the bucket *is* the
# bucket, so the password is required rather than defaulted — weed leaves auth
# off entirely when it is empty. It is read from WEED_ADMIN_* rather than a
# flag, which keeps it off the process command line. -dataDir persists the
# session key and the maintenance-task settings.
seaweedfs-admin:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-aio-seaweedfs-admin
restart: unless-stopped
command: >
admin -port=23646 -master=seaweedfs-master:9333 -dataDir=/data
-metricsPort=9328
depends_on:
seaweedfs-master:
condition: service_healthy
environment:
WEED_ADMIN_USER: "${SEAWEED_ADMIN_USER:-admin}"
WEED_ADMIN_PASSWORD: "${SEAWEED_ADMIN_PASSWORD:?set SEAWEED_ADMIN_PASSWORD in .env}"
volumes:
- seaweed_admin:/data
ports:
- "${SEAWEED_ADMIN_PORT:-23646}:23646"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:23646/health || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 15s
drivervault:
build:
# Project root (one level up from this compose file).
context: ..
dockerfile: Docker-AIO/Dockerfile
args:
# Empty -> bundle uses same-origin "/api", proxied internally by nginx.
- VITE_API_BASE=${VITE_API_BASE:-}
# Bare name = pass through only when set in the environment, so an unset
# PB_VERSION leaves the Dockerfile pin in place instead of overriding it
# with an empty string (which would resolve "latest" at build time).
- PB_VERSION
image: drivervault-aio
container_name: drivervault-aio
restart: unless-stopped
depends_on:
# PocketBase — inside this container — is the process that reads and
# writes the objects, so the gateway has to be serving first, and the
# bucket has to exist before the bootstrap points PocketBase at it.
seaweedfs-s3:
condition: service_healthy
seaweedfs-init:
condition: service_completed_successfully
environment:
# Superuser (also used by the API Server to authenticate to PocketBase).
PB_ADMIN_EMAIL: "${PB_ADMIN_EMAIL:?set PB_ADMIN_EMAIL in .env}"
PB_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD:?set PB_ADMIN_PASSWORD in .env}"
# Match CORS to the web origin (only used if a browser calls the API directly).
CORS_ALLOW_ORIGINS: "${CORS_ALLOW_ORIGINS:-http://localhost:8090}"
# Probed by the panel status page. nginx serves the Web App on port 80
# inside this container, so plain localhost:8090 would never answer.
# Override WEBAPP_URL in .env to make a change from the panel's Web App
# screen permanent; the panel alone only holds it for the container's life.
WEBAPP_URL: "${WEBAPP_URL:-http://127.0.0.1:80}"
# Schema + super-admin bootstrap (idempotent). Leave this ON: a release can
# add collections or fields the server needs, and a stack that skips the
# bootstrap never gets them. The API Server self-heals exactly one thing —
# app_settings, the collection holding the plugin settings, which it
# creates on demand because it cannot serve the plugin panel without it.
# Every other schema change still depends on this flag. Turn it off only
# for a database you know already matches the release.
PB_BOOTSTRAP: "${PB_BOOTSTRAP:-true}"
DRIVERVAULT_SUPERADMIN_EMAIL: "${DRIVERVAULT_SUPERADMIN_EMAIL:-}"
DRIVERVAULT_SUPERADMIN_PASSWORD: "${DRIVERVAULT_SUPERADMIN_PASSWORD:-}"
DRIVERVAULT_SUPERADMIN_NAME: "${DRIVERVAULT_SUPERADMIN_NAME:-Administrator}"
# OCPP charger control (Anker Solix). This image serves plain HTTP, so a
# charger can only connect when TLS is terminated in front of it (set
# OCPP_PUBLIC_URL to the public wss:// base) — or, on a trusted network,
# with OCPP_REQUIRE_TLS=false.
OCPP_REQUIRE_TLS: "${OCPP_REQUIRE_TLS:-true}"
OCPP_PUBLIC_URL: "${OCPP_PUBLIC_URL:-}"
# --- File storage --------------------------------------------------
# supervisord passes these through to the API Server, whose bootstrap
# writes them into PocketBase's
# settings on every boot, idempotently. Only record files move — scans,
# receipts, invoices, part photos. The database and PocketBase's own
# backups stay on pb_data.
PB_S3_ENABLED: "true"
PB_S3_BUCKET: "${PB_S3_BUCKET:-drivervault}"
# The gateway's service name: a server-to-server call inside the compose
# network.
PB_S3_ENDPOINT: "http://seaweedfs-s3:8333"
# SeaweedFS ignores the region; PocketBase insists on having one.
PB_S3_REGION: "${PB_S3_REGION:-us-east-1}"
PB_S3_ACCESS_KEY: "${PB_S3_ACCESS_KEY}"
PB_S3_SECRET: "${PB_S3_SECRET}"
# Path style, because a self-hosted gateway has no per-bucket DNS.
PB_S3_FORCE_PATH_STYLE: "true"
ports:
- "${WEB_PORT:-8090}:80" # Web App
- "${PB_PORT:-8070}:8070" # PocketBase admin UI / API
- "${API_PORT:-8080}:8080" # API Server + panel (root /) + /ocpp/{serial}
volumes:
# The only volume: the API Server keeps no state on disk, so everything
# it owns — plugin settings included — lives in the database.
- pb_data:/pb/pb_data
healthcheck:
# All three processes must answer. Declared here as well as in the image so
# the check is visible, and works against an older pulled image.
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8070/api/health >/dev/null && wget -qO- http://127.0.0.1:8080/healthz >/dev/null && wget -qO- http://127.0.0.1:80/healthz >/dev/null || exit 1"]
interval: 30s
timeout: 5s
retries: 3
start_period: 60s
volumes:
pb_data:
# Shared by master, volume and filer — the same layout `weed server -dir`
# writes, so this file and docker-compose.seaweedfs.yml can swap places on it.
seaweed_data:
# The admin UI's own session key and maintenance-task state. Small, and no
# part of the object store.
seaweed_admin:
+157
View File
@@ -0,0 +1,157 @@
name: drivervault-aio
# Single all-in-one container, with SeaweedFS: PocketBase + API Server + Web App
# (nginx) in one image, plus an S3 object store beside it. Self-contained — one
# file, nothing to layer.
#
# cp .env.seaweedfs.example .env (then edit it)
# docker compose -f docker-compose.seaweedfs.yml up -d --build
#
# The build context is the project root so the Dockerfile can reach both
# "API Server/" and "Web App/".
#
# This is docker-compose.yml plus storage: PocketBase keeps its record files —
# document scans, service and refill receipts, workshop invoices, part photos —
# in a SeaweedFS bucket instead of on the pb_data volume next to the database.
# The database and PocketBase's own backups stay on pb_data. Clients cannot tell
# the difference: an attachment has always been fetched through the API Server,
# never from a storage URL.
#
# SeaweedFS runs as a second container beside the all-in-one, not as a fourth
# process inside it: keeping the object store in that image, on the volume the
# files are being moved off, would defeat the point and would mean rebuilding.
#
# Before turning this on for a stack that already has uploads: PocketBase does
# NOT copy existing files into the bucket. See README.md.
services:
seaweedfs:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-aio-seaweedfs
restart: unless-stopped
# One process, four roles: master, volume, filer and the S3 gateway. -dir is
# the only state it keeps.
command: server -dir=/data -s3 -master.volumeSizeLimitMB=1024
environment:
# SeaweedFS falls back to these when started without an -s3.config file,
# and configuring one identity is what takes the S3 gateway out of its
# default allow-anyone mode. The same credentials PocketBase authenticates
# with below — one pair to set, in .env.
AWS_ACCESS_KEY_ID: "${PB_S3_ACCESS_KEY:?set PB_S3_ACCESS_KEY in .env}"
AWS_SECRET_ACCESS_KEY: "${PB_S3_SECRET:?set PB_S3_SECRET in .env}"
volumes:
# From here on the attachments live here, not on pb_data.
- seaweed_data:/data
# No published port: the stack reaches the gateway over the compose network.
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:9333/cluster/status || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 20s
seaweedfs-init:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-aio-seaweedfs-init
# Runs once and exits. PocketBase never issues a CreateBucket of its own and
# SeaweedFS will not conjure one on first upload, so something has to.
# Creating a bucket that already exists is a no-op, so every later boot
# passes straight through.
restart: "no"
depends_on:
seaweedfs:
condition: service_healthy
entrypoint: ["/bin/sh", "-c"]
# `|| true` so a restart is never blocked by the shell's exit status: this
# step is best-effort, and a gateway that is genuinely unreachable is
# reported by the API Server's own S3 check at boot, with the reason.
command:
- 'echo "s3.bucket.create -name ${PB_S3_BUCKET:-drivervault}" | weed shell -master=seaweedfs:9333 || true'
drivervault:
build:
# Project root (one level up from this compose file).
context: ..
dockerfile: Docker-AIO/Dockerfile
args:
# Empty -> bundle uses same-origin "/api", proxied internally by nginx.
- VITE_API_BASE=${VITE_API_BASE:-}
# Bare name = pass through only when set in the environment, so an unset
# PB_VERSION leaves the Dockerfile pin in place instead of overriding it
# with an empty string (which would resolve "latest" at build time).
- PB_VERSION
image: drivervault-aio
container_name: drivervault-aio
restart: unless-stopped
depends_on:
# PocketBase — inside this container — is the process that reads and
# writes the objects, so the gateway has to be serving first, and the
# bucket has to exist before the bootstrap points PocketBase at it.
seaweedfs:
condition: service_healthy
seaweedfs-init:
condition: service_completed_successfully
environment:
# Superuser (also used by the API Server to authenticate to PocketBase).
PB_ADMIN_EMAIL: "${PB_ADMIN_EMAIL:?set PB_ADMIN_EMAIL in .env}"
PB_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD:?set PB_ADMIN_PASSWORD in .env}"
# Match CORS to the web origin (only used if a browser calls the API directly).
CORS_ALLOW_ORIGINS: "${CORS_ALLOW_ORIGINS:-http://localhost:8090}"
# Probed by the panel status page. nginx serves the Web App on port 80
# inside this container, so plain localhost:8090 would never answer.
# Override WEBAPP_URL in .env to make a change from the panel's Web App
# screen permanent; the panel alone only holds it for the container's life.
WEBAPP_URL: "${WEBAPP_URL:-http://127.0.0.1:80}"
# Schema + super-admin bootstrap (idempotent). Leave this ON: a release can
# add collections or fields the server needs, and a stack that skips the
# bootstrap never gets them. The API Server self-heals exactly one thing —
# app_settings, the collection holding the plugin settings, which it
# creates on demand because it cannot serve the plugin panel without it.
# Every other schema change still depends on this flag. Turn it off only
# for a database you know already matches the release.
PB_BOOTSTRAP: "${PB_BOOTSTRAP:-true}"
DRIVERVAULT_SUPERADMIN_EMAIL: "${DRIVERVAULT_SUPERADMIN_EMAIL:-}"
DRIVERVAULT_SUPERADMIN_PASSWORD: "${DRIVERVAULT_SUPERADMIN_PASSWORD:-}"
DRIVERVAULT_SUPERADMIN_NAME: "${DRIVERVAULT_SUPERADMIN_NAME:-Administrator}"
# OCPP charger control (Anker Solix). This image serves plain HTTP, so a
# charger can only connect when TLS is terminated in front of it (set
# OCPP_PUBLIC_URL to the public wss:// base) — or, on a trusted network,
# with OCPP_REQUIRE_TLS=false.
OCPP_REQUIRE_TLS: "${OCPP_REQUIRE_TLS:-true}"
OCPP_PUBLIC_URL: "${OCPP_PUBLIC_URL:-}"
# --- File storage --------------------------------------------------
# supervisord passes these through to the API Server, whose bootstrap
# writes them into PocketBase's
# settings on every boot, idempotently. Only record files move — scans,
# receipts, invoices, part photos. The database and PocketBase's own
# backups stay on pb_data.
PB_S3_ENABLED: "true"
PB_S3_BUCKET: "${PB_S3_BUCKET:-drivervault}"
# The service name: a server-to-server call inside the compose network.
PB_S3_ENDPOINT: "http://seaweedfs:8333"
# SeaweedFS ignores the region; PocketBase insists on having one.
PB_S3_REGION: "${PB_S3_REGION:-us-east-1}"
PB_S3_ACCESS_KEY: "${PB_S3_ACCESS_KEY}"
PB_S3_SECRET: "${PB_S3_SECRET}"
# Path style, because a self-hosted gateway has no per-bucket DNS.
PB_S3_FORCE_PATH_STYLE: "true"
ports:
- "${WEB_PORT:-8090}:80" # Web App
- "${PB_PORT:-8070}:8070" # PocketBase admin UI / API
- "${API_PORT:-8080}:8080" # API Server + panel (root /) + /ocpp/{serial}
volumes:
# The only volume: the API Server keeps no state on disk, so everything
# it owns — plugin settings included — lives in the database.
- pb_data:/pb/pb_data
healthcheck:
# All three processes must answer. Declared here as well as in the image so
# the check is visible, and works against an older pulled image.
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8070/api/health >/dev/null && wget -qO- http://127.0.0.1:8080/healthz >/dev/null && wget -qO- http://127.0.0.1:80/healthz >/dev/null || exit 1"]
interval: 30s
timeout: 5s
retries: 3
start_period: 60s
volumes:
pb_data:
seaweed_data:
+9 -8
View File
@@ -34,6 +34,15 @@ AUTH_USERS_COLLECTION=users
# public wss:// base, or set OCPP_REQUIRE_TLS=false on a trusted network. # public wss:// base, or set OCPP_REQUIRE_TLS=false on a trusted network.
OCPP_REQUIRE_TLS=true OCPP_REQUIRE_TLS=true
OCPP_PUBLIC_URL= OCPP_PUBLIC_URL=
# Diagnostic only. Set to 1 to log every frame the charger publishes over Anker's
# cloud broker — the ones DriverVault decodes and the ones it cannot, with their
# bytes. It is how an unnamed frame gets named: hold a control read open, do the
# thing in the Anker app, then read the frames back out of the container log.
# Leave blank on a normal stack; a triggered charger writes a line every few
# seconds.
ANKER_MQTT_FRAME_LOG=
# The charger can dial either door: the API Server port directly, or the Web # The charger can dial either door: the API Server port directly, or the Web
# App port, whose BFF now proxies /ocpp/ through to it. The endpoint the panel # App port, whose BFF now proxies /ocpp/ through to it. The endpoint the panel
# shows is the API Server port only when OCPP_PUBLIC_URL says so — left blank it # shows is the API Server port only when OCPP_PUBLIC_URL says so — left blank it
@@ -66,11 +75,3 @@ VITE_API_BASE=
# CORS_ALLOW_ORIGINS browser origins allowed to call the API Server directly. # CORS_ALLOW_ORIGINS browser origins allowed to call the API Server directly.
# POCKETBASE_URL=http://pocketbase:8070 # POCKETBASE_URL=http://pocketbase:8070
# WEBAPP_URL=http://web-app:8090 # WEBAPP_URL=http://web-app:8090
# --- Public hostname + TLS (docker-compose.tls.yml) --------------------------
# Only read when the TLS overlay is layered on. DV_DOMAIN must resolve to this
# host from the internet, with ports 80 and 443 reaching it; the certificate is
# issued automatically on first boot. Setting it also points chargers at
# wss://DV_DOMAIN, which is what lets OCPP_REQUIRE_TLS stay on.
DV_DOMAIN=
DV_ACME_EMAIL=
+9 -8
View File
@@ -47,6 +47,15 @@ AUTH_USERS_COLLECTION=users
# networks only. # networks only.
OCPP_REQUIRE_TLS=true OCPP_REQUIRE_TLS=true
OCPP_PUBLIC_URL= OCPP_PUBLIC_URL=
# Diagnostic only. Set to 1 to log every frame the charger publishes over Anker's
# cloud broker — the ones DriverVault decodes and the ones it cannot, with their
# bytes. It is how an unnamed frame gets named: hold a control read open, do the
# thing in the Anker app, then read the frames back out of the container log.
# Leave blank on a normal stack; a triggered charger writes a line every few
# seconds.
ANKER_MQTT_FRAME_LOG=
# The charger can dial either door: the API Server port directly, or the Web # The charger can dial either door: the API Server port directly, or the Web
# App port, whose BFF now proxies /ocpp/ through to it. The endpoint the panel # App port, whose BFF now proxies /ocpp/ through to it. The endpoint the panel
# shows is the API Server port only when OCPP_PUBLIC_URL says so — left blank it # shows is the API Server port only when OCPP_PUBLIC_URL says so — left blank it
@@ -88,11 +97,3 @@ API_BIND=127.0.0.1
# stack: the API Server keeps no state on disk, so everything it owns (plugin # stack: the API Server keeps no state on disk, so everything it owns (plugin
# settings included) is backed up by backing up this one path. # settings included) is backed up by backing up this one path.
PB_DATA=pb_data PB_DATA=pb_data
# --- Public hostname + TLS (docker-compose.tls.yml) --------------------------
# Only read when the TLS overlay is layered on. DV_DOMAIN must resolve to this
# host from the internet, with ports 80 and 443 reaching it; the certificate is
# issued automatically on first boot. Setting it also points chargers at
# wss://DV_DOMAIN, which is what lets OCPP_REQUIRE_TLS stay on.
DV_DOMAIN=
DV_ACME_EMAIL=
+121
View File
@@ -0,0 +1,121 @@
# DriverVault — production stack config.
# Copy to .env and fill in, then:
# docker compose -f docker-compose.prod.s3.yml pull
# docker compose -f docker-compose.prod.s3.yml up -d
# --- Registry images ---------------------------------------------------------
# Defaults point at the internal registry; override to pin a tag or use a mirror.
PB_IMAGE=10.2.1.10:5500/admin/drivervault-pocketbase:latest
API_IMAGE=10.2.1.10:5500/admin/drivervault-api-server:latest
WEB_IMAGE=10.2.1.10:5500/admin/drivervault-web-app:latest
# --- PocketBase superuser ----------------------------------------------------
# Created/updated on the PocketBase container's first boot. The API Server uses
# these same credentials to manage the database. REQUIRED.
PB_ADMIN_EMAIL=admin@example.com
PB_ADMIN_PASSWORD=change-me-long-password
# --- DriverVault super-admin (app login) -------------------------------------
# The first application user, created by the API Server on boot with role
# "superadmin" if no user with this email exists yet. Leave blank to skip and
# create the first user by hand. This is the account you log in to the web app
# with — distinct from the PocketBase superuser above.
DRIVERVAULT_SUPERADMIN_EMAIL=owner@example.com
DRIVERVAULT_SUPERADMIN_PASSWORD=change-me-long-password
DRIVERVAULT_SUPERADMIN_NAME=Administrator
# Schema creation/reconcile on boot. Leave this true: a release can add
# collections or fields the server needs, and a stack that skips the bootstrap
# never gets them. (The API Server creates app_settings, which holds the plugin
# settings, on demand — but only that one.) Set false only for a database you
# know already matches the release.
PB_BOOTSTRAP=true
# --- API Server --------------------------------------------------------------
# Allowed CORS origin(s) for the web app (match your public URL / WEB_PORT).
CORS_ALLOW_ORIGINS=http://localhost:8090
AUTH_USERS_COLLECTION=users
# --- EV charging control (Anker Solix, OCPP) ---------------------------------
# Only relevant when a charger is set to own/proxy control mode. The charger
# dials in to /ocpp/{serial} on the API Server port, carrying its control token
# in an OCPP Basic-auth header — which a plaintext ws:// would expose, so
# non-TLS connections are rejected by default. Keep the default and terminate
# TLS in a reverse proxy in front of this stack, setting OCPP_PUBLIC_URL to the
# public wss:// base the charger should be pointed at (deriving it from request
# headers is unreliable behind a proxy). Turning the check off is for trusted
# networks only.
OCPP_REQUIRE_TLS=true
OCPP_PUBLIC_URL=
# Diagnostic only. Set to 1 to log every frame the charger publishes over Anker's
# cloud broker — the ones DriverVault decodes and the ones it cannot, with their
# bytes. It is how an unnamed frame gets named: hold a control read open, do the
# thing in the Anker app, then read the frames back out of the container log.
# Leave blank on a normal stack; a triggered charger writes a line every few
# seconds.
ANKER_MQTT_FRAME_LOG=
# The charger can dial either door: the API Server port directly, or the Web
# App port, whose BFF now proxies /ocpp/ through to it. The endpoint the panel
# shows is the API Server port only when OCPP_PUBLIC_URL says so — left blank it
# is whichever host the panel itself was reached on, which is the Web App.
# TRUST_FORWARDED_PROTO lets the BFF pass an inbound X-Forwarded-Proto to the
# API Server: needed when TLS ends at a proxy in front of the stack and
# OCPP_REQUIRE_TLS stays on, and unsafe otherwise, since the header is then
# whatever the client said it was.
TRUST_FORWARDED_PROTO=false
# --- Ports -------------------------------------------------------------------
# WEB_PORT is the public front door (bound on all interfaces).
WEB_PORT=8090
# PocketBase admin UI and the API panel are bound to localhost only by default.
# Set PB_BIND / API_BIND to 0.0.0.0 to expose them on the network.
PB_PORT=8070
PB_BIND=127.0.0.1
API_PORT=8080
API_BIND=127.0.0.1
# --- Settings the API Server panel can also change ---------------------------
# The panel's Settings screens apply these immediately, but only for the life of
# the container — the values below are re-applied on every restart and win. Set
# them here to make a change permanent.
# POCKETBASE_URL where the API Server looks for the database. Defaults to
# the bundled pocketbase service; set it to reach one
# outside this stack.
# WEBAPP_URL the Web App address the panel status page probes. It is
# a container-to-container call, so it must be reachable
# from the API Server, not from your browser.
# CORS_ALLOW_ORIGINS browser origins allowed to call the API Server directly.
# POCKETBASE_URL=http://pocketbase:8070
# WEBAPP_URL=http://web-app:8090
# --- Storage -----------------------------------------------------------------
# One Docker-managed named volume by default. To store it on a host path
# instead, set an absolute path, e.g. PB_DATA=/srv/drivervault/pb_data.
# PB_DATA — the PocketBase database and uploads. It is the only volume in the
# stack: the API Server keeps no state on disk, so everything it owns (plugin
# settings included) is backed up by backing up this one path.
PB_DATA=pb_data
# --- File storage: external S3 -----------------------------------------------
# PocketBase keeps its record files — document scans, service and refill
# receipts, workshop invoices, part photos — in the bucket below instead of on
# PB_DATA. The database and PocketBase's own backups stay where they are.
#
# Nothing in this stack runs a gateway: both the endpoint and the bucket must
# already exist. For a gateway on this Docker host use
# http://host.docker.internal:8333 — the compose file adds the host entry that
# makes that name resolve inside the containers.
PB_S3_ENDPOINT=http://10.2.1.10:8333
PB_S3_BUCKET=drivervault
PB_S3_ACCESS_KEY=
PB_S3_SECRET=
# SeaweedFS and MinIO ignore the region; PocketBase insists on having one.
PB_S3_REGION=us-east-1
# true for SeaweedFS and MinIO, false for AWS S3 proper.
PB_S3_FORCE_PATH_STYLE=true
# Existing uploads are NOT migrated when this is switched on: PocketBase copies
# nothing, so attachments made before the switch stop resolving. Read the file
# storage section of README.md first.
+128
View File
@@ -0,0 +1,128 @@
# DriverVault — production stack config.
# Copy to .env and fill in, then:
# docker compose -f docker-compose.prod.seaweedfs.yml pull
# docker compose -f docker-compose.prod.seaweedfs.yml up -d
# --- Registry images ---------------------------------------------------------
# Defaults point at the internal registry; override to pin a tag or use a mirror.
PB_IMAGE=10.2.1.10:5500/admin/drivervault-pocketbase:latest
API_IMAGE=10.2.1.10:5500/admin/drivervault-api-server:latest
WEB_IMAGE=10.2.1.10:5500/admin/drivervault-web-app:latest
# --- PocketBase superuser ----------------------------------------------------
# Created/updated on the PocketBase container's first boot. The API Server uses
# these same credentials to manage the database. REQUIRED.
PB_ADMIN_EMAIL=admin@example.com
PB_ADMIN_PASSWORD=change-me-long-password
# --- DriverVault super-admin (app login) -------------------------------------
# The first application user, created by the API Server on boot with role
# "superadmin" if no user with this email exists yet. Leave blank to skip and
# create the first user by hand. This is the account you log in to the web app
# with — distinct from the PocketBase superuser above.
DRIVERVAULT_SUPERADMIN_EMAIL=owner@example.com
DRIVERVAULT_SUPERADMIN_PASSWORD=change-me-long-password
DRIVERVAULT_SUPERADMIN_NAME=Administrator
# Schema creation/reconcile on boot. Leave this true: a release can add
# collections or fields the server needs, and a stack that skips the bootstrap
# never gets them. (The API Server creates app_settings, which holds the plugin
# settings, on demand — but only that one.) Set false only for a database you
# know already matches the release.
PB_BOOTSTRAP=true
# --- API Server --------------------------------------------------------------
# Allowed CORS origin(s) for the web app (match your public URL / WEB_PORT).
CORS_ALLOW_ORIGINS=http://localhost:8090
AUTH_USERS_COLLECTION=users
# --- EV charging control (Anker Solix, OCPP) ---------------------------------
# Only relevant when a charger is set to own/proxy control mode. The charger
# dials in to /ocpp/{serial} on the API Server port, carrying its control token
# in an OCPP Basic-auth header — which a plaintext ws:// would expose, so
# non-TLS connections are rejected by default. Keep the default and terminate
# TLS in a reverse proxy in front of this stack, setting OCPP_PUBLIC_URL to the
# public wss:// base the charger should be pointed at (deriving it from request
# headers is unreliable behind a proxy). Turning the check off is for trusted
# networks only.
OCPP_REQUIRE_TLS=true
OCPP_PUBLIC_URL=
# Diagnostic only. Set to 1 to log every frame the charger publishes over Anker's
# cloud broker — the ones DriverVault decodes and the ones it cannot, with their
# bytes. It is how an unnamed frame gets named: hold a control read open, do the
# thing in the Anker app, then read the frames back out of the container log.
# Leave blank on a normal stack; a triggered charger writes a line every few
# seconds.
ANKER_MQTT_FRAME_LOG=
# The charger can dial either door: the API Server port directly, or the Web
# App port, whose BFF now proxies /ocpp/ through to it. The endpoint the panel
# shows is the API Server port only when OCPP_PUBLIC_URL says so — left blank it
# is whichever host the panel itself was reached on, which is the Web App.
# TRUST_FORWARDED_PROTO lets the BFF pass an inbound X-Forwarded-Proto to the
# API Server: needed when TLS ends at a proxy in front of the stack and
# OCPP_REQUIRE_TLS stays on, and unsafe otherwise, since the header is then
# whatever the client said it was.
TRUST_FORWARDED_PROTO=false
# --- Ports -------------------------------------------------------------------
# WEB_PORT is the public front door (bound on all interfaces).
WEB_PORT=8090
# PocketBase admin UI and the API panel are bound to localhost only by default.
# Set PB_BIND / API_BIND to 0.0.0.0 to expose them on the network.
PB_PORT=8070
PB_BIND=127.0.0.1
API_PORT=8080
API_BIND=127.0.0.1
# --- Settings the API Server panel can also change ---------------------------
# The panel's Settings screens apply these immediately, but only for the life of
# the container — the values below are re-applied on every restart and win. Set
# them here to make a change permanent.
# POCKETBASE_URL where the API Server looks for the database. Defaults to
# the bundled pocketbase service; set it to reach one
# outside this stack.
# WEBAPP_URL the Web App address the panel status page probes. It is
# a container-to-container call, so it must be reachable
# from the API Server, not from your browser.
# CORS_ALLOW_ORIGINS browser origins allowed to call the API Server directly.
# POCKETBASE_URL=http://pocketbase:8070
# WEBAPP_URL=http://web-app:8090
# --- Storage -----------------------------------------------------------------
# One Docker-managed named volume by default. To store it on a host path
# instead, set an absolute path, e.g. PB_DATA=/srv/drivervault/pb_data.
# PB_DATA — the PocketBase database and uploads. It is the only volume in the
# stack: the API Server keeps no state on disk, so everything it owns (plugin
# settings included) is backed up by backing up this one path.
PB_DATA=pb_data
# --- File storage: SeaweedFS -------------------------------------------------
# PocketBase keeps its record files — document scans, service and refill
# receipts, workshop invoices, part photos — in the bucket below instead of on
# PB_DATA. The database and PocketBase's own backups stay where they are.
#
# The credentials do double duty: they configure the SeaweedFS gateway's single
# identity *and* are what PocketBase authenticates with. There are no safe
# defaults, and the stack refuses to start without them.
PB_S3_ACCESS_KEY=
PB_S3_SECRET=
# The bucket. Created on first boot by the seaweedfs-init container.
PB_S3_BUCKET=drivervault
# SeaweedFS ignores the region; PocketBase insists on having one.
PB_S3_REGION=us-east-1
# SEAWEED_DATA — where SeaweedFS keeps the files. A Docker-managed named volume
# by default; set an absolute host path for a bind mount, the same way PB_DATA
# works above. Back it up alongside PB_DATA: from here on the attachments live
# here, not in the database volume.
SEAWEED_DATA=seaweed_data
# The gateway image, pinned so a redeploy months from now brings up the same one.
# SEAWEED_IMAGE=chrislusf/seaweedfs:4.45
# The S3 gateway publishes no host port: the stack reaches it over the compose
# network.
# Existing uploads are NOT migrated when this is switched on: PocketBase copies
# nothing, so attachments made before the switch stop resolving. Read the file
# storage section of README.md first.
+160
View File
@@ -0,0 +1,160 @@
# DriverVault — production stack config, SeaweedFS split into its four roles.
# Copy to .env and fill in, then:
# docker compose -f docker-compose.prod.seaweedfs.split.yml pull
# docker compose -f docker-compose.prod.seaweedfs.split.yml up -d
# --- Registry images ---------------------------------------------------------
# Defaults point at the internal registry; override to pin a tag or use a mirror.
PB_IMAGE=10.2.1.10:5500/admin/drivervault-pocketbase:latest
API_IMAGE=10.2.1.10:5500/admin/drivervault-api-server:latest
WEB_IMAGE=10.2.1.10:5500/admin/drivervault-web-app:latest
# --- PocketBase superuser ----------------------------------------------------
# Created/updated on the PocketBase container's first boot. The API Server uses
# these same credentials to manage the database. REQUIRED.
PB_ADMIN_EMAIL=admin@example.com
PB_ADMIN_PASSWORD=change-me-long-password
# --- DriverVault super-admin (app login) -------------------------------------
# The first application user, created by the API Server on boot with role
# "superadmin" if no user with this email exists yet. Leave blank to skip and
# create the first user by hand. This is the account you log in to the web app
# with — distinct from the PocketBase superuser above.
DRIVERVAULT_SUPERADMIN_EMAIL=owner@example.com
DRIVERVAULT_SUPERADMIN_PASSWORD=change-me-long-password
DRIVERVAULT_SUPERADMIN_NAME=Administrator
# Schema creation/reconcile on boot. Leave this true: a release can add
# collections or fields the server needs, and a stack that skips the bootstrap
# never gets them. (The API Server creates app_settings, which holds the plugin
# settings, on demand — but only that one.) Set false only for a database you
# know already matches the release.
PB_BOOTSTRAP=true
# --- API Server --------------------------------------------------------------
# Allowed CORS origin(s) for the web app (match your public URL / WEB_PORT).
CORS_ALLOW_ORIGINS=http://localhost:8090
AUTH_USERS_COLLECTION=users
# --- EV charging control (Anker Solix, OCPP) ---------------------------------
# Only relevant when a charger is set to own/proxy control mode. The charger
# dials in to /ocpp/{serial} on the API Server port, carrying its control token
# in an OCPP Basic-auth header — which a plaintext ws:// would expose, so
# non-TLS connections are rejected by default. Keep the default and terminate
# TLS in a reverse proxy in front of this stack, setting OCPP_PUBLIC_URL to the
# public wss:// base the charger should be pointed at (deriving it from request
# headers is unreliable behind a proxy). Turning the check off is for trusted
# networks only.
OCPP_REQUIRE_TLS=true
OCPP_PUBLIC_URL=
# Diagnostic only. Set to 1 to log every frame the charger publishes over Anker's
# cloud broker — the ones DriverVault decodes and the ones it cannot, with their
# bytes. It is how an unnamed frame gets named: hold a control read open, do the
# thing in the Anker app, then read the frames back out of the container log.
# Leave blank on a normal stack; a triggered charger writes a line every few
# seconds.
ANKER_MQTT_FRAME_LOG=
# The charger can dial either door: the API Server port directly, or the Web
# App port, whose BFF now proxies /ocpp/ through to it. The endpoint the panel
# shows is the API Server port only when OCPP_PUBLIC_URL says so — left blank it
# is whichever host the panel itself was reached on, which is the Web App.
# TRUST_FORWARDED_PROTO lets the BFF pass an inbound X-Forwarded-Proto to the
# API Server: needed when TLS ends at a proxy in front of the stack and
# OCPP_REQUIRE_TLS stays on, and unsafe otherwise, since the header is then
# whatever the client said it was.
TRUST_FORWARDED_PROTO=false
# --- Ports -------------------------------------------------------------------
# WEB_PORT is the public front door (bound on all interfaces).
WEB_PORT=8090
# PocketBase admin UI and the API panel are bound to localhost only by default.
# Set PB_BIND / API_BIND to 0.0.0.0 to expose them on the network — which is
# what a stack running on a remote host needs, behind a reverse proxy.
PB_PORT=8070
PB_BIND=127.0.0.1
API_PORT=8080
API_BIND=127.0.0.1
# --- Settings the API Server panel can also change ---------------------------
# The panel's Settings screens apply these immediately, but only for the life of
# the container — the values below are re-applied on every restart and win. Set
# them here to make a change permanent.
# POCKETBASE_URL where the API Server looks for the database. Defaults to
# the bundled pocketbase service; set it to reach one
# outside this stack.
# WEBAPP_URL the Web App address the panel status page probes. It is
# a container-to-container call, so it must be reachable
# from the API Server, not from your browser.
# CORS_ALLOW_ORIGINS browser origins allowed to call the API Server directly.
# POCKETBASE_URL=http://pocketbase:8070
# WEBAPP_URL=http://web-app:8090
# --- Storage -----------------------------------------------------------------
# One Docker-managed named volume by default. To store it on a host path
# instead, set an absolute path, e.g. PB_DATA=/srv/drivervault/pb_data.
# PB_DATA — the PocketBase database and its backups. The API Server keeps no
# state on disk, so everything it owns (plugin settings included) is backed up
# by backing up this one path — together with SEAWEED_DATA below.
PB_DATA=pb_data
# --- File storage: SeaweedFS -------------------------------------------------
# PocketBase keeps its record files — document scans, service and refill
# receipts, workshop invoices, part photos — in the bucket below instead of on
# PB_DATA. The database and PocketBase's own backups stay where they are.
#
# The credentials do double duty: seaweedfs-init writes them into the filer's
# IAM store as the identity named "drivervault" *and* they are what PocketBase
# authenticates with. There are no safe defaults, and the stack refuses to start
# without them. Change them here and restart to rotate: the seed updates the
# identity in place rather than adding a second one.
PB_S3_ACCESS_KEY=
PB_S3_SECRET=
# The bucket. Created on first boot by the seaweedfs-init container.
PB_S3_BUCKET=drivervault
# SeaweedFS ignores the region; PocketBase insists on having one.
PB_S3_REGION=us-east-1
# SEAWEED_DATA — where SeaweedFS keeps the files. A Docker-managed named volume
# by default; set an absolute host path for a bind mount, the same way PB_DATA
# works above. Back it up alongside PB_DATA: from here on the attachments live
# here, not in the database volume.
#
# The master, volume and filer containers all mount it at /data, which is the
# layout `weed server -dir=/data` writes — so this file and
# docker-compose.prod.seaweedfs.yml are interchangeable on the same volume, with
# nothing to migrate either way.
SEAWEED_DATA=seaweed_data
# The SeaweedFS image, pinned so a redeploy months from now brings up the same
# one. All five SeaweedFS containers run it.
# SEAWEED_IMAGE=chrislusf/seaweedfs:4.45
# The S3 gateway, master, volume and filer publish no host port at all. The admin UI below
# shows what they would: the volume server in particular serves file content by
# id with no authentication, so it stays on the compose network. Reach the
# others with `docker compose exec`.
# --- SeaweedFS admin UI ------------------------------------------------------
# Cluster topology, volumes, buckets, maintenance tasks, and Object Store →
# Users, where further S3 identities are created and revoked. They land in the
# filer's IAM store, the same one seeded above, and the gateway picks them up
# without a restart.
#
# REQUIRED: weed disables authentication entirely when the password is empty,
# and this panel can mint credentials for the bucket.
SEAWEED_ADMIN_USER=admin
SEAWEED_ADMIN_PASSWORD=
# Optional view-only login.
SEAWEED_ADMIN_READONLY_USER=
SEAWEED_ADMIN_READONLY_PASSWORD=
# Bound to localhost by default, like PB_BIND and API_BIND. On a remote host
# that means unreachable — set 0.0.0.0 and put it behind the same reverse proxy
# as the other panels.
SEAWEED_ADMIN_BIND=127.0.0.1
SEAWEED_ADMIN_PORT=23646
# Its own small volume: session key and maintenance-task state, no object data.
SEAWEED_ADMIN_DATA=seaweed_admin
# Existing uploads are NOT migrated when this is switched on: PocketBase copies
# nothing, so attachments made before the switch stop resolving. Read the file
# storage section of README.md first.
+99
View File
@@ -0,0 +1,99 @@
# Copy to .env and fill in. Used by the root docker-compose.s3.yml.
# --- PocketBase superuser (also used by the API Server to authenticate) ------
PB_ADMIN_EMAIL=admin@example.com
PB_ADMIN_PASSWORD=change-me-long-password
# --- DriverVault super-admin (app login) -------------------------------------
# The first application user, created by the API Server on boot with role
# "superadmin" if no user with this email exists yet. Leave these blank and the
# schema is still created but no user is, leaving a stack you cannot log into.
DRIVERVAULT_SUPERADMIN_EMAIL=owner@example.com
DRIVERVAULT_SUPERADMIN_PASSWORD=change-me-long-password
DRIVERVAULT_SUPERADMIN_NAME=Administrator
# Schema creation/reconcile on boot. Leave this true: a release can add
# collections or fields the server needs, and a stack that skips the bootstrap
# never gets them. (The API Server creates app_settings, which holds the plugin
# settings, on demand — but only that one.) Set false only for a database you
# know already matches the release.
PB_BOOTSTRAP=true
# --- API Server -------------------------------------------------------------
# Allowed CORS origin(s) for the web app (match WEB_PORT / your public URL).
# Native mobile apps are not subject to CORS.
CORS_ALLOW_ORIGINS=http://localhost:8090
AUTH_USERS_COLLECTION=users
# --- EV charging control (Anker Solix, OCPP) ---------------------------------
# Only relevant when a charger is set to own/proxy control mode. The charger
# dials in to /ocpp/{serial} on the API Server port, carrying its control token
# in an OCPP Basic-auth header — which a plaintext ws:// would expose, so
# non-TLS connections are rejected by default. This dev stack serves plain
# HTTP: either terminate TLS in front of it and set OCPP_PUBLIC_URL to the
# public wss:// base, or set OCPP_REQUIRE_TLS=false on a trusted network.
OCPP_REQUIRE_TLS=true
OCPP_PUBLIC_URL=
# Diagnostic only. Set to 1 to log every frame the charger publishes over Anker's
# cloud broker — the ones DriverVault decodes and the ones it cannot, with their
# bytes. It is how an unnamed frame gets named: hold a control read open, do the
# thing in the Anker app, then read the frames back out of the container log.
# Leave blank on a normal stack; a triggered charger writes a line every few
# seconds.
ANKER_MQTT_FRAME_LOG=
# The charger can dial either door: the API Server port directly, or the Web
# App port, whose BFF now proxies /ocpp/ through to it. The endpoint the panel
# shows is the API Server port only when OCPP_PUBLIC_URL says so — left blank it
# is whichever host the panel itself was reached on, which is the Web App.
# TRUST_FORWARDED_PROTO lets the BFF pass an inbound X-Forwarded-Proto to the
# API Server: needed when TLS ends at a proxy in front of the stack and
# OCPP_REQUIRE_TLS stays on, and unsafe otherwise, since the header is then
# whatever the client said it was.
TRUST_FORWARDED_PROTO=false
# --- Host port mappings (optional; defaults shown) --------------------------
PB_PORT=8070
API_PORT=8080
WEB_PORT=8090
# --- Web App build -----------------------------------------------------------
# Leave empty so the browser uses same-origin /api (proxied by the BFF).
VITE_API_BASE=
# --- Settings the API Server panel can also change ---------------------------
# The panel's Settings screens apply these immediately, but only for the life of
# the container — the values below are re-applied on every restart and win. Set
# them here to make a change permanent.
# POCKETBASE_URL where the API Server looks for the database. Defaults to
# the bundled pocketbase service; set it to reach one
# outside this stack.
# WEBAPP_URL the Web App address the panel status page probes. It is
# a container-to-container call, so it must be reachable
# from the API Server, not from your browser.
# CORS_ALLOW_ORIGINS browser origins allowed to call the API Server directly.
# POCKETBASE_URL=http://pocketbase:8070
# WEBAPP_URL=http://web-app:8090
# --- File storage: external S3 -----------------------------------------------
# PocketBase keeps its record files — document scans, service and refill
# receipts, workshop invoices, part photos — in the bucket below instead of on
# pb_data. The database and PocketBase's own backups stay where they are.
#
# Nothing in this stack runs a gateway: both the endpoint and the bucket must
# already exist. For a gateway on this Docker host use
# http://host.docker.internal:8333 — the compose file adds the host entry that
# makes that name resolve inside the containers.
PB_S3_ENDPOINT=http://host.docker.internal:8333
PB_S3_BUCKET=drivervault
PB_S3_ACCESS_KEY=
PB_S3_SECRET=
# SeaweedFS and MinIO ignore the region; PocketBase insists on having one.
PB_S3_REGION=us-east-1
# true for SeaweedFS and MinIO, false for AWS S3 proper.
PB_S3_FORCE_PATH_STYLE=true
# Existing uploads are NOT migrated when this is switched on: PocketBase copies
# nothing, so attachments made before the switch stop resolving. Read the file
# storage section of README.md first.
+98
View File
@@ -0,0 +1,98 @@
# Copy to .env and fill in. Used by the root docker-compose.seaweedfs.yml.
# --- PocketBase superuser (also used by the API Server to authenticate) ------
PB_ADMIN_EMAIL=admin@example.com
PB_ADMIN_PASSWORD=change-me-long-password
# --- DriverVault super-admin (app login) -------------------------------------
# The first application user, created by the API Server on boot with role
# "superadmin" if no user with this email exists yet. Leave these blank and the
# schema is still created but no user is, leaving a stack you cannot log into.
DRIVERVAULT_SUPERADMIN_EMAIL=owner@example.com
DRIVERVAULT_SUPERADMIN_PASSWORD=change-me-long-password
DRIVERVAULT_SUPERADMIN_NAME=Administrator
# Schema creation/reconcile on boot. Leave this true: a release can add
# collections or fields the server needs, and a stack that skips the bootstrap
# never gets them. (The API Server creates app_settings, which holds the plugin
# settings, on demand — but only that one.) Set false only for a database you
# know already matches the release.
PB_BOOTSTRAP=true
# --- API Server -------------------------------------------------------------
# Allowed CORS origin(s) for the web app (match WEB_PORT / your public URL).
# Native mobile apps are not subject to CORS.
CORS_ALLOW_ORIGINS=http://localhost:8090
AUTH_USERS_COLLECTION=users
# --- EV charging control (Anker Solix, OCPP) ---------------------------------
# Only relevant when a charger is set to own/proxy control mode. The charger
# dials in to /ocpp/{serial} on the API Server port, carrying its control token
# in an OCPP Basic-auth header — which a plaintext ws:// would expose, so
# non-TLS connections are rejected by default. This dev stack serves plain
# HTTP: either terminate TLS in front of it and set OCPP_PUBLIC_URL to the
# public wss:// base, or set OCPP_REQUIRE_TLS=false on a trusted network.
OCPP_REQUIRE_TLS=true
OCPP_PUBLIC_URL=
# Diagnostic only. Set to 1 to log every frame the charger publishes over Anker's
# cloud broker — the ones DriverVault decodes and the ones it cannot, with their
# bytes. It is how an unnamed frame gets named: hold a control read open, do the
# thing in the Anker app, then read the frames back out of the container log.
# Leave blank on a normal stack; a triggered charger writes a line every few
# seconds.
ANKER_MQTT_FRAME_LOG=
# The charger can dial either door: the API Server port directly, or the Web
# App port, whose BFF now proxies /ocpp/ through to it. The endpoint the panel
# shows is the API Server port only when OCPP_PUBLIC_URL says so — left blank it
# is whichever host the panel itself was reached on, which is the Web App.
# TRUST_FORWARDED_PROTO lets the BFF pass an inbound X-Forwarded-Proto to the
# API Server: needed when TLS ends at a proxy in front of the stack and
# OCPP_REQUIRE_TLS stays on, and unsafe otherwise, since the header is then
# whatever the client said it was.
TRUST_FORWARDED_PROTO=false
# --- Host port mappings (optional; defaults shown) --------------------------
PB_PORT=8070
API_PORT=8080
WEB_PORT=8090
# --- Web App build -----------------------------------------------------------
# Leave empty so the browser uses same-origin /api (proxied by the BFF).
VITE_API_BASE=
# --- Settings the API Server panel can also change ---------------------------
# The panel's Settings screens apply these immediately, but only for the life of
# the container — the values below are re-applied on every restart and win. Set
# them here to make a change permanent.
# POCKETBASE_URL where the API Server looks for the database. Defaults to
# the bundled pocketbase service; set it to reach one
# outside this stack.
# WEBAPP_URL the Web App address the panel status page probes. It is
# a container-to-container call, so it must be reachable
# from the API Server, not from your browser.
# CORS_ALLOW_ORIGINS browser origins allowed to call the API Server directly.
# POCKETBASE_URL=http://pocketbase:8070
# WEBAPP_URL=http://web-app:8090
# --- File storage: SeaweedFS -------------------------------------------------
# PocketBase keeps its record files — document scans, service and refill
# receipts, workshop invoices, part photos — in the bucket below instead of on
# pb_data. The database and PocketBase's own backups stay where they are.
#
# The credentials do double duty: they configure the SeaweedFS gateway's single
# identity *and* are what PocketBase authenticates with. There are no safe
# defaults, and the stack refuses to start without them.
PB_S3_ACCESS_KEY=
PB_S3_SECRET=
# The bucket. Created on first boot by the seaweedfs-init container.
PB_S3_BUCKET=drivervault
# SeaweedFS ignores the region; PocketBase insists on having one.
PB_S3_REGION=us-east-1
# The gateway image, pinned so a rebuild months from now brings up the same one.
# SEAWEED_IMAGE=chrislusf/seaweedfs:4.45
# Existing uploads are NOT migrated when this is switched on: PocketBase copies
# nothing, so attachments made before the switch stop resolving. Read the file
# storage section of README.md first.
+126
View File
@@ -0,0 +1,126 @@
# Copy to .env and fill in. Used by docker-compose.seaweedfs.split.yml — the
# same stack as .env.seaweedfs.example, with SeaweedFS running as separate
# master / volume / filer / S3 containers plus the SeaweedFS admin UI.
# --- PocketBase superuser (also used by the API Server to authenticate) ------
PB_ADMIN_EMAIL=admin@example.com
PB_ADMIN_PASSWORD=change-me-long-password
# --- DriverVault super-admin (app login) -------------------------------------
# The first application user, created by the API Server on boot with role
# "superadmin" if no user with this email exists yet. Leave these blank and the
# schema is still created but no user is, leaving a stack you cannot log into.
DRIVERVAULT_SUPERADMIN_EMAIL=owner@example.com
DRIVERVAULT_SUPERADMIN_PASSWORD=change-me-long-password
DRIVERVAULT_SUPERADMIN_NAME=Administrator
# Schema creation/reconcile on boot. Leave this true: a release can add
# collections or fields the server needs, and a stack that skips the bootstrap
# never gets them. (The API Server creates app_settings, which holds the plugin
# settings, on demand — but only that one.) Set false only for a database you
# know already matches the release.
PB_BOOTSTRAP=true
# --- API Server -------------------------------------------------------------
# Allowed CORS origin(s) for the web app (match WEB_PORT / your public URL).
# Native mobile apps are not subject to CORS.
CORS_ALLOW_ORIGINS=http://localhost:8090
AUTH_USERS_COLLECTION=users
# --- EV charging control (Anker Solix, OCPP) ---------------------------------
# Only relevant when a charger is set to own/proxy control mode. The charger
# dials in to /ocpp/{serial} on the API Server port, carrying its control token
# in an OCPP Basic-auth header — which a plaintext ws:// would expose, so
# non-TLS connections are rejected by default. This dev stack serves plain
# HTTP: either terminate TLS in front of it and set OCPP_PUBLIC_URL to the
# public wss:// base, or set OCPP_REQUIRE_TLS=false on a trusted network.
OCPP_REQUIRE_TLS=true
OCPP_PUBLIC_URL=
# Diagnostic only. Set to 1 to log every frame the charger publishes over Anker's
# cloud broker — the ones DriverVault decodes and the ones it cannot, with their
# bytes. It is how an unnamed frame gets named: hold a control read open, do the
# thing in the Anker app, then read the frames back out of the container log.
# Leave blank on a normal stack; a triggered charger writes a line every few
# seconds.
ANKER_MQTT_FRAME_LOG=
# The charger can dial either door: the API Server port directly, or the Web
# App port, whose BFF now proxies /ocpp/ through to it. The endpoint the panel
# shows is the API Server port only when OCPP_PUBLIC_URL says so — left blank it
# is whichever host the panel itself was reached on, which is the Web App.
# TRUST_FORWARDED_PROTO lets the BFF pass an inbound X-Forwarded-Proto to the
# API Server: needed when TLS ends at a proxy in front of the stack and
# OCPP_REQUIRE_TLS stays on, and unsafe otherwise, since the header is then
# whatever the client said it was.
TRUST_FORWARDED_PROTO=false
# --- Host port mappings (optional; defaults shown) --------------------------
PB_PORT=8070
API_PORT=8080
WEB_PORT=8090
# --- Web App build -----------------------------------------------------------
# Leave empty so the browser uses same-origin /api (proxied by the BFF).
VITE_API_BASE=
# --- Settings the API Server panel can also change ---------------------------
# The panel's Settings screens apply these immediately, but only for the life of
# the container — the values below are re-applied on every restart and win. Set
# them here to make a change permanent.
# POCKETBASE_URL where the API Server looks for the database. Defaults to
# the bundled pocketbase service; set it to reach one
# outside this stack.
# WEBAPP_URL the Web App address the panel status page probes. It is
# a container-to-container call, so it must be reachable
# from the API Server, not from your browser.
# CORS_ALLOW_ORIGINS browser origins allowed to call the API Server directly.
# POCKETBASE_URL=http://pocketbase:8070
# WEBAPP_URL=http://web-app:8090
# --- File storage: SeaweedFS -------------------------------------------------
# PocketBase keeps its record files — document scans, service and refill
# receipts, workshop invoices, part photos — in the bucket below instead of on
# pb_data. The database and PocketBase's own backups stay where they are.
#
# The credentials do double duty: seaweedfs-init writes them into the filer's
# IAM store as the identity named "drivervault" *and* they are what PocketBase
# authenticates with. There are no safe defaults, and the stack refuses to start
# without them. Change them here and restart to rotate: the seed updates the
# identity in place rather than adding a second one.
PB_S3_ACCESS_KEY=
PB_S3_SECRET=
# The bucket. Created on first boot by the seaweedfs-init container.
PB_S3_BUCKET=drivervault
# SeaweedFS ignores the region; PocketBase insists on having one.
PB_S3_REGION=us-east-1
# The SeaweedFS image, pinned so a rebuild months from now brings up the same
# one. All five SeaweedFS containers run it.
# SEAWEED_IMAGE=chrislusf/seaweedfs:4.45
# --- SeaweedFS admin UI ------------------------------------------------------
# http://localhost:23646 — cluster topology, volumes, buckets, and
# Object Store → Users, where further S3 identities are created and revoked.
# They land in the filer's IAM store, the same one seeded above, and the gateway
# picks them up without a restart.
#
# REQUIRED: weed disables authentication entirely when the password is empty,
# and this panel can mint credentials for the bucket.
SEAWEED_ADMIN_USER=admin
SEAWEED_ADMIN_PASSWORD=
# SEAWEED_ADMIN_PORT=23646
# --- SeaweedFS host ports (optional; defaults shown) -------------------------
# Published for aws-cli, `weed shell` and poking around while developing. The
# stack itself reaches every one of these over the compose network, and the S3
# gateway too, which is not published so a second stack cannot clash on it.
# Note SEAWEED_VOLUME_PORT: the volume server serves file content by id with NO
# authentication, so do not carry this mapping over to a shared machine. It
# lands on 8081 because API_PORT already has 8080.
# SEAWEED_MASTER_PORT=9333
# SEAWEED_VOLUME_PORT=8081
# SEAWEED_FILER_PORT=8888
# Existing uploads are NOT migrated when this is switched on: PocketBase copies
# nothing, so attachments made before the switch stop resolving. Read the file
# storage section of README.md first.
-24
View File
@@ -1,24 +0,0 @@
# Caddy in front of the stack: one hostname, TLS from Let's Encrypt, everything
# behind it spoken to over the compose network in plain HTTP.
#
# Both doors are the same door here. Browsers get the Web App; chargers dial
# /ocpp/{serial} on the same hostname, and the BFF carries that through to the
# API Server. Caddy proxies WebSocket upgrades without being told to, so there
# is nothing to configure for the charger case.
#
# DV_DOMAIN and DV_ACME_EMAIL come from .env via docker-compose.tls.yml.
{
email {$DV_ACME_EMAIL}
}
{$DV_DOMAIN} {
encode zstd gzip
# X-Forwarded-Proto is set by Caddy to the scheme the client used. The API
# Server reads it to decide a charger arrived over TLS, which is why the
# web-app service is given TRUST_FORWARDED_PROTO=true — without that the BFF
# would overwrite this header with its own plaintext hop and a charger would
# be rejected under OCPP_REQUIRE_TLS.
reverse_proxy web-app:8090
}
+110 -22
View File
@@ -78,6 +78,102 @@ instead. PocketBase runs as root, so a root-owned host directory is fine.
> `WEBAPP_URL` and `CORS_ALLOW_ORIGINS` in `.env` to change them permanently — > `WEBAPP_URL` and `CORS_ALLOW_ORIGINS` in `.env` to change them permanently —
> in this stack the compose environment wins over anything the panel writes. > in this stack the compose environment wins over anything the panel writes.
## File storage (SeaweedFS / S3)
Uploaded files — document scans, service and refill receipts, workshop invoices,
part photos — live inside `pb_data` by default, next to the database. Two further
compose files put them in an S3 bucket instead, so the blobs and the database can
be sized, backed up and moved independently. Nothing else changes: an attachment has
always been fetched through the API Server (`GET /api/service-records/{id}/file`),
never from a storage URL, so the Web App, the phone app and the Home Assistant
plugin cannot tell the difference.
Each shape is one self-contained compose file — nothing to layer, nothing to
remember — with an `.env` example of the same name:
| Shape | From the registry | From source |
|---|---|---|
| **Local storage** — the default, unchanged | `docker-compose.prod.yml` | `docker-compose.yml` |
| **SeaweedFS in this stack** | `docker-compose.prod.seaweedfs.yml` | `docker-compose.seaweedfs.yml` |
| **SeaweedFS, split into its roles** | `docker-compose.prod.seaweedfs.split.yml` | `docker-compose.seaweedfs.split.yml` |
| **An S3 endpoint outside it** | `docker-compose.prod.s3.yml` | `docker-compose.s3.yml` |
So `docker-compose.prod.seaweedfs.yml` is configured from
`.env.prod.seaweedfs.example`, `docker-compose.s3.yml` from `.env.s3.example`,
and so on:
```sh
cp .env.prod.seaweedfs.example .env # then edit it — PB_S3_* have no defaults
docker compose -f docker-compose.prod.seaweedfs.yml pull
docker compose -f docker-compose.prod.seaweedfs.yml up -d
```
Set `PB_S3_ACCESS_KEY` and `PB_S3_SECRET` first — both storage files refuse to
start without them. The SeaweedFS ones add a `seaweedfs` container (master,
volume, filer and S3 gateway in one process, on its own `seaweed_data` volume)
plus a one-shot `seaweedfs-init` that creates the bucket, because PocketBase never
issues a `CreateBucket` of its own. The external-S3 ones add no containers at
all: set `PB_S3_ENDPOINT`, and create the bucket yourself.
### Split SeaweedFS
`weed server -s3` runs master, volume, filer and gateway as four goroutines in
one process. The `.split.` files run them as four containers, plus a fifth: the
SeaweedFS **admin UI** on port 23646, where the cluster can be inspected and —
under *Object Store → Users* — further S3 identities minted and revoked. Split
also gets you per-role restarts and upgrades, per-role Prometheus metrics, and
room to add a second volume server later.
Identities work differently there, and it matters. SeaweedFS reads credentials
from, in descending priority: an `-s3.config` file, the filer's IAM store, then
`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` — and a higher source *replaces*
a lower one rather than adding to it. The single-process files use the env vars,
which is why nothing else may write identities there: the first user added in a
panel would displace PocketBase's key. So in the split files `seaweedfs-init`
seeds PocketBase's identity into the filer's store instead — the same store the
admin UI writes — and the gateway runs with no config file at all. One source of
truth, PocketBase's key visible in the panel beside every other, and new keys
picked up without a restart. Rotating `PB_S3_SECRET` in `.env` and restarting
updates that identity in place.
Set `SEAWEED_ADMIN_PASSWORD`: `weed admin` serves the panel with no
authentication when it is empty, and a panel that can mint bucket credentials is
the bucket. In the prod file it is bound to loopback like `PB_BIND` and
`API_BIND`, so a remote host needs `SEAWEED_ADMIN_BIND=0.0.0.0` behind the same
reverse proxy. That file publishes nothing for master, volume and filer — the
volume server serves file content by id with no authentication of any kind, and
the admin UI already shows what those ports would.
Switching between `docker-compose.seaweedfs.yml` and its `.split.` twin needs no
migration: master, volume and filer share one `/data` mount, which is exactly
the layout `weed server -dir=/data` writes.
On every boot the API Server's bootstrap writes PocketBase's *Files storage*
settings from those variables, then asks PocketBase to prove it can reach the
bucket. Watch for it in the log:
```
[api] bootstrap: ✓ file storage → S3 (drivervault at http://seaweedfs:8333)
[api] bootstrap: ✓ S3 storage reachable
```
A boot that finds the settings already correct logs `• file storage already on S3`
and writes nothing.
Two things to know before turning it on:
- **Existing files are not migrated.** PocketBase copies nothing when the setting
flips, so attachments uploaded before the switch stop resolving. Copy
`pb_data/storage/<collectionId>/<recordId>/<file>` into the bucket root, keeping
that layout, *before* enabling it — or start from a stack with no attachments.
- **Going back to the plain compose file is not an off switch.** It leaves
PocketBase pointed at
the bucket, deliberately: files already written there are reachable only while
it is. Move them back and turn it off in PocketBase's own admin UI. For the same
reason a rotation of `PB_S3_SECRET` alone is invisible to the bootstrap —
PocketBase masks the stored secret on read — so change another `PB_S3_*` value
alongside it, or set it in the admin UI.
## Charger control (OCPP) ## Charger control (OCPP)
Chargers in own/proxy mode dial in to `/ocpp/{serial}`, authenticating with a Chargers in own/proxy mode dial in to `/ocpp/{serial}`, authenticating with a
@@ -93,34 +189,26 @@ A plaintext `ws://` puts the control token on the wire in the clear, so
### With a public hostname and TLS ### With a public hostname and TLS
`docker-compose.tls.yml` adds Caddy in front of the stack: one hostname, a Nothing in this stack terminates TLS. Put your own reverse proxy in front of the
certificate issued on first boot, and everything behind it spoken to over the Web App port, give it a certificate and a hostname, and set four things by hand:
compose network. Browsers and chargers arrive at the same name.
```sh ```sh
# in .env # in .env
DV_DOMAIN=drivervault.example.com OCPP_PUBLIC_URL=wss://drivervault.example.com
DV_ACME_EMAIL=you@example.com OCPP_REQUIRE_TLS=true
CORS_ALLOW_ORIGINS=https://drivervault.example.com
docker compose -f docker-compose.prod.yml -f docker-compose.tls.yml up -d TRUST_FORWARDED_PROTO=true
``` ```
The overlay sets the rest for you: `OCPP_PUBLIC_URL=wss://$DV_DOMAIN`, `TRUST_FORWARDED_PROTO` is the easy one to miss: without it the Web App's BFF
`OCPP_REQUIRE_TLS=true`, `CORS_ALLOW_ORIGINS=https://$DV_DOMAIN`, and overwrites the proxy's `X-Forwarded-Proto` with its own plaintext hop and every
`TRUST_FORWARDED_PROTO=true` on the Web App so the BFF passes Caddy's charger is rejected as insecure. Only set it when that proxy really is the only
`X-Forwarded-Proto` to the API Server instead of overwriting it with its own way in — otherwise a charger could claim `wss` over a plaintext connection.
plaintext hop. Point the charger's OCPP backend at the endpoint the panel then
shows, with the control token as its authorization key.
Two things the overlay cannot arrange: `DV_DOMAIN` must resolve to the host from Point the charger's OCPP backend at the endpoint the panel then shows, with the
the internet with ports 80 and 443 reaching it (Caddy needs `:80` for the ACME control token as its authorization key. The charger has to resolve that hostname
challenge), and the charger must be able to resolve that name too — behind NAT too: behind NAT that usually means hairpin NAT, or a split-DNS entry pointing the
that usually means hairpin NAT or a split-DNS entry pointing it at the LAN name at the LAN address.
address.
Using a proxy you already run instead? Terminate TLS there, forward to the Web
App port, and set the same four variables by hand — the `X-Forwarded-Proto` one
included, or chargers will be rejected as insecure.
## Notes ## Notes
+174
View File
@@ -0,0 +1,174 @@
name: drivervault
# Production DriverVault stack, with external S3 — pulls prebuilt images from
# the registry instead of building from source. Self-contained: one file, no
# overlays. Everything an operator needs to set lives in .env.
#
# 1. cp .env.prod.s3.example .env (then edit it — PB_S3_* especially)
# 2. docker compose -f docker-compose.prod.s3.yml pull
# 3. docker compose -f docker-compose.prod.s3.yml up -d
#
# This is docker-compose.prod.yml pointed at an S3 endpoint that already exists
# somewhere else — its own host, another compose project, or any S3-compatible
# service. PocketBase keeps its record files — document scans, service and
# refill receipts, workshop invoices, part photos — in that bucket instead of on
# the pb_data volume. The database and PocketBase's own backups stay on PB_DATA.
# Clients cannot tell the difference: an attachment has always been fetched
# through the API Server, never from a storage URL.
#
# The bucket must already exist, and nothing here runs the gateway. For a
# SeaweedFS that comes up with the stack, use docker-compose.prod.seaweedfs.yml.
#
# Before turning this on for a stack that already has uploads: PocketBase does
# NOT copy existing files into the bucket. See README.md.
#
# Traffic flow (browser): Web App BFF --/api--> API Server --> PocketBase.
#
# On first boot:
# • PocketBase upserts the superuser from PB_ADMIN_* (create-if-missing).
# • the API Server creates any missing collections, reconciles existing ones,
# and creates the DriverVault super-admin from DRIVERVAULT_SUPERADMIN_*.
# Both steps are idempotent, so restarts and upgrades are safe.
services:
pocketbase:
image: "${PB_IMAGE:-10.2.1.10:5500/admin/drivervault-pocketbase:latest}"
container_name: drivervault-pocketbase
restart: unless-stopped
extra_hosts:
# Lets PB_S3_ENDPOINT name the Docker host as host.docker.internal.
# Harmless when the endpoint is somewhere else entirely.
- "host.docker.internal:host-gateway"
environment:
# The superuser is created/updated on boot (the API Server authenticates
# with it). This is the only place the first superuser can be created — the
# REST API cannot bootstrap it.
PB_ADMIN_EMAIL: "${PB_ADMIN_EMAIL:?set PB_ADMIN_EMAIL in .env}"
PB_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD:?set PB_ADMIN_PASSWORD in .env}"
volumes:
# Named volume by default; set PB_DATA to a host path in .env for a bind mount.
- "${PB_DATA:-pb_data}:/pb/pb_data"
ports:
# Bound to localhost by default — the admin UI (/_/) is reachable only on
# the host. Set PB_BIND=0.0.0.0 in .env to expose it on the network.
- "${PB_BIND:-127.0.0.1}:${PB_PORT:-8070}:8070"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8070/api/health || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 10s
api-server:
image: "${API_IMAGE:-10.2.1.10:5500/admin/drivervault-api-server:latest}"
container_name: drivervault-api
restart: unless-stopped
extra_hosts:
# Lets PB_S3_ENDPOINT name the Docker host as host.docker.internal.
# Harmless when the endpoint is somewhere else entirely.
- "host.docker.internal:host-gateway"
depends_on:
pocketbase:
condition: service_healthy
environment:
API_ADDR: ":8080"
# Reach PocketBase by its service name on the internal network. Override
# POCKETBASE_URL in .env to point the API Server at a database outside
# this stack — that is also how you make a retarget done from the panel
# permanent, since the panel's change lasts only for the container's life.
POCKETBASE_URL: "${POCKETBASE_URL:-http://pocketbase:8070}"
POCKETBASE_ADMIN_EMAIL: "${PB_ADMIN_EMAIL}"
POCKETBASE_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD}"
# Probed by the panel status page. This is a server-to-server call inside
# the compose network, so the default is the service name — plain
# localhost:8090 would resolve to this container itself. Override
# WEBAPP_URL in .env to make a change from the panel's Web App screen
# permanent; the panel alone only holds it for the container's life.
WEBAPP_URL: "${WEBAPP_URL:-http://web-app:8090}"
CORS_ALLOW_ORIGINS: "${CORS_ALLOW_ORIGINS:-http://localhost:8090}"
AUTH_USERS_COLLECTION: "${AUTH_USERS_COLLECTION:-users}"
# Schema + super-admin bootstrap (idempotent). Leave this ON: a release can
# add collections or fields the server needs, and a stack that skips the
# bootstrap never gets them. The API Server self-heals exactly one thing —
# app_settings, the collection holding the plugin settings, which it
# creates on demand because it cannot serve the plugin panel without it.
# Every other schema change still depends on this flag. Turn it off only
# for a database you know already matches the release.
PB_BOOTSTRAP: "${PB_BOOTSTRAP:-true}"
DRIVERVAULT_SUPERADMIN_EMAIL: "${DRIVERVAULT_SUPERADMIN_EMAIL:-}"
DRIVERVAULT_SUPERADMIN_PASSWORD: "${DRIVERVAULT_SUPERADMIN_PASSWORD:-}"
DRIVERVAULT_SUPERADMIN_NAME: "${DRIVERVAULT_SUPERADMIN_NAME:-Administrator}"
# OCPP charger control (Anker Solix). Chargers are rejected unless they
# reach the server over TLS. Behind a TLS-terminating reverse proxy, set
# OCPP_PUBLIC_URL to the public wss:// base and API_BIND so the proxy can
# reach this port; only drop OCPP_REQUIRE_TLS on a trusted network.
OCPP_REQUIRE_TLS: "${OCPP_REQUIRE_TLS:-true}"
OCPP_PUBLIC_URL: "${OCPP_PUBLIC_URL:-}"
# Diagnostic: set ANKER_MQTT_FRAME_LOG=1 in .env to log every frame the
# charger publishes over Anker's broker, decoded ones and unreadable ones
# alike, with their bytes. It is how a frame nobody has named gets named —
# do something in the Anker app while a control read holds the connection
# open, and read the frames back out of the log. Off by default: with it on
# a charger under a live trigger writes a line every few seconds.
ANKER_MQTT_FRAME_LOG: "${ANKER_MQTT_FRAME_LOG:-}"
# --- File storage --------------------------------------------------
# Read by the API Server's bootstrap, which writes them into PocketBase's
# settings on every boot, idempotently. Only record files move — scans,
# receipts, invoices, part photos. The database and PocketBase's own
# backups stay on PB_DATA. The bucket must already exist: nothing here
# creates it.
PB_S3_ENABLED: "true"
PB_S3_BUCKET: "${PB_S3_BUCKET:-drivervault}"
PB_S3_ENDPOINT: "${PB_S3_ENDPOINT:?set PB_S3_ENDPOINT in .env}"
PB_S3_REGION: "${PB_S3_REGION:-us-east-1}"
PB_S3_ACCESS_KEY: "${PB_S3_ACCESS_KEY:?set PB_S3_ACCESS_KEY in .env}"
PB_S3_SECRET: "${PB_S3_SECRET:?set PB_S3_SECRET in .env}"
# true for SeaweedFS and MinIO, false for AWS S3 proper.
PB_S3_FORCE_PATH_STYLE: "${PB_S3_FORCE_PATH_STYLE:-true}"
ports:
# Localhost-only by default (the Web App reaches it over the internal
# network). Set API_BIND=0.0.0.0 to expose the API panel — and the
# /ocpp/{serial} endpoint chargers dial into — on the network.
- "${API_BIND:-127.0.0.1}:${API_PORT:-8080}:8080"
# No volume: the API Server keeps no state on disk — every setting it owns,
# plugin settings included, lives in PocketBase under PB_DATA.
healthcheck:
# Declared here rather than relying only on the image's HEALTHCHECK, so the
# depends_on gate below still works against an older pulled image.
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 20s
web-app:
image: "${WEB_IMAGE:-10.2.1.10:5500/admin/drivervault-web-app:latest}"
container_name: drivervault-web
restart: unless-stopped
depends_on:
# The image now ships a HEALTHCHECK, so wait for the API Server to be
# serving rather than merely started.
api-server:
condition: service_healthy
environment:
# The BFF reverse-proxies /api/* — and /ocpp/*, the address chargers are
# told to dial — to the API Server over the internal network.
API_BASE: "http://api-server:8080"
# Believe an inbound X-Forwarded-Proto. The API Server reads it to decide a
# charger arrived over TLS, so leave this off unless a TLS-terminating
# proxy in front of the stack is the only way in: otherwise a charger could
# claim wss over a plaintext connection. Set it to true when TLS ends at
# that proxy and OCPP_PUBLIC_URL names a wss:// base through it.
TRUST_FORWARDED_PROTO: "${TRUST_FORWARDED_PROTO:-false}"
ports:
# The public front door. Bound on all interfaces so browsers can reach it.
- "${WEB_PORT:-8090}:8090"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8090/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 10s
volumes:
pb_data:
@@ -0,0 +1,390 @@
name: drivervault
# Production DriverVault stack, with SeaweedFS split into its four roles —
# pulls prebuilt images from the registry instead of building from source.
# Self-contained: one file, no overlays. Everything an operator needs to set
# lives in .env.
#
# 1. cp .env.prod.seaweedfs.split.example .env (then edit it)
# 2. docker compose -f docker-compose.prod.seaweedfs.split.yml pull
# 3. docker compose -f docker-compose.prod.seaweedfs.split.yml up -d
#
# This is docker-compose.prod.seaweedfs.yml with the storage layer taken apart.
# `weed server -s3` runs master, volume, filer and gateway as goroutines in one
# process; here each is its own container, plus the SeaweedFS admin UI. What
# that buys:
#
# • the admin UI (weed admin) — a cluster view, and Object Store → Users,
# where S3 identities are created and revoked without touching a file;
# • per-role restart, upgrade and Prometheus metrics;
# • room to add a second volume server later, on this host or another.
#
# What it costs: five containers instead of one, five healthchecks to keep the
# boot order honest, and one more port worth binding carefully. If none of the
# above is wanted, use docker-compose.prod.seaweedfs.yml — the S3 behaviour is
# identical.
#
# The on-disk layout is deliberately the same as the single-process file's:
# master, volume and filer share one /data mount, exactly as `weed server -dir`
# lays it out (master raft state, volume .dat/.idx, the filer's filerldb2/ — no
# filename overlap). So the two files are interchangeable on the same SEAWEED_DATA,
# with no migration either way. A *second* volume server would need its own.
#
# Only the admin UI publishes a host port. The S3 gateway, master, volume and
# filer are reachable over the compose network, through the admin UI, or with
# `docker compose exec` — the volume server in particular serves file content by
# id with no authentication at all, so it has no business on a public interface.
#
# Before turning this on for a stack that already has uploads: PocketBase does
# NOT copy existing files into the bucket. See README.md.
#
# Traffic flow (browser): Web App BFF --/api--> API Server --> PocketBase.
#
# On first boot:
# • PocketBase upserts the superuser from PB_ADMIN_* (create-if-missing).
# • the API Server creates any missing collections, reconciles existing ones,
# and creates the DriverVault super-admin from DRIVERVAULT_SUPERADMIN_*.
# Both steps are idempotent, so restarts and upgrades are safe.
services:
# --- SeaweedFS: master -----------------------------------------------------
# Keeps the volume/topology metadata and hands out file ids. -ip is the name
# the other roles are told to reach it by, so it must be the service name and
# not the container IP the process would otherwise detect.
seaweedfs-master:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-seaweedfs-master
restart: unless-stopped
command: >
master -ip=seaweedfs-master -ip.bind=0.0.0.0 -mdir=/data
-volumeSizeLimitMB=1024 -metricsPort=9324
volumes:
# Named volume by default; set SEAWEED_DATA to a host path in .env for a
# bind mount, exactly as PB_DATA works. Back it up alongside PB_DATA —
# from here on the attachments live here, not in the database volume.
- "${SEAWEED_DATA:-seaweed_data}:/data"
# No published port: the master UI is one of the pages the admin UI serves.
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:9333/cluster/status || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 15s
# --- SeaweedFS: volume server ---------------------------------------------
# Where the bytes actually land. -max=0 lets it size itself from free disk
# rather than the default cap of 8 volumes.
seaweedfs-volume:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-seaweedfs-volume
restart: unless-stopped
command: >
volume -master=seaweedfs-master:9333 -ip=seaweedfs-volume -ip.bind=0.0.0.0
-port=8080 -dir=/data -max=0 -metricsPort=9325
depends_on:
seaweedfs-master:
condition: service_healthy
volumes:
- "${SEAWEED_DATA:-seaweed_data}:/data"
# No published port, and this one is not an oversight: 8080 serves file
# content by file id with NO authentication — the S3 credentials do not
# apply to it. Publishing it would publish every attachment in the stack.
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 15s
# --- SeaweedFS: filer ------------------------------------------------------
# Gives the flat volume store a directory tree — buckets, object keys — and
# holds the S3 identities the admin UI writes. -defaultStoreDir is where its
# embedded leveldb goes; without it that would be the container's working
# directory, and the identities would not survive a recreate.
seaweedfs-filer:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-seaweedfs-filer
restart: unless-stopped
command: >
filer -master=seaweedfs-master:9333 -ip=seaweedfs-filer -ip.bind=0.0.0.0
-port=8888 -defaultStoreDir=/data -metricsPort=9326
depends_on:
seaweedfs-volume:
condition: service_healthy
volumes:
- "${SEAWEED_DATA:-seaweed_data}:/data"
# No published port. The filer's gRPC side (8888 + 10000) carries the IAM
# service that mints S3 credentials; keep both ends of it on the compose
# network.
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8888/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 15s
# --- SeaweedFS: bucket and identity seed ----------------------------------
# Runs once and exits, before the gateway starts. Two jobs:
#
# 1. create the bucket — PocketBase never issues a CreateBucket of its own;
# 2. write PocketBase's S3 identity into the filer's IAM store.
#
# (2) is why this stack does not set AWS_ACCESS_KEY_ID on the gateway, the way
# docker-compose.prod.seaweedfs.yml does. Those env vars are the *lowest*
# priority credential source in SeaweedFS: they are read only while the filer's
# store is empty, so the first identity added in the admin UI would silently
# displace them and lock PocketBase out. Seeding the store the admin UI itself
# writes leaves one source of truth, and the key PocketBase uses appears under
# Object Store → Users like any other.
#
# Both commands update in place, so every later boot re-applies the values from
# .env and changes nothing else — which is also how a rotated PB_S3_SECRET
# reaches the gateway.
#
# The closing grep is the gate: an empty IAM store means the gateway would come
# up in its allow-anyone default, so this fails loudly instead and the gateway
# below never starts. No `|| true` here, deliberately.
seaweedfs-init:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-seaweedfs-init
restart: "no"
depends_on:
seaweedfs-filer:
condition: service_healthy
environment:
# Passed as env and expanded by the shell inside the container, so the
# secret stays out of the container's argv.
PB_S3_BUCKET: "${PB_S3_BUCKET:-drivervault}"
PB_S3_ACCESS_KEY: "${PB_S3_ACCESS_KEY:?set PB_S3_ACCESS_KEY in .env}"
PB_S3_SECRET: "${PB_S3_SECRET:?set PB_S3_SECRET in .env}"
entrypoint: ["/bin/sh", "-c"]
command:
- |
set -e
printf '%s\n' \
"s3.bucket.create -name $$PB_S3_BUCKET" \
"s3.configure -user drivervault -access_key $$PB_S3_ACCESS_KEY -secret_key $$PB_S3_SECRET -actions Admin -apply" \
| weed shell -master=seaweedfs-master:9333 -filer=seaweedfs-filer:8888
echo "s3.configure" \
| weed shell -master=seaweedfs-master:9333 -filer=seaweedfs-filer:8888 \
| grep -q "$$PB_S3_ACCESS_KEY"
# --- SeaweedFS: S3 gateway -------------------------------------------------
# The endpoint PocketBase talks to. No -config file: with only -filer given,
# credentials come from the filer's IAM store, which is what lets the admin UI
# add and revoke identities without a restart. A config file would take
# priority over that store and make the admin UI's users inert.
seaweedfs-s3:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-seaweedfs-s3
restart: unless-stopped
command: >
s3 -filer=seaweedfs-filer:8888 -ip.bind=0.0.0.0 -port=8333
-metricsPort=9327
depends_on:
seaweedfs-filer:
condition: service_healthy
# Never serve before an identity exists — see seaweedfs-init above.
seaweedfs-init:
condition: service_completed_successfully
# No published port: the stack reaches the gateway over the compose network.
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8333/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 15s
# --- SeaweedFS: admin UI ---------------------------------------------------
# Cluster topology, volumes, buckets, maintenance tasks, and Object Store →
# Users, where S3 access keys are minted and revoked. It finds the filer
# through the master, so -master is all it needs.
#
# Bound to loopback by default, like the PocketBase and API panels: on a remote
# host that means unreachable, so set SEAWEED_ADMIN_BIND=0.0.0.0 the same way
# PB_BIND and API_BIND get set — and put it behind the same reverse proxy.
#
# An unauthenticated panel that can mint credentials for the bucket *is* the
# bucket, so the password is required rather than defaulted — weed leaves auth
# off entirely when it is empty. It is read from WEED_ADMIN_* rather than a
# flag, which keeps it off the process command line. -dataDir persists the
# session key and the maintenance-task settings.
seaweedfs-admin:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-seaweedfs-admin
restart: unless-stopped
command: >
admin -port=23646 -master=seaweedfs-master:9333 -dataDir=/data
-metricsPort=9328
depends_on:
seaweedfs-master:
condition: service_healthy
environment:
WEED_ADMIN_USER: "${SEAWEED_ADMIN_USER:-admin}"
WEED_ADMIN_PASSWORD: "${SEAWEED_ADMIN_PASSWORD:?set SEAWEED_ADMIN_PASSWORD in .env}"
# Optional view-only login. weed ignores it unless the admin password
# above is set, which it is.
WEED_ADMIN_READONLY_USER: "${SEAWEED_ADMIN_READONLY_USER:-}"
WEED_ADMIN_READONLY_PASSWORD: "${SEAWEED_ADMIN_READONLY_PASSWORD:-}"
volumes:
# Its own small volume: session key and maintenance state, no object data.
- "${SEAWEED_ADMIN_DATA:-seaweed_admin}:/data"
ports:
- "${SEAWEED_ADMIN_BIND:-127.0.0.1}:${SEAWEED_ADMIN_PORT:-23646}:23646"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:23646/health || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 15s
pocketbase:
image: "${PB_IMAGE:-10.2.1.10:5500/admin/drivervault-pocketbase:latest}"
container_name: drivervault-pocketbase
restart: unless-stopped
depends_on:
# PocketBase is the process that reads and writes the objects, so the
# gateway has to be serving before it is asked to store anything.
seaweedfs-s3:
condition: service_healthy
environment:
# The superuser is created/updated on boot (the API Server authenticates
# with it). This is the only place the first superuser can be created — the
# REST API cannot bootstrap it.
PB_ADMIN_EMAIL: "${PB_ADMIN_EMAIL:?set PB_ADMIN_EMAIL in .env}"
PB_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD:?set PB_ADMIN_PASSWORD in .env}"
volumes:
# Named volume by default; set PB_DATA to a host path in .env for a bind mount.
- "${PB_DATA:-pb_data}:/pb/pb_data"
ports:
# Bound to localhost by default — the admin UI (/_/) is reachable only on
# the host. Set PB_BIND=0.0.0.0 in .env to expose it on the network.
- "${PB_BIND:-127.0.0.1}:${PB_PORT:-8070}:8070"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8070/api/health || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 10s
api-server:
image: "${API_IMAGE:-10.2.1.10:5500/admin/drivervault-api-server:latest}"
container_name: drivervault-api
restart: unless-stopped
depends_on:
pocketbase:
condition: service_healthy
# The bucket must exist before the bootstrap points PocketBase at it.
seaweedfs-init:
condition: service_completed_successfully
environment:
API_ADDR: ":8080"
# Reach PocketBase by its service name on the internal network. Override
# POCKETBASE_URL in .env to point the API Server at a database outside
# this stack — that is also how you make a retarget done from the panel
# permanent, since the panel's change lasts only for the container's life.
POCKETBASE_URL: "${POCKETBASE_URL:-http://pocketbase:8070}"
POCKETBASE_ADMIN_EMAIL: "${PB_ADMIN_EMAIL}"
POCKETBASE_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD}"
# Probed by the panel status page. This is a server-to-server call inside
# the compose network, so the default is the service name — plain
# localhost:8090 would resolve to this container itself. Override
# WEBAPP_URL in .env to make a change from the panel's Web App screen
# permanent; the panel alone only holds it for the container's life.
WEBAPP_URL: "${WEBAPP_URL:-http://web-app:8090}"
CORS_ALLOW_ORIGINS: "${CORS_ALLOW_ORIGINS:-http://localhost:8090}"
AUTH_USERS_COLLECTION: "${AUTH_USERS_COLLECTION:-users}"
# Schema + super-admin bootstrap (idempotent). Leave this ON: a release can
# add collections or fields the server needs, and a stack that skips the
# bootstrap never gets them. The API Server self-heals exactly one thing —
# app_settings, the collection holding the plugin settings, which it
# creates on demand because it cannot serve the plugin panel without it.
# Every other schema change still depends on this flag. Turn it off only
# for a database you know already matches the release.
PB_BOOTSTRAP: "${PB_BOOTSTRAP:-true}"
DRIVERVAULT_SUPERADMIN_EMAIL: "${DRIVERVAULT_SUPERADMIN_EMAIL:-}"
DRIVERVAULT_SUPERADMIN_PASSWORD: "${DRIVERVAULT_SUPERADMIN_PASSWORD:-}"
DRIVERVAULT_SUPERADMIN_NAME: "${DRIVERVAULT_SUPERADMIN_NAME:-Administrator}"
# OCPP charger control (Anker Solix). Chargers are rejected unless they
# reach the server over TLS. Behind a TLS-terminating reverse proxy, set
# OCPP_PUBLIC_URL to the public wss:// base and API_BIND so the proxy can
# reach this port; only drop OCPP_REQUIRE_TLS on a trusted network.
OCPP_REQUIRE_TLS: "${OCPP_REQUIRE_TLS:-true}"
OCPP_PUBLIC_URL: "${OCPP_PUBLIC_URL:-}"
# Diagnostic: set ANKER_MQTT_FRAME_LOG=1 in .env to log every frame the
# charger publishes over Anker's broker, decoded ones and unreadable ones
# alike, with their bytes. It is how a frame nobody has named gets named —
# do something in the Anker app while a control read holds the connection
# open, and read the frames back out of the log. Off by default: with it on
# a charger under a live trigger writes a line every few seconds.
ANKER_MQTT_FRAME_LOG: "${ANKER_MQTT_FRAME_LOG:-}"
# --- File storage --------------------------------------------------
# Read by the API Server's bootstrap, which writes them into PocketBase's
# settings on every boot, idempotently. Only record files move — scans,
# receipts, invoices, part photos. The database and PocketBase's own
# backups stay on PB_DATA.
PB_S3_ENABLED: "true"
PB_S3_BUCKET: "${PB_S3_BUCKET:-drivervault}"
# The gateway's service name: a server-to-server call inside the compose
# network.
PB_S3_ENDPOINT: "http://seaweedfs-s3:8333"
# SeaweedFS ignores the region; PocketBase insists on having one.
PB_S3_REGION: "${PB_S3_REGION:-us-east-1}"
PB_S3_ACCESS_KEY: "${PB_S3_ACCESS_KEY}"
PB_S3_SECRET: "${PB_S3_SECRET}"
# Path style, because a self-hosted gateway has no per-bucket DNS.
PB_S3_FORCE_PATH_STYLE: "true"
ports:
# Localhost-only by default (the Web App reaches it over the internal
# network). Set API_BIND=0.0.0.0 to expose the API panel — and the
# /ocpp/{serial} endpoint chargers dial into — on the network.
- "${API_BIND:-127.0.0.1}:${API_PORT:-8080}:8080"
# No volume: the API Server keeps no state on disk — every setting it owns,
# plugin settings included, lives in PocketBase under PB_DATA.
healthcheck:
# Declared here rather than relying only on the image's HEALTHCHECK, so the
# depends_on gate below still works against an older pulled image.
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 20s
web-app:
image: "${WEB_IMAGE:-10.2.1.10:5500/admin/drivervault-web-app:latest}"
container_name: drivervault-web
restart: unless-stopped
depends_on:
# The image now ships a HEALTHCHECK, so wait for the API Server to be
# serving rather than merely started.
api-server:
condition: service_healthy
environment:
# The BFF reverse-proxies /api/* — and /ocpp/*, the address chargers are
# told to dial — to the API Server over the internal network.
API_BASE: "http://api-server:8080"
# Believe an inbound X-Forwarded-Proto. The API Server reads it to decide a
# charger arrived over TLS, so leave this off unless a TLS-terminating
# proxy in front of the stack is the only way in: otherwise a charger could
# claim wss over a plaintext connection. Set it to true when TLS ends at
# that proxy and OCPP_PUBLIC_URL names a wss:// base through it.
TRUST_FORWARDED_PROTO: "${TRUST_FORWARDED_PROTO:-false}"
ports:
# The public front door. Bound on all interfaces so browsers can reach it.
- "${WEB_PORT:-8090}:8090"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8090/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 10s
volumes:
pb_data:
# Shared by master, volume and filer — the same layout `weed server -dir`
# writes, so this file and docker-compose.prod.seaweedfs.yml can swap places
# on it.
seaweed_data:
# The admin UI's own session key and maintenance-task state. Small, and no
# part of the object store.
seaweed_admin:
+217
View File
@@ -0,0 +1,217 @@
name: drivervault
# Production DriverVault stack, with SeaweedFS — pulls prebuilt images from the
# registry instead of building from source. Self-contained: one file, no
# overlays. Everything an operator needs to set lives in .env.
#
# 1. cp .env.prod.seaweedfs.example .env (then edit it)
# 2. docker compose -f docker-compose.prod.seaweedfs.yml pull
# 3. docker compose -f docker-compose.prod.seaweedfs.yml up -d
#
# This is docker-compose.prod.yml plus an S3 object store: PocketBase keeps its
# record files — document scans, service and refill receipts, workshop invoices,
# part photos — in a SeaweedFS bucket instead of on the pb_data volume next to
# the database. The database and PocketBase's own backups stay on PB_DATA.
# Clients cannot tell the difference: an attachment has always been fetched
# through the API Server, never from a storage URL.
#
# Before turning this on for a stack that already has uploads: PocketBase does
# NOT copy existing files into the bucket. See README.md.
#
# Traffic flow (browser): Web App BFF --/api--> API Server --> PocketBase.
#
# On first boot:
# • PocketBase upserts the superuser from PB_ADMIN_* (create-if-missing).
# • the API Server creates any missing collections, reconciles existing ones,
# and creates the DriverVault super-admin from DRIVERVAULT_SUPERADMIN_*.
# Both steps are idempotent, so restarts and upgrades are safe.
services:
seaweedfs:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-seaweedfs
restart: unless-stopped
# One process, four roles: master, volume, filer and the S3 gateway. -dir is
# the only state it keeps.
command: server -dir=/data -s3 -master.volumeSizeLimitMB=1024
environment:
# SeaweedFS falls back to these when started without an -s3.config file,
# and configuring one identity is what takes the S3 gateway out of its
# default allow-anyone mode. The same credentials PocketBase authenticates
# with below — one pair to set, in .env.
AWS_ACCESS_KEY_ID: "${PB_S3_ACCESS_KEY:?set PB_S3_ACCESS_KEY in .env}"
AWS_SECRET_ACCESS_KEY: "${PB_S3_SECRET:?set PB_S3_SECRET in .env}"
volumes:
# Named volume by default; set SEAWEED_DATA to a host path in .env for a
# bind mount, exactly as PB_DATA works. Back it up alongside PB_DATA —
# from here on the attachments live here, not in the database volume.
- "${SEAWEED_DATA:-seaweed_data}:/data"
# No published port: the stack reaches the gateway over the compose network.
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:9333/cluster/status || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 20s
seaweedfs-init:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-seaweedfs-init
# Runs once and exits. PocketBase never issues a CreateBucket of its own and
# SeaweedFS will not conjure one on first upload, so something has to.
# Creating a bucket that already exists is a no-op, so every later boot
# passes straight through.
restart: "no"
depends_on:
seaweedfs:
condition: service_healthy
entrypoint: ["/bin/sh", "-c"]
# `|| true` so a restart is never blocked by the shell's exit status: this
# step is best-effort, and a gateway that is genuinely unreachable is
# reported by the API Server's own S3 check at boot, with the reason.
command:
- 'echo "s3.bucket.create -name ${PB_S3_BUCKET:-drivervault}" | weed shell -master=seaweedfs:9333 || true'
pocketbase:
image: "${PB_IMAGE:-10.2.1.10:5500/admin/drivervault-pocketbase:latest}"
container_name: drivervault-pocketbase
restart: unless-stopped
depends_on:
# PocketBase is the process that reads and writes the objects, so the
# gateway has to be serving before it is asked to store anything.
seaweedfs:
condition: service_healthy
environment:
# The superuser is created/updated on boot (the API Server authenticates
# with it). This is the only place the first superuser can be created — the
# REST API cannot bootstrap it.
PB_ADMIN_EMAIL: "${PB_ADMIN_EMAIL:?set PB_ADMIN_EMAIL in .env}"
PB_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD:?set PB_ADMIN_PASSWORD in .env}"
volumes:
# Named volume by default; set PB_DATA to a host path in .env for a bind mount.
- "${PB_DATA:-pb_data}:/pb/pb_data"
ports:
# Bound to localhost by default — the admin UI (/_/) is reachable only on
# the host. Set PB_BIND=0.0.0.0 in .env to expose it on the network.
- "${PB_BIND:-127.0.0.1}:${PB_PORT:-8070}:8070"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8070/api/health || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 10s
api-server:
image: "${API_IMAGE:-10.2.1.10:5500/admin/drivervault-api-server:latest}"
container_name: drivervault-api
restart: unless-stopped
depends_on:
pocketbase:
condition: service_healthy
# The bucket must exist before the bootstrap points PocketBase at it.
seaweedfs-init:
condition: service_completed_successfully
environment:
API_ADDR: ":8080"
# Reach PocketBase by its service name on the internal network. Override
# POCKETBASE_URL in .env to point the API Server at a database outside
# this stack — that is also how you make a retarget done from the panel
# permanent, since the panel's change lasts only for the container's life.
POCKETBASE_URL: "${POCKETBASE_URL:-http://pocketbase:8070}"
POCKETBASE_ADMIN_EMAIL: "${PB_ADMIN_EMAIL}"
POCKETBASE_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD}"
# Probed by the panel status page. This is a server-to-server call inside
# the compose network, so the default is the service name — plain
# localhost:8090 would resolve to this container itself. Override
# WEBAPP_URL in .env to make a change from the panel's Web App screen
# permanent; the panel alone only holds it for the container's life.
WEBAPP_URL: "${WEBAPP_URL:-http://web-app:8090}"
CORS_ALLOW_ORIGINS: "${CORS_ALLOW_ORIGINS:-http://localhost:8090}"
AUTH_USERS_COLLECTION: "${AUTH_USERS_COLLECTION:-users}"
# Schema + super-admin bootstrap (idempotent). Leave this ON: a release can
# add collections or fields the server needs, and a stack that skips the
# bootstrap never gets them. The API Server self-heals exactly one thing —
# app_settings, the collection holding the plugin settings, which it
# creates on demand because it cannot serve the plugin panel without it.
# Every other schema change still depends on this flag. Turn it off only
# for a database you know already matches the release.
PB_BOOTSTRAP: "${PB_BOOTSTRAP:-true}"
DRIVERVAULT_SUPERADMIN_EMAIL: "${DRIVERVAULT_SUPERADMIN_EMAIL:-}"
DRIVERVAULT_SUPERADMIN_PASSWORD: "${DRIVERVAULT_SUPERADMIN_PASSWORD:-}"
DRIVERVAULT_SUPERADMIN_NAME: "${DRIVERVAULT_SUPERADMIN_NAME:-Administrator}"
# OCPP charger control (Anker Solix). Chargers are rejected unless they
# reach the server over TLS. Behind a TLS-terminating reverse proxy, set
# OCPP_PUBLIC_URL to the public wss:// base and API_BIND so the proxy can
# reach this port; only drop OCPP_REQUIRE_TLS on a trusted network.
OCPP_REQUIRE_TLS: "${OCPP_REQUIRE_TLS:-true}"
OCPP_PUBLIC_URL: "${OCPP_PUBLIC_URL:-}"
# Diagnostic: set ANKER_MQTT_FRAME_LOG=1 in .env to log every frame the
# charger publishes over Anker's broker, decoded ones and unreadable ones
# alike, with their bytes. It is how a frame nobody has named gets named —
# do something in the Anker app while a control read holds the connection
# open, and read the frames back out of the log. Off by default: with it on
# a charger under a live trigger writes a line every few seconds.
ANKER_MQTT_FRAME_LOG: "${ANKER_MQTT_FRAME_LOG:-}"
# --- File storage --------------------------------------------------
# Read by the API Server's bootstrap, which writes them into PocketBase's
# settings on every boot, idempotently. Only record files move — scans,
# receipts, invoices, part photos. The database and PocketBase's own
# backups stay on PB_DATA.
PB_S3_ENABLED: "true"
PB_S3_BUCKET: "${PB_S3_BUCKET:-drivervault}"
# The service name: a server-to-server call inside the compose network.
PB_S3_ENDPOINT: "http://seaweedfs:8333"
# SeaweedFS ignores the region; PocketBase insists on having one.
PB_S3_REGION: "${PB_S3_REGION:-us-east-1}"
PB_S3_ACCESS_KEY: "${PB_S3_ACCESS_KEY}"
PB_S3_SECRET: "${PB_S3_SECRET}"
# Path style, because a self-hosted gateway has no per-bucket DNS.
PB_S3_FORCE_PATH_STYLE: "true"
ports:
# Localhost-only by default (the Web App reaches it over the internal
# network). Set API_BIND=0.0.0.0 to expose the API panel — and the
# /ocpp/{serial} endpoint chargers dial into — on the network.
- "${API_BIND:-127.0.0.1}:${API_PORT:-8080}:8080"
# No volume: the API Server keeps no state on disk — every setting it owns,
# plugin settings included, lives in PocketBase under PB_DATA.
healthcheck:
# Declared here rather than relying only on the image's HEALTHCHECK, so the
# depends_on gate below still works against an older pulled image.
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 20s
web-app:
image: "${WEB_IMAGE:-10.2.1.10:5500/admin/drivervault-web-app:latest}"
container_name: drivervault-web
restart: unless-stopped
depends_on:
# The image now ships a HEALTHCHECK, so wait for the API Server to be
# serving rather than merely started.
api-server:
condition: service_healthy
environment:
# The BFF reverse-proxies /api/* — and /ocpp/*, the address chargers are
# told to dial — to the API Server over the internal network.
API_BASE: "http://api-server:8080"
# Believe an inbound X-Forwarded-Proto. The API Server reads it to decide a
# charger arrived over TLS, so leave this off unless a TLS-terminating
# proxy in front of the stack is the only way in: otherwise a charger could
# claim wss over a plaintext connection. Set it to true when TLS ends at
# that proxy and OCPP_PUBLIC_URL names a wss:// base through it.
TRUST_FORWARDED_PROTO: "${TRUST_FORWARDED_PROTO:-false}"
ports:
# The public front door. Bound on all interfaces so browsers can reach it.
- "${WEB_PORT:-8090}:8090"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8090/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 10s
volumes:
pb_data:
seaweed_data:
+7
View File
@@ -81,6 +81,13 @@ services:
# reach this port; only drop OCPP_REQUIRE_TLS on a trusted network. # reach this port; only drop OCPP_REQUIRE_TLS on a trusted network.
OCPP_REQUIRE_TLS: "${OCPP_REQUIRE_TLS:-true}" OCPP_REQUIRE_TLS: "${OCPP_REQUIRE_TLS:-true}"
OCPP_PUBLIC_URL: "${OCPP_PUBLIC_URL:-}" OCPP_PUBLIC_URL: "${OCPP_PUBLIC_URL:-}"
# Diagnostic: set ANKER_MQTT_FRAME_LOG=1 in .env to log every frame the
# charger publishes over Anker's broker, decoded ones and unreadable ones
# alike, with their bytes. It is how a frame nobody has named gets named —
# do something in the Anker app while a control read holds the connection
# open, and read the frames back out of the log. Off by default: with it on
# a charger under a live trigger writes a line every few seconds.
ANKER_MQTT_FRAME_LOG: "${ANKER_MQTT_FRAME_LOG:-}"
ports: ports:
# Localhost-only by default (the Web App reaches it over the internal # Localhost-only by default (the Web App reaches it over the internal
# network). Set API_BIND=0.0.0.0 to expose the API panel — and the # network). Set API_BIND=0.0.0.0 to expose the API panel — and the
+174
View File
@@ -0,0 +1,174 @@
name: drivervault
# Full DriverVault stack, with external S3: PocketBase (database) + API Server +
# Web App, built from source, storing files in an S3 endpoint that already
# exists somewhere else. Self-contained — one file, nothing to layer.
#
# cp .env.s3.example .env (then edit it — PB_S3_* especially)
# docker compose -f docker-compose.s3.yml up -d --build
#
# Traffic flow (browser): Web App BFF --/api--> API Server --> PocketBase.
#
# This is docker-compose.yml plus storage: PocketBase keeps its record files —
# document scans, service and refill receipts, workshop invoices, part photos —
# in that bucket instead of on the pb_data volume next to the database. The
# database and PocketBase's own backups stay on pb_data. Clients cannot tell the
# difference: an attachment has always been fetched through the API Server,
# never from a storage URL.
#
# The bucket must already exist, and nothing here runs the gateway. For a
# SeaweedFS that comes up with the stack, use docker-compose.seaweedfs.yml.
#
# Before turning this on for a stack that already has uploads: PocketBase does
# NOT copy existing files into the bucket. See README.md.
services:
pocketbase:
build:
context: ./pocketbase
image: drivervault-pocketbase
container_name: drivervault-pocketbase
restart: unless-stopped
extra_hosts:
# Lets PB_S3_ENDPOINT name the Docker host as host.docker.internal.
# Harmless when the endpoint is somewhere else entirely.
- "host.docker.internal:host-gateway"
environment:
# Superuser is created/updated on boot so the API Server can authenticate.
PB_ADMIN_EMAIL: "${PB_ADMIN_EMAIL:?set PB_ADMIN_EMAIL in .env}"
PB_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD:?set PB_ADMIN_PASSWORD in .env}"
volumes:
- pb_data:/pb/pb_data
ports:
# Admin UI / API exposed on the host for management (http://host:8070/_/).
- "${PB_PORT:-8070}:8070"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8070/api/health || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 10s
api-server:
build:
context: ../API Server
image: drivervault-api
container_name: drivervault-api
restart: unless-stopped
extra_hosts:
# Lets PB_S3_ENDPOINT name the Docker host as host.docker.internal.
# Harmless when the endpoint is somewhere else entirely.
- "host.docker.internal:host-gateway"
depends_on:
pocketbase:
condition: service_healthy
environment:
API_ADDR: ":8080"
# Reach PocketBase by its service name on the internal network. Override
# POCKETBASE_URL in .env to point the API Server at a database outside
# this stack — that is also how you make a retarget done from the panel
# permanent, since the panel's change lasts only for the container's life.
POCKETBASE_URL: "${POCKETBASE_URL:-http://pocketbase:8070}"
POCKETBASE_ADMIN_EMAIL: "${PB_ADMIN_EMAIL}"
POCKETBASE_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD}"
# Probed by the panel status page. This is a server-to-server call inside
# the compose network, so the default is the service name — plain
# localhost:8090 would resolve to this container itself. Override
# WEBAPP_URL in .env to make a change from the panel's Web App screen
# permanent; the panel alone only holds it for the container's life.
WEBAPP_URL: "${WEBAPP_URL:-http://web-app:8090}"
# Same-origin requests go through the Web App BFF, so CORS is only needed
# if the browser ever calls the API Server directly. Default to the web origin.
CORS_ALLOW_ORIGINS: "${CORS_ALLOW_ORIGINS:-http://localhost:8090}"
AUTH_USERS_COLLECTION: "${AUTH_USERS_COLLECTION:-users}"
# Schema + super-admin bootstrap (idempotent). Without the SUPERADMIN vars
# the collections are still created but no app user is, leaving a stack
# you cannot log into.
#
# Leave the bootstrap ON: a release can add collections or fields the
# server needs, and a stack that skips it never gets them. The API Server
# self-heals exactly one thing — app_settings, the collection holding the
# plugin settings, which it creates on demand because it cannot serve the
# plugin panel without it. Every other schema change still depends on this
# flag. Turn it off only for a database you know matches the release.
PB_BOOTSTRAP: "${PB_BOOTSTRAP:-true}"
DRIVERVAULT_SUPERADMIN_EMAIL: "${DRIVERVAULT_SUPERADMIN_EMAIL:-}"
DRIVERVAULT_SUPERADMIN_PASSWORD: "${DRIVERVAULT_SUPERADMIN_PASSWORD:-}"
DRIVERVAULT_SUPERADMIN_NAME: "${DRIVERVAULT_SUPERADMIN_NAME:-Administrator}"
# OCPP charger control (Anker Solix). Chargers are rejected unless they
# connect over TLS; set OCPP_REQUIRE_TLS=false in .env only when TLS is
# terminated in front of this stack or for local dev on a trusted network.
OCPP_REQUIRE_TLS: "${OCPP_REQUIRE_TLS:-true}"
OCPP_PUBLIC_URL: "${OCPP_PUBLIC_URL:-}"
# Diagnostic: set ANKER_MQTT_FRAME_LOG=1 in .env to log every frame the
# charger publishes over Anker's broker, decoded ones and unreadable ones
# alike, with their bytes. It is how a frame nobody has named gets named —
# do something in the Anker app while a control read holds the connection
# open, and read the frames back out of the log. Off by default: with it on
# a charger under a live trigger writes a line every few seconds.
ANKER_MQTT_FRAME_LOG: "${ANKER_MQTT_FRAME_LOG:-}"
# --- File storage --------------------------------------------------
# Read by the API Server's bootstrap, which writes them into PocketBase's
# settings on every boot, idempotently. Only record files move — scans,
# receipts, invoices, part photos. The database and PocketBase's own
# backups stay on pb_data. The bucket must already exist: nothing here
# creates it.
PB_S3_ENABLED: "true"
PB_S3_BUCKET: "${PB_S3_BUCKET:-drivervault}"
PB_S3_ENDPOINT: "${PB_S3_ENDPOINT:?set PB_S3_ENDPOINT in .env}"
PB_S3_REGION: "${PB_S3_REGION:-us-east-1}"
PB_S3_ACCESS_KEY: "${PB_S3_ACCESS_KEY:?set PB_S3_ACCESS_KEY in .env}"
PB_S3_SECRET: "${PB_S3_SECRET:?set PB_S3_SECRET in .env}"
# true for SeaweedFS and MinIO, false for AWS S3 proper.
PB_S3_FORCE_PATH_STYLE: "${PB_S3_FORCE_PATH_STYLE:-true}"
ports:
# Optional direct access to the API Server (and its panel at /); the Web
# App reaches it over the internal network, not this host port. Chargers
# dialling /ocpp/{serial} also arrive here.
- "${API_PORT:-8080}:8080"
# No volume: the API Server keeps no state on disk — every setting it owns,
# plugin settings included, lives in PocketBase under pb_data.
healthcheck:
# Declared here rather than relying only on the image's HEALTHCHECK, so the
# depends_on gate below still works against an older pulled image.
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 20s
web-app:
build:
context: ../Web App
args:
# Empty -> bundle uses same-origin "/api", which the BFF proxies below.
VITE_API_BASE: "${VITE_API_BASE:-}"
image: drivervault-web
container_name: drivervault-web
restart: unless-stopped
depends_on:
# The image now ships a HEALTHCHECK, so wait for the API Server to be
# serving rather than merely started.
api-server:
condition: service_healthy
environment:
# The BFF reverse-proxies /api/* — and /ocpp/*, the address chargers are
# told to dial — to the API Server over the internal network.
API_BASE: "http://api-server:8080"
# Believe an inbound X-Forwarded-Proto. The API Server reads it to decide a
# charger arrived over TLS, so leave this off unless a TLS-terminating
# proxy in front of the stack is the only way in: otherwise a charger could
# claim wss over a plaintext connection. Set it to true when TLS ends at
# that proxy and OCPP_PUBLIC_URL names a wss:// base through it.
TRUST_FORWARDED_PROTO: "${TRUST_FORWARDED_PROTO:-false}"
ports:
- "${WEB_PORT:-8090}:8090"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8090/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 10s
volumes:
pb_data:
+376
View File
@@ -0,0 +1,376 @@
name: drivervault
# Full DriverVault stack, with SeaweedFS split into its four roles: PocketBase
# (database) + API Server + Web App, built from source, plus master, volume,
# filer, S3 gateway and the SeaweedFS admin UI as separate containers.
# Self-contained — one file, nothing to layer.
#
# cp .env.seaweedfs.split.example .env (then edit it)
# docker compose -f docker-compose.seaweedfs.split.yml up -d --build
#
# Traffic flow (browser): Web App BFF --/api--> API Server --> PocketBase.
#
# This is docker-compose.seaweedfs.yml with the storage layer taken apart.
# `weed server -s3` runs master, volume, filer and gateway as goroutines in one
# process; here each is its own container. What that buys:
#
# • the admin UI (weed admin) — a cluster view, and Object Store → Users,
# where S3 identities are created and revoked without touching a file;
# • per-role restart, upgrade and Prometheus metrics;
# • room to add a second volume server later, on this host or another.
#
# What it costs: five containers instead of one, and five healthchecks to keep
# the boot order honest. If none of the above is wanted, use
# docker-compose.seaweedfs.yml — the S3 behaviour is identical.
#
# The on-disk layout is deliberately the same as the single-process file's:
# master, volume and filer share one /data mount, exactly as `weed server -dir`
# lays it out (master raft state, volume .dat/.idx, the filer's filerldb2/ — no
# filename overlap). So the two files are interchangeable on the same volume,
# with no migration either way. A *second* volume server would need its own.
#
# Before turning this on for a stack that already has uploads: PocketBase does
# NOT copy existing files into the bucket. See README.md.
services:
# --- SeaweedFS: master -----------------------------------------------------
# Keeps the volume/topology metadata and hands out file ids. -ip is the name
# the other roles are told to reach it by, so it must be the service name and
# not the container IP the process would otherwise detect.
seaweedfs-master:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-seaweedfs-master
restart: unless-stopped
command: >
master -ip=seaweedfs-master -ip.bind=0.0.0.0 -mdir=/data
-volumeSizeLimitMB=1024 -metricsPort=9324
volumes:
- seaweed_data:/data
ports:
# Master UI / API. Useful while developing; the admin UI below covers the
# same ground with a nicer face.
- "${SEAWEED_MASTER_PORT:-9333}:9333"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:9333/cluster/status || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 15s
# --- SeaweedFS: volume server ---------------------------------------------
# Where the bytes actually land. -max=0 lets it size itself from free disk
# rather than the default cap of 8 volumes.
seaweedfs-volume:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-seaweedfs-volume
restart: unless-stopped
command: >
volume -master=seaweedfs-master:9333 -ip=seaweedfs-volume -ip.bind=0.0.0.0
-port=8080 -dir=/data -max=0 -metricsPort=9325
depends_on:
seaweedfs-master:
condition: service_healthy
volumes:
- seaweed_data:/data
ports:
# This port serves file content by file id with NO authentication — the S3
# credentials do not apply to it. Publish it only where you would be
# willing to publish the bucket itself. Mapped to 8081 on the host because
# 8080 there is the API Server.
- "${SEAWEED_VOLUME_PORT:-8081}:8080"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 15s
# --- SeaweedFS: filer ------------------------------------------------------
# Gives the flat volume store a directory tree — buckets, object keys — and
# holds the S3 identities the admin UI writes. -defaultStoreDir is where its
# embedded leveldb goes; without it that would be the container's working
# directory, and the identities would not survive a recreate.
seaweedfs-filer:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-seaweedfs-filer
restart: unless-stopped
command: >
filer -master=seaweedfs-master:9333 -ip=seaweedfs-filer -ip.bind=0.0.0.0
-port=8888 -defaultStoreDir=/data -metricsPort=9326
depends_on:
seaweedfs-volume:
condition: service_healthy
volumes:
- seaweed_data:/data
ports:
- "${SEAWEED_FILER_PORT:-8888}:8888"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8888/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 15s
# --- SeaweedFS: bucket and identity seed ----------------------------------
# Runs once and exits, before the gateway starts. Two jobs:
#
# 1. create the bucket — PocketBase never issues a CreateBucket of its own;
# 2. write PocketBase's S3 identity into the filer's IAM store.
#
# (2) is why this stack does not set AWS_ACCESS_KEY_ID on the gateway, the way
# docker-compose.seaweedfs.yml does. Those env vars are the *lowest* priority
# credential source in SeaweedFS: they are read only while the filer's store is
# empty, so the first identity added in the admin UI would silently displace
# them and lock PocketBase out. Seeding the store the admin UI itself writes
# leaves one source of truth, and the key PocketBase uses appears under
# Object Store → Users like any other.
#
# Both commands update in place, so every later boot re-applies the values from
# .env and changes nothing else — which is also how a rotated PB_S3_SECRET
# reaches the gateway.
#
# The closing grep is the gate: an empty IAM store means the gateway would come
# up in its allow-anyone default, so this fails loudly instead and the gateway
# below never starts. No `|| true` here, deliberately.
seaweedfs-init:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-seaweedfs-init
restart: "no"
depends_on:
seaweedfs-filer:
condition: service_healthy
environment:
# Passed as env and expanded by the shell inside the container, so the
# secret stays out of the container's argv.
PB_S3_BUCKET: "${PB_S3_BUCKET:-drivervault}"
PB_S3_ACCESS_KEY: "${PB_S3_ACCESS_KEY:?set PB_S3_ACCESS_KEY in .env}"
PB_S3_SECRET: "${PB_S3_SECRET:?set PB_S3_SECRET in .env}"
entrypoint: ["/bin/sh", "-c"]
command:
- |
set -e
printf '%s\n' \
"s3.bucket.create -name $$PB_S3_BUCKET" \
"s3.configure -user drivervault -access_key $$PB_S3_ACCESS_KEY -secret_key $$PB_S3_SECRET -actions Admin -apply" \
| weed shell -master=seaweedfs-master:9333 -filer=seaweedfs-filer:8888
echo "s3.configure" \
| weed shell -master=seaweedfs-master:9333 -filer=seaweedfs-filer:8888 \
| grep -q "$$PB_S3_ACCESS_KEY"
# --- SeaweedFS: S3 gateway -------------------------------------------------
# The endpoint PocketBase talks to. No -config file: with only -filer given,
# credentials come from the filer's IAM store, which is what lets the admin UI
# add and revoke identities without a restart. A config file would take
# priority over that store and make the admin UI's users inert.
seaweedfs-s3:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-seaweedfs-s3
restart: unless-stopped
command: >
s3 -filer=seaweedfs-filer:8888 -ip.bind=0.0.0.0 -port=8333
-metricsPort=9327
depends_on:
seaweedfs-filer:
condition: service_healthy
# Never serve before an identity exists — see seaweedfs-init above.
seaweedfs-init:
condition: service_completed_successfully
# No published port: the stack reaches the gateway over the compose network.
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8333/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 15s
# --- SeaweedFS: admin UI ---------------------------------------------------
# http://localhost:23646 — cluster topology, volumes, buckets, maintenance
# tasks, and Object Store → Users, where S3 access keys are minted and revoked.
# It finds the filer through the master, so -master is all it needs.
#
# An unauthenticated panel that can mint credentials for the bucket *is* the
# bucket, so the password is required rather than defaulted — weed leaves auth
# off entirely when it is empty. It is read from WEED_ADMIN_* rather than a
# flag, which keeps it off the process command line. -dataDir persists the
# session key and the maintenance-task settings.
seaweedfs-admin:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-seaweedfs-admin
restart: unless-stopped
command: >
admin -port=23646 -master=seaweedfs-master:9333 -dataDir=/data
-metricsPort=9328
depends_on:
seaweedfs-master:
condition: service_healthy
environment:
WEED_ADMIN_USER: "${SEAWEED_ADMIN_USER:-admin}"
WEED_ADMIN_PASSWORD: "${SEAWEED_ADMIN_PASSWORD:?set SEAWEED_ADMIN_PASSWORD in .env}"
volumes:
- seaweed_admin:/data
ports:
- "${SEAWEED_ADMIN_PORT:-23646}:23646"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:23646/health || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 15s
pocketbase:
build:
context: ./pocketbase
image: drivervault-pocketbase
container_name: drivervault-pocketbase
restart: unless-stopped
depends_on:
# PocketBase is the process that reads and writes the objects, so the
# gateway has to be serving before it is asked to store anything.
seaweedfs-s3:
condition: service_healthy
environment:
# Superuser is created/updated on boot so the API Server can authenticate.
PB_ADMIN_EMAIL: "${PB_ADMIN_EMAIL:?set PB_ADMIN_EMAIL in .env}"
PB_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD:?set PB_ADMIN_PASSWORD in .env}"
volumes:
- pb_data:/pb/pb_data
ports:
# Admin UI / API exposed on the host for management (http://host:8070/_/).
- "${PB_PORT:-8070}:8070"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8070/api/health || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 10s
api-server:
build:
context: ../API Server
image: drivervault-api
container_name: drivervault-api
restart: unless-stopped
depends_on:
pocketbase:
condition: service_healthy
# The bucket must exist before the bootstrap points PocketBase at it.
seaweedfs-init:
condition: service_completed_successfully
environment:
API_ADDR: ":8080"
# Reach PocketBase by its service name on the internal network. Override
# POCKETBASE_URL in .env to point the API Server at a database outside
# this stack — that is also how you make a retarget done from the panel
# permanent, since the panel's change lasts only for the container's life.
POCKETBASE_URL: "${POCKETBASE_URL:-http://pocketbase:8070}"
POCKETBASE_ADMIN_EMAIL: "${PB_ADMIN_EMAIL}"
POCKETBASE_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD}"
# Probed by the panel status page. This is a server-to-server call inside
# the compose network, so the default is the service name — plain
# localhost:8090 would resolve to this container itself. Override
# WEBAPP_URL in .env to make a change from the panel's Web App screen
# permanent; the panel alone only holds it for the container's life.
WEBAPP_URL: "${WEBAPP_URL:-http://web-app:8090}"
# Same-origin requests go through the Web App BFF, so CORS is only needed
# if the browser ever calls the API Server directly. Default to the web origin.
CORS_ALLOW_ORIGINS: "${CORS_ALLOW_ORIGINS:-http://localhost:8090}"
AUTH_USERS_COLLECTION: "${AUTH_USERS_COLLECTION:-users}"
# Schema + super-admin bootstrap (idempotent). Without the SUPERADMIN vars
# the collections are still created but no app user is, leaving a stack
# you cannot log into.
#
# Leave the bootstrap ON: a release can add collections or fields the
# server needs, and a stack that skips it never gets them. The API Server
# self-heals exactly one thing — app_settings, the collection holding the
# plugin settings, which it creates on demand because it cannot serve the
# plugin panel without it. Every other schema change still depends on this
# flag. Turn it off only for a database you know matches the release.
PB_BOOTSTRAP: "${PB_BOOTSTRAP:-true}"
DRIVERVAULT_SUPERADMIN_EMAIL: "${DRIVERVAULT_SUPERADMIN_EMAIL:-}"
DRIVERVAULT_SUPERADMIN_PASSWORD: "${DRIVERVAULT_SUPERADMIN_PASSWORD:-}"
DRIVERVAULT_SUPERADMIN_NAME: "${DRIVERVAULT_SUPERADMIN_NAME:-Administrator}"
# OCPP charger control (Anker Solix). Chargers are rejected unless they
# connect over TLS; set OCPP_REQUIRE_TLS=false in .env only when TLS is
# terminated in front of this stack or for local dev on a trusted network.
OCPP_REQUIRE_TLS: "${OCPP_REQUIRE_TLS:-true}"
OCPP_PUBLIC_URL: "${OCPP_PUBLIC_URL:-}"
# Diagnostic: set ANKER_MQTT_FRAME_LOG=1 in .env to log every frame the
# charger publishes over Anker's broker, decoded ones and unreadable ones
# alike, with their bytes. It is how a frame nobody has named gets named —
# do something in the Anker app while a control read holds the connection
# open, and read the frames back out of the log. Off by default: with it on
# a charger under a live trigger writes a line every few seconds.
ANKER_MQTT_FRAME_LOG: "${ANKER_MQTT_FRAME_LOG:-}"
# --- File storage --------------------------------------------------
# Read by the API Server's bootstrap, which writes them into PocketBase's
# settings on every boot, idempotently. Only record files move — scans,
# receipts, invoices, part photos. The database and PocketBase's own
# backups stay on pb_data.
PB_S3_ENABLED: "true"
PB_S3_BUCKET: "${PB_S3_BUCKET:-drivervault}"
# The gateway's service name: a server-to-server call inside the compose
# network.
PB_S3_ENDPOINT: "http://seaweedfs-s3:8333"
# SeaweedFS ignores the region; PocketBase insists on having one.
PB_S3_REGION: "${PB_S3_REGION:-us-east-1}"
PB_S3_ACCESS_KEY: "${PB_S3_ACCESS_KEY}"
PB_S3_SECRET: "${PB_S3_SECRET}"
# Path style, because a self-hosted gateway has no per-bucket DNS.
PB_S3_FORCE_PATH_STYLE: "true"
ports:
# Optional direct access to the API Server (and its panel at /); the Web
# App reaches it over the internal network, not this host port. Chargers
# dialling /ocpp/{serial} also arrive here.
- "${API_PORT:-8080}:8080"
# No volume: the API Server keeps no state on disk — every setting it owns,
# plugin settings included, lives in PocketBase under pb_data.
healthcheck:
# Declared here rather than relying only on the image's HEALTHCHECK, so the
# depends_on gate below still works against an older pulled image.
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 20s
web-app:
build:
context: ../Web App
args:
# Empty -> bundle uses same-origin "/api", which the BFF proxies below.
VITE_API_BASE: "${VITE_API_BASE:-}"
image: drivervault-web
container_name: drivervault-web
restart: unless-stopped
depends_on:
# The image now ships a HEALTHCHECK, so wait for the API Server to be
# serving rather than merely started.
api-server:
condition: service_healthy
environment:
# The BFF reverse-proxies /api/* — and /ocpp/*, the address chargers are
# told to dial — to the API Server over the internal network.
API_BASE: "http://api-server:8080"
# Believe an inbound X-Forwarded-Proto. The API Server reads it to decide a
# charger arrived over TLS, so leave this off unless a TLS-terminating
# proxy in front of the stack is the only way in: otherwise a charger could
# claim wss over a plaintext connection. Set it to true when TLS ends at
# that proxy and OCPP_PUBLIC_URL names a wss:// base through it.
TRUST_FORWARDED_PROTO: "${TRUST_FORWARDED_PROTO:-false}"
ports:
- "${WEB_PORT:-8090}:8090"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8090/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 10s
volumes:
pb_data:
# Shared by master, volume and filer — the same layout `weed server -dir`
# writes, so this file and docker-compose.seaweedfs.yml can swap places on it.
seaweed_data:
# The admin UI's own session key and maintenance-task state. Small, and no
# part of the object store.
seaweed_admin:
+216
View File
@@ -0,0 +1,216 @@
name: drivervault
# Full DriverVault stack, with SeaweedFS: PocketBase (database) + API Server +
# Web App, built from source, plus an S3 object store. Self-contained — one
# file, nothing to layer.
#
# cp .env.seaweedfs.example .env (then edit it)
# docker compose -f docker-compose.seaweedfs.yml up -d --build
#
# Traffic flow (browser): Web App BFF --/api--> API Server --> PocketBase.
#
# This is docker-compose.yml plus storage: PocketBase keeps its record files —
# document scans, service and refill receipts, workshop invoices, part photos —
# in a SeaweedFS bucket instead of on the pb_data volume next to the database.
# The database and PocketBase's own backups stay on pb_data. Clients cannot tell
# the difference: an attachment has always been fetched through the API Server,
# never from a storage URL.
#
# Before turning this on for a stack that already has uploads: PocketBase does
# NOT copy existing files into the bucket. See README.md.
services:
seaweedfs:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-seaweedfs
restart: unless-stopped
# One process, four roles: master, volume, filer and the S3 gateway. -dir is
# the only state it keeps.
command: server -dir=/data -s3 -master.volumeSizeLimitMB=1024
environment:
# SeaweedFS falls back to these when started without an -s3.config file,
# and configuring one identity is what takes the S3 gateway out of its
# default allow-anyone mode. The same credentials PocketBase authenticates
# with below — one pair to set, in .env.
AWS_ACCESS_KEY_ID: "${PB_S3_ACCESS_KEY:?set PB_S3_ACCESS_KEY in .env}"
AWS_SECRET_ACCESS_KEY: "${PB_S3_SECRET:?set PB_S3_SECRET in .env}"
volumes:
# From here on the attachments live here, not on pb_data.
- seaweed_data:/data
# No published port: the stack reaches the gateway over the compose network.
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:9333/cluster/status || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 20s
seaweedfs-init:
image: "${SEAWEED_IMAGE:-chrislusf/seaweedfs:4.45}"
container_name: drivervault-seaweedfs-init
# Runs once and exits. PocketBase never issues a CreateBucket of its own and
# SeaweedFS will not conjure one on first upload, so something has to.
# Creating a bucket that already exists is a no-op, so every later boot
# passes straight through.
restart: "no"
depends_on:
seaweedfs:
condition: service_healthy
entrypoint: ["/bin/sh", "-c"]
# `|| true` so a restart is never blocked by the shell's exit status: this
# step is best-effort, and a gateway that is genuinely unreachable is
# reported by the API Server's own S3 check at boot, with the reason.
command:
- 'echo "s3.bucket.create -name ${PB_S3_BUCKET:-drivervault}" | weed shell -master=seaweedfs:9333 || true'
pocketbase:
build:
context: ./pocketbase
image: drivervault-pocketbase
container_name: drivervault-pocketbase
restart: unless-stopped
depends_on:
# PocketBase is the process that reads and writes the objects, so the
# gateway has to be serving before it is asked to store anything.
seaweedfs:
condition: service_healthy
environment:
# Superuser is created/updated on boot so the API Server can authenticate.
PB_ADMIN_EMAIL: "${PB_ADMIN_EMAIL:?set PB_ADMIN_EMAIL in .env}"
PB_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD:?set PB_ADMIN_PASSWORD in .env}"
volumes:
- pb_data:/pb/pb_data
ports:
# Admin UI / API exposed on the host for management (http://host:8070/_/).
- "${PB_PORT:-8070}:8070"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8070/api/health || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 10s
api-server:
build:
context: ../API Server
image: drivervault-api
container_name: drivervault-api
restart: unless-stopped
depends_on:
pocketbase:
condition: service_healthy
# The bucket must exist before the bootstrap points PocketBase at it.
seaweedfs-init:
condition: service_completed_successfully
environment:
API_ADDR: ":8080"
# Reach PocketBase by its service name on the internal network. Override
# POCKETBASE_URL in .env to point the API Server at a database outside
# this stack — that is also how you make a retarget done from the panel
# permanent, since the panel's change lasts only for the container's life.
POCKETBASE_URL: "${POCKETBASE_URL:-http://pocketbase:8070}"
POCKETBASE_ADMIN_EMAIL: "${PB_ADMIN_EMAIL}"
POCKETBASE_ADMIN_PASSWORD: "${PB_ADMIN_PASSWORD}"
# Probed by the panel status page. This is a server-to-server call inside
# the compose network, so the default is the service name — plain
# localhost:8090 would resolve to this container itself. Override
# WEBAPP_URL in .env to make a change from the panel's Web App screen
# permanent; the panel alone only holds it for the container's life.
WEBAPP_URL: "${WEBAPP_URL:-http://web-app:8090}"
# Same-origin requests go through the Web App BFF, so CORS is only needed
# if the browser ever calls the API Server directly. Default to the web origin.
CORS_ALLOW_ORIGINS: "${CORS_ALLOW_ORIGINS:-http://localhost:8090}"
AUTH_USERS_COLLECTION: "${AUTH_USERS_COLLECTION:-users}"
# Schema + super-admin bootstrap (idempotent). Without the SUPERADMIN vars
# the collections are still created but no app user is, leaving a stack
# you cannot log into.
#
# Leave the bootstrap ON: a release can add collections or fields the
# server needs, and a stack that skips it never gets them. The API Server
# self-heals exactly one thing — app_settings, the collection holding the
# plugin settings, which it creates on demand because it cannot serve the
# plugin panel without it. Every other schema change still depends on this
# flag. Turn it off only for a database you know matches the release.
PB_BOOTSTRAP: "${PB_BOOTSTRAP:-true}"
DRIVERVAULT_SUPERADMIN_EMAIL: "${DRIVERVAULT_SUPERADMIN_EMAIL:-}"
DRIVERVAULT_SUPERADMIN_PASSWORD: "${DRIVERVAULT_SUPERADMIN_PASSWORD:-}"
DRIVERVAULT_SUPERADMIN_NAME: "${DRIVERVAULT_SUPERADMIN_NAME:-Administrator}"
# OCPP charger control (Anker Solix). Chargers are rejected unless they
# connect over TLS; set OCPP_REQUIRE_TLS=false in .env only when TLS is
# terminated in front of this stack or for local dev on a trusted network.
OCPP_REQUIRE_TLS: "${OCPP_REQUIRE_TLS:-true}"
OCPP_PUBLIC_URL: "${OCPP_PUBLIC_URL:-}"
# Diagnostic: set ANKER_MQTT_FRAME_LOG=1 in .env to log every frame the
# charger publishes over Anker's broker, decoded ones and unreadable ones
# alike, with their bytes. It is how a frame nobody has named gets named —
# do something in the Anker app while a control read holds the connection
# open, and read the frames back out of the log. Off by default: with it on
# a charger under a live trigger writes a line every few seconds.
ANKER_MQTT_FRAME_LOG: "${ANKER_MQTT_FRAME_LOG:-}"
# --- File storage --------------------------------------------------
# Read by the API Server's bootstrap, which writes them into PocketBase's
# settings on every boot, idempotently. Only record files move — scans,
# receipts, invoices, part photos. The database and PocketBase's own
# backups stay on pb_data.
PB_S3_ENABLED: "true"
PB_S3_BUCKET: "${PB_S3_BUCKET:-drivervault}"
# The service name: a server-to-server call inside the compose network.
PB_S3_ENDPOINT: "http://seaweedfs:8333"
# SeaweedFS ignores the region; PocketBase insists on having one.
PB_S3_REGION: "${PB_S3_REGION:-us-east-1}"
PB_S3_ACCESS_KEY: "${PB_S3_ACCESS_KEY}"
PB_S3_SECRET: "${PB_S3_SECRET}"
# Path style, because a self-hosted gateway has no per-bucket DNS.
PB_S3_FORCE_PATH_STYLE: "true"
ports:
# Optional direct access to the API Server (and its panel at /); the Web
# App reaches it over the internal network, not this host port. Chargers
# dialling /ocpp/{serial} also arrive here.
- "${API_PORT:-8080}:8080"
# No volume: the API Server keeps no state on disk — every setting it owns,
# plugin settings included, lives in PocketBase under pb_data.
healthcheck:
# Declared here rather than relying only on the image's HEALTHCHECK, so the
# depends_on gate below still works against an older pulled image.
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 20s
web-app:
build:
context: ../Web App
args:
# Empty -> bundle uses same-origin "/api", which the BFF proxies below.
VITE_API_BASE: "${VITE_API_BASE:-}"
image: drivervault-web
container_name: drivervault-web
restart: unless-stopped
depends_on:
# The image now ships a HEALTHCHECK, so wait for the API Server to be
# serving rather than merely started.
api-server:
condition: service_healthy
environment:
# The BFF reverse-proxies /api/* — and /ocpp/*, the address chargers are
# told to dial — to the API Server over the internal network.
API_BASE: "http://api-server:8080"
# Believe an inbound X-Forwarded-Proto. The API Server reads it to decide a
# charger arrived over TLS, so leave this off unless a TLS-terminating
# proxy in front of the stack is the only way in: otherwise a charger could
# claim wss over a plaintext connection. Set it to true when TLS ends at
# that proxy and OCPP_PUBLIC_URL names a wss:// base through it.
TRUST_FORWARDED_PROTO: "${TRUST_FORWARDED_PROTO:-false}"
ports:
- "${WEB_PORT:-8090}:8090"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8090/healthz || exit 1"]
interval: 10s
timeout: 3s
retries: 12
start_period: 10s
volumes:
pb_data:
seaweed_data:
-61
View File
@@ -1,61 +0,0 @@
name: drivervault
# TLS overlay — put a public hostname and a real certificate in front of the
# stack. Layer it on top of either base file:
#
# docker compose -f docker-compose.prod.yml -f docker-compose.tls.yml up -d
#
# What it changes:
# • Caddy terminates TLS on :443 and proxies everything to the Web App BFF,
# which already carries /api/ and /ocpp/ through to the API Server. One
# hostname serves browsers and chargers alike.
# • The charger endpoint the panel hands out becomes wss://$DV_DOMAIN/ocpp/…,
# so OCPP_REQUIRE_TLS goes back on and the control token stops crossing the
# network in the clear.
#
# Requirements, none of which this file can arrange for you:
# • DV_DOMAIN resolves to this host from the public internet, and ports 80 and
# 443 reach it (Caddy needs :80 for the ACME challenge, and keeps it for the
# redirect afterwards).
# • The charger can resolve DV_DOMAIN too. On a LAN behind NAT that usually
# means hairpin NAT or a split-DNS entry pointing the name at 10.2.1.10 —
# otherwise the charger looks up a public address it cannot route to.
services:
caddy:
image: "${CADDY_IMAGE:-caddy:2-alpine}"
container_name: drivervault-caddy
restart: unless-stopped
depends_on:
web-app:
condition: service_healthy
environment:
DV_DOMAIN: "${DV_DOMAIN:?set DV_DOMAIN in .env}"
# Let's Encrypt sends expiry warnings here if renewal ever stops working.
DV_ACME_EMAIL: "${DV_ACME_EMAIL:?set DV_ACME_EMAIL in .env}"
ports:
- "80:80"
- "443:443"
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
# Certificates live here. Keep the volume: wiping it re-issues on next
# boot and Let's Encrypt rate-limits that.
- caddy_data:/data
- caddy_config:/config
api-server:
environment:
# Derived from the one hostname, so there is a single thing to set.
OCPP_REQUIRE_TLS: "true"
OCPP_PUBLIC_URL: "wss://${DV_DOMAIN}"
CORS_ALLOW_ORIGINS: "https://${DV_DOMAIN}"
web-app:
environment:
# Caddy terminates TLS and says so in X-Forwarded-Proto. Believe it —
# that header is now set by the proxy in front, not by whoever dialed in.
TRUST_FORWARDED_PROTO: "true"
volumes:
caddy_data:
caddy_config:
+7
View File
@@ -74,6 +74,13 @@ services:
# terminated in front of this stack or for local dev on a trusted network. # terminated in front of this stack or for local dev on a trusted network.
OCPP_REQUIRE_TLS: "${OCPP_REQUIRE_TLS:-true}" OCPP_REQUIRE_TLS: "${OCPP_REQUIRE_TLS:-true}"
OCPP_PUBLIC_URL: "${OCPP_PUBLIC_URL:-}" OCPP_PUBLIC_URL: "${OCPP_PUBLIC_URL:-}"
# Diagnostic: set ANKER_MQTT_FRAME_LOG=1 in .env to log every frame the
# charger publishes over Anker's broker, decoded ones and unreadable ones
# alike, with their bytes. It is how a frame nobody has named gets named —
# do something in the Anker app while a control read holds the connection
# open, and read the frames back out of the log. Off by default: with it on
# a charger under a live trigger writes a line every few seconds.
ANKER_MQTT_FRAME_LOG: "${ANKER_MQTT_FRAME_LOG:-}"
ports: ports:
# Optional direct access to the API Server (and its panel at /); the Web # Optional direct access to the API Server (and its panel at /); the Web
# App reaches it over the internal network, not this host port. Chargers # App reaches it over the internal network, not this host port. Chargers
+65 -27
View File
@@ -92,25 +92,55 @@ navigation bar** — Garage, Charging, Settings, and Users for admins — in an
workshop visit, refill, charge, document and part (PDF or image, up to 10MB). Picked workshop visit, refill, charge, document and part (PDF or image, up to 10MB). Picked
with `file_picker`, fetched back through the API Server — never a public URL — with `file_picker`, fetched back through the API Server — never a public URL —
and opened with the phone's own viewer via `open_filex`. and opened with the phone's own viewer via `open_filex`.
- **Charging** — mirrors the web `Charging.vue`, split into two tabs. **Public** - **Charging** — mirrors the web `Charging.vue`, split into three tabs.
is a discovery map with a demo session and nearby stations: presentational **Public** is a discovery map with a demo session and nearby stations:
placeholders, because there is no public-charging API yet (same as the web). presentational placeholders, because there is no public-charging API yet (same
**Home** is not a placeholder. It lists the chargers you own — imported from a as the web). **Home** is not a placeholder. It lists the chargers you own —
service you connected, the same move the garage makes for a car — and above imported from a service you connected, the same move the garage makes for a
them four cards about the one you picked: **control** (start/stop, a current car — and above them six cards about the one you picked:
limit, boost or reset depending on the transport), **connection** (which - **control** — start/stop, boost, skip a start delay, reboot, and the current
charger, and either its serial or its address on your network), **readings** limit on the one transport that has nowhere else to put it. It opens with
(everything the charger reports over Modbus — per-phase power, its settings, the charger it acts on, picture and name, because the buttons drive whichever
what it is, and any alarm), and **information** (everything the record holds, serial is in force and that is not always the record highlighted below.
with the service's live view of whether it is reachable). Control needs a mode - **RFID cards** — who may start a charge without a phone. The list the
picked under Settings → Integrations — Modbus TCP over the local network, or account holds, a card added by number or by holding it against the charger's
Own/Proxy CSMS over OCPP — but the information card stands without one. own reader (the reader opens for twenty seconds and the number arrives on its
Each card folds away, remembered per device; the tabs and the cards rearrange own), and the charger's own list read back from the device, which is the half
from the ⇅ button in the app bar, and that arrangement is saved on your that actually decides whether a card opens it. When the two disagree the card
profile, so it follows the account the way the garage order does. says which list each card is missing from.
- **charger settings** — what the charger is set to, written back. Over Modbus
that is four registers (the current limit, phase count, boost, the control
timeout); over the Anker cloud it is the charger's whole settings group, in
sections — charging, schedule, load balancing, solar, panel and light, local
network — one write per section, because the charger takes a command whole.
- **connection** — which charger, and either its serial or its address on your
network.
- **readings** — everything the charger reports: per-phase power, its
settings, what it is, and any alarm.
- **information** — everything the record holds, with the service's live view
of whether it is reachable, the fields the service sent under its own names,
and each of the account's per-charger views read a record at a time.
Control needs a mode picked under Settings → Integrations — Modbus TCP over
the local network, the Anker cloud, or Own/Proxy CSMS over OCPP — but the
information and RFID cards stand without one. Each card folds away, remembered
per device; the tabs and the cards rearrange from the ⇅ button in the app bar,
and that arrangement is saved on your profile, so it follows the account the
way the garage order does. A card added after you arranged yours appears beside
the neighbour it was written to sit under, rather than at the bottom.
**Scheduler** is the third tab: one list of charging tasks covering every
charger you own, where the charger's own cloud schedule is one window inside
one box. A task is a whole flow — start at 23:00, cap to 10 A at 01:00, stop at
06:30 — on the days you pick and the chargers you pick, named once and switched
on and off as one. Naming no charger means every charger you own, including the
ones you import later. The clock is the server's, so a task fires whether or
not the app is open; each row says how its last firing went, and any step can
be fired now to find out whether it will reach the charger before the night it
matters.
- **Settings** — account (name / email verification / password), appearance - **Settings** — account (name / email verification / password), appearance
(theme + dark mode, **language**, **region**, date format, **currency**, font (theme + dark mode, **language**, **region**, date format, **time format**,
size), profile (avatar via `image_picker`, bio), **integrations** (Toyota, **first day of the week**, **currency**, font size), profile (avatar via `image_picker`, bio), **integrations** (Toyota,
Anker Solix), **Security** (biometric toggle), **Organization** (create your Anker Solix), **Security** (biometric toggle), **Organization** (create your
own — which makes you its admin — or rename/delete the one you administer), own — which makes you its admin — or rename/delete the one you administer),
**data export/import**, and the account-deletion state machine. Export writes **data export/import**, and the account-deletion state machine. Export writes
@@ -265,15 +295,23 @@ Running it on your own car:
- The service is declared under `androidx.car.app.category.IOT`. It is the - The service is declared under `androidx.car.app.category.IOT`. It is the
closest of the categories the library defines — DriverVault is a garage, not a closest of the categories the library defines — DriverVault is a garage, not a
map, a media player or a parking service — and a Play Store submission would map, a media player or a parking service — and a Play Store submission would
be reviewed against it. This build is sideloaded, so what matters instead is be reviewed against it. Getting it onto a car at all is the next line.
the next line. - **A sideloaded build never appears on a real head unit**, and no setting on the
- Android Auto refuses apps it did not get from the Play Store until you tell it phone changes that. Android Auto's **Unknown sources** developer option is the
otherwise: in the **Android Auto** settings on the phone, tap the version ten one everybody reaches for here, but it covers media, messaging-notification and
times to unlock **Developer settings**, then turn on **Unknown sources**. parked apps only — [Google's testing
- To try it without a car, run Google's guide](https://developer.android.com/training/cars/testing) says in as many
[Desktop Head Unit](https://developer.android.com/training/cars/testing/dhu). words that it does not apply to apps built with the Car App Library. A car will
A debug build accepts any host so the DHU can connect; a release build only list DriverVault only if the APK was installed *from Play*: an internal testing
accepts the signed hosts the library ships an allowlist for. track, or internal app sharing, is enough — no public listing, no review.
- To try it without Play — which is how these screens were written — run Google's
[Desktop Head Unit](https://developer.android.com/training/cars/testing/dhu),
which does take a sideloaded build. In the **Android Auto** settings on the
phone, tap the version ten times to unlock **Developer settings**, then
**Start head unit server**; on the machine, `adb forward tcp:5277 tcp:5277` and
run `desktop-head-unit`. Install the **debug** APK for this: a debug build
accepts any host so the DHU can connect, while a release build only accepts the
signed hosts the library ships an allowlist for.
## Configure the API endpoint ## Configure the API endpoint
@@ -50,9 +50,13 @@
<meta-data <meta-data
android:name="com.google.android.gms.car.application" android:name="com.google.android.gms.car.application"
android:resource="@xml/automotive_app_desc"/> android:resource="@xml/automotive_app_desc"/>
<!-- Level 2, not 1: GarageScreen asks the host for ConstraintManager to
size its list, and that service arrived at level 2. Every shipping
host is far above this; the floor just has to not claim less than
the screens actually use. -->
<meta-data <meta-data
android:name="androidx.car.app.minCarApiLevel" android:name="androidx.car.app.minCarApiLevel"
android:value="1"/> android:value="2"/>
<service <service
android:name=".car.DriverVaultCarAppService" android:name=".car.DriverVaultCarAppService"
android:exported="true"> android:exported="true">
@@ -40,7 +40,12 @@ class CarStrings private constructor(
companion object { companion object {
private const val BASE = "en" private const val BASE = "en"
private val PLACEHOLDER = Regex("""\{(\w+)}""") // Both braces escaped, as in i18n.dart's twin of this pattern.
// Android compiles regexes through ICU rather than java.util.regex,
// and ICU refuses a closing brace that opens no quantifier — a lone
// "}" here throws PatternSyntaxException the first time CarStrings
// is touched, which on a head unit is a screen that never draws.
private val PLACEHOLDER = Regex("""\{(\w+)\}""")
/** Loads the files for the account's language, falling back to English. */ /** Loads the files for the account's language, falling back to English. */
fun of(context: Context): CarStrings { fun of(context: Context): CarStrings {
Loaded 100 of 129 files, more files were not shown because too many files have changed in this diff. Show more