Accounts people can create, and photos on a server with no bucket
A tenant had exactly the users somebody had created with a command on the
server. That is not a missing screen: a shop with an owner and four staff
either shared one password or raised a ticket per person, and a phone app
for the shop floor could not exist while there was one account to sign in
as.
Registration is by invitation, never open signup - the same line already
drawn around creating a company. The code carries the address and the role
and the request carries only a password, so a code that gets forwarded
cannot become somebody else's account, and a staff invitation cannot be
redeemed as an owner. Single use lives in the UPDATE and the account is
created in the same transaction.
Deactivating a member revokes their sessions in that transaction too. An
access token lives twelve hours, so without it "remove their access"
removed it sometime tomorrow. The session list and revoke that go with it
are the benefit of opaque tokens the product had been paying for and never
collecting: nothing could say what was signed in, let alone stop one.
Face images now work on a deployment with no object storage, which was
every local install and every self-hosted site - the arrivals feed said
"not storing customer photos" for every customer forever, on the screen
whose whole job is to show a face. Bounded to one row per visitor, so it
grows with the customer base and not with footfall; the bucket stays
primary wherever one exists.
Image.auth says whether a URL needs the session, because a browser img
cannot load one that does, a mobile image view can, and a webview can do
neither - the desktop client resolves those to a data URI in Go.
Found by running it, not by tests:
* UPDATE ... RETURNING gives the value AFTER the update, so the prune
read back empty keys, deleted nothing, and the table grew with
footfall exactly as if it were not there. The fake agreed with either
version; only the live Postgres test caught it.
* Trusting only the auth flag broke every shop card, because Sites.jsx
rebuilt a partial snapshot object and dropped it. A relative URL is
now sufficient on its own.
* ago() renders a future time as "just now", so a code valid for a week
read "expires just now".
Verified live against real Postgres: invite, preview, escalation refused,
register into a session, replay 404, staff forbidden, device revoked and
401 at once, last owner refused, and a 92,405-byte camera JPEG stored,
served to its owner, 401 with no session, 404 to another tenant, and
rendered in a browser.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HViLj9gYNRtSr7YVZmW5sn
This commit is contained in:
334
API.md
Normal file
334
API.md
Normal file
@@ -0,0 +1,334 @@
|
||||
# Behavision API — for the web console and a mobile app
|
||||
|
||||
Base URL: `https://platform.loyaly.ai` (locally `http://127.0.0.1:8088`).
|
||||
Everything is JSON unless stated. All times are RFC 3339 UTC unless a field says
|
||||
otherwise.
|
||||
|
||||
There is **one API**, not a web one and a mobile one. The web console in this
|
||||
repository uses exactly these calls; anything it can do, an app can do.
|
||||
|
||||
---
|
||||
|
||||
## 1. Signing in
|
||||
|
||||
### `POST /api/auth/login`
|
||||
|
||||
```json
|
||||
{ "email": "priya@tenext.in", "password": "…", "device": "Pixel 8" }
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"access_token": "…",
|
||||
"refresh_token": "…",
|
||||
"expires_at": "2026-09-05T18:00:00Z",
|
||||
"user": { "id": "…", "email": "…", "full_name": "Priya R",
|
||||
"role": "staff", "client_id": "…", "client_name": "TeNext Retail" }
|
||||
}
|
||||
```
|
||||
|
||||
Send `Authorization: Bearer <access_token>` on every other call.
|
||||
|
||||
**`device` is worth sending.** It is the only thing that lets somebody look at
|
||||
their list of signed-in devices and tell which one to sign out. Keep it coarse
|
||||
and human — `"Pixel 8"`, `"Shop till"` — never a device identifier; a
|
||||
fingerprint here is a tracking signal nobody asked for.
|
||||
|
||||
Failures:
|
||||
|
||||
| status | `error` | what it means |
|
||||
|---|---|---|
|
||||
| 401 | `bad_credentials` | Wrong password **or** no such account. Deliberately the same answer: telling them apart turns this form into a way to find out who works at a customer. Show the server's `message`. |
|
||||
| 429 | `too_many_attempts` | 10 failures per account / 60 per IP in 15 minutes. Cleared by a success. |
|
||||
|
||||
### `POST /api/auth/refresh`
|
||||
|
||||
```json
|
||||
{ "refresh_token": "…", "device": "Pixel 8" }
|
||||
```
|
||||
|
||||
Returns the same shape. **Both tokens rotate** — the old refresh token stops
|
||||
working the instant the new one is issued, so a copy taken off a resold device
|
||||
cannot keep working alongside the real one.
|
||||
|
||||
Three rules a client must follow, and all three have already been the cause of a
|
||||
bug in this codebase:
|
||||
|
||||
1. **An expired access token returns 401 with `"error": "token_expired"`**,
|
||||
distinct from a real 401. Refresh once and retry, silently — otherwise staff
|
||||
are thrown back to a login form twice a day.
|
||||
2. **Serialise refresh behind one lock.** The refresh token is single use, so
|
||||
four screens polling at once would each spend it and three would lose,
|
||||
logging the user out at random.
|
||||
3. **Persist the rotated tokens before doing anything else.** A client that
|
||||
refreshes and is then killed comes back holding a token the server has
|
||||
already invalidated — indistinguishable from a normal expiry, at the worst
|
||||
possible moment.
|
||||
|
||||
Marshal the request body **before** the first attempt: a retry has to send it
|
||||
again, and a stream is spent after the first read.
|
||||
|
||||
### `POST /api/auth/logout` · `GET /api/auth/me`
|
||||
|
||||
Logout revokes the calling session. `me` returns the `user` object above.
|
||||
|
||||
---
|
||||
|
||||
## 2. Joining — how somebody gets an account
|
||||
|
||||
There is **no open registration**, by design. A manager or owner mints a code
|
||||
and hands it over; the holder chooses their own password.
|
||||
|
||||
### `POST /api/team/invitations` — manager or owner
|
||||
|
||||
```json
|
||||
{ "email": "arjun@tenext.in", "full_name": "Arjun", "role": "manager",
|
||||
"expires_in_days": 7 }
|
||||
```
|
||||
|
||||
```json
|
||||
{ "id": "…", "email": "arjun@tenext.in", "role": "manager",
|
||||
"code": "LQOUHR-AYYTPE-7Q756N-PGAAN6",
|
||||
"expires_at": "…", "created_at": "…" }
|
||||
```
|
||||
|
||||
**`code` is returned exactly once and is not recoverable.** Only a hash is
|
||||
stored. Show it immediately; do not expect to read it back.
|
||||
|
||||
`role` is `staff`, `manager` or `owner`. Only an owner may mint an owner.
|
||||
`admin` is not accepted at all.
|
||||
|
||||
### `GET /api/auth/invitation?code=…` — **no auth**
|
||||
|
||||
```json
|
||||
{ "client_name": "TeNext Retail", "email": "arjun@tenext.in",
|
||||
"full_name": "Arjun", "role": "manager" }
|
||||
```
|
||||
|
||||
Call this before asking anyone to choose a password, so the screen can say what
|
||||
they are joining and a mistyped code is caught early. Unknown, expired, spent
|
||||
and withdrawn all return **404 `invalid_code`** with one message.
|
||||
|
||||
### `POST /api/auth/register` — **no auth**
|
||||
|
||||
```json
|
||||
{ "code": "LQOUHR-AYYTPE-7Q756N-PGAAN6",
|
||||
"full_name": "Arjun", "password": "…", "device": "Pixel 8" }
|
||||
```
|
||||
|
||||
Returns **201** and a full session — the same shape as login. Sign the person
|
||||
straight in; do not send them to a login form.
|
||||
|
||||
**Do not send `email` or `role`.** They come from the invitation, and the
|
||||
request is rejected outright if it names either. That is what stops a forwarded
|
||||
code becoming somebody else's account, or a staff invitation being redeemed as
|
||||
an owner.
|
||||
|
||||
Dashes and case in the code are ignored. A rejected attempt (short password,
|
||||
wrong code) does **not** spend the invitation.
|
||||
|
||||
| status | `error` |
|
||||
|---|---|
|
||||
| 400 | password under 8 characters, or a body naming `email`/`role` |
|
||||
| 404 | `invalid_code` |
|
||||
| 409 | `conflict` — that address already has an account; sign in instead |
|
||||
|
||||
### `GET` / `DELETE /api/team/invitations[/{id}]` — manager or owner
|
||||
|
||||
List what is still pending, or withdraw one before it is used.
|
||||
|
||||
---
|
||||
|
||||
## 3. Devices
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `GET /api/auth/sessions` | this account's signed-in devices |
|
||||
| `DELETE /api/auth/sessions/{id}` | sign one out, immediately |
|
||||
| `POST /api/auth/sessions/revoke-others` | sign out everywhere else |
|
||||
|
||||
```json
|
||||
[{ "id": "…", "device": "Pixel 8", "created_at": "…",
|
||||
"last_used_at": "…", "expires_at": "…", "current": true }]
|
||||
```
|
||||
|
||||
`current` marks the session making the request — label it, and warn before
|
||||
somebody signs out the device in their hand. `revoke-others` deliberately keeps
|
||||
the caller's own session.
|
||||
|
||||
A person can revoke only their own sessions. To remove a colleague's access,
|
||||
deactivate them (below); that revokes every session they hold.
|
||||
|
||||
---
|
||||
|
||||
## 4. The team
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `GET /api/team` | everybody in this company |
|
||||
| `PATCH /api/team/{id}` | `{"role": "manager"}` and/or `{"active": false}` |
|
||||
|
||||
Deactivating signs that person out **immediately** and stops them signing back
|
||||
in. Reactivating restores the account but not their old sessions.
|
||||
|
||||
409 `last_owner` if the change would leave the company with no active owner.
|
||||
|
||||
---
|
||||
|
||||
## 5. Who just walked in — the screen a mobile app is for
|
||||
|
||||
### `GET /api/visits`
|
||||
|
||||
`?limit=50&cursor=…&site_id=…`
|
||||
|
||||
```json
|
||||
{
|
||||
"arrivals": [{
|
||||
"visit_id": "…", "seq": 412,
|
||||
"occurred_at": "2026-09-05T06:01:45Z",
|
||||
"site_id": "…", "site": "TeNext Chennai", "camera_id": "Office1",
|
||||
"visitor_id": "…", "label": "Priya",
|
||||
"is_new_visitor": false, "similarity": 0.71, "quality": 0.66,
|
||||
"attributes": { "gender": "Male", "age": 32, "emotion": "neutral" },
|
||||
"image": { "available": true,
|
||||
"url": "/api/faces/8e7d3d7a-….jpg", "auth": true }
|
||||
}],
|
||||
"cursor": "djE6NDEy",
|
||||
"polled_at": "…"
|
||||
}
|
||||
```
|
||||
|
||||
**Echo `cursor` back on every poll.** It is opaque and it is the only thing that
|
||||
makes the feed lossless: a burst larger than `limit` leaves rows behind, and
|
||||
polling by timestamp alone would skip them permanently. Rows are **ascending**,
|
||||
so the last row's position is your new cursor — which the response already gives
|
||||
you. A cursor that fails to parse means the format changed; drop it and poll
|
||||
again without one.
|
||||
|
||||
An empty poll returns your own cursor back, not an empty string.
|
||||
|
||||
### `GET /api/visits/stream` — server-sent events
|
||||
|
||||
The same rows, pushed. Send `Authorization` (so `EventSource` will not do —
|
||||
read the stream with an HTTP client) and resume with `Last-Event-ID` or
|
||||
`?cursor=`. Falls back to polling cleanly; the failure mode is latency, never
|
||||
silence.
|
||||
|
||||
---
|
||||
|
||||
## 6. Photos
|
||||
|
||||
**A missing photo is data, not an error.** Images are off by default across the
|
||||
whole product, so on most deployments every arrival legitimately has none. Show
|
||||
initials or a placeholder — a screen of red for a system working as configured
|
||||
is a screen whose real errors get ignored.
|
||||
|
||||
```json
|
||||
"image": { "available": false,
|
||||
"reason": "This system is not storing customer photos." }
|
||||
```
|
||||
|
||||
When a photo **is** available there are two kinds of URL, and the `auth` flag is
|
||||
how you tell them apart. Do not infer it from the shape of the URL.
|
||||
|
||||
| | `auth` | how to load it |
|
||||
|---|---|---|
|
||||
| presigned object-storage link | absent/false | use it directly; it carries its own signature and expires in `expires_in` seconds |
|
||||
| served by this API | `true` | send `Authorization: Bearer …` |
|
||||
|
||||
- **Mobile**: an image view can attach the header —
|
||||
`Image source={{ uri, headers: { Authorization: 'Bearer …' } }}`.
|
||||
- **Web**: an `<img>` cannot. Fetch it and use an object URL
|
||||
(`URL.createObjectURL`), and **revoke it** on unmount — a screen left open all
|
||||
afternoon otherwise holds hundreds of copies of the same photograph.
|
||||
|
||||
Prefix a relative URL with the base URL. Treat any relative URL as needing auth
|
||||
whether or not the flag is set: there is no public one.
|
||||
|
||||
### `GET /api/visitors/{id}/image`
|
||||
|
||||
The same `image` object for one customer's latest photo. 404 `no_image` (nothing
|
||||
captured) or 404 `images_disabled` (this deployment stores none) — two different
|
||||
absences, because a shop can act on one and not the other.
|
||||
|
||||
Every hand-out of a photo link is written to the audit log. **Fetch it once per
|
||||
screen**, not once per component: two components asking for the same face put
|
||||
two rows in *"who looked at my customers"* for one glance at one person.
|
||||
|
||||
---
|
||||
|
||||
## 7. Customers
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `GET /api/visitors?q=…` | search by name or phone |
|
||||
| `GET /api/visitors/{id}/history` | their past visits |
|
||||
| `PUT /api/visitors/{id}/profile` | name, phone, notes — staff and above |
|
||||
| `DELETE /api/visitors/{id}` | **erasure** — manager and above |
|
||||
| `POST /api/purchases` | link a sale to a visit |
|
||||
|
||||
Erasure destroys the face template and the photo outright and keeps the visit
|
||||
rows, unlinked. It is irreversible. If the photo cannot be deleted the whole
|
||||
request fails with **502** and *nothing* is erased — so an error there means the
|
||||
data is still there, and must be reported as a failure, never swallowed.
|
||||
|
||||
---
|
||||
|
||||
## 8. Shops, cameras, reports
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `GET /api/sites` | estate health: online, cameras up, `fraction_below_gate` |
|
||||
| `GET /api/sites/{id}/check` | five-step smoke test for one shop |
|
||||
| `GET /api/cameras` | cameras and their latest still |
|
||||
| `GET /api/cameras/{id}/live` | live view relayed from the shop PC (SSE) |
|
||||
| `GET /api/reports/footfall` | `?from=&to=&site=&tz=&bucket=` |
|
||||
| `GET /api/reports/conversion` | same parameters; revenue and basket size |
|
||||
|
||||
**The site parameter is spelled differently here.** Reports take `site`; the
|
||||
arrivals feed takes `site_id`. That is a wart, not a rule — but an unknown query
|
||||
parameter is silently ignored, so getting it wrong returns the whole estate
|
||||
rather than an error.
|
||||
|
||||
Dates are `YYYY-MM-DD`. `to` is **inclusive**: "1st to the 7th" includes the
|
||||
7th.
|
||||
|
||||
Two arithmetic traps the API is explicit about, so a client does not reinvent
|
||||
them wrongly:
|
||||
|
||||
- **`total` is unique people over the window; the chart does not sum to it.**
|
||||
Somebody who came Monday and Thursday is one person and two bucket-visitors.
|
||||
Show the server's `total`, with `visits` underneath.
|
||||
- **`new + returning` can be less than the total.** A site sending counts
|
||||
without templates records real footfall by an unidentified person, which
|
||||
belongs to neither.
|
||||
|
||||
Report buckets are **local wall time with no offset**, labelled by `timezone`.
|
||||
Do not parse them as a `Date` — the viewer's own zone would shift every label.
|
||||
|
||||
---
|
||||
|
||||
## 9. Errors
|
||||
|
||||
```json
|
||||
{ "error": "invalid_code", "message": "That invitation code is not valid. Ask for a new one." }
|
||||
```
|
||||
|
||||
`message` is written to be shown to a person; prefer it over inventing your own.
|
||||
`error` is the stable code to branch on — **never match on the prose**, which is
|
||||
rewritten freely.
|
||||
|
||||
| status | meaning |
|
||||
|---|---|
|
||||
| 400 | the request was wrong; `message` says how |
|
||||
| 401 | not signed in, or `token_expired` → refresh once and retry |
|
||||
| 403 | signed in, but this role may not |
|
||||
| 404 | not found — **also** what another tenant's data returns, always |
|
||||
| 409 | a conflict `message` explains (`last_owner`, duplicate address) |
|
||||
| 429 | throttled |
|
||||
| 501 | the feature is off for this deployment, not an error |
|
||||
| 502 | a downstream failure; for erasure it means **nothing was deleted** |
|
||||
|
||||
Roles, in increasing order: `staff` → `manager` → `owner`. A platform admin has
|
||||
`role: "admin"` **and an empty `client_id`** — the two together, never the role
|
||||
alone.
|
||||
198
CLAUDE.md
198
CLAUDE.md
@@ -2408,3 +2408,201 @@ not in normal running — but the margin is what makes `/api/health` reporting
|
||||
already holds **17 embeddings tagged `w600k_mbf` and 19 tagged `w600k_r50`**:
|
||||
proof that the fallback has silently fired before, and that model-tagging is
|
||||
what stopped it corrupting anything.
|
||||
|
||||
## Accounts: how a second person gets one (`invitations`, migration 010)
|
||||
|
||||
A tenant had exactly the users `provision user` had created on the server's
|
||||
command line. That is not a missing screen, it is a missing product: a shop with
|
||||
an owner and four staff either shared one password between five people or raised
|
||||
a support ticket per person, and **a phone app for shop-floor staff could not
|
||||
exist at all** while there was only ever one account to sign in as.
|
||||
|
||||
Registration is by **invitation**, never open signup — the same line
|
||||
`handlers_admin.go` already draws around creating a company. An endpoint a
|
||||
stranger can call to create an account is a far larger thing to secure than one
|
||||
reachable only through somebody who already has one.
|
||||
|
||||
```
|
||||
POST /api/team/invitations manager+ -> the code, ONCE
|
||||
GET /api/auth/invitation?code=… unauthenticated preview
|
||||
POST /api/auth/register unauthenticated -> a SESSION
|
||||
```
|
||||
|
||||
- **The code decides the address and the role; the request decides only the
|
||||
password and a display name.** A code gets forwarded, screenshotted and
|
||||
pasted into chat, so if the body could name either, one staff invitation would
|
||||
be an owner account for anybody who saw it. `decode` rejects unknown fields,
|
||||
so a client cannot even ask — verified live: `unknown field "role"` → 400.
|
||||
- **`register` returns a session, not a 201.** Sending somebody who chose a
|
||||
password four seconds ago to a sign-in form to type it again is the sort of
|
||||
thing that gets blamed on the password.
|
||||
- **Single use is enforced by the UPDATE** (`used_at IS NULL` and the write are
|
||||
one statement) and the account is created **in the same transaction**. A spent
|
||||
invitation with no user is unusable and invisible; a user with the invitation
|
||||
still open is a second account waiting for whoever else has the code. Same
|
||||
rule, same reason, as agent enrolment.
|
||||
- **Unknown, expired, spent and revoked read identically.** The difference only
|
||||
helps somebody guessing, and the holder's next step is the same in all four.
|
||||
- **`admin` is not an invitable role.** A platform administrator is defined by
|
||||
having *no* client, so an invitation — which always carries one — could never
|
||||
mint a real one. What it *could* do is create the tenant-scoped `role='admin'`
|
||||
row that `adminOnly` exists to reject, so it is refused at the constraint.
|
||||
- **A manager cannot mint an owner.** Promoting somebody past yourself is an
|
||||
escalation, and it is the shape of this endpoint that matters if a manager
|
||||
account is ever taken over.
|
||||
- A failed attempt (short password, mistyped code) does **not** spend the
|
||||
invitation. One typo must not cost somebody their invitation.
|
||||
|
||||
### Removing access has to mean now
|
||||
|
||||
`PATCH /api/team/{id}` with `{"active": false}` revokes every session that user
|
||||
holds **in the same transaction**. An access token lives twelve hours, so
|
||||
without that, "remove their access" removes it sometime tomorrow — which is not
|
||||
what anybody pressing that button believes they have just done.
|
||||
|
||||
`OwnerCount` refuses the change that locks a company out of itself: the last
|
||||
active owner may not demote or deactivate themselves. There is no way back from
|
||||
that except a shell on the server, which is precisely what this surface exists
|
||||
to stop needing.
|
||||
|
||||
### Devices: the benefit of opaque tokens, finally collected
|
||||
|
||||
`GET /api/auth/sessions`, `DELETE /api/auth/sessions/{id}`,
|
||||
`POST /api/auth/sessions/revoke-others`.
|
||||
|
||||
The argument for a session table over JWTs was always that this system puts
|
||||
customer data on shop-floor PCs and staff phones that get lost, resold and
|
||||
shared — so *"log that device out, now"* has to actually work. **Nothing could
|
||||
list what was signed in, let alone stop one.** The cost was being paid and the
|
||||
benefit was not being collected.
|
||||
|
||||
- A person may revoke only their **own** sessions; the store scopes the update
|
||||
by `user_id`, because a session id travels in that list and is not a secret.
|
||||
Removing a colleague's access is a different question with a different answer
|
||||
(deactivate them).
|
||||
- **"Sign out everywhere else" keeps the caller's own session.** Somebody who
|
||||
has just lost a phone must not also be signed out of the device they are
|
||||
holding while they deal with it.
|
||||
- `device` is a coarse label (`"Chrome on Mac"`), never a fingerprint. The
|
||||
question it answers is only *"which of these is the one in my hand"*.
|
||||
|
||||
## Face images without an object-storage bucket (`visit_faces`, migration 011)
|
||||
|
||||
009 did this for camera snapshots and its own comment says why face images are
|
||||
different: *"Face images grow with every visitor who ever walks in, which is why
|
||||
they stay in a bucket."* That is true of images kept **per visit**, and it is
|
||||
exactly why this table is bounded to **one row per visitor** instead.
|
||||
|
||||
The gap it closes is the one 009 closed a level up. With no bucket the API
|
||||
answered *"This system is not storing customer photos"* for every arrival,
|
||||
forever — including on the mobile feed, whose entire purpose is to put a face in
|
||||
front of somebody so they can recognise the customer walking towards them. Every
|
||||
local install and every self-hosted customer who does not want an S3 account got
|
||||
nothing.
|
||||
|
||||
```
|
||||
engine data/outbox/<uuid>.jpg (only when app.store_faces is on)
|
||||
agent POST /api/agent/upload-url -> 501 images_disabled
|
||||
POST /api/agent/faces -> {"key": "db:<uuid>"}
|
||||
server visits.image_key = 'db:…'
|
||||
staff GET /api/visits -> {"image":{"available":true,
|
||||
"url":"/api/faces/<uuid>.jpg",
|
||||
"auth":true}}
|
||||
```
|
||||
|
||||
What makes this acceptable in Postgres when per-visit images are not:
|
||||
|
||||
- **The engine still gates capture.** `app.store_faces` is false by default and
|
||||
no crop is written without it. This changes what happens to an image that
|
||||
already exists; it does not change whether one is taken.
|
||||
- **One row survives per visitor.** `RecordVisit` prunes the previous row as it
|
||||
links a newer one, so storage is (customers × ~20 KB) — it grows with the
|
||||
customer base, not with footfall. A shop seen by 5,000 people holds ~100 MB
|
||||
whether they visit once or a thousand times.
|
||||
- **Nothing reads a superseded face anyway.** Every surface shows the customer's
|
||||
latest view, which is what `VisitorImageKey` has always returned.
|
||||
- **Orphans are swept.** An agent uploads before the server has decided who the
|
||||
person is, so a row is briefly unreferenced by design — and permanently so if
|
||||
the visit that would have claimed it never arrives. That is a stored
|
||||
photograph of a real person that erasure could never reach, because erasure
|
||||
finds images through the visitor and this row has none.
|
||||
|
||||
The bucket stays primary wherever one exists: a presigned PUT never passes the
|
||||
bytes through the API at all, which is what makes it the right route at estate
|
||||
scale. The fallback is chosen by the **sentinel** `bridge.ErrImagesOff`, never
|
||||
by matching a message — getting that wrong from prose somebody later rewords
|
||||
would silently stop every customer photo in the estate. Same rule the camera
|
||||
snapshot fallback already follows.
|
||||
|
||||
### `UPDATE … RETURNING` returns the value AFTER the update
|
||||
|
||||
The prune's first version read the superseded keys with
|
||||
`UPDATE visits SET image_key = '' … RETURNING image_key`. Postgres returns the
|
||||
**new** row, so every key came back as the empty string it had just been set to,
|
||||
the delete list was always empty, and `visit_faces` grew with footfall exactly
|
||||
as if the prune did not exist. The visit rows looked perfectly correct; only the
|
||||
row count gave it away.
|
||||
|
||||
It is one CTE now — `doomed` reads the pre-image and drives both the update and
|
||||
the delete — which cannot have that bug. **The in-memory fake would have agreed
|
||||
with either version**; only `TestLiveOnlyOneFaceSurvivesPerVisitor` against a
|
||||
real Postgres caught it, which is the whole reason the live store tests exist.
|
||||
|
||||
### `Image.auth`, and one function that decides where a photo is
|
||||
|
||||
`s.imageFor(key)` is the single place that turns a stored key into the `Image` a
|
||||
client receives — the arrivals feed, the live stream and the customer record all
|
||||
go through it. There are now two places an image can live and four distinct
|
||||
reasons there may not be one, and computing that twice is how the shops screen
|
||||
once ended up labelled **Working** in green directly above *"2 of 3 cameras not
|
||||
connecting"*.
|
||||
|
||||
`auth: true` says the URL is one of ours and needs the session's bearer, rather
|
||||
than a presigned link carrying its own signature. It exists because the two are
|
||||
genuinely different to fetch and **a client cannot tell them apart by looking**:
|
||||
|
||||
- A browser `<img>` **cannot** load the authenticated one — no header — so the
|
||||
web app fetches it and hands over an object URL (`Shot.jsx`).
|
||||
- A **mobile** image view *can* attach the header and load it directly.
|
||||
- The **desktop** webview can do neither: a relative src resolves against
|
||||
`wails://`, not the cloud. `cloud.VisitorImage` therefore fetches the bytes in
|
||||
Go, where the session already lives, and returns a `data:` URI. The
|
||||
alternative — a local proxy inside the app holding the session — is a second
|
||||
authenticated surface on a shop PC to get wrong.
|
||||
|
||||
**Both signals are accepted, and that is not belt-and-braces.** A relative URL
|
||||
always needs the session; there is no public one. Trusting only the flag broke
|
||||
every shop card the moment `Sites.jsx`'s `bestView()` rebuilt a partial
|
||||
`{url, at}` copy and dropped it — found by opening the page, not by a test. The
|
||||
flag adds only the case a URL cannot express: an absolute link that still needs
|
||||
a bearer, which arrives the first time object storage is served from this host.
|
||||
|
||||
The bytes endpoint writes **no audit row**. Every read of a face is recorded
|
||||
where the *link* is handed out — one row per arrivals page, one per customer
|
||||
record — and the bucket route's bytes never touch this server, so counting the
|
||||
fetch as well would count one deployment twice and the other once.
|
||||
|
||||
`ago()` clamps at zero and renders a future timestamp as *"just now"*. That is
|
||||
right for a heartbeat whose clock runs slightly ahead and completely wrong for
|
||||
an expiry: a code valid for a week read *"expires just now"*, which tells the
|
||||
operator not to bother handing it over. `until()` is its opposite number.
|
||||
|
||||
### Verified live, 5 September 2026
|
||||
|
||||
Against real Postgres, on the demo tenant:
|
||||
|
||||
- Owner invites a staff member → code minted once → unauthenticated preview
|
||||
names the company, address and role → a body naming `role` or `email` is
|
||||
refused → proper redemption returns a **signed-in session** → replay 404s.
|
||||
- Staff can read arrivals, shops and the team; **cannot** invite (403).
|
||||
- Two devices listed, the calling one marked `current`; revoking the phone 401s
|
||||
its token immediately while the till keeps working.
|
||||
- Deactivating a member 401s their live session **at once**, and they cannot
|
||||
sign back in. The only owner cannot demote themselves (409 `last_owner`).
|
||||
- Agent enrols → `upload-url` answers **501 images_disabled** → falls back to
|
||||
`POST /api/agent/faces` → a 92,405-byte office-camera JPEG stored in Postgres,
|
||||
served as `image/jpeg` to the owner, **401 with no session**, **404 to another
|
||||
tenant**, and rendered in the arrivals feed avatar in a real browser.
|
||||
- HTML, PDF, GIF and empty bodies are all refused as face images: the check is
|
||||
on the magic bytes, never the `Content-Type` header, because this endpoint
|
||||
stores what it is handed and serves it back to a browser.
|
||||
|
||||
@@ -106,6 +106,18 @@ func (u *SpacesUploader) UploadBytes(ctx context.Context, body []byte) (string,
|
||||
}
|
||||
|
||||
target, err := u.target(ctx)
|
||||
if errors.Is(err, ErrImagesOff) {
|
||||
// No object storage on this server. Send the bytes to the API itself,
|
||||
// which holds them for a deployment that has no bucket - the same
|
||||
// fallback camera snapshots already take, and chosen by the SENTINEL
|
||||
// rather than by matching the message, because a prose change would
|
||||
// otherwise silently stop every photo in the estate.
|
||||
//
|
||||
// Only after target() has spoken. The unclaimed case returns the same
|
||||
// sentinel from the guard at the top of this function, and a PC with no
|
||||
// credentials has no server to PUT to either.
|
||||
return u.uploadDirect(ctx, body)
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -135,6 +147,54 @@ func (u *SpacesUploader) UploadBytes(ctx context.Context, body []byte) (string,
|
||||
return target.Key, nil
|
||||
}
|
||||
|
||||
// uploadDirect posts the image to our own API, for a deployment with no bucket.
|
||||
//
|
||||
// Deliberately the second choice. A presigned PUT never passes a photograph
|
||||
// through the server at all, which is what makes it the right route wherever
|
||||
// object storage exists; this one is what stops "no S3 account" from meaning
|
||||
// "no customer photo, ever" on every local install and every self-hosted site.
|
||||
//
|
||||
// The server decides where it lands and returns the key, exactly as the
|
||||
// presigned route does. That symmetry is the point: the caller cannot tell
|
||||
// which route ran, so the queued visit, the read path and erasure all stay
|
||||
// single implementations.
|
||||
func (u *SpacesUploader) uploadDirect(ctx context.Context, body []byte) (string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
|
||||
strings.TrimRight(u.BaseURL, "/")+"/api/agent/faces", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+u.Token)
|
||||
req.Header.Set("Content-Type", "image/jpeg")
|
||||
req.ContentLength = int64(len(body))
|
||||
|
||||
resp, err := u.httpClient().Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("upload face: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode == http.StatusNotImplemented {
|
||||
// This server stores no images at all. Stop trying rather than retry
|
||||
// every visitor forever.
|
||||
return "", ErrImagesOff
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
|
||||
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
|
||||
return "", fmt.Errorf("upload face returned %s: %s",
|
||||
resp.Status, strings.TrimSpace(string(msg)))
|
||||
}
|
||||
var out struct {
|
||||
Key string `json:"key"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, 8<<10)).Decode(&out); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if out.Key == "" {
|
||||
return "", errors.New("server stored the face but named no key for it")
|
||||
}
|
||||
return out.Key, nil
|
||||
}
|
||||
|
||||
func (u *SpacesUploader) target(ctx context.Context) (uploadTarget, error) {
|
||||
var out uploadTarget
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package bridge
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -200,3 +201,80 @@ func TestNoUploaderMeansNoImageAndNoLeftovers(t *testing.T) {
|
||||
t.Fatal("the local image was left on disk")
|
||||
}
|
||||
}
|
||||
|
||||
// A deployment with no object storage must still get a photo onto the customer
|
||||
// record. Until the fallback existed, `images_disabled` meant every local
|
||||
// install and every self-hosted site showed no face for anybody, forever.
|
||||
func TestNoBucketFallsBackToTheServer(t *testing.T) {
|
||||
var askedURL, postedFace bool
|
||||
var gotBody []byte
|
||||
var gotAuth, gotType string
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/agent/upload-url":
|
||||
askedURL = true
|
||||
// What a server with no bucket answers.
|
||||
w.WriteHeader(http.StatusNotImplemented)
|
||||
_, _ = w.Write([]byte(`{"error":"images_disabled"}`))
|
||||
case "/api/agent/faces":
|
||||
postedFace = true
|
||||
gotAuth = r.Header.Get("Authorization")
|
||||
gotType = r.Header.Get("Content-Type")
|
||||
gotBody, _ = io.ReadAll(r.Body)
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = w.Write([]byte(`{"key":"db:11111111-1111-4111-8111-111111111111"}`))
|
||||
default:
|
||||
t.Errorf("unexpected request to %s", r.URL.Path)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
u := &SpacesUploader{BaseURL: srv.URL, Token: "agent-token", Client: srv.Client()}
|
||||
img := []byte{0xFF, 0xD8, 0xFF, 0xE0, 'x', 'y', 'z'}
|
||||
key, err := u.UploadBytes(context.Background(), img)
|
||||
if err != nil {
|
||||
t.Fatalf("upload: %v", err)
|
||||
}
|
||||
if !askedURL {
|
||||
t.Error("the presigned route must be tried first - it is the right one where a bucket exists")
|
||||
}
|
||||
if !postedFace {
|
||||
t.Fatal("no fallback upload was made")
|
||||
}
|
||||
if !strings.HasPrefix(key, "db:") {
|
||||
t.Errorf("want the server's own key, got %q", key)
|
||||
}
|
||||
if !bytes.Equal(gotBody, img) {
|
||||
t.Error("the bytes sent are not the bytes given")
|
||||
}
|
||||
if gotAuth != "Bearer agent-token" || gotType != "image/jpeg" {
|
||||
t.Errorf("auth %q type %q", gotAuth, gotType)
|
||||
}
|
||||
}
|
||||
|
||||
// A server that stores no images AT ALL must stop the agent trying, rather than
|
||||
// have it retry every visitor forever. Distinct from a failure, which is why
|
||||
// it is a sentinel and not a message.
|
||||
func TestAServerThatStoresNothingSaysSoOnce(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotImplemented)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
u := &SpacesUploader{BaseURL: srv.URL, Token: "agent-token", Client: srv.Client()}
|
||||
_, err := u.UploadBytes(context.Background(), []byte{0xFF, 0xD8, 0xFF, 0xE0})
|
||||
if !errors.Is(err, ErrImagesOff) {
|
||||
t.Fatalf("want ErrImagesOff so the caller stops trying, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// An unclaimed PC has no server to send anything to. The fallback must not fire
|
||||
// there - it would be a request to nowhere on every single visit.
|
||||
func TestAnUnclaimedAgentDoesNotTryToUpload(t *testing.T) {
|
||||
u := &SpacesUploader{} // no BaseURL, no token
|
||||
if _, err := u.UploadBytes(context.Background(), []byte{0xFF, 0xD8}); !errors.Is(err, ErrImagesOff) {
|
||||
t.Fatalf("want ErrImagesOff, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ package cloud
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -393,6 +394,11 @@ type Photo struct {
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
Available bool `json:"available"`
|
||||
Reason string `json:"reason"`
|
||||
// Auth is set by the server when the URL is one of its own endpoints and
|
||||
// needs this session's bearer, rather than a presigned object-store link
|
||||
// that carries its own signature. It never reaches the front end - see
|
||||
// VisitorImage, which resolves it here.
|
||||
Auth bool `json:"auth"`
|
||||
}
|
||||
|
||||
// VisitorImage fetches a short-lived signed link to this customer's photo.
|
||||
@@ -413,9 +419,91 @@ func (c *Client) VisitorImage(ctx context.Context, id string) (Photo, error) {
|
||||
return Photo{}, err
|
||||
}
|
||||
out.Available = out.URL != ""
|
||||
|
||||
// A deployment with no object storage serves the photo from the API itself,
|
||||
// which means a RELATIVE url that needs this session's bearer. Neither
|
||||
// works in the window: a webview <img> resolves a relative src against
|
||||
// wails://, not against the cloud, and it cannot send an Authorization
|
||||
// header at all - so handing it straight through renders a broken picture
|
||||
// on exactly the deployments that have just started storing photos.
|
||||
//
|
||||
// Fetched here and passed as a data: URI. The alternative is a local proxy
|
||||
// inside this process holding the session, which is a second authenticated
|
||||
// surface on the shop PC to get wrong. One photo per sheet, ~90 KB, and the
|
||||
// server already records the read where the link was handed out.
|
||||
if out.Available && out.Auth {
|
||||
data, err := c.fetchImage(ctx, out.URL)
|
||||
if err != nil {
|
||||
// The record itself is worth far more than the picture, so this is
|
||||
// an absence with a reason rather than a failure that blanks the
|
||||
// customer - the same rule the whole image path follows.
|
||||
return Photo{Reason: "That photo could not be loaded."}, nil
|
||||
}
|
||||
out.URL = data
|
||||
out.Auth = false
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// fetchImage reads an image this server holds itself and returns a data: URI.
|
||||
//
|
||||
// Deliberately not routed through send(): that decodes JSON into `out`, and
|
||||
// these are bytes. It shares the token and the expiry retry, because a sheet
|
||||
// opened twelve hours after the last one must not show a broken photo.
|
||||
func (c *Client) fetchImage(ctx context.Context, path string) (string, error) {
|
||||
body, err := c.imageBytes(ctx, path)
|
||||
if errors.Is(err, errTokenExpired) {
|
||||
if rerr := c.Refresh(ctx); rerr != nil {
|
||||
return "", rerr
|
||||
}
|
||||
body, err = c.imageBytes(ctx, path)
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(body), nil
|
||||
}
|
||||
|
||||
// maxPhotoBytes bounds what will be pulled into memory and then base64'd into
|
||||
// the window. Face crops are ~20 KB and a camera still ~100 KB; anything near
|
||||
// this is a different file or a fault, and a shop PC should not spend its
|
||||
// memory finding that out.
|
||||
const maxPhotoBytes = 4 << 20
|
||||
|
||||
func (c *Client) imageBytes(ctx context.Context, path string) ([]byte, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.Base+path, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.mu.RLock()
|
||||
tok := c.token
|
||||
c.mu.RUnlock()
|
||||
if tok != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cannot reach %s: %w", c.Base, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusUnauthorized {
|
||||
var e struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 8192))
|
||||
_ = json.Unmarshal(body, &e)
|
||||
if e.Error == "token_expired" {
|
||||
return nil, errTokenExpired
|
||||
}
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
if resp.StatusCode >= 400 {
|
||||
return nil, fmt.Errorf("photo: %s", resp.Status)
|
||||
}
|
||||
return io.ReadAll(io.LimitReader(resp.Body, maxPhotoBytes))
|
||||
}
|
||||
|
||||
// ForgetVisitor erases a customer: face template, photo and profile.
|
||||
//
|
||||
// Irreversible by design — a soft-deleted face template is a retained
|
||||
|
||||
@@ -42,6 +42,27 @@ type Store interface {
|
||||
SessionByRefresh(ctx context.Context, hash []byte) (auth.Principal, time.Time, error)
|
||||
RotateSession(ctx context.Context, sessionID string, s NewSession) error
|
||||
RevokeSession(ctx context.Context, sessionID string) error
|
||||
// Which devices are signed in, and signing one of them out. This is what
|
||||
// an opaque-token session table buys over a JWT, and until these existed
|
||||
// the product paid the cost of that choice without the benefit.
|
||||
UserSessions(ctx context.Context, userID string) ([]DeviceSession, error)
|
||||
RevokeUserSession(ctx context.Context, userID, sessionID string) error
|
||||
RevokeOtherSessions(ctx context.Context, userID, keepSessionID string) (int, error)
|
||||
|
||||
// --- team and invitations ---
|
||||
// Registration is by invitation: the code carries the address and the role
|
||||
// so neither can be chosen by whoever redeems it.
|
||||
CreateInvitation(ctx context.Context, in NewInvitation) (Invitation, error)
|
||||
PendingInvitations(ctx context.Context, clientID string) ([]Invitation, error)
|
||||
RevokeInvitation(ctx context.Context, clientID, id string) error
|
||||
InvitationByCode(ctx context.Context, hash []byte) (InvitationPreview, error)
|
||||
// RedeemInvitation spends the code and creates the account in ONE
|
||||
// transaction: a spent invitation with no user behind it is unusable, and a
|
||||
// user with the invitation still open is a second account waiting for
|
||||
// whoever else was forwarded the code.
|
||||
RedeemInvitation(ctx context.Context, hash []byte, fullName, passwordHash string) (UserRecord, error)
|
||||
Team(ctx context.Context, clientID string) ([]TeamMember, error)
|
||||
UpdateTeamMember(ctx context.Context, clientID, userID string, up TeamUpdate) (TeamMember, error)
|
||||
|
||||
// --- reports ---
|
||||
Footfall(ctx context.Context, q ReportQuery) ([]FootfallPoint, Totals, error)
|
||||
@@ -98,6 +119,11 @@ type Store interface {
|
||||
AgentByToken(ctx context.Context, hash []byte) (AgentPrincipal, error)
|
||||
|
||||
// --- images ---
|
||||
// Face images held by this server, for a deployment with no object
|
||||
// storage. Where a bucket is configured none of these three is called.
|
||||
PutVisitFace(ctx context.Context, clientID, siteID string, jpeg []byte) (string, error)
|
||||
VisitFace(ctx context.Context, clientID, key string) ([]byte, error)
|
||||
DeleteVisitFaces(ctx context.Context, clientID string, keys []string) error
|
||||
VisitorImageKey(ctx context.Context, clientID, visitorID string) (string, error)
|
||||
VisitorImageKeys(ctx context.Context, clientID, visitorID string) ([]string, error)
|
||||
ForgetVisitor(ctx context.Context, clientID, visitorID string) error
|
||||
@@ -196,6 +222,26 @@ func (s *Server) Routes() *http.ServeMux {
|
||||
mux.HandleFunc("POST /api/auth/refresh", s.handleRefresh)
|
||||
mux.HandleFunc("POST /api/auth/logout", s.authed(s.handleLogout))
|
||||
mux.HandleFunc("GET /api/auth/me", s.authed(s.handleMe))
|
||||
// Registration. Unauthenticated for the same reason agent enrolment is:
|
||||
// whoever is doing this has no account yet, and requiring one first would
|
||||
// mean shipping a password to everybody who needs one.
|
||||
mux.HandleFunc("GET /api/auth/invitation", s.handleInvitationPreview)
|
||||
mux.HandleFunc("POST /api/auth/register", s.handleRegister)
|
||||
// Devices. A person may list and revoke their own sessions; removing a
|
||||
// colleague's access is a different question, answered by deactivating them
|
||||
// on the team endpoint below.
|
||||
mux.HandleFunc("GET /api/auth/sessions", s.authed(s.handleSessions))
|
||||
mux.HandleFunc("DELETE /api/auth/sessions/{id}", s.authed(s.handleRevokeSession))
|
||||
mux.HandleFunc("POST /api/auth/sessions/revoke-others",
|
||||
s.authed(s.handleRevokeOtherSessions))
|
||||
|
||||
// --- the people who work here ---
|
||||
mux.HandleFunc("GET /api/team", s.authed(s.handleTeam))
|
||||
mux.HandleFunc("PATCH /api/team/{id}", s.authed(s.handleUpdateTeamMember))
|
||||
mux.HandleFunc("GET /api/team/invitations", s.authed(s.handleInvitations))
|
||||
mux.HandleFunc("POST /api/team/invitations", s.authed(s.handleInvite))
|
||||
mux.HandleFunc("DELETE /api/team/invitations/{id}",
|
||||
s.authed(s.handleRevokeInvitation))
|
||||
|
||||
mux.HandleFunc("GET /api/reports/footfall", s.authed(s.handleFootfall))
|
||||
mux.HandleFunc("GET /api/reports/conversion", s.authed(s.handleConversion))
|
||||
@@ -250,6 +296,8 @@ func (s *Server) Routes() *http.ServeMux {
|
||||
mux.HandleFunc("POST /api/agent/enrol", s.handleEnrol)
|
||||
// Authenticated by the agent's own API token, not a user session.
|
||||
mux.HandleFunc("POST /api/agent/upload-url", s.agentAuthed(s.handleUploadURL))
|
||||
// The fallback the agent takes when upload-url answers images_disabled.
|
||||
mux.HandleFunc("POST /api/agent/faces", s.agentAuthed(s.handlePutFace))
|
||||
// What this shop PC should be running, and what it reports back.
|
||||
mux.HandleFunc("GET /api/agent/cameras", s.agentAuthed(s.handleAgentCameras))
|
||||
mux.HandleFunc("POST /api/agent/cameras", s.agentAuthed(s.handleAgentCameraReport))
|
||||
@@ -262,6 +310,11 @@ func (s *Server) Routes() *http.ServeMux {
|
||||
mux.HandleFunc("POST /api/agent/checks", s.agentAuthed(s.handleAgentCheckResult))
|
||||
|
||||
mux.HandleFunc("GET /api/visitors/{id}/image", s.authed(s.handleVisitorImage))
|
||||
// The bytes of a face this server holds itself. Session-authenticated
|
||||
// rather than a signed link: there is no third party to delegate to, and an
|
||||
// unauthenticated URL would be a way to reach a customer's photograph with
|
||||
// no session at all.
|
||||
mux.HandleFunc("GET /api/faces/{id}", s.authed(s.handleGetFace))
|
||||
// The erasure path. Destroys the template and the photo; keeps the
|
||||
// anonymous visit counts, which are legitimate aggregate data.
|
||||
mux.HandleFunc("DELETE /api/visitors/{id}", s.authed(s.handleForgetVisitor))
|
||||
|
||||
@@ -200,6 +200,11 @@ func TestNoPhotoIsDataNotAnError(t *testing.T) {
|
||||
s.Blob = nil
|
||||
seedUser(fs)
|
||||
seedArrivals(fs, 1)
|
||||
// No key, because that is what this deployment actually produces: the
|
||||
// engine's `app.store_faces` is off, so no crop is ever captured and no
|
||||
// key is ever written. A bucket key on a server with no bucket is a
|
||||
// different state entirely and gets its own sentence below.
|
||||
fs.arrivals[0].ImageKey = ""
|
||||
sess := login(t, s, "manager@acme.com", "correct horse battery")
|
||||
|
||||
page := getPage(t, s, "/api/visits", sess.Token)
|
||||
@@ -212,6 +217,54 @@ func TestNoPhotoIsDataNotAnError(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
// Three absences now, not two: face images may live in a bucket OR in this
|
||||
// database, so "there is no bucket" stopped being a synonym for "there are
|
||||
// no photos" the moment the fallback existed.
|
||||
t.Run("a bucket key on a server that has lost its bucket", func(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
s.Blob = nil
|
||||
seedUser(fs)
|
||||
seedArrivals(fs, 1) // seeded with an object-store key
|
||||
sess := login(t, s, "manager@acme.com", "correct horse battery")
|
||||
|
||||
page := getPage(t, s, "/api/visits", sess.Token)
|
||||
got := page.Arrivals[0].Image
|
||||
if got.Available {
|
||||
t.Fatalf("nothing can be served without the bucket, got %+v", got)
|
||||
}
|
||||
// Deliberately NOT "we store no photos". The photo exists and this
|
||||
// server can no longer reach it, which is a configuration fault
|
||||
// somebody can fix - and reporting it as an ordinary empty record is
|
||||
// how it would go unnoticed for a year.
|
||||
if !strings.Contains(got.Reason, "no longer reach") {
|
||||
t.Errorf("want a configuration reason, got %q", got.Reason)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a face this server holds itself", func(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
s.Blob = nil // no object storage anywhere
|
||||
seedUser(fs)
|
||||
seedArrivals(fs, 1)
|
||||
fs.arrivals[0].ImageKey = "db:00000000-0000-4000-b000-000000000001"
|
||||
sess := login(t, s, "manager@acme.com", "correct horse battery")
|
||||
|
||||
page := getPage(t, s, "/api/visits", sess.Token)
|
||||
got := page.Arrivals[0].Image
|
||||
if !got.Available {
|
||||
t.Fatalf("a stored face should be offered, got %+v", got)
|
||||
}
|
||||
// Auth is what tells a client this URL needs the session bearer. A
|
||||
// browser <img> cannot load it and a mobile image view can, and there
|
||||
// is nothing in the URL itself that says so.
|
||||
if !got.Auth {
|
||||
t.Error("a face held by this server must be marked as needing auth")
|
||||
}
|
||||
if strings.Contains(got.URL, "db:") {
|
||||
t.Errorf("the storage key leaked into the URL: %q", got.URL)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("this visit simply had none", func(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
s.Blob = &fakeBlob{}
|
||||
|
||||
230
server/internal/api/faces_test.go
Normal file
230
server/internal/api/faces_test.go
Normal file
@@ -0,0 +1,230 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Face images held by this server, for a deployment with no object storage.
|
||||
//
|
||||
// The property under test throughout is that the two storage routes differ in
|
||||
// exactly one hop: the key is minted differently and everything downstream -
|
||||
// ingest, the feed, the customer record, erasure - is one implementation.
|
||||
|
||||
func putFace(t *testing.T, srv *Server, token string, body []byte) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
rr := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/agent/faces", bytes.NewReader(body))
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
srv.Routes().ServeHTTP(rr, req)
|
||||
return rr
|
||||
}
|
||||
|
||||
func TestAnAgentStoresAFaceAndAPersonReadsItBack(t *testing.T) {
|
||||
srv, fs := newServer(t)
|
||||
srv.Blob = nil // no object storage anywhere: the case this exists for
|
||||
fs.addAgent("agent-token", AgentPrincipal{ClientID: "client-acme", SiteID: "site-1"})
|
||||
seedUser(fs)
|
||||
|
||||
img := jpegBytes(512)
|
||||
rr := putFace(t, srv, "agent-token", img)
|
||||
if rr.Code != http.StatusCreated {
|
||||
t.Fatalf("upload: %d %s", rr.Code, rr.Body)
|
||||
}
|
||||
var out struct {
|
||||
Key string `json:"key"`
|
||||
}
|
||||
if err := json.Unmarshal(rr.Body.Bytes(), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A prefixed key, so `visits.image_key` can name an object in either store
|
||||
// and the read path can tell which without a second lookup.
|
||||
if !strings.HasPrefix(out.Key, "db:") {
|
||||
t.Fatalf("want a db: key, got %q", out.Key)
|
||||
}
|
||||
// The tenant and the site come from the AGENT's credential, never the
|
||||
// request, so a shop PC cannot file an image under another company.
|
||||
if fs.lastFaceClient != "client-acme" || fs.lastFaceSite != "site-1" {
|
||||
t.Fatalf("stored against %s/%s", fs.lastFaceClient, fs.lastFaceSite)
|
||||
}
|
||||
|
||||
sess := login(t, srv, "manager@acme.com", "correct horse battery")
|
||||
rec := do(t, srv, "GET", faceURL(out.Key), sess.Token, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("read back: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := rec.Header().Get("Content-Type"); got != "image/jpeg" {
|
||||
t.Errorf("content type %q", got)
|
||||
}
|
||||
if !bytes.Equal(rec.Body.Bytes(), img) {
|
||||
t.Error("the bytes that came back are not the ones that went in")
|
||||
}
|
||||
}
|
||||
|
||||
// This endpoint stores what it is handed and serves it back to a browser, so
|
||||
// the one thing it must not become is a way to park arbitrary content under a
|
||||
// URL this server will serve. Checked against the bytes, never the header.
|
||||
func TestOnlyAJPEGIsStoredAsAFace(t *testing.T) {
|
||||
srv, fs := newServer(t)
|
||||
fs.addAgent("agent-token", AgentPrincipal{ClientID: "client-acme", SiteID: "site-1"})
|
||||
|
||||
for _, body := range []string{
|
||||
"<html><script>alert(1)</script></html>",
|
||||
"GIF89a",
|
||||
"%PDF-1.4",
|
||||
"",
|
||||
} {
|
||||
rr := putFace(t, srv, "agent-token", []byte(body))
|
||||
if rr.Code == http.StatusCreated {
|
||||
t.Errorf("accepted %q as a face image", body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFaceIsNotReadableWithoutASession(t *testing.T) {
|
||||
srv, fs := newServer(t)
|
||||
fs.addAgent("agent-token", AgentPrincipal{ClientID: "client-acme", SiteID: "site-1"})
|
||||
rr := putFace(t, srv, "agent-token", jpegBytes(64))
|
||||
var out struct {
|
||||
Key string `json:"key"`
|
||||
}
|
||||
_ = json.Unmarshal(rr.Body.Bytes(), &out)
|
||||
|
||||
// The reason it is session-authenticated rather than a signed link: there
|
||||
// is no third party to delegate to, and an unauthenticated URL would be a
|
||||
// way to reach a customer's photograph with no session at all.
|
||||
if rec := do(t, srv, "GET", faceURL(out.Key), "", nil); rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("a face was served with no session, got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnotherTenantCannotReadYourStoredFace(t *testing.T) {
|
||||
srv, fs := newServer(t)
|
||||
fs.addAgent("acme-agent", AgentPrincipal{ClientID: "client-acme", SiteID: "site-1"})
|
||||
seedUser(fs)
|
||||
fs.addUser("other@beta.com", "correct horse battery", UserRecord{
|
||||
ID: "u2", ClientID: "client-beta", ClientName: "Beta Ltd",
|
||||
FullName: "Bo", Role: "manager", Active: true,
|
||||
})
|
||||
|
||||
rr := putFace(t, srv, "acme-agent", jpegBytes(64))
|
||||
var out struct {
|
||||
Key string `json:"key"`
|
||||
}
|
||||
_ = json.Unmarshal(rr.Body.Bytes(), &out)
|
||||
|
||||
// An image key travels in API responses, so a caller who kept one - or
|
||||
// guessed one - must get nothing rather than somebody else's customer.
|
||||
beta := login(t, srv, "other@beta.com", "correct horse battery")
|
||||
if rec := do(t, srv, "GET", faceURL(out.Key), beta.Token, nil); rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("another tenant read a stored face, got %d", rec.Code)
|
||||
}
|
||||
acme := login(t, srv, "manager@acme.com", "correct horse battery")
|
||||
if rec := do(t, srv, "GET", faceURL(out.Key), acme.Token, nil); rec.Code != http.StatusOK {
|
||||
t.Fatalf("the owning tenant could not read its own face, got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// The customer record has to work on a deployment with no bucket too - it is
|
||||
// the screen staff use to recognise the person in front of them.
|
||||
func TestTheCustomerPhotoWorksWithNoObjectStorage(t *testing.T) {
|
||||
srv, fs := newServer(t)
|
||||
srv.Blob = nil
|
||||
fs.addAgent("agent-token", AgentPrincipal{ClientID: "client-acme", SiteID: "site-1"})
|
||||
seedUser(fs)
|
||||
|
||||
rr := putFace(t, srv, "agent-token", jpegBytes(64))
|
||||
var up struct {
|
||||
Key string `json:"key"`
|
||||
}
|
||||
_ = json.Unmarshal(rr.Body.Bytes(), &up)
|
||||
const visitor = "44444444-4444-4444-8444-444444444444"
|
||||
fs.imageKeys[visitor] = up.Key
|
||||
|
||||
sess := login(t, srv, "manager@acme.com", "correct horse battery")
|
||||
rec := do(t, srv, "GET", "/api/visitors/"+visitor+"/image", sess.Token, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("customer photo: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var img Image
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &img); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !img.Available || !img.Auth {
|
||||
t.Fatalf("want an available image that needs the session, got %+v", img)
|
||||
}
|
||||
// The storage key names a tenant's prefix and must never be what a client
|
||||
// receives, on either route.
|
||||
if strings.Contains(rec.Body.String(), "db:") {
|
||||
t.Errorf("the storage key leaked: %s", rec.Body.String())
|
||||
}
|
||||
// Reading a face is worth an audit row wherever the LINK is handed out.
|
||||
// Recorded here rather than at the byte fetch, because the bucket route's
|
||||
// bytes never touch this server and the two must be counted the same way.
|
||||
if !audited(fs, "image.view") {
|
||||
t.Error("reading a customer photo left no audit row")
|
||||
}
|
||||
}
|
||||
|
||||
func audited(fs *fakeStore, action string) bool {
|
||||
fs.mu.Lock()
|
||||
defer fs.mu.Unlock()
|
||||
for _, a := range fs.audits {
|
||||
if a.Action == action {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Erasure has to destroy an image this server holds, not only one in a bucket.
|
||||
// A face image that survives an erasure request is the one outcome that
|
||||
// endpoint must never produce.
|
||||
func TestErasureDestroysAStoredFace(t *testing.T) {
|
||||
srv, fs := newServer(t)
|
||||
srv.Blob = nil
|
||||
fs.addAgent("agent-token", AgentPrincipal{ClientID: "client-acme", SiteID: "site-1"})
|
||||
seedUser(fs)
|
||||
|
||||
rr := putFace(t, srv, "agent-token", jpegBytes(64))
|
||||
var up struct {
|
||||
Key string `json:"key"`
|
||||
}
|
||||
_ = json.Unmarshal(rr.Body.Bytes(), &up)
|
||||
const visitor = "55555555-5555-4555-8555-555555555555"
|
||||
fs.imageKeys[visitor] = up.Key
|
||||
|
||||
sess := login(t, srv, "manager@acme.com", "correct horse battery")
|
||||
if rec := do(t, srv, "DELETE", "/api/visitors/"+visitor, sess.Token, nil); rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("erase: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := do(t, srv, "GET", faceURL(up.Key), sess.Token, nil); rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("the face survived erasure, got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// If the image cannot be destroyed, NOTHING is erased and the caller is told.
|
||||
// Reporting a legal request as honoured when it was not is the failure this
|
||||
// path exists to prevent.
|
||||
func TestAFailedFaceDeleteAbortsTheWholeErasure(t *testing.T) {
|
||||
srv, fs := newServer(t)
|
||||
srv.Blob = nil
|
||||
seedUser(fs)
|
||||
const visitor = "66666666-6666-4666-8666-666666666666"
|
||||
fs.imageKeys[visitor] = "db:66666666-6666-4666-8666-666666666666"
|
||||
fs.faceDeleteErr = errors.New("storage is down")
|
||||
|
||||
sess := login(t, srv, "manager@acme.com", "correct horse battery")
|
||||
rec := do(t, srv, "DELETE", "/api/visitors/"+visitor, sess.Token, nil)
|
||||
if rec.Code != http.StatusBadGateway {
|
||||
t.Fatalf("want 502 and nothing erased, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if len(fs.forgotten) != 0 {
|
||||
t.Fatalf("the record was erased even though the photo could not be: %v", fs.forgotten)
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -70,6 +71,14 @@ type fakeStore struct {
|
||||
lastCheckKind string
|
||||
lastCheckSeconds int
|
||||
|
||||
// Invitations, and the faces this server holds itself.
|
||||
invites map[string]*fakeInvite // by code hash hex
|
||||
faces map[string][]byte // "client/id"
|
||||
lastFaceClient string
|
||||
lastFaceSite string
|
||||
deletedFaces []string
|
||||
faceDeleteErr error
|
||||
|
||||
cameras []Camera
|
||||
agentCameras []AgentCamera
|
||||
lastCameraReport AgentCameraReport
|
||||
@@ -97,6 +106,7 @@ type fakeSession struct {
|
||||
id string
|
||||
p auth.Principal
|
||||
accessExp, refreshExp time.Time
|
||||
device string
|
||||
revoked bool
|
||||
}
|
||||
|
||||
@@ -150,7 +160,11 @@ func (f *fakeStore) CreateSession(_ context.Context, n NewSession) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.nextID++
|
||||
id := "sess-" + itoa(f.nextID)
|
||||
// uuid-SHAPED, because the handlers validate the shape of an id before
|
||||
// spending a database round trip on it. A fake that mints "sess-1" would
|
||||
// make every id-addressed session route 404 in tests and pass in
|
||||
// production, which is the wrong way round.
|
||||
id := fmt.Sprintf("00000000-0000-4000-8000-%012d", f.nextID)
|
||||
var rec UserRecord
|
||||
for _, u := range f.users {
|
||||
if u.ID == n.UserID {
|
||||
@@ -165,6 +179,7 @@ func (f *fakeStore) CreateSession(_ context.Context, n NewSession) error {
|
||||
FullName: rec.FullName, Role: rec.Role,
|
||||
},
|
||||
accessExp: n.AccessExpiry, refreshExp: n.RefreshExp,
|
||||
device: n.Device,
|
||||
}
|
||||
f.sessions[id] = s
|
||||
f.byAccess[hex.EncodeToString(n.AccessHash)] = id
|
||||
@@ -673,3 +688,228 @@ func (f *fakeStore) addCameraRef(id, client, site, engineID string) {
|
||||
}
|
||||
|
||||
type cameraRef struct{ client, site, engineID string }
|
||||
|
||||
// ==================================== team, invitations, sessions, faces ====
|
||||
//
|
||||
// These behave rather than merely satisfy the interface: single use, tenant
|
||||
// scoping and "the role comes from the invitation" are the properties the
|
||||
// handlers are trusted for, so a fake that always says yes would make the tests
|
||||
// that check them meaningless.
|
||||
|
||||
type fakeInvite struct {
|
||||
id, clientID, email, fullName, role string
|
||||
expires time.Time
|
||||
used, revoked bool
|
||||
}
|
||||
|
||||
func (f *fakeStore) CreateInvitation(_ context.Context, in NewInvitation) (Invitation, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.invites == nil {
|
||||
f.invites = map[string]*fakeInvite{}
|
||||
}
|
||||
f.nextID++
|
||||
id := fmt.Sprintf("00000000-0000-4000-9000-%012d", f.nextID)
|
||||
f.invites[hex.EncodeToString(in.CodeHash)] = &fakeInvite{
|
||||
id: id, clientID: in.ClientID, email: in.Email,
|
||||
fullName: in.FullName, role: in.Role, expires: in.ExpiresAt,
|
||||
}
|
||||
return Invitation{
|
||||
ID: id, Email: in.Email, FullName: in.FullName, Role: in.Role,
|
||||
ExpiresAt: in.ExpiresAt.UTC().Format(time.RFC3339),
|
||||
CreatedAt: time.Now().UTC().Format(time.RFC3339),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) PendingInvitations(_ context.Context, clientID string) ([]Invitation, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
var out []Invitation
|
||||
for _, v := range f.invites {
|
||||
if v.clientID != clientID || v.used || v.revoked {
|
||||
continue
|
||||
}
|
||||
out = append(out, Invitation{ID: v.id, Email: v.email,
|
||||
FullName: v.fullName, Role: v.role,
|
||||
ExpiresAt: v.expires.UTC().Format(time.RFC3339)})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) RevokeInvitation(_ context.Context, clientID, id string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for _, v := range f.invites {
|
||||
if v.id == id && v.clientID == clientID && !v.used && !v.revoked {
|
||||
v.revoked = true
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errors.New("no such pending invitation")
|
||||
}
|
||||
|
||||
func (f *fakeStore) InvitationByCode(_ context.Context, hash []byte) (InvitationPreview, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
v, ok := f.invites[hex.EncodeToString(hash)]
|
||||
if !ok || v.used || v.revoked || time.Now().After(v.expires) {
|
||||
return InvitationPreview{}, errors.New("that invitation is not valid")
|
||||
}
|
||||
return InvitationPreview{Client: "Fake Co", Email: v.email,
|
||||
FullName: v.fullName, Role: v.role}, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) RedeemInvitation(_ context.Context, hash []byte,
|
||||
fullName, passwordHash string) (UserRecord, error) {
|
||||
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
v, ok := f.invites[hex.EncodeToString(hash)]
|
||||
if !ok || v.used || v.revoked || time.Now().After(v.expires) {
|
||||
return UserRecord{}, errors.New("that invitation is not valid")
|
||||
}
|
||||
if _, taken := f.users[v.email]; taken {
|
||||
return UserRecord{}, errors.New("app_users_email_idx")
|
||||
}
|
||||
// Marked spent BEFORE the account exists, mirroring the real store's one
|
||||
// transaction: a test that redeems the same code twice must get one user.
|
||||
v.used = true
|
||||
f.nextID++
|
||||
rec := UserRecord{
|
||||
ID: fmt.Sprintf("00000000-0000-4000-a000-%012d", f.nextID),
|
||||
// From the INVITATION, never from the request - which is the property
|
||||
// worth having a fake at all for.
|
||||
ClientID: v.clientID, ClientName: "Fake Co", Email: v.email,
|
||||
FullName: fullName, Role: v.role, Active: true, Found: true,
|
||||
PasswordHash: passwordHash,
|
||||
}
|
||||
if rec.FullName == "" {
|
||||
rec.FullName = v.fullName
|
||||
}
|
||||
f.users[v.email] = rec
|
||||
return rec, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Team(_ context.Context, clientID string) ([]TeamMember, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
var out []TeamMember
|
||||
for _, u := range f.users {
|
||||
if u.ClientID != clientID {
|
||||
continue
|
||||
}
|
||||
out = append(out, TeamMember{ID: u.ID, Email: u.Email,
|
||||
FullName: u.FullName, Role: u.Role, Active: u.Active})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) UpdateTeamMember(_ context.Context, clientID, userID string,
|
||||
up TeamUpdate) (TeamMember, error) {
|
||||
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for email, u := range f.users {
|
||||
if u.ID != userID || u.ClientID != clientID {
|
||||
continue
|
||||
}
|
||||
if up.Role != nil {
|
||||
u.Role = *up.Role
|
||||
}
|
||||
if up.Active != nil {
|
||||
u.Active = *up.Active
|
||||
if !u.Active {
|
||||
// The real store revokes in the same transaction; the fake
|
||||
// does it here so a test can prove "they have left" actually
|
||||
// signs them out rather than waiting twelve hours.
|
||||
for _, s := range f.sessions {
|
||||
if s.p.UserID == userID {
|
||||
s.revoked = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
f.users[email] = u
|
||||
return TeamMember{ID: u.ID, Email: u.Email, FullName: u.FullName,
|
||||
Role: u.Role, Active: u.Active}, nil
|
||||
}
|
||||
return TeamMember{}, errors.New("no such team member")
|
||||
}
|
||||
|
||||
func (f *fakeStore) UserSessions(_ context.Context, userID string) ([]DeviceSession, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
var out []DeviceSession
|
||||
for _, s := range f.sessions {
|
||||
if s.p.UserID != userID || s.revoked {
|
||||
continue
|
||||
}
|
||||
out = append(out, DeviceSession{ID: s.id, Device: s.device,
|
||||
ExpiresAt: s.refreshExp.UTC().Format(time.RFC3339)})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) RevokeUserSession(_ context.Context, userID, sessionID string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
s, ok := f.sessions[sessionID]
|
||||
// Scoped by user id, exactly as the real UPDATE is: a session id travels in
|
||||
// a list and is not a secret, so it must not sign anybody else out.
|
||||
if !ok || s.p.UserID != userID || s.revoked {
|
||||
return errors.New("no such session")
|
||||
}
|
||||
s.revoked = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) RevokeOtherSessions(_ context.Context, userID, keep string) (int, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
n := 0
|
||||
for _, s := range f.sessions {
|
||||
if s.p.UserID == userID && s.id != keep && !s.revoked {
|
||||
s.revoked = true
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) PutVisitFace(_ context.Context, clientID, siteID string,
|
||||
jpeg []byte) (string, error) {
|
||||
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.faces == nil {
|
||||
f.faces = map[string][]byte{}
|
||||
}
|
||||
f.nextID++
|
||||
id := fmt.Sprintf("00000000-0000-4000-b000-%012d", f.nextID)
|
||||
f.faces[clientID+"/"+id] = jpeg
|
||||
f.lastFaceClient, f.lastFaceSite = clientID, siteID
|
||||
return "db:" + id, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) VisitFace(_ context.Context, clientID, key string) ([]byte, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
img, ok := f.faces[clientID+"/"+strings.TrimPrefix(key, "db:")]
|
||||
if !ok {
|
||||
return nil, errors.New("no such face image")
|
||||
}
|
||||
return img, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) DeleteVisitFaces(_ context.Context, clientID string, keys []string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.faceDeleteErr != nil {
|
||||
return f.faceDeleteErr
|
||||
}
|
||||
for _, k := range keys {
|
||||
delete(f.faces, clientID+"/"+strings.TrimPrefix(k, "db:"))
|
||||
f.deletedFaces = append(f.deletedFaces, k)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -122,27 +122,9 @@ func (s *Server) attachImages(r *http.Request, rows []Arrival) {
|
||||
for i := range rows {
|
||||
key := rows[i].ImageKey
|
||||
rows[i].ImageKey = ""
|
||||
switch {
|
||||
case s.Blob == nil:
|
||||
rows[i].Image.Reason = "This system is not storing customer photos."
|
||||
case key == "":
|
||||
rows[i].Image.Reason = "No photo was captured for this visit."
|
||||
default:
|
||||
url, err := s.Blob.PresignGet(key, viewTTL)
|
||||
if err != nil {
|
||||
// Log it, but never fail the feed over a picture. The visit is
|
||||
// the number the customer pays for; the photo is decoration on
|
||||
// top of it. This is the same rule the agent follows when an
|
||||
// upload fails.
|
||||
s.logf("ERROR presign arrival image: %v", err)
|
||||
rows[i].Image.Reason = "That photo could not be loaded."
|
||||
continue
|
||||
}
|
||||
rows[i].Image = Image{Available: true, URL: url,
|
||||
ExpiresIn: int(viewTTL.Seconds())}
|
||||
if rows[i].VisitorID != "" {
|
||||
seen = append(seen, rows[i].VisitorID)
|
||||
}
|
||||
rows[i].Image = s.imageFor(key)
|
||||
if rows[i].Image.Available && rows[i].VisitorID != "" {
|
||||
seen = append(seen, rows[i].VisitorID)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -59,6 +59,11 @@ func (s *Server) attachSnapshots(cams []Camera) {
|
||||
Available: true,
|
||||
URL: "/api/cameras/" + cams[i].ID + "/snapshot.jpg",
|
||||
ExpiresIn: int(snapshotTTL.Seconds()),
|
||||
// Says out loud that this URL needs the session's bearer.
|
||||
// Clients used to infer it from the URL being relative, which
|
||||
// is true today and stops being true the first time object
|
||||
// storage is served from this same host.
|
||||
Auth: true,
|
||||
}
|
||||
case key == "":
|
||||
cams[i].Snapshot.Reason = "No picture from this camera yet."
|
||||
|
||||
186
server/internal/api/handlers_faces.go
Normal file
186
server/internal/api/handlers_faces.go
Normal file
@@ -0,0 +1,186 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Face images held by this server, for a deployment with no object storage.
|
||||
//
|
||||
// Where a bucket IS configured nothing here is used: the agent keeps asking for
|
||||
// a presigned URL and the reader keeps getting a signed link, which never puts
|
||||
// a photograph through this process at all and is the right route at estate
|
||||
// scale. This is the fallback that stops "no S3 account" from meaning "no
|
||||
// customer photo, ever", which is what every local install and every
|
||||
// self-hosted customer got - including on the mobile arrivals feed, whose whole
|
||||
// job is to put a face in front of somebody.
|
||||
//
|
||||
// Migration 011 carries the argument for why this is bounded and therefore safe
|
||||
// to keep in Postgres when per-visit images are not: one row survives per
|
||||
// customer, so it grows with the customer base and not with footfall.
|
||||
|
||||
// maxFaceBytes caps one upload. The engine writes ~20 KB crops; 2 MB is
|
||||
// generous for a large one and small enough that a misbehaving agent cannot use
|
||||
// this as free storage.
|
||||
const maxFaceBytes = 2 << 20
|
||||
|
||||
// faceMaxAge is how long a client may reuse a face it has already fetched.
|
||||
// The image for a given key never changes - a newer view gets a new key - so
|
||||
// this is only bounded to keep a signed-out device from holding one for ever.
|
||||
const faceMaxAge = 5 * time.Minute
|
||||
|
||||
// handlePutFace takes one face crop from a shop PC.
|
||||
//
|
||||
// The client and site come from the agent's own credential and are never read
|
||||
// off the request, so a shop PC physically cannot file an image under another
|
||||
// tenant - the same rule every other agent-authenticated write here follows.
|
||||
//
|
||||
// The response is a KEY, which the agent then puts on the queued visit exactly
|
||||
// as it does with a bucket object. That symmetry is deliberate: the two storage
|
||||
// routes differ in one hop and in nothing else, so the ingest path, the read
|
||||
// path and erasure all stay single implementations.
|
||||
func (s *Server) handlePutFace(w http.ResponseWriter, r *http.Request, ap AgentPrincipal) {
|
||||
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxFaceBytes+1))
|
||||
if err != nil || len(body) > maxFaceBytes {
|
||||
writeErr(w, http.StatusRequestEntityTooLarge, "too_large",
|
||||
fmt.Sprintf("A face image must be under %d KB.", maxFaceBytes/1024))
|
||||
return
|
||||
}
|
||||
if len(body) == 0 {
|
||||
badRequest(w, "the image is empty")
|
||||
return
|
||||
}
|
||||
// Checked against the bytes, never the Content-Type header. This endpoint
|
||||
// stores what it is handed and serves it back to a browser, so the one
|
||||
// thing it must not become is a way to park arbitrary content under a URL
|
||||
// this server will serve.
|
||||
if !isJPEG(body) {
|
||||
badRequest(w, "a face image must be a JPEG")
|
||||
return
|
||||
}
|
||||
|
||||
key, err := s.Store.PutVisitFace(r.Context(), ap.ClientID, ap.SiteID, body)
|
||||
if err != nil {
|
||||
s.serverError(w, "store face", err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"key": key})
|
||||
}
|
||||
|
||||
// handleGetFace serves one back to a signed-in person.
|
||||
//
|
||||
// Session-authenticated rather than a signed link, and that is the same call
|
||||
// camera snapshots already made: there is no third party to delegate to - the
|
||||
// bytes are in our own database - and minting an unauthenticated URL so that a
|
||||
// plain <img src> could load it would add a way to reach a photograph of
|
||||
// somebody's customer with no session at all.
|
||||
//
|
||||
// The consequence is a real one and clients must handle it: a browser <img>
|
||||
// cannot send an Authorization header, so the web app fetches this and hands
|
||||
// over an object URL. A mobile image view can attach the header directly. The
|
||||
// `auth` flag on every Image says which kind of URL it is holding.
|
||||
//
|
||||
// No audit row is written here. Every read of a face is recorded where the LINK
|
||||
// is handed out - the arrivals page writes one row per page, the customer
|
||||
// record one per look - and the two paths must not disagree about what counts
|
||||
// as a read. Recording the byte fetch as well would double-count the DB
|
||||
// deployment and leave the bucket deployment, whose bytes never touch this
|
||||
// server, counted once.
|
||||
func (s *Server) handleGetFace(w http.ResponseWriter, r *http.Request) {
|
||||
p := PrincipalFrom(r.Context())
|
||||
img, err := s.Store.VisitFace(r.Context(), p.ClientID, faceKey(r.PathValue("id")))
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "no_image", "There is no photo here.")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "image/jpeg")
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(img)))
|
||||
w.Header().Set("Cache-Control", "private, max-age="+
|
||||
strconv.Itoa(int(faceMaxAge.Seconds())))
|
||||
// A photograph of a customer must not travel to a third party in a Referer
|
||||
// header if this URL is ever rendered inside a page that links out.
|
||||
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||
if _, err := w.Write(img); err != nil && !errors.Is(err, http.ErrHandlerTimeout) {
|
||||
s.logf("WARN write face: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// faceKey rebuilds the stored key from the id in the path.
|
||||
//
|
||||
// The route is `/api/faces/{id}.jpg` so a client can hand the URL to an image
|
||||
// view that decides what to do by extension, and the `.jpg` is presentation
|
||||
// rather than part of the key.
|
||||
func faceKey(id string) string {
|
||||
if n := len(id); n > 4 && id[n-4:] == ".jpg" {
|
||||
id = id[:n-4]
|
||||
}
|
||||
return dbKeyPrefix + id
|
||||
}
|
||||
|
||||
// dbKeyPrefix mirrors store.DBKeyPrefix. Duplicated rather than imported
|
||||
// because this package must not depend on the concrete store - the whole point
|
||||
// of the Store interface - and it is a wire constant that changing on one side
|
||||
// alone would break loudly and immediately in the tests either way.
|
||||
const dbKeyPrefix = "db:"
|
||||
|
||||
// isDBKey reports whether an image key names a row here rather than an object
|
||||
// in a bucket.
|
||||
func isDBKey(key string) bool {
|
||||
return len(key) > len(dbKeyPrefix) && key[:len(dbKeyPrefix)] == dbKeyPrefix
|
||||
}
|
||||
|
||||
// faceURL is the path a client fetches for a stored face.
|
||||
func faceURL(key string) string {
|
||||
return "/api/faces/" + key[len(dbKeyPrefix):] + ".jpg"
|
||||
}
|
||||
|
||||
// imageFor turns one stored image key into the Image a client receives.
|
||||
//
|
||||
// ONE function decides this, for every surface: the arrivals feed, the live
|
||||
// stream, the customer record. There are now two places an image can live and
|
||||
// four distinct reasons there may not be one, and the failure this avoids is
|
||||
// the one the shops screen already hit once - two surfaces computing the same
|
||||
// fact separately and disagreeing about it in front of a user.
|
||||
//
|
||||
// A missing photo is DATA, not an error. Images are off by default across the
|
||||
// whole product, so on most deployments every arrival legitimately has none; a
|
||||
// client that renders a failure state would show a screen of red for a system
|
||||
// working exactly as configured. The two absences are told apart because a shop
|
||||
// can act on one and not the other.
|
||||
func (s *Server) imageFor(key string) Image {
|
||||
switch {
|
||||
case key == "" && s.Blob == nil:
|
||||
return Image{Reason: "This system is not storing customer photos."}
|
||||
case key == "":
|
||||
return Image{Reason: "No photo was captured for this visit."}
|
||||
|
||||
case isDBKey(key):
|
||||
// Held by this server. A relative URL that needs the caller's session -
|
||||
// see handleGetFace for why it is not a signed link - so it carries no
|
||||
// expiry: it is valid for exactly as long as the session is.
|
||||
return Image{Available: true, URL: faceURL(key), Auth: true}
|
||||
|
||||
case s.Blob == nil:
|
||||
// A bucket key on a server with no bucket. Only reachable if object
|
||||
// storage was configured once and has since been removed, and it is
|
||||
// worth its own sentence: the photo exists somewhere and this
|
||||
// deployment can no longer reach it, which is a configuration problem
|
||||
// rather than a customer with no picture.
|
||||
return Image{Reason: "This server can no longer reach its image storage."}
|
||||
|
||||
default:
|
||||
url, err := s.Blob.PresignGet(key, viewTTL)
|
||||
if err != nil {
|
||||
// Logged, never fatal. The visit is the number the customer pays
|
||||
// for; the photo is decoration on top of it. Same rule the agent
|
||||
// follows when an upload fails.
|
||||
s.logf("ERROR presign image: %v", err)
|
||||
return Image{Reason: "That photo could not be loaded."}
|
||||
}
|
||||
return Image{Available: true, URL: url, ExpiresIn: int(viewTTL.Seconds())}
|
||||
}
|
||||
}
|
||||
@@ -91,31 +91,36 @@ func (s *Server) handleVisitorImage(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusNotFound, "not_found", "That customer no longer exists.")
|
||||
return
|
||||
}
|
||||
if s.Blob == nil {
|
||||
writeErr(w, http.StatusNotFound, "images_disabled",
|
||||
"This server does not store images.")
|
||||
return
|
||||
}
|
||||
key, err := s.Store.VisitorImageKey(r.Context(), p.ClientID, id)
|
||||
if err != nil || key == "" {
|
||||
writeErr(w, http.StatusNotFound, "no_image",
|
||||
"There is no photo for this customer.")
|
||||
return
|
||||
}
|
||||
url, err := s.Blob.PresignGet(key, viewTTL)
|
||||
if err != nil {
|
||||
s.serverError(w, "presign read", err)
|
||||
key = ""
|
||||
}
|
||||
// The same function every other surface uses. Two ways to answer "where is
|
||||
// this person's photo" would eventually answer differently, and the one
|
||||
// that mattered would be whichever the customer was looking at.
|
||||
img := s.imageFor(key)
|
||||
if !img.Available {
|
||||
// Absence, with the reason. `no_image` and `images_disabled` are
|
||||
// separate codes because the desktop and mobile clients act on them
|
||||
// differently: one is a customer with no picture yet, the other is a
|
||||
// deployment that stores none and should stop asking.
|
||||
code := "no_image"
|
||||
if key == "" && s.Blob == nil {
|
||||
code = "images_disabled"
|
||||
}
|
||||
writeErr(w, http.StatusNotFound, code, img.Reason)
|
||||
return
|
||||
}
|
||||
// Every read of a face image is worth a row. If a client asks "who looked
|
||||
// at my customers", an audit trail is the only answer that is not a guess.
|
||||
// Recorded HERE, where the link is handed out, for both storage routes -
|
||||
// the bucket's bytes never touch this server, so the fetch itself is not a
|
||||
// place both paths could be counted.
|
||||
s.Store.Audit(r.Context(), AuditEntry{
|
||||
ClientID: p.ClientID, ActorID: p.UserID, ActorKind: "user",
|
||||
Action: "image.view", Entity: "visitor", EntityID: id,
|
||||
})
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"url": url, "expires_in": int(viewTTL.Seconds()),
|
||||
})
|
||||
writeJSON(w, http.StatusOK, img)
|
||||
}
|
||||
|
||||
// handleForgetVisitor is the erasure path.
|
||||
@@ -146,8 +151,21 @@ func (s *Server) handleForgetVisitor(w http.ResponseWriter, r *http.Request) {
|
||||
s.serverError(w, "list images for erasure", err)
|
||||
return
|
||||
}
|
||||
// Images this server holds itself. Deleted before the row, for the same
|
||||
// reason the bucket objects are: if the database commits first and this
|
||||
// fails, the keys are gone and nothing knows which images to remove.
|
||||
if err := s.Store.DeleteVisitFaces(r.Context(), p.ClientID, keys); err != nil {
|
||||
s.logf("ERROR erasure %s: cannot delete stored faces: %v", id, err)
|
||||
writeErr(w, http.StatusBadGateway, "storage_error",
|
||||
"The photo could not be deleted, so nothing was erased. "+
|
||||
"Please try again.")
|
||||
return
|
||||
}
|
||||
if s.Blob != nil {
|
||||
for _, key := range keys {
|
||||
if isDBKey(key) {
|
||||
continue // already gone, above
|
||||
}
|
||||
if err := s.Blob.Delete(r.Context(), key); err != nil {
|
||||
// Refuse the whole request. Reporting an erasure as done while
|
||||
// a face image is still in the bucket is the one outcome this
|
||||
|
||||
80
server/internal/api/handlers_sessions.go
Normal file
80
server/internal/api/handlers_sessions.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Which devices are signed in, and signing one of them out.
|
||||
//
|
||||
// This is the point of opaque tokens in a table rather than JWTs, and until now
|
||||
// the product had the cost of that choice without the benefit. The argument
|
||||
// recorded for it was that this system puts customer data on shop-floor PCs and
|
||||
// staff phones that get lost, resold and shared between people, so "log that
|
||||
// device out, now" has to actually work - and there was no endpoint that could
|
||||
// list what was signed in, let alone stop one.
|
||||
//
|
||||
// It matters most on mobile, which is why it arrives with it: a phone is the
|
||||
// device most likely to leave the building in somebody's pocket.
|
||||
|
||||
func (s *Server) handleSessions(w http.ResponseWriter, r *http.Request) {
|
||||
p := PrincipalFrom(r.Context())
|
||||
rows, err := s.Store.UserSessions(r.Context(), p.UserID)
|
||||
if err != nil {
|
||||
s.serverError(w, "list sessions", err)
|
||||
return
|
||||
}
|
||||
if rows == nil {
|
||||
rows = []DeviceSession{}
|
||||
}
|
||||
// Marked here rather than in SQL: which session is "this one" is a property
|
||||
// of the request, and the store has no business knowing about requests.
|
||||
for i := range rows {
|
||||
rows[i].Current = rows[i].ID == p.SessionID
|
||||
}
|
||||
writeJSON(w, http.StatusOK, rows)
|
||||
}
|
||||
|
||||
// handleRevokeSession signs one device out.
|
||||
//
|
||||
// A person may only revoke their OWN sessions - the store scopes the update by
|
||||
// user id, so a session id, which is not a secret and travels in the list
|
||||
// above, cannot be used to sign somebody else out. Removing a colleague's
|
||||
// access is a different question with a different answer: deactivate them
|
||||
// through the team endpoint, which revokes every session they have.
|
||||
func (s *Server) handleRevokeSession(w http.ResponseWriter, r *http.Request) {
|
||||
p := PrincipalFrom(r.Context())
|
||||
id := r.PathValue("id")
|
||||
if !looksLikeUUID(id) {
|
||||
writeErr(w, http.StatusNotFound, "not_found", "No such device.")
|
||||
return
|
||||
}
|
||||
if err := s.Store.RevokeUserSession(r.Context(), p.UserID, id); err != nil {
|
||||
writeErr(w, http.StatusNotFound, "not_found", "No such device.")
|
||||
return
|
||||
}
|
||||
s.Store.Audit(r.Context(), AuditEntry{
|
||||
ClientID: p.ClientID, ActorID: p.UserID, ActorKind: "user",
|
||||
Action: "auth.session.revoke", Entity: "session", EntityID: id,
|
||||
})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// handleRevokeOtherSessions is "sign out everywhere else".
|
||||
//
|
||||
// It deliberately keeps the caller's own session. Somebody who has just lost a
|
||||
// phone should not also be signed out of the device in their hand, in the
|
||||
// middle of dealing with it.
|
||||
func (s *Server) handleRevokeOtherSessions(w http.ResponseWriter, r *http.Request) {
|
||||
p := PrincipalFrom(r.Context())
|
||||
n, err := s.Store.RevokeOtherSessions(r.Context(), p.UserID, p.SessionID)
|
||||
if err != nil {
|
||||
s.serverError(w, "revoke sessions", err)
|
||||
return
|
||||
}
|
||||
s.Store.Audit(r.Context(), AuditEntry{
|
||||
ClientID: p.ClientID, ActorID: p.UserID, ActorKind: "user",
|
||||
Action: "auth.session.revoke_others", Entity: "session",
|
||||
Detail: map[string]any{"count": n},
|
||||
})
|
||||
writeJSON(w, http.StatusOK, map[string]any{"signed_out": n})
|
||||
}
|
||||
390
server/internal/api/handlers_team.go
Normal file
390
server/internal/api/handlers_team.go
Normal file
@@ -0,0 +1,390 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/loyaly/behavision-server/internal/auth"
|
||||
)
|
||||
|
||||
// Adding people to a company: invitations, registration, and the team list.
|
||||
//
|
||||
// Registration is by INVITATION, and that is the same decision handlers_admin.go
|
||||
// records for creating a company: an endpoint a stranger can call to create an
|
||||
// account is a far larger thing to secure than one reachable only through
|
||||
// somebody who already has one. What was missing was not the openness - it was
|
||||
// that a tenant could not add a SECOND person at all except by somebody with a
|
||||
// shell on the server running `provision user`. A shop with an owner and four
|
||||
// staff either shared one password between five people or raised a ticket per
|
||||
// person, and a phone app for shop-floor staff could not exist while there was
|
||||
// only ever one account to sign in as.
|
||||
//
|
||||
// So: a manager mints a code, hands it over, and the holder chooses their own
|
||||
// password. The code carries the address and the role; the request carries only
|
||||
// the password and a name. That split is load-bearing and is why this is not
|
||||
// simply "create a user with these fields" - see handleRegister.
|
||||
|
||||
const (
|
||||
// Long enough to reach somebody who is not at work today, short enough that
|
||||
// a code left in a chat thread is worthless before anyone scrolls back to
|
||||
// it. An expired invitation costs one click to reissue.
|
||||
invitationTTL = 7 * 24 * time.Hour
|
||||
maxInvitation = 30 * 24 * time.Hour
|
||||
)
|
||||
|
||||
// handleInvite mints one invitation.
|
||||
//
|
||||
// Manager and above. Not staff: the holder of a code gets an account inside
|
||||
// this company, so it is a credential, not a convenience.
|
||||
func (s *Server) handleInvite(w http.ResponseWriter, r *http.Request) {
|
||||
p := PrincipalFrom(r.Context())
|
||||
if !p.CanManageSites() || p.ClientID == "" {
|
||||
writeErr(w, http.StatusForbidden, "forbidden",
|
||||
"Your account cannot invite people to this company.")
|
||||
return
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Email string `json:"email"`
|
||||
FullName string `json:"full_name"`
|
||||
Role string `json:"role"`
|
||||
Days int `json:"expires_in_days"`
|
||||
}
|
||||
if err := decode(w, r, &body); err != nil {
|
||||
badRequest(w, err.Error())
|
||||
return
|
||||
}
|
||||
email := auth.NormalizeEmail(body.Email)
|
||||
if email == "" || !strings.Contains(email, "@") {
|
||||
badRequest(w, "an email address is required - it is what they will sign in with")
|
||||
return
|
||||
}
|
||||
role := strings.ToLower(trim(body.Role))
|
||||
if role == "" {
|
||||
role = "staff"
|
||||
}
|
||||
// 'admin' is absent on purpose. A platform administrator is defined by
|
||||
// having no company at all, so an invitation could never mint a real one -
|
||||
// what it could do is create the tenant-scoped row with role='admin' that
|
||||
// adminOnly exists to reject, and a role nothing can use is a trap rather
|
||||
// than a feature.
|
||||
switch role {
|
||||
case "owner", "manager", "staff":
|
||||
default:
|
||||
badRequest(w, "role must be owner, manager or staff")
|
||||
return
|
||||
}
|
||||
// Only an owner may create another owner. A manager promoting somebody past
|
||||
// themselves is an escalation, and it is the one shape of this endpoint
|
||||
// that would matter if a manager account were ever taken over.
|
||||
if role == "owner" && p.Role != "owner" && p.Role != "admin" {
|
||||
writeErr(w, http.StatusForbidden, "forbidden",
|
||||
"Only an owner can invite another owner.")
|
||||
return
|
||||
}
|
||||
|
||||
ttl := invitationTTL
|
||||
if body.Days > 0 {
|
||||
ttl = time.Duration(body.Days) * 24 * time.Hour
|
||||
if ttl > maxInvitation {
|
||||
ttl = maxInvitation
|
||||
}
|
||||
}
|
||||
|
||||
code, err := auth.NewEnrolmentCode()
|
||||
if err != nil {
|
||||
s.serverError(w, "mint invitation", err)
|
||||
return
|
||||
}
|
||||
inv, err := s.Store.CreateInvitation(r.Context(), NewInvitation{
|
||||
ClientID: p.ClientID,
|
||||
Email: email,
|
||||
FullName: clip(trim(body.FullName), 200),
|
||||
Role: role,
|
||||
CodeHash: auth.HashToken(auth.NormalizeCode(code)),
|
||||
InvitedBy: p.UserID,
|
||||
ExpiresAt: s.now().Add(ttl),
|
||||
})
|
||||
if err != nil {
|
||||
s.serverError(w, "create invitation", err)
|
||||
return
|
||||
}
|
||||
// The plaintext exists here and in this response, and nowhere else. Like
|
||||
// every other secret this system mints, it is shown once: one a support
|
||||
// engineer can look up later is one anybody with support access can redeem.
|
||||
inv.Code = code
|
||||
|
||||
s.Store.Audit(r.Context(), AuditEntry{
|
||||
ClientID: p.ClientID, ActorID: p.UserID, ActorKind: "user",
|
||||
Action: "team.invite", Entity: "invitation", EntityID: inv.ID,
|
||||
Detail: map[string]any{"email": email, "role": role},
|
||||
})
|
||||
writeJSON(w, http.StatusCreated, inv)
|
||||
}
|
||||
|
||||
func (s *Server) handleInvitations(w http.ResponseWriter, r *http.Request) {
|
||||
p := PrincipalFrom(r.Context())
|
||||
if !p.CanManageSites() || p.ClientID == "" {
|
||||
writeErr(w, http.StatusForbidden, "forbidden",
|
||||
"Your account cannot see this company's invitations.")
|
||||
return
|
||||
}
|
||||
rows, err := s.Store.PendingInvitations(r.Context(), p.ClientID)
|
||||
if err != nil {
|
||||
s.serverError(w, "list invitations", err)
|
||||
return
|
||||
}
|
||||
if rows == nil {
|
||||
rows = []Invitation{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, rows)
|
||||
}
|
||||
|
||||
func (s *Server) handleRevokeInvitation(w http.ResponseWriter, r *http.Request) {
|
||||
p := PrincipalFrom(r.Context())
|
||||
if !p.CanManageSites() || p.ClientID == "" {
|
||||
writeErr(w, http.StatusForbidden, "forbidden",
|
||||
"Your account cannot withdraw invitations.")
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if !looksLikeUUID(id) {
|
||||
writeErr(w, http.StatusNotFound, "not_found", "No such invitation.")
|
||||
return
|
||||
}
|
||||
if err := s.Store.RevokeInvitation(r.Context(), p.ClientID, id); err != nil {
|
||||
// Already used or already withdrawn. Reported rather than swallowed:
|
||||
// "I cancelled it" and "somebody had already joined with it" need
|
||||
// opposite next steps from whoever pressed the button.
|
||||
writeErr(w, http.StatusNotFound, "not_found",
|
||||
"That invitation is no longer pending.")
|
||||
return
|
||||
}
|
||||
s.Store.Audit(r.Context(), AuditEntry{
|
||||
ClientID: p.ClientID, ActorID: p.UserID, ActorKind: "user",
|
||||
Action: "team.invite.revoke", Entity: "invitation", EntityID: id,
|
||||
})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// handleInvitationPreview lets a client show what a code is for before asking
|
||||
// somebody to choose a password.
|
||||
//
|
||||
// Unauthenticated, because the holder has no account yet - that is the whole
|
||||
// point - and it discloses only what the code itself already asserts: the
|
||||
// company, the address it was issued for, and the role. Unknown, expired, spent
|
||||
// and revoked are one identical answer, exactly as enrolment already does:
|
||||
// telling them apart only helps somebody guessing codes, and the holder's next
|
||||
// step is the same in all four cases.
|
||||
func (s *Server) handleInvitationPreview(w http.ResponseWriter, r *http.Request) {
|
||||
code := auth.NormalizeCode(r.URL.Query().Get("code"))
|
||||
if code == "" {
|
||||
badRequest(w, "a code is required")
|
||||
return
|
||||
}
|
||||
prev, err := s.Store.InvitationByCode(r.Context(), auth.HashToken(code))
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "invalid_code",
|
||||
"That invitation code is not valid. Ask for a new one.")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, prev)
|
||||
}
|
||||
|
||||
// handleRegister turns a code into an account and signs the person in.
|
||||
//
|
||||
// Unauthenticated for the same reason `POST /api/agent/enrol` is: whoever is
|
||||
// doing this has no account yet, and requiring one first would mean shipping a
|
||||
// password to everybody who needs one.
|
||||
//
|
||||
// The email and the role come from the INVITATION, never from this body. A code
|
||||
// forwarded to a colleague must not become an account for them, and a staff
|
||||
// invitation must not be redeemed as an owner - which is exactly what a
|
||||
// caller-supplied role would allow. The only things the request decides are the
|
||||
// password and the display name.
|
||||
//
|
||||
// It returns a Session, identical in shape to login. A new member's next screen
|
||||
// is the app, not a sign-in form they have to fill in with the password they
|
||||
// chose four seconds ago.
|
||||
func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Code string `json:"code"`
|
||||
FullName string `json:"full_name"`
|
||||
Password string `json:"password"`
|
||||
Device string `json:"device"`
|
||||
}
|
||||
if err := decode(w, r, &body); err != nil {
|
||||
badRequest(w, err.Error())
|
||||
return
|
||||
}
|
||||
code := auth.NormalizeCode(body.Code)
|
||||
if code == "" {
|
||||
badRequest(w, "an invitation code is required")
|
||||
return
|
||||
}
|
||||
|
||||
// Throttled on the code, by IP. Redeeming is the one unauthenticated write
|
||||
// in this package that creates a row, so an unbounded one is a way to grind
|
||||
// through the code space and to fill a table while doing it.
|
||||
_, perIP := s.throttles()
|
||||
ipKey := clientIP(r)
|
||||
if !perIP.Allow(ipKey) {
|
||||
writeErr(w, http.StatusTooManyRequests, "too_many_attempts",
|
||||
"Too many attempts. Wait a few minutes and try again.")
|
||||
return
|
||||
}
|
||||
|
||||
if err := auth.CheckPasswordPolicy(body.Password); err != nil {
|
||||
badRequest(w, err.Error())
|
||||
return
|
||||
}
|
||||
hash, err := auth.HashPassword(body.Password)
|
||||
if err != nil {
|
||||
s.serverError(w, "hash password", err)
|
||||
return
|
||||
}
|
||||
|
||||
rec, err := s.Store.RedeemInvitation(r.Context(), auth.HashToken(code),
|
||||
clip(trim(body.FullName), 200), hash)
|
||||
if err != nil {
|
||||
perIP.Fail(ipKey)
|
||||
if msg, ok := conflictMessage(err); ok {
|
||||
// The address already has an account somewhere on the platform.
|
||||
// Worth saying plainly: the fix is to sign in, not to try again.
|
||||
writeErr(w, http.StatusConflict, "conflict", msg)
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusNotFound, "invalid_code",
|
||||
"That invitation code is not valid. Ask for a new one.")
|
||||
return
|
||||
}
|
||||
perIP.Reset(ipKey)
|
||||
|
||||
sess, err := s.mint(r, rec, body.Device)
|
||||
if err != nil {
|
||||
// The account exists and the invitation is spent. Say so rather than
|
||||
// implying nothing happened - the recovery is to sign in, and telling
|
||||
// them to redeem again would fail forever.
|
||||
s.logf("ERROR register: created %s but could not start a session: %v", rec.ID, err)
|
||||
writeErr(w, http.StatusInternalServerError, "server_error",
|
||||
"Your account was created but we could not sign you in. Please sign in.")
|
||||
return
|
||||
}
|
||||
s.Store.Audit(r.Context(), AuditEntry{
|
||||
ClientID: rec.ClientID, ActorID: rec.ID, ActorKind: "user",
|
||||
Action: "team.register", Entity: "user", EntityID: rec.ID,
|
||||
Detail: map[string]any{"role": rec.Role, "device": trim(body.Device)},
|
||||
})
|
||||
s.logf("registered %s (%s) into client %s", rec.Email, rec.Role, rec.ClientID)
|
||||
writeJSON(w, http.StatusCreated, sess)
|
||||
}
|
||||
|
||||
func (s *Server) handleTeam(w http.ResponseWriter, r *http.Request) {
|
||||
p := PrincipalFrom(r.Context())
|
||||
if p.ClientID == "" {
|
||||
writeErr(w, http.StatusForbidden, "forbidden",
|
||||
"This account does not belong to a company.")
|
||||
return
|
||||
}
|
||||
rows, err := s.Store.Team(r.Context(), p.ClientID)
|
||||
if err != nil {
|
||||
s.serverError(w, "list team", err)
|
||||
return
|
||||
}
|
||||
if rows == nil {
|
||||
rows = []TeamMember{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, rows)
|
||||
}
|
||||
|
||||
// handleUpdateTeamMember changes a role, or turns an account off.
|
||||
//
|
||||
// Deactivating is the "they have left" button, and the store revokes their
|
||||
// sessions in the same transaction: an access token lives twelve hours, so
|
||||
// without that, removing somebody's access would remove it sometime tomorrow.
|
||||
func (s *Server) handleUpdateTeamMember(w http.ResponseWriter, r *http.Request) {
|
||||
p := PrincipalFrom(r.Context())
|
||||
if !p.CanManageSites() || p.ClientID == "" {
|
||||
writeErr(w, http.StatusForbidden, "forbidden",
|
||||
"Your account cannot change who works here.")
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if !looksLikeUUID(id) {
|
||||
writeErr(w, http.StatusNotFound, "not_found", "No such team member.")
|
||||
return
|
||||
}
|
||||
|
||||
var up TeamUpdate
|
||||
if err := decode(w, r, &up); err != nil {
|
||||
badRequest(w, err.Error())
|
||||
return
|
||||
}
|
||||
if up.Role == nil && up.Active == nil {
|
||||
badRequest(w, "nothing to change - send a role, an active flag, or both")
|
||||
return
|
||||
}
|
||||
if up.Role != nil {
|
||||
role := strings.ToLower(trim(*up.Role))
|
||||
switch role {
|
||||
case "owner", "manager", "staff":
|
||||
default:
|
||||
badRequest(w, "role must be owner, manager or staff")
|
||||
return
|
||||
}
|
||||
if role == "owner" && p.Role != "owner" && p.Role != "admin" {
|
||||
writeErr(w, http.StatusForbidden, "forbidden",
|
||||
"Only an owner can make somebody else an owner.")
|
||||
return
|
||||
}
|
||||
up.Role = &role
|
||||
}
|
||||
|
||||
// The company must keep an owner. Losing the last one leaves a tenant
|
||||
// nobody can administer, and the only way back is a shell on the server -
|
||||
// which is the thing this whole surface exists to stop needing.
|
||||
demoting := up.Role != nil && *up.Role != "owner"
|
||||
disabling := up.Active != nil && !*up.Active
|
||||
if demoting || disabling {
|
||||
if last, err := s.lastOwner(r, id); err != nil {
|
||||
s.serverError(w, "count owners", err)
|
||||
return
|
||||
} else if last {
|
||||
writeErr(w, http.StatusConflict, "last_owner",
|
||||
"This is the company's only owner. Make somebody else an owner first.")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
m, err := s.Store.UpdateTeamMember(r.Context(), p.ClientID, id, up)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "not_found", "No such team member.")
|
||||
return
|
||||
}
|
||||
s.Store.Audit(r.Context(), AuditEntry{
|
||||
ClientID: p.ClientID, ActorID: p.UserID, ActorKind: "user",
|
||||
Action: "team.update", Entity: "user", EntityID: id,
|
||||
Detail: map[string]any{"role": m.Role, "active": m.Active},
|
||||
})
|
||||
writeJSON(w, http.StatusOK, m)
|
||||
}
|
||||
|
||||
// lastOwner reports whether the named member is the only active owner left.
|
||||
func (s *Server) lastOwner(r *http.Request, userID string) (bool, error) {
|
||||
p := PrincipalFrom(r.Context())
|
||||
rows, err := s.Store.Team(r.Context(), p.ClientID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
owners, isOwner := 0, false
|
||||
for _, m := range rows {
|
||||
if m.Role == "owner" && m.Active {
|
||||
owners++
|
||||
if m.ID == userID {
|
||||
isOwner = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return isOwner && owners == 1, nil
|
||||
}
|
||||
147
server/internal/api/sessions_test.go
Normal file
147
server/internal/api/sessions_test.go
Normal file
@@ -0,0 +1,147 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// "Log that device out, now" is the entire argument for keeping sessions in a
|
||||
// table instead of issuing JWTs. These are the tests that the argument is
|
||||
// actually cashed in.
|
||||
|
||||
func sessionList(t *testing.T, s *Server, token string) []DeviceSession {
|
||||
t.Helper()
|
||||
rec := do(t, s, "GET", "/api/auth/sessions", token, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("sessions: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var out []DeviceSession
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func loginAs(t *testing.T, s *Server, email, password, device string) Session {
|
||||
t.Helper()
|
||||
rec := do(t, s, "POST", "/api/auth/login", "", map[string]string{
|
||||
"email": email, "password": password, "device": device})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("login: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var sess Session
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &sess); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return sess
|
||||
}
|
||||
|
||||
func TestAPersonCanSeeAndSignOutTheirOwnDevices(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
seedUser(fs)
|
||||
phone := loginAs(t, s, "manager@acme.com", "correct horse battery", "Pixel 8")
|
||||
till := loginAs(t, s, "manager@acme.com", "correct horse battery", "Shop PC")
|
||||
|
||||
rows := sessionList(t, s, till.Token)
|
||||
if len(rows) != 2 {
|
||||
t.Fatalf("want two devices, got %d: %+v", len(rows), rows)
|
||||
}
|
||||
var phoneID string
|
||||
for _, r := range rows {
|
||||
if r.Device == "Pixel 8" {
|
||||
phoneID = r.ID
|
||||
}
|
||||
// The device making the request must be labelled, or somebody signs
|
||||
// themselves out of the machine in their hand without meaning to.
|
||||
if r.Device == "Shop PC" && !r.Current {
|
||||
t.Error("the calling session is not marked current")
|
||||
}
|
||||
if r.Device == "Pixel 8" && r.Current {
|
||||
t.Error("another device is marked current")
|
||||
}
|
||||
}
|
||||
if phoneID == "" {
|
||||
t.Fatalf("the phone is not in the list: %+v", rows)
|
||||
}
|
||||
|
||||
if rec := do(t, s, "DELETE", "/api/auth/sessions/"+phoneID, till.Token, nil); rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("revoke: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
// Immediately, not when the access token happens to expire. A lost phone is
|
||||
// the case this exists for and twelve hours is not an answer.
|
||||
if rec := do(t, s, "GET", "/api/auth/me", phone.Token, nil); rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("the revoked device is still signed in, got %d", rec.Code)
|
||||
}
|
||||
if rec := do(t, s, "GET", "/api/auth/me", till.Token, nil); rec.Code != http.StatusOK {
|
||||
t.Fatalf("the calling device was signed out too, got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// A session id travels in the list above and is not a secret. The store scopes
|
||||
// the revoke by user id so one cannot be used to sign a colleague out.
|
||||
func TestOneUserCannotRevokeAnothersSession(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
seedUser(fs)
|
||||
seedMember(fs, acmeStaffID, "sam@acme.com", "Sam", "staff")
|
||||
|
||||
victim := loginAs(t, s, "sam@acme.com", "correct horse battery", "Sam's phone")
|
||||
attacker := loginAs(t, s, "manager@acme.com", "correct horse battery", "Laptop")
|
||||
|
||||
// The id is obtained the way an attacker would have to: it is not in the
|
||||
// attacker's own list at all, so this uses the real one directly.
|
||||
var victimID string
|
||||
for _, r := range sessionList(t, s, victim.Token) {
|
||||
victimID = r.ID
|
||||
}
|
||||
if rec := do(t, s, "DELETE", "/api/auth/sessions/"+victimID, attacker.Token, nil); rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("one user revoked another's session, got %d", rec.Code)
|
||||
}
|
||||
if rec := do(t, s, "GET", "/api/auth/me", victim.Token, nil); rec.Code != http.StatusOK {
|
||||
t.Fatal("the victim was signed out by somebody else")
|
||||
}
|
||||
}
|
||||
|
||||
// Somebody who has just lost a phone must not also be signed out of the device
|
||||
// they are holding while they deal with it.
|
||||
func TestSignOutEverywhereElseKeepsTheCurrentDevice(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
seedUser(fs)
|
||||
lost := loginAs(t, s, "manager@acme.com", "correct horse battery", "Lost phone")
|
||||
old := loginAs(t, s, "manager@acme.com", "correct horse battery", "Old tablet")
|
||||
here := loginAs(t, s, "manager@acme.com", "correct horse battery", "Laptop")
|
||||
|
||||
rec := do(t, s, "POST", "/api/auth/sessions/revoke-others", here.Token, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("revoke others: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var out struct {
|
||||
SignedOut int `json:"signed_out"`
|
||||
}
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &out)
|
||||
if out.SignedOut != 2 {
|
||||
t.Errorf("want two devices signed out, got %d", out.SignedOut)
|
||||
}
|
||||
for name, tok := range map[string]string{"lost phone": lost.Token, "old tablet": old.Token} {
|
||||
if rec := do(t, s, "GET", "/api/auth/me", tok, nil); rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s is still signed in, got %d", name, rec.Code)
|
||||
}
|
||||
}
|
||||
if rec := do(t, s, "GET", "/api/auth/me", here.Token, nil); rec.Code != http.StatusOK {
|
||||
t.Fatal("signing out everywhere else signed out this device too")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionRoutesNeedASession(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
seedUser(fs)
|
||||
for _, c := range []struct{ method, path string }{
|
||||
{"GET", "/api/auth/sessions"},
|
||||
{"DELETE", "/api/auth/sessions/" + acmeStaffID},
|
||||
{"POST", "/api/auth/sessions/revoke-others"},
|
||||
} {
|
||||
if rec := do(t, s, c.method, c.path, "", nil); rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s %s: want 401, got %d", c.method, c.path, rec.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
349
server/internal/api/team_test.go
Normal file
349
server/internal/api/team_test.go
Normal file
@@ -0,0 +1,349 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Registration is by invitation, and almost everything worth testing here is a
|
||||
// property of that choice: what the code decides versus what the request
|
||||
// decides, and who is allowed to mint one.
|
||||
|
||||
// Real user ids are uuids and the id-addressed routes check the shape before
|
||||
// spending a database round trip. A fixture using "u5" would 404 on the guard
|
||||
// rather than on the rule under test - which is a test that passes for the
|
||||
// wrong reason, and would keep passing if tenant scoping were removed.
|
||||
const (
|
||||
acmeStaffID = "11111111-1111-4111-8111-111111111111"
|
||||
acmeOwnerID = "22222222-2222-4222-8222-222222222222"
|
||||
acmeOtherID = "33333333-3333-4333-8333-333333333333"
|
||||
)
|
||||
|
||||
func seedMember(fs *fakeStore, id, email, name, role string) {
|
||||
fs.addUser(email, "correct horse battery", UserRecord{
|
||||
ID: id, ClientID: "client-acme", ClientName: "Acme Retail",
|
||||
FullName: name, Role: role, Active: true,
|
||||
})
|
||||
}
|
||||
|
||||
func invite(t *testing.T, s *Server, token string, body map[string]any) Invitation {
|
||||
t.Helper()
|
||||
rec := do(t, s, "POST", "/api/team/invitations", token, body)
|
||||
if rec.Code != http.StatusCreated {
|
||||
t.Fatalf("invite: got %d, body %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var inv Invitation
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &inv); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return inv
|
||||
}
|
||||
|
||||
func TestAnInvitationBecomesAnAccountAndASession(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
seedUser(fs)
|
||||
sess := login(t, s, "manager@acme.com", "correct horse battery")
|
||||
|
||||
inv := invite(t, s, sess.Token, map[string]any{
|
||||
"email": "Nikhil@Acme.com", "full_name": "Nikhil", "role": "staff"})
|
||||
if inv.Code == "" {
|
||||
t.Fatal("the response that mints a code must carry it - it is not recoverable later")
|
||||
}
|
||||
// Normalised on the way in, so the address somebody types at sign-in is the
|
||||
// one that was invited whatever case they used.
|
||||
if inv.Email != "nikhil@acme.com" {
|
||||
t.Errorf("email should be normalised, got %q", inv.Email)
|
||||
}
|
||||
|
||||
rec := do(t, s, "POST", "/api/auth/register", "", map[string]any{
|
||||
"code": inv.Code, "password": "a-good-long-password", "device": "Pixel 8"})
|
||||
if rec.Code != http.StatusCreated {
|
||||
t.Fatalf("register: got %d, body %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var out Session
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A session, not just a 201. Sending somebody who has just chosen a
|
||||
// password to a sign-in form to type it again is the sort of thing that
|
||||
// gets blamed on the password.
|
||||
if out.Token == "" || out.RefreshToken == "" {
|
||||
t.Fatal("registration should sign the new member in")
|
||||
}
|
||||
if out.User.Email != "nikhil@acme.com" || out.User.Role != "staff" {
|
||||
t.Errorf("wrong account: %+v", out.User)
|
||||
}
|
||||
if out.User.ClientID != "client-acme" {
|
||||
t.Errorf("joined the wrong company: %q", out.User.ClientID)
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), "$2a$") {
|
||||
t.Error("password hash leaked into the registration response")
|
||||
}
|
||||
|
||||
// And the account works.
|
||||
again := login(t, s, "nikhil@acme.com", "a-good-long-password")
|
||||
if again.User.ID != out.User.ID {
|
||||
t.Error("registered account cannot sign in as itself")
|
||||
}
|
||||
}
|
||||
|
||||
// The single most important test in this file. A code is forwarded, pasted into
|
||||
// a chat, screenshotted; if the body could name the address or the role, one
|
||||
// staff invitation would be an owner account for anybody who saw it.
|
||||
func TestTheCodeDecidesTheAddressAndTheRoleNotTheRequest(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
seedUser(fs)
|
||||
sess := login(t, s, "manager@acme.com", "correct horse battery")
|
||||
inv := invite(t, s, sess.Token, map[string]any{
|
||||
"email": "nikhil@acme.com", "role": "staff"})
|
||||
|
||||
// Unknown fields are refused outright, which is the strongest form of this:
|
||||
// a client cannot even ask.
|
||||
rec := do(t, s, "POST", "/api/auth/register", "", map[string]any{
|
||||
"code": inv.Code, "password": "a-good-long-password",
|
||||
"email": "attacker@example.com", "role": "owner"})
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("a body naming an address or a role must be refused, got %d: %s",
|
||||
rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// And redeemed properly, the account is still staff at the invited address.
|
||||
rec = do(t, s, "POST", "/api/auth/register", "", map[string]any{
|
||||
"code": inv.Code, "password": "a-good-long-password"})
|
||||
var out Session
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &out)
|
||||
if out.User.Email != "nikhil@acme.com" || out.User.Role != "staff" {
|
||||
t.Fatalf("the invitation did not decide the account: %+v", out.User)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnInvitationIsSingleUse(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
seedUser(fs)
|
||||
sess := login(t, s, "manager@acme.com", "correct horse battery")
|
||||
inv := invite(t, s, sess.Token, map[string]any{"email": "one@acme.com"})
|
||||
|
||||
first := do(t, s, "POST", "/api/auth/register", "", map[string]any{
|
||||
"code": inv.Code, "password": "a-good-long-password"})
|
||||
if first.Code != http.StatusCreated {
|
||||
t.Fatalf("first redemption: %d %s", first.Code, first.Body.String())
|
||||
}
|
||||
second := do(t, s, "POST", "/api/auth/register", "", map[string]any{
|
||||
"code": inv.Code, "password": "another-long-password"})
|
||||
if second.Code == http.StatusCreated {
|
||||
t.Fatal("a spent invitation created a second account")
|
||||
}
|
||||
}
|
||||
|
||||
func TestARevokedInvitationCannotBeRedeemed(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
seedUser(fs)
|
||||
sess := login(t, s, "manager@acme.com", "correct horse battery")
|
||||
inv := invite(t, s, sess.Token, map[string]any{"email": "gone@acme.com"})
|
||||
|
||||
if rec := do(t, s, "DELETE", "/api/team/invitations/"+inv.ID, sess.Token, nil); rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("revoke: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
rec := do(t, s, "POST", "/api/auth/register", "", map[string]any{
|
||||
"code": inv.Code, "password": "a-good-long-password"})
|
||||
if rec.Code == http.StatusCreated {
|
||||
t.Fatal("a withdrawn invitation still worked")
|
||||
}
|
||||
}
|
||||
|
||||
// Unknown, expired, spent and revoked are one answer. The difference only ever
|
||||
// helps somebody guessing, and the holder's next step is identical in all four.
|
||||
func TestAnInvalidCodeSaysNothingAboutWhy(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
seedUser(fs)
|
||||
sess := login(t, s, "manager@acme.com", "correct horse battery")
|
||||
inv := invite(t, s, sess.Token, map[string]any{"email": "used@acme.com"})
|
||||
_ = do(t, s, "POST", "/api/auth/register", "", map[string]any{
|
||||
"code": inv.Code, "password": "a-good-long-password"})
|
||||
|
||||
spent := do(t, s, "POST", "/api/auth/register", "", map[string]any{
|
||||
"code": inv.Code, "password": "a-good-long-password"})
|
||||
invented := do(t, s, "POST", "/api/auth/register", "", map[string]any{
|
||||
"code": "AAAAAA-BBBBBB-CCCCCC-DDDDDD", "password": "a-good-long-password"})
|
||||
|
||||
if spent.Code != invented.Code || spent.Body.String() != invented.Body.String() {
|
||||
t.Fatalf("a spent code is distinguishable from an invented one:\n%d %s\n%d %s",
|
||||
spent.Code, spent.Body.String(), invented.Code, invented.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaffCannotInviteAndAManagerCannotMintAnOwner(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
seedMember(fs, acmeStaffID, "sam@acme.com", "Sam", "staff")
|
||||
seedUser(fs)
|
||||
|
||||
staff := login(t, s, "sam@acme.com", "correct horse battery")
|
||||
if rec := do(t, s, "POST", "/api/team/invitations", staff.Token,
|
||||
map[string]any{"email": "x@acme.com"}); rec.Code != http.StatusForbidden {
|
||||
t.Errorf("staff should not be able to invite, got %d", rec.Code)
|
||||
}
|
||||
|
||||
// A manager promoting somebody past themselves is an escalation, and it is
|
||||
// the shape of this endpoint that would matter if a manager account were
|
||||
// ever taken over.
|
||||
mgr := login(t, s, "manager@acme.com", "correct horse battery")
|
||||
if rec := do(t, s, "POST", "/api/team/invitations", mgr.Token,
|
||||
map[string]any{"email": "boss@acme.com", "role": "owner"}); rec.Code != http.StatusForbidden {
|
||||
t.Errorf("a manager minted an owner invitation, got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// 'admin' is a platform administrator, which is defined by having no company at
|
||||
// all. An invitation always carries one, so the role could never work - what it
|
||||
// could do is create the tenant-scoped row with role='admin' that adminOnly
|
||||
// exists to reject.
|
||||
func TestAnInvitationCannotMintAPlatformAdmin(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
seedUser(fs)
|
||||
sess := login(t, s, "manager@acme.com", "correct horse battery")
|
||||
|
||||
rec := do(t, s, "POST", "/api/team/invitations", sess.Token,
|
||||
map[string]any{"email": "root@acme.com", "role": "admin"})
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("admin should not be an invitable role, got %d: %s",
|
||||
rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnInvitationIsScopedToTheInvitersCompany(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
seedUser(fs)
|
||||
fs.addUser("other@beta.com", "correct horse battery", UserRecord{
|
||||
ID: "u2", ClientID: "client-beta", ClientName: "Beta Ltd",
|
||||
FullName: "Bo", Role: "manager", Active: true,
|
||||
})
|
||||
acme := login(t, s, "manager@acme.com", "correct horse battery")
|
||||
beta := login(t, s, "other@beta.com", "correct horse battery")
|
||||
|
||||
inv := invite(t, s, acme.Token, map[string]any{"email": "new@acme.com"})
|
||||
|
||||
// Beta cannot see it...
|
||||
rec := do(t, s, "GET", "/api/team/invitations", beta.Token, nil)
|
||||
if strings.Contains(rec.Body.String(), "new@acme.com") {
|
||||
t.Fatalf("another tenant can see Acme's invitations: %s", rec.Body.String())
|
||||
}
|
||||
// ...nor withdraw it.
|
||||
if rec := do(t, s, "DELETE", "/api/team/invitations/"+inv.ID, beta.Token, nil); rec.Code == http.StatusNoContent {
|
||||
t.Fatal("another tenant withdrew Acme's invitation")
|
||||
}
|
||||
}
|
||||
|
||||
// The preview is unauthenticated by necessity - the holder has no account yet -
|
||||
// so what it discloses is the whole question.
|
||||
func TestThePreviewShowsWhatToJoinAndNothingElse(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
seedUser(fs)
|
||||
sess := login(t, s, "manager@acme.com", "correct horse battery")
|
||||
inv := invite(t, s, sess.Token, map[string]any{
|
||||
"email": "nikhil@acme.com", "full_name": "Nikhil", "role": "manager"})
|
||||
|
||||
rec := do(t, s, "GET", "/api/auth/invitation?code="+inv.Code, "", nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("preview: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var prev InvitationPreview
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &prev); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if prev.Role != "manager" || prev.Email != "nikhil@acme.com" {
|
||||
t.Errorf("preview should say what is being joined: %+v", prev)
|
||||
}
|
||||
// It must not become a way to read a company's staff list or anything else
|
||||
// about it beyond the one line the code already asserts.
|
||||
if strings.Contains(rec.Body.String(), "manager@acme.com") {
|
||||
t.Error("the preview disclosed the inviter's address")
|
||||
}
|
||||
|
||||
if rec := do(t, s, "GET", "/api/auth/invitation?code=NOPE", "", nil); rec.Code != http.StatusNotFound {
|
||||
t.Errorf("an invented code should 404, got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationEnforcesThePasswordFloor(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
seedUser(fs)
|
||||
sess := login(t, s, "manager@acme.com", "correct horse battery")
|
||||
inv := invite(t, s, sess.Token, map[string]any{"email": "short@acme.com"})
|
||||
|
||||
rec := do(t, s, "POST", "/api/auth/register", "", map[string]any{
|
||||
"code": inv.Code, "password": "short"})
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("a short password was accepted, got %d", rec.Code)
|
||||
}
|
||||
// And the invitation is NOT spent by a rejected attempt - otherwise one
|
||||
// mistyped password would cost the person their invitation.
|
||||
ok := do(t, s, "POST", "/api/auth/register", "", map[string]any{
|
||||
"code": inv.Code, "password": "a-good-long-password"})
|
||||
if ok.Code != http.StatusCreated {
|
||||
t.Fatalf("a failed attempt burned the invitation: %d %s", ok.Code, ok.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------- team --
|
||||
|
||||
func TestDeactivatingSomebodySignsThemOutNow(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
seedUser(fs)
|
||||
seedMember(fs, acmeStaffID, "leaver@acme.com", "Lee", "staff")
|
||||
mgr := login(t, s, "manager@acme.com", "correct horse battery")
|
||||
leaver := login(t, s, "leaver@acme.com", "correct horse battery")
|
||||
|
||||
if rec := do(t, s, "GET", "/api/auth/me", leaver.Token, nil); rec.Code != http.StatusOK {
|
||||
t.Fatalf("the leaver should be signed in to begin with, got %d", rec.Code)
|
||||
}
|
||||
|
||||
rec := do(t, s, "PATCH", "/api/team/"+acmeStaffID, mgr.Token, map[string]any{"active": false})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("deactivate: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
// The whole point. An access token lives twelve hours, so without revoking
|
||||
// the session, "remove their access" would remove it sometime tomorrow -
|
||||
// which is not what anybody pressing that button believes they have done.
|
||||
if rec := do(t, s, "GET", "/api/auth/me", leaver.Token, nil); rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("a deactivated account is still signed in, got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheLastOwnerCannotRemoveThemselves(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
seedMember(fs, acmeOwnerID, "boss@acme.com", "Bea", "owner")
|
||||
sess := login(t, s, "boss@acme.com", "correct horse battery")
|
||||
|
||||
for _, body := range []map[string]any{{"active": false}, {"role": "staff"}} {
|
||||
rec := do(t, s, "PATCH", "/api/team/"+acmeOwnerID, sess.Token, body)
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Fatalf("the only owner removed themselves with %v: %d %s",
|
||||
body, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTeamIsScopedToTheCallersCompany(t *testing.T) {
|
||||
s, fs := newServer(t)
|
||||
seedUser(fs)
|
||||
fs.addUser("other@beta.com", "correct horse battery", UserRecord{
|
||||
ID: "u2", ClientID: "client-beta", ClientName: "Beta Ltd",
|
||||
FullName: "Bo", Role: "manager", Active: true,
|
||||
})
|
||||
seedMember(fs, acmeOtherID, "asha@acme.com", "Asha", "manager")
|
||||
beta := login(t, s, "other@beta.com", "correct horse battery")
|
||||
|
||||
rec := do(t, s, "GET", "/api/team", beta.Token, nil)
|
||||
if strings.Contains(rec.Body.String(), "manager@acme.com") {
|
||||
t.Fatalf("another tenant's staff are visible: %s", rec.Body.String())
|
||||
}
|
||||
// And a uuid guessed from elsewhere changes nothing.
|
||||
// A real, well-formed id belonging to the OTHER tenant. The 404 must come
|
||||
// from the client scope in the UPDATE, not from the shape check above it.
|
||||
if rec := do(t, s, "PATCH", "/api/team/"+acmeOtherID, beta.Token,
|
||||
map[string]any{"role": "staff"}); rec.Code != http.StatusNotFound {
|
||||
t.Errorf("cross-tenant team edit was not refused, got %d", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -283,6 +283,16 @@ type Image struct {
|
||||
Available bool `json:"available"`
|
||||
URL string `json:"url,omitempty"`
|
||||
ExpiresIn int `json:"expires_in,omitempty"`
|
||||
// Auth says the URL is one of ours and needs this session's bearer token,
|
||||
// rather than a presigned object-store link that carries its own signature.
|
||||
//
|
||||
// It exists because the two are genuinely different to fetch and a client
|
||||
// cannot tell them apart by looking. A browser <img> can load the signed
|
||||
// one and CANNOT load this one, so the web app fetches it and hands over an
|
||||
// object URL; a mobile image view can attach the header and load it
|
||||
// directly. Guessing from whether the URL is absolute would work today and
|
||||
// break the first time object storage lives on the same host.
|
||||
Auth bool `json:"auth,omitempty"`
|
||||
// Reason is user-facing prose, present only when Available is false.
|
||||
Reason string `json:"reason,omitempty"`
|
||||
// Key is the object-store key, carried from the store to the handler that
|
||||
@@ -588,3 +598,100 @@ type CheckStep struct {
|
||||
Detail string `json:"detail"`
|
||||
Advice string `json:"advice,omitempty"`
|
||||
}
|
||||
|
||||
// ==================================================== team and invitations ==
|
||||
|
||||
// NewInvitation is an invitation about to be written. Only the hash crosses
|
||||
// this boundary; the plaintext code exists in the handler and in the one
|
||||
// response that returns it, and nowhere else.
|
||||
type NewInvitation struct {
|
||||
ClientID string
|
||||
Email string
|
||||
FullName string
|
||||
Role string
|
||||
CodeHash []byte
|
||||
InvitedBy string
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
// Invitation is a pending invitation as a manager sees it. It carries no code:
|
||||
// the plaintext is returned exactly once, by the request that created it, and
|
||||
// is not recoverable afterwards. A code a support engineer can look up later is
|
||||
// a code anyone with support access can redeem.
|
||||
type Invitation struct {
|
||||
ID string `json:"id"`
|
||||
Email string `json:"email"`
|
||||
FullName string `json:"full_name,omitempty"`
|
||||
Role string `json:"role"`
|
||||
InvitedBy string `json:"invited_by,omitempty"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
// Code is present ONLY on the response that mints it.
|
||||
Code string `json:"code,omitempty"`
|
||||
}
|
||||
|
||||
// InvitationPreview is what an unauthenticated client may learn from a code it
|
||||
// already holds: which company, for which address, in what role.
|
||||
//
|
||||
// Enough to render "Join TeNext Retail as a manager" before asking somebody to
|
||||
// choose a password, and no more. Unknown, expired, spent and revoked codes are
|
||||
// all one answer, for the reason enrolment already records: the difference only
|
||||
// helps somebody guessing, and the holder's next step is identical in all four
|
||||
// cases.
|
||||
type InvitationPreview struct {
|
||||
Client string `json:"client_name"`
|
||||
Email string `json:"email"`
|
||||
FullName string `json:"full_name,omitempty"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
// Registration is a redeemed invitation turning into an account. The email and
|
||||
// role come from the INVITATION, never from the request body: a code forwarded
|
||||
// to somebody else must not become an account for them, and a staff invitation
|
||||
// must not be redeemed into an owner.
|
||||
type Registration struct {
|
||||
Code string
|
||||
FullName string
|
||||
Password string
|
||||
Device string
|
||||
}
|
||||
|
||||
// TeamMember is one person in a company, as the team screen lists them.
|
||||
type TeamMember struct {
|
||||
ID string `json:"id"`
|
||||
Email string `json:"email"`
|
||||
FullName string `json:"full_name"`
|
||||
Role string `json:"role"`
|
||||
Active bool `json:"active"`
|
||||
LastLoginAt string `json:"last_login_at,omitempty"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
// TeamUpdate changes one member. Both fields are optional; a nil means "leave
|
||||
// this alone", which is what lets one endpoint serve "make them a manager" and
|
||||
// "they have left" without either silently doing the other.
|
||||
type TeamUpdate struct {
|
||||
Role *string `json:"role,omitempty"`
|
||||
Active *bool `json:"active,omitempty"`
|
||||
}
|
||||
|
||||
// ==================================================== devices and sessions ==
|
||||
|
||||
// DeviceSession is one signed-in device, as its owner sees it.
|
||||
//
|
||||
// This list is the point of opaque tokens rather than JWTs. The whole argument
|
||||
// for a session table was that "log that device out, now" has to actually work
|
||||
// on a product that puts customer data on shop-floor PCs and staff phones that
|
||||
// get lost, resold and shared - and until this existed there was no way to ask
|
||||
// what was signed in, let alone stop it.
|
||||
type DeviceSession struct {
|
||||
ID string `json:"id"`
|
||||
Device string `json:"device"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
LastUsedAt string `json:"last_used_at,omitempty"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
// Current marks the session making this request, so a client can label it
|
||||
// and can warn before somebody signs themselves out of the device in their
|
||||
// hand.
|
||||
Current bool `json:"current"`
|
||||
}
|
||||
|
||||
187
server/internal/store/api_faces.go
Normal file
187
server/internal/store/api_faces.go
Normal file
@@ -0,0 +1,187 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// Face images held by this server, for a deployment with no object storage.
|
||||
//
|
||||
// The bucket stays primary wherever one is configured: a presigned PUT never
|
||||
// passes the bytes through the API at all, which is what makes it the right
|
||||
// route at estate scale. This is the fallback that stops "no S3 account" from
|
||||
// meaning "no photograph of any customer, ever" - see migration 011 for why it
|
||||
// is bounded and therefore safe to keep here.
|
||||
|
||||
// DBKeyPrefix marks an image key that names a row in this database rather than
|
||||
// an object in a bucket.
|
||||
//
|
||||
// One column, `visits.image_key`, names either. A prefix rather than a second
|
||||
// nullable column because every read already has the key in hand and can tell
|
||||
// which store to ask without a further lookup - and because a key that does not
|
||||
// say where it lives is a key some future caller will hand to the wrong one.
|
||||
const DBKeyPrefix = "db:"
|
||||
|
||||
// ErrNoFace means there is no stored image under that key. Ordinary absence,
|
||||
// not a fault: most deployments store no faces at all.
|
||||
var ErrNoFace = errors.New("no such face image")
|
||||
|
||||
// PutVisitFace stores one face crop and returns the key that names it.
|
||||
//
|
||||
// The client and site come from the AGENT'S credential, never from the request,
|
||||
// so a shop PC cannot file an image under another tenant. There is no visitor
|
||||
// id yet - the server has not matched the template at this point - so the row
|
||||
// is claimed later, by RecordVisit, and swept if that never happens.
|
||||
func (s *Store) PutVisitFace(ctx context.Context, clientID, siteID string,
|
||||
jpeg []byte) (string, error) {
|
||||
|
||||
var id string
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
INSERT INTO visit_faces (client_id, site_id, image, bytes)
|
||||
VALUES ($1::uuid, $2::uuid, $3, $4)
|
||||
RETURNING id::text`, clientID, siteID, jpeg, len(jpeg)).Scan(&id)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("store face: %w", err)
|
||||
}
|
||||
return DBKeyPrefix + id, nil
|
||||
}
|
||||
|
||||
// VisitFace reads one back, scoped to the tenant that is asking.
|
||||
//
|
||||
// The client id is in the WHERE clause and not merely checked afterwards: an
|
||||
// image key travels in an API response, and a caller who kept one from a
|
||||
// previous tenancy - or guessed one - must get nothing rather than a photograph
|
||||
// of somebody else's customer.
|
||||
func (s *Store) VisitFace(ctx context.Context, clientID, key string) ([]byte, error) {
|
||||
id, ok := strings.CutPrefix(key, DBKeyPrefix)
|
||||
if !ok || !looksLikeUUID(id) {
|
||||
return nil, ErrNoFace
|
||||
}
|
||||
var img []byte
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT image FROM visit_faces
|
||||
WHERE id = $1::uuid AND client_id = $2::uuid`, id, clientID).Scan(&img)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNoFace
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read face: %w", err)
|
||||
}
|
||||
return img, nil
|
||||
}
|
||||
|
||||
// DeleteVisitFaces erases stored faces outright.
|
||||
//
|
||||
// Used by the erasure path, which must destroy the image rather than unlink it.
|
||||
// The rule the bucket path already follows applies unchanged: a face image that
|
||||
// survives an erasure request is the one outcome that endpoint must never
|
||||
// produce, so a failure here has to reach the caller.
|
||||
func (s *Store) DeleteVisitFaces(ctx context.Context, clientID string, keys []string) error {
|
||||
ids := make([]string, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
if id, ok := strings.CutPrefix(k, DBKeyPrefix); ok && looksLikeUUID(id) {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
DELETE FROM visit_faces
|
||||
WHERE client_id = $1::uuid AND id = ANY($2::uuid[])`, clientID, ids)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete faces: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// pruneVisitorFaces keeps ONE stored face per visitor: the newest.
|
||||
//
|
||||
// This is what bounds the table to the customer base rather than to footfall,
|
||||
// and it is the whole reason face images may live in Postgres at all. It runs
|
||||
// inside RecordVisit's transaction, right after the visit is linked to a
|
||||
// person, so the superseded row and the key that named it disappear together.
|
||||
//
|
||||
// ONE statement, and that is not tidiness. The first version read the old keys
|
||||
// with `UPDATE visits SET image_key = ” ... RETURNING image_key` - which
|
||||
// returns the value AFTER the update, so every key came back as the empty
|
||||
// string it had just been set to, the delete list was always empty, and the
|
||||
// table grew with footfall exactly as if the prune did not exist. The visits
|
||||
// looked right; only the row count gave it away. A CTE cannot have that bug:
|
||||
// `doomed` reads the pre-image, and both the update and the delete are driven
|
||||
// from it.
|
||||
//
|
||||
// The old key is blanked rather than marked deleted. `image_deleted_at` means
|
||||
// an erasure was performed and is what an auditor reads; borrowing it to mean
|
||||
// "we kept a better photo" would put ordinary housekeeping into the record of
|
||||
// legal requests.
|
||||
func pruneVisitorFaces(ctx context.Context, tx pgx.Tx, clientID, visitorID, keepVisitID string) error {
|
||||
_, err := tx.Exec(ctx, `
|
||||
WITH doomed AS (
|
||||
SELECT v.id, v.image_key
|
||||
FROM visits v
|
||||
WHERE v.client_id = $1::uuid
|
||||
AND v.visitor_id = $2::uuid
|
||||
AND v.id <> $3::uuid
|
||||
AND v.image_key LIKE 'db:%'
|
||||
), cleared AS (
|
||||
UPDATE visits SET image_key = ''
|
||||
WHERE id IN (SELECT id FROM doomed)
|
||||
)
|
||||
DELETE FROM visit_faces f
|
||||
WHERE f.client_id = $1::uuid
|
||||
-- Joined on the text form deliberately: the alternative is casting a
|
||||
-- substring of a stored key to uuid, which throws on a malformed row
|
||||
-- and would take an ordinary visit down with it.
|
||||
AND 'db:' || f.id::text IN (SELECT image_key FROM doomed)`,
|
||||
clientID, visitorID, keepVisitID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("prune faces: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SweepOrphanFaces removes images no visit ever claimed.
|
||||
//
|
||||
// An agent uploads a face before the server has decided who it is, so a row is
|
||||
// briefly unreferenced by design. It stays that way for good if the visit that
|
||||
// would have claimed it never arrives - a dropped queue, a corrupt entry - and
|
||||
// that is one stored photograph of a real person that nothing points at and
|
||||
// nothing would ever delete. Erasure could not reach it either: it is found
|
||||
// through the visitor, and this row has none.
|
||||
func (s *Store) SweepOrphanFaces(ctx context.Context, olderThan string) (int, error) {
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
DELETE FROM visit_faces f
|
||||
WHERE f.captured_at < now() - $1::interval
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM visits v
|
||||
WHERE v.image_key = 'db:' || f.id::text)`, olderThan)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("sweep faces: %w", err)
|
||||
}
|
||||
return int(tag.RowsAffected()), nil
|
||||
}
|
||||
|
||||
func looksLikeUUID(s string) bool {
|
||||
if len(s) != 36 {
|
||||
return false
|
||||
}
|
||||
for i, c := range s {
|
||||
switch i {
|
||||
case 8, 13, 18, 23:
|
||||
if c != '-' {
|
||||
return false
|
||||
}
|
||||
default:
|
||||
isHex := (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
|
||||
if !isHex {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
261
server/internal/store/api_faces_live_test.go
Normal file
261
server/internal/store/api_faces_live_test.go
Normal file
@@ -0,0 +1,261 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/loyaly/behavision-server/internal/contract"
|
||||
"github.com/loyaly/behavision-server/internal/ingest"
|
||||
)
|
||||
|
||||
// Face images held by this server, against a real database.
|
||||
//
|
||||
// The prune is the whole reason this is allowed to live in Postgres at all -
|
||||
// migration 011 argues it explicitly against 009's "face images grow with every
|
||||
// visitor who ever walks in" - so it is the one behaviour that must be proved
|
||||
// against the real thing rather than a fake that would simply agree with me.
|
||||
|
||||
func seedAgentSite(t *testing.T, st *Store, name string) ingest.Site {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
var site ingest.Site
|
||||
if err := st.pool.QueryRow(ctx, `
|
||||
INSERT INTO clients (name, slug) VALUES ($1, $1) RETURNING id::text`,
|
||||
name).Scan(&site.ClientID); err != nil {
|
||||
t.Fatalf("seed client: %v", err)
|
||||
}
|
||||
if err := st.pool.QueryRow(ctx, `
|
||||
INSERT INTO sites (client_id, name, slug) VALUES ($1::uuid, $2, $3)
|
||||
RETURNING id::text`, site.ClientID, name, name).Scan(&site.SiteID); err != nil {
|
||||
t.Fatalf("seed site: %v", err)
|
||||
}
|
||||
if err := st.pool.QueryRow(ctx, `
|
||||
INSERT INTO agents (client_id, site_id, mqtt_username)
|
||||
VALUES ($1::uuid, $2::uuid, $3)
|
||||
RETURNING id::text`, site.ClientID, site.SiteID, name).Scan(&site.AgentID); err != nil {
|
||||
t.Fatalf("seed agent: %v", err)
|
||||
}
|
||||
site.Slug = name
|
||||
return site
|
||||
}
|
||||
|
||||
func embedding(seed float32) []float32 {
|
||||
v := make([]float32, contract.EmbeddingDim)
|
||||
for i := range v {
|
||||
v[i] = seed
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// The bound: one person seen many times leaves ONE stored image, not one per
|
||||
// visit. Without this the table grows with footfall, which is precisely the
|
||||
// property that keeps face images out of the database everywhere else.
|
||||
func TestLiveOnlyOneFaceSurvivesPerVisitor(t *testing.T) {
|
||||
st := liveStore(t)
|
||||
ctx := context.Background()
|
||||
site := seedAgentSite(t, st, "faces-"+stamp())
|
||||
|
||||
var keys []string
|
||||
for i := 0; i < 5; i++ {
|
||||
key, err := st.PutVisitFace(ctx, site.ClientID, site.SiteID,
|
||||
[]byte(fmt.Sprintf("jpeg-%d", i)))
|
||||
if err != nil {
|
||||
t.Fatalf("store face %d: %v", i, err)
|
||||
}
|
||||
keys = append(keys, key)
|
||||
|
||||
// The SAME person every time: one embedding, so the matcher resolves
|
||||
// them to one visitor.
|
||||
ok, err := st.RecordVisit(ctx, site, &contract.Visit{
|
||||
EventID: fmt.Sprintf("%s-%d", site.Slug, i),
|
||||
OccurredAt: time.Now().UTC().Add(time.Duration(i) * time.Second),
|
||||
CameraID: "door",
|
||||
IsNew: i == 0,
|
||||
Quality: 0.8,
|
||||
Similarity: 0.9,
|
||||
Embedding: embedding(0.05),
|
||||
ImageKey: key,
|
||||
})
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("visit %d: ok=%v err=%v", i, ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
var stored int
|
||||
if err := st.pool.QueryRow(ctx,
|
||||
`SELECT count(*) FROM visit_faces WHERE client_id = $1::uuid`,
|
||||
site.ClientID).Scan(&stored); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored != 1 {
|
||||
t.Fatalf("five visits by one person left %d stored faces - the table "+
|
||||
"grows with footfall, which is exactly what migration 011 promises "+
|
||||
"it does not", stored)
|
||||
}
|
||||
|
||||
// And it is the NEWEST that survived: every surface shows a customer's
|
||||
// latest view, so keeping an older one would quietly show a stale face.
|
||||
var surviving string
|
||||
if err := st.pool.QueryRow(ctx,
|
||||
`SELECT 'db:' || id::text FROM visit_faces WHERE client_id = $1::uuid`,
|
||||
site.ClientID).Scan(&surviving); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if surviving != keys[len(keys)-1] {
|
||||
t.Errorf("kept %s, want the newest %s", surviving, keys[len(keys)-1])
|
||||
}
|
||||
|
||||
// The superseded keys are blanked, not left dangling. A visit advertising
|
||||
// an image that is not there renders as a broken picture on the one screen
|
||||
// meant to show it.
|
||||
var dangling int
|
||||
if err := st.pool.QueryRow(ctx, `
|
||||
SELECT count(*) FROM visits v
|
||||
WHERE v.client_id = $1::uuid AND v.image_key LIKE 'db:%'
|
||||
AND NOT EXISTS (SELECT 1 FROM visit_faces f
|
||||
WHERE 'db:' || f.id::text = v.image_key)`,
|
||||
site.ClientID).Scan(&dangling); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dangling != 0 {
|
||||
t.Errorf("%d visits point at a face that is gone", dangling)
|
||||
}
|
||||
|
||||
// image_deleted_at is the record of an ERASURE and is what an auditor
|
||||
// reads. Ordinary housekeeping must not write into it.
|
||||
var marked int
|
||||
if err := st.pool.QueryRow(ctx, `
|
||||
SELECT count(*) FROM visits
|
||||
WHERE client_id = $1::uuid AND image_deleted_at IS NOT NULL`,
|
||||
site.ClientID).Scan(&marked); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if marked != 0 {
|
||||
t.Errorf("%d visits were marked as erased by a routine prune", marked)
|
||||
}
|
||||
}
|
||||
|
||||
// Two different people keep one face each. The prune must be scoped to the
|
||||
// person, not to the site - otherwise every new arrival would delete the
|
||||
// previous customer's photo.
|
||||
func TestLiveThePruneIsPerPersonNotPerSite(t *testing.T) {
|
||||
st := liveStore(t)
|
||||
ctx := context.Background()
|
||||
site := seedAgentSite(t, st, "faces2-"+stamp())
|
||||
|
||||
for i, seed := range []float32{0.05, -0.05} {
|
||||
key, err := st.PutVisitFace(ctx, site.ClientID, site.SiteID,
|
||||
[]byte(fmt.Sprintf("person-%d", i)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ok, err := st.RecordVisit(ctx, site, &contract.Visit{
|
||||
EventID: fmt.Sprintf("%s-p%d", site.Slug, i),
|
||||
OccurredAt: time.Now().UTC(),
|
||||
CameraID: "door",
|
||||
IsNew: true,
|
||||
Quality: 0.8,
|
||||
Embedding: embedding(seed),
|
||||
ImageKey: key,
|
||||
}); err != nil || !ok {
|
||||
t.Fatalf("visit: ok=%v err=%v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
var stored int
|
||||
if err := st.pool.QueryRow(ctx,
|
||||
`SELECT count(*) FROM visit_faces WHERE client_id = $1::uuid`,
|
||||
site.ClientID).Scan(&stored); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored != 2 {
|
||||
t.Fatalf("two people should keep one face each, got %d", stored)
|
||||
}
|
||||
}
|
||||
|
||||
// An agent uploads a face BEFORE the server has decided who it is, so a row is
|
||||
// briefly unreferenced by design - and permanently so if the visit that would
|
||||
// have claimed it never arrives. That is a stored photograph of a real person
|
||||
// that nothing points at, which erasure could never reach because it is found
|
||||
// through the visitor and this row has none.
|
||||
func TestLiveAnUnclaimedFaceIsSweptAway(t *testing.T) {
|
||||
st := liveStore(t)
|
||||
ctx := context.Background()
|
||||
site := seedAgentSite(t, st, "faces3-"+stamp())
|
||||
|
||||
key, err := st.PutVisitFace(ctx, site.ClientID, site.SiteID, []byte("orphan"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Age it past the sweep window rather than sleeping.
|
||||
if _, err := st.pool.Exec(ctx, `
|
||||
UPDATE visit_faces SET captured_at = now() - interval '3 days'
|
||||
WHERE 'db:' || id::text = $1`, key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
n, err := st.SweepOrphanFaces(ctx, "1 day")
|
||||
if err != nil {
|
||||
t.Fatalf("sweep: %v", err)
|
||||
}
|
||||
if n < 1 {
|
||||
t.Fatal("the orphan was not swept")
|
||||
}
|
||||
if _, err := st.VisitFace(ctx, site.ClientID, key); err == nil {
|
||||
t.Fatal("the orphan is still readable")
|
||||
}
|
||||
}
|
||||
|
||||
// A face a visit DOES point at must survive the sweep, however old it is. A
|
||||
// regular customer's photo is exactly the row that gets old.
|
||||
func TestLiveTheSweepKeepsAClaimedFace(t *testing.T) {
|
||||
st := liveStore(t)
|
||||
ctx := context.Background()
|
||||
site := seedAgentSite(t, st, "faces4-"+stamp())
|
||||
|
||||
key, err := st.PutVisitFace(ctx, site.ClientID, site.SiteID, []byte("kept"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ok, err := st.RecordVisit(ctx, site, &contract.Visit{
|
||||
EventID: site.Slug + "-keep", OccurredAt: time.Now().UTC(),
|
||||
CameraID: "door", IsNew: true, Quality: 0.8,
|
||||
Embedding: embedding(0.07), ImageKey: key,
|
||||
}); err != nil || !ok {
|
||||
t.Fatalf("visit: ok=%v err=%v", ok, err)
|
||||
}
|
||||
if _, err := st.pool.Exec(ctx, `
|
||||
UPDATE visit_faces SET captured_at = now() - interval '400 days'
|
||||
WHERE 'db:' || id::text = $1`, key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := st.SweepOrphanFaces(ctx, "1 day"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.VisitFace(ctx, site.ClientID, key); err != nil {
|
||||
t.Fatalf("a claimed face was swept away: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// An image key travels in API responses. A caller who kept one, or guessed one,
|
||||
// must get nothing rather than another company's customer.
|
||||
func TestLiveAFaceIsNotReadableByAnotherTenant(t *testing.T) {
|
||||
st := liveStore(t)
|
||||
ctx := context.Background()
|
||||
a := seedAgentSite(t, st, "facesa-"+stamp())
|
||||
b := seedAgentSite(t, st, "facesb-"+stamp())
|
||||
|
||||
key, err := st.PutVisitFace(ctx, a.ClientID, a.SiteID, []byte("private"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.VisitFace(ctx, b.ClientID, key); err == nil {
|
||||
t.Fatal("another tenant read a stored face")
|
||||
}
|
||||
if _, err := st.VisitFace(ctx, a.ClientID, key); err != nil {
|
||||
t.Fatalf("the owning tenant could not read its own face: %v", err)
|
||||
}
|
||||
}
|
||||
347
server/internal/store/api_team.go
Normal file
347
server/internal/store/api_team.go
Normal file
@@ -0,0 +1,347 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/loyaly/behavision-server/internal/api"
|
||||
)
|
||||
|
||||
// Adding people to a company, and taking them out again.
|
||||
//
|
||||
// Registration here is by invitation only. `handlers_team.go` carries the
|
||||
// product argument; what matters at this layer is that every statement is
|
||||
// scoped by the CALLER'S client id, taken from their session, so a manager
|
||||
// cannot invite somebody into, list, or remove a member of a company that is
|
||||
// not theirs by guessing a uuid.
|
||||
|
||||
// CreateInvitation writes a pending invitation for one company.
|
||||
//
|
||||
// The client id is not trusted from a caller anywhere above this, but it is
|
||||
// still joined against `clients` here rather than inserted blind: a foreign-key
|
||||
// violation surfaces as an opaque 500, and a row that names a company which has
|
||||
// since been deleted is worse than a clean refusal.
|
||||
func (s *Store) CreateInvitation(ctx context.Context, in api.NewInvitation) (api.Invitation, error) {
|
||||
var out api.Invitation
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
INSERT INTO invitations (client_id, email, full_name, role, code_hash,
|
||||
invited_by, expires_at)
|
||||
SELECT c.id, $2, $3, $4, $5, $6::uuid, $7
|
||||
FROM clients c
|
||||
WHERE c.id = $1::uuid
|
||||
RETURNING id::text, email, full_name, role,
|
||||
to_char(expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"'),
|
||||
to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')`,
|
||||
in.ClientID, in.Email, in.FullName, in.Role, in.CodeHash,
|
||||
nullUUID(in.InvitedBy), in.ExpiresAt,
|
||||
).Scan(&out.ID, &out.Email, &out.FullName, &out.Role,
|
||||
&out.ExpiresAt, &out.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return api.Invitation{}, errors.New("no such company")
|
||||
}
|
||||
if err != nil {
|
||||
return api.Invitation{}, fmt.Errorf("create invitation: %w", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// PendingInvitations lists the invitations that have been sent and not yet
|
||||
// taken up. Spent and revoked rows are history and are deliberately not here:
|
||||
// the question this list answers is "who is still waiting to join".
|
||||
func (s *Store) PendingInvitations(ctx context.Context, clientID string) ([]api.Invitation, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT i.id::text, i.email, i.full_name, i.role,
|
||||
COALESCE(u.full_name, u.email, ''),
|
||||
to_char(i.expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"'),
|
||||
to_char(i.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')
|
||||
FROM invitations i
|
||||
LEFT JOIN app_users u ON u.id = i.invited_by
|
||||
WHERE i.client_id = $1::uuid
|
||||
AND i.used_at IS NULL AND i.revoked_at IS NULL
|
||||
AND i.expires_at > now()
|
||||
ORDER BY i.created_at DESC`, clientID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list invitations: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []api.Invitation
|
||||
for rows.Next() {
|
||||
var v api.Invitation
|
||||
if err := rows.Scan(&v.ID, &v.Email, &v.FullName, &v.Role,
|
||||
&v.InvitedBy, &v.ExpiresAt, &v.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// RevokeInvitation withdraws one before it is used.
|
||||
//
|
||||
// Scoped by client in the UPDATE, and it refuses an already-spent invitation
|
||||
// rather than silently doing nothing: "I revoked it" and "somebody had already
|
||||
// joined with it" need opposite follow-up actions from whoever asked.
|
||||
func (s *Store) RevokeInvitation(ctx context.Context, clientID, id string) error {
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
UPDATE invitations SET revoked_at = now()
|
||||
WHERE id = $2::uuid AND client_id = $1::uuid
|
||||
AND used_at IS NULL AND revoked_at IS NULL`, clientID, id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("revoke invitation: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return errors.New("no such pending invitation")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// InvitationByCode is the unauthenticated preview: what a holder may learn
|
||||
// about a code they already have.
|
||||
//
|
||||
// Every way of not being valid returns the same error, so this cannot be used
|
||||
// to tell an expired code from an invented one.
|
||||
func (s *Store) InvitationByCode(ctx context.Context, hash []byte) (api.InvitationPreview, error) {
|
||||
var out api.InvitationPreview
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT c.name, i.email, i.full_name, i.role
|
||||
FROM invitations i
|
||||
JOIN clients c ON c.id = i.client_id
|
||||
WHERE i.code_hash = $1
|
||||
AND i.used_at IS NULL AND i.revoked_at IS NULL
|
||||
AND i.expires_at > now()`, hash,
|
||||
).Scan(&out.Client, &out.Email, &out.FullName, &out.Role)
|
||||
if err != nil {
|
||||
return api.InvitationPreview{}, errors.New("that invitation is not valid")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// RedeemInvitation turns a code into an account, in ONE transaction.
|
||||
//
|
||||
// Two properties, and both were learned elsewhere in this system:
|
||||
//
|
||||
// - Single use is enforced BY the update. `used_at IS NULL` and the write are
|
||||
// one statement, so two people racing on one invitation cannot both win.
|
||||
// Check-then-update would be exactly that race, and the loser would get a
|
||||
// second account rather than an error.
|
||||
// - The account and the redemption commit together. A spent invitation with
|
||||
// no user behind it is an invitation nobody can use and nobody can see is
|
||||
// broken; a user with the invitation still open is a second account waiting
|
||||
// to be created by anyone who was forwarded the code.
|
||||
//
|
||||
// The email and the role come from the ROW, never from the request. A code
|
||||
// passed on to a colleague must not become an account for them, and a staff
|
||||
// invitation must not be redeemed as an owner.
|
||||
func (s *Store) RedeemInvitation(ctx context.Context, hash []byte,
|
||||
fullName, passwordHash string) (api.UserRecord, error) {
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return api.UserRecord{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx) //nolint:errcheck // no-op once committed
|
||||
|
||||
var clientID, email, role, invitedName string
|
||||
err = tx.QueryRow(ctx, `
|
||||
UPDATE invitations SET used_at = now()
|
||||
WHERE code_hash = $1
|
||||
AND used_at IS NULL AND revoked_at IS NULL AND expires_at > now()
|
||||
RETURNING client_id::text, email, role, full_name`, hash,
|
||||
).Scan(&clientID, &email, &role, &invitedName)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return api.UserRecord{}, errors.New("that invitation is not valid")
|
||||
}
|
||||
if err != nil {
|
||||
return api.UserRecord{}, fmt.Errorf("redeem invitation: %w", err)
|
||||
}
|
||||
|
||||
if fullName == "" {
|
||||
// The inviter may have typed a name; use it rather than leaving a
|
||||
// blank row that every screen then renders as an email address.
|
||||
fullName = invitedName
|
||||
}
|
||||
|
||||
var rec api.UserRecord
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO app_users (client_id, email, password_hash, full_name, role)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5)
|
||||
RETURNING id::text, email, full_name, role`,
|
||||
clientID, email, passwordHash, fullName, role,
|
||||
).Scan(&rec.ID, &rec.Email, &rec.FullName, &rec.Role)
|
||||
if err != nil {
|
||||
return api.UserRecord{}, fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
|
||||
var clientName string
|
||||
if err := tx.QueryRow(ctx, `SELECT name FROM clients WHERE id = $1::uuid`,
|
||||
clientID).Scan(&clientName); err != nil {
|
||||
return api.UserRecord{}, err
|
||||
}
|
||||
|
||||
// Recorded against the new account, not the inviter: this is the moment a
|
||||
// person gained access, and the row should name who did.
|
||||
rec.ClientID, rec.ClientName, rec.Active, rec.Found = clientID, clientName, true, true
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return api.UserRecord{}, err
|
||||
}
|
||||
return rec, nil
|
||||
}
|
||||
|
||||
// Team lists the people in one company.
|
||||
func (s *Store) Team(ctx context.Context, clientID string) ([]api.TeamMember, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id::text, email, full_name, role, active,
|
||||
COALESCE(to_char(last_login_at AT TIME ZONE 'UTC',
|
||||
'YYYY-MM-DD"T"HH24:MI:SS"Z"'), ''),
|
||||
to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')
|
||||
FROM app_users
|
||||
WHERE client_id = $1::uuid
|
||||
ORDER BY active DESC, full_name, email`, clientID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list team: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []api.TeamMember
|
||||
for rows.Next() {
|
||||
var m api.TeamMember
|
||||
if err := rows.Scan(&m.ID, &m.Email, &m.FullName, &m.Role, &m.Active,
|
||||
&m.LastLoginAt, &m.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// UpdateTeamMember changes a role, or deactivates somebody who has left.
|
||||
//
|
||||
// Deactivating REVOKES their sessions in the same transaction. Leaving them
|
||||
// live would mean "remove their access" removed it in twelve hours' time,
|
||||
// whenever their access token happened to expire - which is not what anybody
|
||||
// pressing that button believes they have just done, and is precisely the case
|
||||
// an opaque-token session table exists to handle.
|
||||
func (s *Store) UpdateTeamMember(ctx context.Context, clientID, userID string,
|
||||
up api.TeamUpdate) (api.TeamMember, error) {
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return api.TeamMember{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx) //nolint:errcheck // no-op once committed
|
||||
|
||||
var m api.TeamMember
|
||||
err = tx.QueryRow(ctx, `
|
||||
UPDATE app_users
|
||||
SET role = COALESCE($3, role),
|
||||
active = COALESCE($4, active)
|
||||
WHERE id = $2::uuid AND client_id = $1::uuid
|
||||
RETURNING id::text, email, full_name, role, active,
|
||||
COALESCE(to_char(last_login_at AT TIME ZONE 'UTC',
|
||||
'YYYY-MM-DD"T"HH24:MI:SS"Z"'), ''),
|
||||
to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')`,
|
||||
clientID, userID, up.Role, up.Active,
|
||||
).Scan(&m.ID, &m.Email, &m.FullName, &m.Role, &m.Active,
|
||||
&m.LastLoginAt, &m.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return api.TeamMember{}, errors.New("no such team member")
|
||||
}
|
||||
if err != nil {
|
||||
return api.TeamMember{}, fmt.Errorf("update team member: %w", err)
|
||||
}
|
||||
|
||||
if up.Active != nil && !*up.Active {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
UPDATE sessions SET revoked_at = now()
|
||||
WHERE user_id = $1::uuid AND revoked_at IS NULL`, userID); err != nil {
|
||||
return api.TeamMember{}, fmt.Errorf("revoke sessions: %w", err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return api.TeamMember{}, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// OwnerCount counts the active owners of a company.
|
||||
//
|
||||
// Used to refuse the change that locks a company out of its own account: the
|
||||
// last owner may not demote or deactivate themselves. There is no support path
|
||||
// back from that except a shell on the server, which is the thing this whole
|
||||
// surface exists to stop needing.
|
||||
func (s *Store) OwnerCount(ctx context.Context, clientID string) (int, error) {
|
||||
var n int
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT count(*) FROM app_users
|
||||
WHERE client_id = $1::uuid AND role = 'owner' AND active`, clientID).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// ============================================================== sessions ====
|
||||
|
||||
// UserSessions lists one person's live sessions, newest first.
|
||||
func (s *Store) UserSessions(ctx context.Context, userID string) ([]api.DeviceSession, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id::text, device,
|
||||
to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"'),
|
||||
COALESCE(to_char(last_used_at AT TIME ZONE 'UTC',
|
||||
'YYYY-MM-DD"T"HH24:MI:SS"Z"'), ''),
|
||||
to_char(refresh_expires_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')
|
||||
FROM sessions
|
||||
WHERE user_id = $1::uuid AND revoked_at IS NULL
|
||||
AND refresh_expires_at > now()
|
||||
ORDER BY COALESCE(last_used_at, created_at) DESC`, userID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list sessions: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []api.DeviceSession
|
||||
for rows.Next() {
|
||||
var d api.DeviceSession
|
||||
if err := rows.Scan(&d.ID, &d.Device, &d.CreatedAt,
|
||||
&d.LastUsedAt, &d.ExpiresAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, d)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// RevokeUserSession signs one device out.
|
||||
//
|
||||
// Scoped by user_id in the UPDATE, so a session id - which is not a secret and
|
||||
// travels in a list - cannot be used to sign somebody else out.
|
||||
func (s *Store) RevokeUserSession(ctx context.Context, userID, sessionID string) error {
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
UPDATE sessions SET revoked_at = now()
|
||||
WHERE id = $2::uuid AND user_id = $1::uuid AND revoked_at IS NULL`,
|
||||
userID, sessionID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("revoke session: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return errors.New("no such session")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RevokeOtherSessions is the "sign out everywhere else" button.
|
||||
//
|
||||
// It keeps the caller's own session deliberately: somebody who has just lost a
|
||||
// phone should not also be signed out of the device they are holding, which
|
||||
// would leave them re-authenticating in the middle of an emergency.
|
||||
func (s *Store) RevokeOtherSessions(ctx context.Context, userID, keepSessionID string) (int, error) {
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
UPDATE sessions SET revoked_at = now()
|
||||
WHERE user_id = $1::uuid AND id <> $2::uuid AND revoked_at IS NULL`,
|
||||
userID, keepSessionID)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("revoke sessions: %w", err)
|
||||
}
|
||||
return int(tag.RowsAffected()), nil
|
||||
}
|
||||
@@ -150,6 +150,14 @@ func (s *Store) RecordVisit(ctx context.Context, site ingest.Site,
|
||||
visitorID, v.OccurredAt, site.ClientID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
// Now that we know who this was, drop any face this server was holding
|
||||
// for them from an earlier visit. Only ever one survives per person,
|
||||
// which is what bounds visit_faces to the customer base rather than to
|
||||
// footfall - see migration 011. A bucket deployment writes no such keys
|
||||
// and this does nothing.
|
||||
if err := pruneVisitorFaces(ctx, tx, site.ClientID, visitorID, visitID); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(ctx,
|
||||
|
||||
1
server/internal/web/dist/assets/index-Bgt5SnW3.css
vendored
Normal file
1
server/internal/web/dist/assets/index-Bgt5SnW3.css
vendored
Normal file
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
46
server/internal/web/dist/assets/index-Dv7hKDIX.js
vendored
Normal file
46
server/internal/web/dist/assets/index-Dv7hKDIX.js
vendored
Normal file
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
4
server/internal/web/dist/index.html
vendored
4
server/internal/web/dist/index.html
vendored
@@ -5,8 +5,8 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="color-scheme" content="dark" />
|
||||
<title>Behavision</title>
|
||||
<script type="module" crossorigin src="/assets/index-tRretU9M.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-CtuyPF09.css">
|
||||
<script type="module" crossorigin src="/assets/index-Dv7hKDIX.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-Bgt5SnW3.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
60
server/migrations/010_invitations.sql
Normal file
60
server/migrations/010_invitations.sql
Normal file
@@ -0,0 +1,60 @@
|
||||
-- Adding a second person to a company.
|
||||
--
|
||||
-- Until now a tenant had exactly the users `provision user` had created on the
|
||||
-- server's own command line. That is not a gap in a UI, it is a gap in the
|
||||
-- product: a shop with an owner and four staff either shares one password
|
||||
-- between five people or raises a support ticket to add each of them, and a
|
||||
-- mobile app for shop floor staff cannot exist at all when there is only one
|
||||
-- account to sign in with.
|
||||
--
|
||||
-- Registration is by INVITATION, never open signup. That is the same line
|
||||
-- `handlers_admin.go` already draws for creating a company: an endpoint a
|
||||
-- stranger can call to create an account is a much larger thing to secure than
|
||||
-- one reachable only through a manager who already has one, and a self-created
|
||||
-- account in a tenant is a row nobody asked for holding a place in a table
|
||||
-- every query joins against.
|
||||
--
|
||||
-- The single-use guarantee is the same one enrolment codes use, and for the
|
||||
-- same reason: it lives in the UPDATE (`used_at IS NULL` and the write are one
|
||||
-- statement), never in a check followed by a write, so two people racing on one
|
||||
-- invitation cannot both win.
|
||||
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS invitations (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
client_id uuid NOT NULL REFERENCES clients(id) ON DELETE CASCADE,
|
||||
-- The address the invitation was issued FOR. It becomes the account's
|
||||
-- address on redemption and is not caller-supplied at that point: letting
|
||||
-- the redeemer choose would turn one invitation into an account for
|
||||
-- anybody who was forwarded the email.
|
||||
email text NOT NULL,
|
||||
full_name text NOT NULL DEFAULT '',
|
||||
-- 'admin' is deliberately NOT allowed. A platform administrator is defined
|
||||
-- by having no client at all, so an invitation - which always carries one -
|
||||
-- could never mint a real one; what it could do is put the string 'admin'
|
||||
-- on a tenant-scoped row, and `adminOnly` guards against exactly that
|
||||
-- combination existing. Refusing it here means it cannot be created in the
|
||||
-- first place.
|
||||
role text NOT NULL DEFAULT 'staff',
|
||||
-- Only the hash. An invitation is a credential for as long as it is
|
||||
-- unused, so a database dump must not contain a working one - the same
|
||||
-- rule sessions and enrolment codes already follow.
|
||||
code_hash bytea NOT NULL UNIQUE,
|
||||
invited_by uuid REFERENCES app_users(id) ON DELETE SET NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
used_at timestamptz,
|
||||
used_by uuid REFERENCES app_users(id) ON DELETE SET NULL,
|
||||
revoked_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT invitations_role_known
|
||||
CHECK (role IN ('owner', 'manager', 'staff'))
|
||||
);
|
||||
|
||||
-- Pending invitations only. The list a manager looks at is "who has been asked
|
||||
-- and has not joined yet"; spent and revoked rows are history.
|
||||
CREATE INDEX IF NOT EXISTS invitations_pending_idx
|
||||
ON invitations (client_id, created_at DESC)
|
||||
WHERE used_at IS NULL AND revoked_at IS NULL;
|
||||
|
||||
COMMIT;
|
||||
60
server/migrations/011_visit_faces.sql
Normal file
60
server/migrations/011_visit_faces.sql
Normal file
@@ -0,0 +1,60 @@
|
||||
-- Face images for a deployment that has no object storage.
|
||||
--
|
||||
-- 009 did this for camera snapshots and its own comment says why face images
|
||||
-- are different: "Face images grow with every visitor who ever walks in, which
|
||||
-- is why they stay in a bucket." That is true of face images kept PER VISIT,
|
||||
-- and it is the reason this table is bounded to one row per visitor instead.
|
||||
--
|
||||
-- The problem it fixes is the one 009 fixed one level up. With no bucket the
|
||||
-- API answers "This system is not storing customer photos" for every arrival,
|
||||
-- forever - including on the mobile feed, whose entire purpose is to put a face
|
||||
-- in front of somebody so they can recognise the customer walking towards them.
|
||||
-- A shop that turned `app.store_faces` on and has no S3 account got nothing.
|
||||
--
|
||||
-- What makes this bounded, which is the only reason it is acceptable here:
|
||||
--
|
||||
-- * The engine still gates capture. `app.store_faces` is false by default and
|
||||
-- no crop is written without it, so this table changes what happens to an
|
||||
-- image that already exists - it does not change whether one is taken.
|
||||
-- * ONE ROW SURVIVES PER VISITOR. `RecordVisit` prunes the previous row when
|
||||
-- it links a newer one, so storage is (customers x ~20 KB) and grows with
|
||||
-- the customer base, not with footfall. A shop seen by 5,000 people holds
|
||||
-- about 100 MB whether they visit once or a thousand times.
|
||||
-- * Nothing reads a superseded face anyway. Every surface - the arrivals
|
||||
-- feed, the customer record, the mobile app - shows the customer's latest
|
||||
-- view, which is what `VisitorImageKey` has always returned.
|
||||
--
|
||||
-- Where a bucket IS configured this table is never written: the presigned path
|
||||
-- stays primary, because it never passes the bytes through the API at all,
|
||||
-- which is what makes it the right route at estate scale.
|
||||
--
|
||||
-- Keys are prefixed `db:` in `visits.image_key` so one column can name an
|
||||
-- object in either place and the read path can tell which without a second
|
||||
-- lookup or a nullable column.
|
||||
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS visit_faces (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
-- Denormalised like every other table here: a cross-tenant read should
|
||||
-- require a wrong WHERE clause rather than a forgotten join.
|
||||
client_id uuid NOT NULL REFERENCES clients(id) ON DELETE CASCADE,
|
||||
site_id uuid NOT NULL REFERENCES sites(id) ON DELETE CASCADE,
|
||||
image bytea NOT NULL,
|
||||
bytes integer NOT NULL,
|
||||
captured_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS visit_faces_client_idx
|
||||
ON visit_faces (client_id);
|
||||
|
||||
-- An agent uploads a face BEFORE the server has decided who it is, so a row can
|
||||
-- exist for a few milliseconds with no visit pointing at it - and permanently,
|
||||
-- if the visit that would have claimed it never arrives because the queue was
|
||||
-- dropped. That is a leak of exactly one image per lost visit, so it is swept
|
||||
-- rather than left: anything older than a day with no visit referencing it is
|
||||
-- an orphan, and this index is what makes finding them cheap.
|
||||
CREATE INDEX IF NOT EXISTS visit_faces_age_idx
|
||||
ON visit_faces (captured_at);
|
||||
|
||||
COMMIT;
|
||||
@@ -6,6 +6,7 @@ import Live from './views/Live.jsx'
|
||||
import CamerasView from './views/Cameras.jsx'
|
||||
import Assistant from './views/Assistant.jsx'
|
||||
import Clients from './views/Clients.jsx'
|
||||
import Team from './views/Team.jsx'
|
||||
|
||||
// A platform admin has no client of their own, so the tenant screens have
|
||||
// nothing to show them. Rather than render empty pages, they get the one screen
|
||||
@@ -22,6 +23,7 @@ const TENANT_VIEWS = [
|
||||
{ id: 'sites', label: 'Shops', View: Sites },
|
||||
{ id: 'live', label: 'Live', View: Live },
|
||||
{ id: 'cameras', label: 'Cameras', View: CamerasView },
|
||||
{ id: 'team', label: 'Team', View: Team },
|
||||
]
|
||||
const ADMIN_VIEWS = [
|
||||
{ id: 'clients', label: 'Companies', View: Clients },
|
||||
|
||||
@@ -122,6 +122,23 @@ async function fetchImage(path, retry = true) {
|
||||
parsed?.message || `That picture could not be loaded (${res.status}).`)
|
||||
}
|
||||
|
||||
// A label for the session list, so somebody can tell which device to sign out.
|
||||
// Deliberately coarse and never an identifier: a fingerprint here would be a
|
||||
// tracking signal we have no reason to hold, and the question this answers is
|
||||
// only "which of these is the one in my hand".
|
||||
function deviceName() {
|
||||
const ua = navigator.userAgent || ''
|
||||
const os = /Windows/.test(ua) ? 'Windows'
|
||||
: /Mac OS X|Macintosh/.test(ua) ? 'Mac'
|
||||
: /Android/.test(ua) ? 'Android'
|
||||
: /iPhone|iPad/.test(ua) ? 'iOS' : 'Unknown'
|
||||
const browser = /Edg\//.test(ua) ? 'Edge'
|
||||
: /Chrome\//.test(ua) ? 'Chrome'
|
||||
: /Safari\//.test(ua) ? 'Safari'
|
||||
: /Firefox\//.test(ua) ? 'Firefox' : 'browser'
|
||||
return `${browser} on ${os}`
|
||||
}
|
||||
|
||||
const qs = (params) => {
|
||||
const p = new URLSearchParams()
|
||||
for (const [k, v] of Object.entries(params || {})) {
|
||||
@@ -136,7 +153,7 @@ export const api = {
|
||||
const res = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password }),
|
||||
body: JSON.stringify({ email, password, device: deviceName() }),
|
||||
})
|
||||
const body = await res.json().catch(() => null)
|
||||
if (!res.ok) {
|
||||
@@ -147,6 +164,39 @@ export const api = {
|
||||
return body.user
|
||||
},
|
||||
|
||||
// What a code says it is for, before anybody is asked to choose a password.
|
||||
// Unauthenticated by necessity: the holder has no account yet.
|
||||
async previewInvitation(code) {
|
||||
const res = await fetch('/api/auth/invitation' + qs({ code }))
|
||||
const body = await res.json().catch(() => null)
|
||||
if (!res.ok) {
|
||||
throw new ApiError(res.status, body?.error || '',
|
||||
body?.message || 'That invitation code is not valid.')
|
||||
}
|
||||
return body
|
||||
},
|
||||
|
||||
// Redeem an invitation. Returns a signed-in session, not just an account:
|
||||
// sending somebody who has just chosen a password to a sign-in form to type
|
||||
// it again is the sort of thing that gets blamed on the password.
|
||||
//
|
||||
// The address and the role are NOT sent - they come from the invitation, and
|
||||
// the server refuses a body that names either.
|
||||
async register({ code, full_name, password }) {
|
||||
const res = await fetch('/api/auth/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code, full_name, password, device: deviceName() }),
|
||||
})
|
||||
const body = await res.json().catch(() => null)
|
||||
if (!res.ok) {
|
||||
throw new ApiError(res.status, body?.error || '',
|
||||
body?.message || 'Could not create the account.')
|
||||
}
|
||||
setTokens(body.access_token, body.refresh_token)
|
||||
return body.user
|
||||
},
|
||||
|
||||
async logout() {
|
||||
try { await send('POST', '/api/auth/logout') } catch { /* already gone */ }
|
||||
clearTokens()
|
||||
@@ -196,6 +246,25 @@ export const api = {
|
||||
|
||||
clients: () => send('GET', '/api/admin/clients'),
|
||||
createClient: (input) => send('POST', '/api/admin/clients', input),
|
||||
|
||||
// The people who work here.
|
||||
team: () => send('GET', '/api/team'),
|
||||
updateMember: (id, changes) =>
|
||||
send('PATCH', `/api/team/${encodeURIComponent(id)}`, changes),
|
||||
invitations: () => send('GET', '/api/team/invitations'),
|
||||
// The code comes back in full exactly once - only a hash is stored - so
|
||||
// whatever calls this has to show it there and then and must not expect to
|
||||
// read it back later. Same contract as enrolmentCode above.
|
||||
invite: (input) => send('POST', '/api/team/invitations', input),
|
||||
revokeInvitation: (id) =>
|
||||
send('DELETE', `/api/team/invitations/${encodeURIComponent(id)}`),
|
||||
|
||||
// Devices this account is signed in on. The point of holding sessions in a
|
||||
// table rather than issuing JWTs is that signing one out actually works.
|
||||
sessions: () => send('GET', '/api/auth/sessions'),
|
||||
revokeSession: (id) =>
|
||||
send('DELETE', `/api/auth/sessions/${encodeURIComponent(id)}`),
|
||||
signOutOthers: () => send('POST', '/api/auth/sessions/revoke-others'),
|
||||
}
|
||||
|
||||
// The live stream, read with fetch rather than EventSource.
|
||||
|
||||
@@ -182,7 +182,12 @@ button.ghost:hover { border-color: var(--muted); color: var(--ink); }
|
||||
.arrivals { list-style: none; padding: 0; display: grid; gap: 8px; }
|
||||
.card.arrival { display: flex; align-items: center; gap: 14px; padding: 11px 14px; }
|
||||
.face { width: 46px; height: 46px; border-radius: 50%; flex: none;
|
||||
object-fit: cover; background: var(--surface-2); }
|
||||
overflow: hidden; object-fit: cover; background: var(--surface-2); }
|
||||
/* .face is a <span> wrapping the picture rather than the <img> itself, because
|
||||
a face served from this server's own database has to be fetched with the
|
||||
session before it can be shown. The image inside still has to fill the
|
||||
circle, and the wrapper clips it. */
|
||||
.face > img { width: 100%; height: 100%; object-fit: cover; display: block; }
|
||||
.face.initials { display: grid; place-items: center; color: var(--muted);
|
||||
font-size: 15px; font-weight: 600; letter-spacing: .02em; }
|
||||
.who-col { display: flex; flex-direction: column; gap: 1px; flex: 1; min-width: 0; }
|
||||
@@ -536,3 +541,30 @@ button.ghost.danger:hover { border-color: var(--bad); }
|
||||
font-size: 13px; color: rgba(255, 255, 255, .78);
|
||||
background: rgba(0, 0, 0, .35);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- team --- */
|
||||
.rows tr.inactive td { opacity: .55; }
|
||||
.rows .role { text-transform: capitalize; }
|
||||
.rows td.right { text-align: right; }
|
||||
.pill.muted { margin-left: 8px; font-size: 11px; padding: 1px 7px; border-radius: 999px;
|
||||
background: var(--surface-2); color: var(--muted); vertical-align: middle; }
|
||||
.pending { margin-top: 26px; }
|
||||
.pending h2 { font-size: 14px; font-weight: 600; color: var(--muted); margin: 0 0 10px; }
|
||||
.invites { list-style: none; padding: 0; display: grid; gap: 8px; }
|
||||
.card.invite { display: flex; align-items: center; justify-content: space-between;
|
||||
gap: 14px; padding: 11px 14px; }
|
||||
.card.invite .sub { display: block; }
|
||||
/* The code is read aloud and typed in, so it is set wide and monospaced.
|
||||
Grouped in sixes by the server for the same reason. */
|
||||
.creds code.big { font-size: 16px; letter-spacing: .06em; }
|
||||
|
||||
/* A button that reads as a link. Used where the action is a change of screen
|
||||
rather than a submission, so it must not look like the primary button next
|
||||
to it. */
|
||||
.linkish { background: none; border: 0; padding: 0; font: inherit;
|
||||
color: var(--accent); cursor: pointer; text-decoration: underline;
|
||||
text-underline-offset: 2px; }
|
||||
.linkish:hover { opacity: .8; }
|
||||
/* The code is read off a screen or a phone call, so it is set wide. */
|
||||
.codefield { font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
letter-spacing: .04em; text-transform: uppercase; }
|
||||
|
||||
@@ -125,7 +125,7 @@ function CameraCard({ cam, canEdit, onEdit, onWatch }) {
|
||||
onKeyDown={e => canEdit && e.key === 'Enter' && onEdit()}>
|
||||
<div className="shot">
|
||||
{cam.snapshot?.available
|
||||
? <Shot url={cam.snapshot.url} alt={`View from ${cam.label}`} />
|
||||
? <Shot image={cam.snapshot} alt={`View from ${cam.label}`} />
|
||||
: <div className="noshot">
|
||||
<span className="lens" aria-hidden="true" />
|
||||
{cam.snapshot?.reason || 'No picture yet.'}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { api, streamArrivals } from '../api.js'
|
||||
import { ago, Loading, Problem } from './Sites.jsx'
|
||||
import Shot from './Shot.jsx'
|
||||
|
||||
// Who just walked in, pushed as it happens.
|
||||
//
|
||||
@@ -103,9 +104,16 @@ function Arrival({ a }) {
|
||||
// Photos are off unless a shop turns them on, so "no photo" is the ordinary
|
||||
// case. Initials, never an error state — a screen full of red for a system
|
||||
// working exactly as configured teaches people to ignore it.
|
||||
//
|
||||
// The picture goes through Shot rather than a bare <img> because a face can
|
||||
// now come from either of two places: a presigned link to object storage, or
|
||||
// this server's own database on a deployment with no bucket. The second cannot
|
||||
// be loaded by an <img> at all — it needs the session — so a plain src here
|
||||
// showed a broken image on exactly the deployments that had just started
|
||||
// storing photos.
|
||||
function Face({ image, name }) {
|
||||
if (image?.available) {
|
||||
return <img className="face" src={image.url} alt="" loading="lazy" />
|
||||
return <span className="face"><Shot image={image} alt="" /></span>
|
||||
}
|
||||
return (
|
||||
<span className="face initials" title={image?.reason || ''} aria-hidden="true">
|
||||
|
||||
@@ -1,7 +1,21 @@
|
||||
import { useState } from 'react'
|
||||
import { api } from '../api.js'
|
||||
|
||||
// Sign in, or join with an invitation.
|
||||
//
|
||||
// Both live on this screen because they answer the same question — "let me in"
|
||||
// — and the person arriving with a code has no account yet, so they cannot be
|
||||
// asked to sign in first. That is the same reason the endpoint behind it is
|
||||
// unauthenticated, and the same reason a shop PC claims itself before anybody
|
||||
// signs in on it.
|
||||
export default function Login({ onSignedIn }) {
|
||||
const [joining, setJoining] = useState(false)
|
||||
return joining
|
||||
? <Join onSignedIn={onSignedIn} onCancel={() => setJoining(false)} />
|
||||
: <SignIn onSignedIn={onSignedIn} onJoin={() => setJoining(true)} />
|
||||
}
|
||||
|
||||
function SignIn({ onSignedIn, onJoin }) {
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
@@ -51,7 +65,122 @@ export default function Login({ onSignedIn }) {
|
||||
{busy ? 'Signing in…' : 'Sign in'}
|
||||
</button>
|
||||
<p className="foot">
|
||||
Accounts are created by Loyaly. Ask your account manager if you need one.
|
||||
Been invited? <button type="button" className="linkish" onClick={onJoin}>
|
||||
Use your invitation code
|
||||
</button>
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Redeeming an invitation.
|
||||
//
|
||||
// Two steps deliberately. The code is checked FIRST, so somebody who has
|
||||
// mistyped it finds out before choosing a password — and so the screen can say
|
||||
// which company they are joining, which is the only thing that makes "is this
|
||||
// the right code" answerable by the person holding it.
|
||||
function Join({ onSignedIn, onCancel }) {
|
||||
const [code, setCode] = useState('')
|
||||
const [invite, setInvite] = useState(null)
|
||||
const [fullName, setFullName] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [confirm, setConfirm] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
const check = async (e) => {
|
||||
e.preventDefault()
|
||||
setBusy(true); setError('')
|
||||
try {
|
||||
const prev = await api.previewInvitation(code.trim())
|
||||
setInvite(prev)
|
||||
setFullName(prev.full_name || '')
|
||||
} catch (err) {
|
||||
// Unknown, expired, spent and withdrawn are one message from the server.
|
||||
// The difference only helps somebody guessing codes, and the next step is
|
||||
// the same in all four cases: ask for a new one.
|
||||
setError(err.message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const join = async (e) => {
|
||||
e.preventDefault()
|
||||
if (password !== confirm) {
|
||||
setError('Those two passwords are not the same.')
|
||||
return
|
||||
}
|
||||
setBusy(true); setError('')
|
||||
try {
|
||||
// The address and the role are not sent. They belong to the invitation.
|
||||
const user = await api.register({ code: code.trim(), full_name: fullName, password })
|
||||
onSignedIn(user)
|
||||
} catch (err) {
|
||||
setError(err.message)
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="signin">
|
||||
<form className="card" onSubmit={invite ? join : check}>
|
||||
<span className="mark big" aria-hidden="true" />
|
||||
<h1>{invite ? `Join ${invite.client_name}` : 'Behavision'}</h1>
|
||||
|
||||
{!invite ? (
|
||||
<>
|
||||
<p className="sub">Enter the invitation code you were given.</p>
|
||||
<label>
|
||||
Invitation code
|
||||
<input
|
||||
value={code} onChange={e => setCode(e.target.value)}
|
||||
autoFocus required autoComplete="off" spellCheck="false"
|
||||
placeholder="ABCDEF-123456-GHIJKL-789012" className="codefield"
|
||||
/>
|
||||
<span className="hint">Dashes and capitals do not matter.</span>
|
||||
</label>
|
||||
{error && <p className="error" role="alert">{error}</p>}
|
||||
<button className="primary" disabled={busy || !code.trim()}>
|
||||
{busy ? 'Checking…' : 'Continue'}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="sub">
|
||||
You are joining as <b>{invite.role}</b>, signing in with{' '}
|
||||
<code>{invite.email}</code>. Choose a password only you know.
|
||||
</p>
|
||||
<label>
|
||||
Your name
|
||||
<input value={fullName} onChange={e => setFullName(e.target.value)}
|
||||
autoFocus autoComplete="name" />
|
||||
</label>
|
||||
<label>
|
||||
Password
|
||||
<input type="password" value={password} required minLength={8}
|
||||
autoComplete="new-password"
|
||||
onChange={e => setPassword(e.target.value)} />
|
||||
<span className="hint">At least 8 characters. Longer is the only thing that helps.</span>
|
||||
</label>
|
||||
<label>
|
||||
Password again
|
||||
<input type="password" value={confirm} required
|
||||
autoComplete="new-password"
|
||||
onChange={e => setConfirm(e.target.value)} />
|
||||
</label>
|
||||
{error && <p className="error" role="alert">{error}</p>}
|
||||
<button className="primary" disabled={busy || !password || !confirm}>
|
||||
{busy ? 'Creating your account…' : 'Create account and sign in'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
<p className="foot">
|
||||
<button type="button" className="linkish" onClick={onCancel}>
|
||||
Back to sign in
|
||||
</button>
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@@ -1,24 +1,45 @@
|
||||
import { useAuthedImage } from '../hooks.js'
|
||||
|
||||
// One camera picture, however this deployment stores them.
|
||||
// One picture from the API, however this deployment stores them.
|
||||
//
|
||||
// Two shapes arrive here and they need different handling, which is exactly
|
||||
// why it is one component rather than an <img> repeated on each screen:
|
||||
//
|
||||
// * An ABSOLUTE url is a presigned link to object storage. It carries its
|
||||
// own signature, so a plain <img src> loads it.
|
||||
// * A RELATIVE url is served by this server from its own database, for a
|
||||
// deployment with no bucket. An <img> cannot send an Authorization header,
|
||||
// so it has to be fetched with the session and handed over as an object
|
||||
// URL. Minting an unauthenticated link instead would put a photograph of
|
||||
// somebody's shop floor behind no session at all, which is the thing this
|
||||
// path exists to avoid.
|
||||
export default function Shot({ url, alt }) {
|
||||
const local = typeof url === 'string' && url.startsWith('/')
|
||||
// * A presigned link to object storage carries its own signature, so a plain
|
||||
// <img src> loads it.
|
||||
// * A picture this server holds itself - for a deployment with no bucket -
|
||||
// is served from an endpoint that requires the session. An <img> cannot
|
||||
// send an Authorization header, so it has to be fetched and handed over as
|
||||
// an object URL. Minting an unauthenticated link instead would put a
|
||||
// photograph of somebody's shop floor, or of a customer, behind no session
|
||||
// at all, which is the thing that path exists to avoid.
|
||||
//
|
||||
// Which one it is comes from the API's own `auth` flag, not from the shape of
|
||||
// the URL. Guessing by whether it starts with "/" is right today and stops
|
||||
// being right the first time object storage is served from this same host -
|
||||
// and the failure then is a photograph that silently will not load.
|
||||
export default function Shot({ image, url, alt }) {
|
||||
// `image` is the whole object from the API; `url` is the older call shape,
|
||||
// kept working so a screen that has not been updated still renders. The
|
||||
// fallback heuristic applies only when nothing told us.
|
||||
const src0 = image ? image.url : url
|
||||
// Either signal is enough, and that is not belt-and-braces. A RELATIVE url is
|
||||
// served by this server and always needs the session - there is no such thing
|
||||
// as a public one - so it is sufficient on its own, and a caller that rebuilds
|
||||
// an image object and loses `auth` cannot turn a working picture into a broken
|
||||
// one. (It did exactly that once: Sites.jsx returned `{url, at}` from its
|
||||
// snapshot picker, the flag went missing, and every shop card showed a broken
|
||||
// image.) The FLAG is what adds the case the URL cannot express: an absolute
|
||||
// link that still needs a bearer, which happens the first time object storage
|
||||
// is served from this same host.
|
||||
const needsAuth =
|
||||
(image && !!image.auth) ||
|
||||
(typeof src0 === 'string' && src0.startsWith('/'))
|
||||
|
||||
// Hooks cannot be called conditionally, so this always runs and simply has
|
||||
// nothing to do when the URL is already usable.
|
||||
const fetched = useAuthedImage(local ? url : null)
|
||||
const src = local ? fetched : url
|
||||
const fetched = useAuthedImage(needsAuth ? src0 : null)
|
||||
const src = needsAuth ? fetched : src0
|
||||
if (!src) return null
|
||||
return <img src={src} alt={alt} loading="lazy" />
|
||||
}
|
||||
|
||||
@@ -135,7 +135,7 @@ function SiteCard({ site, cams, verdict, onCheck }) {
|
||||
tabIndex={0} onKeyDown={e => e.key === 'Enter' && onCheck()}>
|
||||
<div className="shot">
|
||||
{view.url
|
||||
? <Shot url={view.url} alt={`View inside ${site.name}`} />
|
||||
? <Shot image={view} alt={`View inside ${site.name}`} />
|
||||
: <div className="noshot">
|
||||
<ShopMark />
|
||||
{view.reason && <span>{view.reason}</span>}
|
||||
@@ -205,7 +205,11 @@ function bestView(cams) {
|
||||
if (!c.snapshot?.available || !c.snapshot.url) continue
|
||||
if (!best || (c.snapshot_at || '') > (best.snapshot_at || '')) best = c
|
||||
}
|
||||
if (best) return { url: best.snapshot.url, at: best.snapshot_at }
|
||||
// The WHOLE snapshot object, not just its url. It carries `auth`, which says
|
||||
// whether the picture has to be fetched with the session or can be handed
|
||||
// straight to an <img> - and rebuilding a partial copy here is how that flag
|
||||
// gets silently dropped on one screen and not another.
|
||||
if (best) return { ...best.snapshot, at: best.snapshot_at }
|
||||
const reason = cams.map(c => c.snapshot?.reason).find(Boolean)
|
||||
return { reason: reason || 'No picture from this shop yet.' }
|
||||
}
|
||||
@@ -237,6 +241,25 @@ export function ago(iso) {
|
||||
return `${Math.round(hrs / 24)} days ago`
|
||||
}
|
||||
|
||||
// How long until a moment in the future.
|
||||
//
|
||||
// `ago` clamps at zero and reads a future timestamp as "just now", which is
|
||||
// right for a heartbeat whose clock is a little ahead and completely wrong for
|
||||
// an expiry: a code valid for a week rendered as "expires just now", which
|
||||
// tells the operator not to bother handing it over.
|
||||
export function until(iso) {
|
||||
if (!iso) return 'never'
|
||||
const then = new Date(iso).getTime()
|
||||
if (Number.isNaN(then)) return '—'
|
||||
const secs = (then - Date.now()) / 1000
|
||||
if (secs <= 0) return 'expired'
|
||||
const mins = Math.round(secs / 60)
|
||||
if (mins < 60) return `in ${mins} min`
|
||||
const hrs = Math.round(mins / 60)
|
||||
if (hrs < 48) return `in ${hrs} h`
|
||||
return `in ${Math.round(hrs / 24)} days`
|
||||
}
|
||||
|
||||
export function Loading() {
|
||||
return <div className="state"><span className="spinner" aria-hidden="true" />Loading…</div>
|
||||
}
|
||||
|
||||
214
web/src/views/Team.jsx
Normal file
214
web/src/views/Team.jsx
Normal file
@@ -0,0 +1,214 @@
|
||||
import { useState } from 'react'
|
||||
import { api } from '../api.js'
|
||||
import { usePolled } from '../hooks.js'
|
||||
import { ago, until, Loading, Problem } from './Sites.jsx'
|
||||
|
||||
// The people who work here, and how somebody new gets an account.
|
||||
//
|
||||
// Registration is by invitation, never open signup — the same line the platform
|
||||
// draws around creating a company. What was missing was not openness: it was
|
||||
// that a shop could not add a SECOND person at all without somebody running a
|
||||
// command on the server, so five members of staff shared one password and a
|
||||
// phone app for the shop floor could not exist.
|
||||
//
|
||||
// A manager mints a code and hands it over; the holder chooses their own
|
||||
// password. The code carries the address and the role, so passing it on cannot
|
||||
// turn a staff invitation into an owner account for whoever received it.
|
||||
export default function Team({ user }) {
|
||||
const team = usePolled(() => api.team(), 0, [])
|
||||
const invites = usePolled(() => api.invitations(), 0, [])
|
||||
const [inviting, setInviting] = useState(false)
|
||||
const [minted, setMinted] = useState(null)
|
||||
const [busy, setBusy] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const canManage = user.role === 'owner' || user.role === 'manager'
|
||||
const members = team.data || []
|
||||
const pending = invites.data || []
|
||||
|
||||
const change = async (id, changes) => {
|
||||
setBusy(id); setError('')
|
||||
try {
|
||||
await api.updateMember(id, changes)
|
||||
team.reload()
|
||||
} catch (err) {
|
||||
setError(err.message)
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<header className="head">
|
||||
<h1>Team</h1>
|
||||
{canManage && (
|
||||
<button className="primary" onClick={() => { setMinted(null); setInviting(true) }}>
|
||||
Invite someone
|
||||
</button>
|
||||
)}
|
||||
</header>
|
||||
|
||||
{minted && <InviteCode invite={minted} onDismiss={() => setMinted(null)} />}
|
||||
{error && <p className="error" role="alert">{error}</p>}
|
||||
|
||||
{team.loading && !team.data ? <Loading /> :
|
||||
team.error ? <Problem error={team.error} /> : (
|
||||
<div className="tablewrap">
|
||||
<table className="rows">
|
||||
<thead>
|
||||
<tr><th>Name</th><th>Email</th><th>Role</th><th>Last signed in</th>
|
||||
{canManage && <th />}</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{members.map(m => (
|
||||
<tr key={m.id} className={m.active ? '' : 'inactive'}>
|
||||
<td><strong>{m.full_name || '—'}</strong>
|
||||
{!m.active && <span className="pill muted">No access</span>}</td>
|
||||
<td><code>{m.email}</code></td>
|
||||
<td>{canManage && m.id !== user.id ? (
|
||||
<select value={m.role} disabled={busy === m.id}
|
||||
onChange={e => change(m.id, { role: e.target.value })}>
|
||||
{/* 'admin' is absent: a platform administrator is
|
||||
defined by having no company, so the role could
|
||||
never work on a row that has one. */}
|
||||
<option value="staff">Staff</option>
|
||||
<option value="manager">Manager</option>
|
||||
{user.role === 'owner' && <option value="owner">Owner</option>}
|
||||
</select>
|
||||
) : <span className="role">{m.role}</span>}</td>
|
||||
<td className="sub">{m.last_login_at ? ago(m.last_login_at) : 'Never'}</td>
|
||||
{canManage && (
|
||||
<td className="right">
|
||||
{m.id === user.id ? null : m.active ? (
|
||||
<button className="ghost danger" disabled={busy === m.id}
|
||||
onClick={() => change(m.id, { active: false })}>
|
||||
Remove access
|
||||
</button>
|
||||
) : (
|
||||
<button className="ghost" disabled={busy === m.id}
|
||||
onClick={() => change(m.id, { active: true })}>
|
||||
Restore
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{canManage && pending.length > 0 && (
|
||||
<section className="pending">
|
||||
<h2>Waiting to join</h2>
|
||||
<ul className="invites">
|
||||
{pending.map(i => (
|
||||
<li key={i.id} className="card invite">
|
||||
<div>
|
||||
<strong>{i.email}</strong>
|
||||
<span className="sub">
|
||||
invited as {i.role}
|
||||
{i.invited_by ? ` by ${i.invited_by}` : ''} · expires {until(i.expires_at)}
|
||||
</span>
|
||||
</div>
|
||||
<button className="ghost danger" onClick={async () => {
|
||||
await api.revokeInvitation(i.id); invites.reload()
|
||||
}}>Withdraw</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{inviting && (
|
||||
<InviteForm
|
||||
canMintOwner={user.role === 'owner'}
|
||||
onClose={() => setInviting(false)}
|
||||
onDone={(inv) => { setInviting(false); setMinted(inv); invites.reload() }}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function InviteForm({ canMintOwner, onClose, onDone }) {
|
||||
const [form, setForm] = useState({ email: '', full_name: '', role: 'staff' })
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const set = (k) => (e) => setForm({ ...form, [k]: e.target.value })
|
||||
|
||||
const submit = async (e) => {
|
||||
e.preventDefault()
|
||||
setBusy(true); setError('')
|
||||
try {
|
||||
onDone(await api.invite(form))
|
||||
} catch (err) {
|
||||
setError(err.message)
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="overlay" onClick={onClose}>
|
||||
<aside className="drawer narrow" onClick={e => e.stopPropagation()}>
|
||||
<header className="drawer-head">
|
||||
<h2>Invite someone</h2>
|
||||
<button className="ghost" onClick={onClose}>Close</button>
|
||||
</header>
|
||||
<form className="drawer-body" onSubmit={submit}>
|
||||
<label>Their email
|
||||
<input type="email" value={form.email} onChange={set('email')}
|
||||
required autoFocus autoComplete="off" name="invitee" />
|
||||
<span className="hint">
|
||||
This is the address they will sign in with, and it is fixed by the
|
||||
invitation — passing the code on cannot make it somebody else’s
|
||||
account.
|
||||
</span>
|
||||
</label>
|
||||
<label>Their name
|
||||
<input value={form.full_name} onChange={set('full_name')}
|
||||
autoComplete="off" name="invitee-name" />
|
||||
</label>
|
||||
<label>Role
|
||||
<select value={form.role} onChange={set('role')}>
|
||||
<option value="staff">Staff — see customers and shops</option>
|
||||
<option value="manager">Manager — also set up cameras and invite people</option>
|
||||
{canMintOwner && <option value="owner">Owner — full control</option>}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
{error && <p className="error" role="alert">{error}</p>}
|
||||
<button className="primary" disabled={busy}>
|
||||
{busy ? 'Creating…' : 'Create invitation'}
|
||||
</button>
|
||||
</form>
|
||||
</aside>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Shown once, and it says so. Only a hash is stored, so this cannot be read
|
||||
// back later — the same rule every other secret in this product follows, and
|
||||
// the reason is the same: a code support can look up is a code anybody with
|
||||
// support access can redeem.
|
||||
function InviteCode({ invite, onDismiss }) {
|
||||
return (
|
||||
<div className="banner ok credentials">
|
||||
<div>
|
||||
<b>Invitation for {invite.email}.</b> Give them this code. It is shown
|
||||
once, works once, and cannot be recovered.
|
||||
<dl className="creds">
|
||||
<div><dt>Code</dt><dd><code className="big">{invite.code}</code></dd></div>
|
||||
<div><dt>Role</dt><dd>{invite.role}</dd></div>
|
||||
</dl>
|
||||
<p className="sub">
|
||||
They open the app, choose “I have an invitation code”, and pick their
|
||||
own password. Nobody else ever sees it.
|
||||
</p>
|
||||
</div>
|
||||
<button className="ghost" onClick={onDismiss}>Done</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user