oficina / base Public

Merge origin/main into native/slice-1-app

Brings in Base's main at 44ecb80, with the
server half (native exchange, /api/v1, Ask set-up with Oficina ID) and
ask-disconnect-sticks, so the native app's tree is tested against the
final contract before it lands.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 2683f1c3c49fc4c60efab8211b53cb1ad2894929 parent 006a191parent 44ecb80
32 files changed, +3,836 −161
  • README.md +24 −0
  • docs/api/base-native-v1.md +264 −0
  • go.mod +6 −5
  • go.sum +10 −8
  • internal/config/oficina.go +15 −0
  • internal/equipo/equipotest/fake.go +53 −0
  • internal/equipo/equipotest/native.go +283 −0
  • internal/equipo/native.go +127 −0
  • internal/look/static/ask.js +3 −2
  • internal/store/disconnected_test.go +64 −0
  • internal/store/equipo.go +82 −26
  • internal/store/hosttokens_test.go +1 −1
  • internal/store/members.go +7 −2
  • internal/store/migrations/0012_ask_disconnected.sql +4 −0
  • internal/store/oficina_links.go +30 −0
  • internal/web/api.go +148 −0
  • internal/web/app.go +69 −17
  • internal/web/ask.go +39 −16
  • internal/web/ask_connect.go +114 −46
  • internal/web/ask_oficina_native.go +246 −0
  • internal/web/ask_relay.go +3 −2
  • internal/web/home.go +51 −29
  • internal/web/oficina.go +87 −5
  • internal/web/settings.go +1 −1
  • internal/webtest/api_test.go +190 −0
  • internal/webtest/ask_disconnect_test.go +304 −0
  • internal/webtest/ask_link_race_test.go +232 −0
  • internal/webtest/ask_native_contract_test.go +498 −0
  • internal/webtest/ask_oficina_native_test.go +378 −0
  • internal/webtest/native_test.go +274 −0
  • internal/webtest/oficina_harness_test.go +7 −1
  • internal/webtest/oficina_origin_test.go +222 −0
diff --git a/README.md b/README.md
index 876de92..7b74326 100644
--- a/README.md
+++ b/README.md
@@ -88,6 +88,30 @@ email and passkeys stay below it. Everyone signs in with their email once and
connects their Oficina account from Settings; after that, Oficina signs them
in. Only members get in, and inviting people is still by email.
+Each connection is tied to `BASE_ORIGIN`. If you move Base to a new address,
+Oficina ID stops signing people in until they connect again: each person
+signs in with their email once and connects their Oficina account, from
+Settings or straight from "Sign in with Oficina". The old connection is
+cleared then. Nothing else is needed.
+
+Base's Mac and iPhone app signs in with Oficina ID too, through
+`POST /native/oficina-id`; its session lasts seven days, and the app renews
+it. Someone must have signed in to Base on the web with Oficina ID once
+before the app lets them in. The app reads and calls what
+`docs/api/base-native-v1.md` describes.
+
+The app connects Ask Base with Oficina ID, so there's no code to approve in
+Equipo. Base signs the person in to Equipo with Oficina ID on their behalf
+and keeps the Equipo key sealed, as it does one from the code. This works
+only for someone Equipo has already linked to their Oficina ID (they've
+signed in to Equipo with it); for anyone else the app shows that Ask isn't
+set up for them yet, and they can connect it with a code from Base on the
+web. A key made this way lasts seven days, not thirty: it ends with the
+Equipo session it was made with, or sooner if the person signs out of
+Equipo or leaves the team there. The app makes a new one after five days,
+without asking. Base never signs that Equipo session out, because doing so
+would end the key.
+
To install apps, Base also needs to reach the Platform. Without these five and
`BASE_ASSERTION_KEY`, it still runs and logs that installs are off.
diff --git a/docs/api/base-native-v1.md b/docs/api/base-native-v1.md
new file mode 100644
index 0000000..620fa6d
--- /dev/null
+++ b/docs/api/base-native-v1.md
@@ -0,0 +1,264 @@
+# Base's API for its native app, v1
+
+What Base's Mac and iPhone app may rely on. Everything here is pinned by
+tests in `internal/webtest` (`native_test.go`, `api_test.go`,
+`ask_native_contract_test.go`, `ask_oficina_native_test.go`). The Ask
+routes are the same ones the web's `ask.js` uses, so a change that breaks
+this document breaks the web too.
+
+## Signing in
+
+- **`POST /native/oficina-id`** is connect's native exchange
+ (`connect.NativeExchange`; Home spec 2026-11-14-oficina-id-native.md §7).
+ The kit sends `{assertion, verifier}` as JSON, with no `Origin`, no
+ `Sec-Fetch-Site` and no cookie.
+ - `200 {"state":"ok","name":"__Host-rastrillo_session","value":…,"expires_at":<unix>}`:
+ the session, seven days from now, absolute.
+ - `403 {"state":"unknown"}`: no member here is linked to this Oficina ID.
+ Base admits only people who have signed in to Base on the web with
+ Oficina ID once (slice 1).
+ - `400 invalid`, `401 failed` (get a fresh assertion), `503 unavailable`,
+ as connect documents. Base never answers `409 choose`.
+- **The session** is the cookie `name=value`. Every other request sends it
+ with `Origin: <Base's origin>`; a POST without that `Origin` is refused
+ (403, Base's CSRF check).
+- **`POST /signout`** ends the session it carries, and nothing else:
+ `204` to a JSON request (`Content-Type` or `Accept` of
+ `application/json`), `303 /signed-out` to a form.
+- **Refusals.** Anything under `/api/`, and any request whose `Accept`
+ names `application/json` or `text/event-stream`, hears
+ `401 {"code":"unauthenticated"}` (no-store, never a redirect) when it has
+ no session, or a session that names nobody who is a member now: unlinked,
+ removed, or a native session more than seven days old. Mint a new session
+ and try once more.
+
+## Reads
+
+### `GET /api/v1/me`
+
+```json
+{
+ "member": {"id": "…", "name": "Ana Ruiz", "email": "ana@acme.test", "initials": "AR", "owner": false},
+ "base": {"name": "Acme", "slug": "acme", "origin": "https://base.acme.example", "timezone": "Europe/Dublin"},
+ "appearance": "system",
+ "equipo_origin": "https://equipo.acme.example"
+}
+```
+
+- `member.name` is the member's name, or their address's local part,
+ capitalised. `member.id` is Base's member id, never the address.
+- `base.timezone` is an IANA name.
+- `appearance` is `system`, `light` or `dark`. Change it with the web's
+ `POST /settings/appearance`, form field `theme` (`system`, `light` or
+ `dark`), which answers `303 /settings`.
+- `equipo_origin` is `null` when Ask Base is off. The app asks Oficina ID
+ for an assertion addressed to it (Ask set-up, below).
+
+### `GET /api/v1/home`
+
+```json
+{
+ "greeting": "Good morning, Ana.",
+ "lede": "One step until Acme's Base is ready.",
+ "steps": [{"label": "Signed in", "done": true}, {"label": "Invite your team", "done": false}, {"label": "Install your first app", "done": true}],
+ "apps": [
+ {"id": "calls", "kind": "oficina", "name": "Calls", "url": "https://calls.oficina.works/", "icon_url": "/static/oficina/calls.<hash>.svg", "bundle_id": "works.oficina.calls", "scheme": "oficina-calls"},
+ {"id": "docs", "kind": "oficina", "name": "Docs", "url": "https://docs.oficina.works/", "icon_url": "/static/oficina/docs.<hash>.svg", "bundle_id": "works.oficina.docs"},
+ {"id": "scratchpad", "kind": "installed", "name": "Scratchpad", "url": "https://acme-scratchpad.example/", "tint": "rose", "icon_svg": "<svg …>"},
+ {"id": "store", "kind": "own", "name": "Store", "url": "https://base.acme.example/store", "tint": "teal", "icon_svg": "<svg …>"}
+ ]
+}
+```
+
+- `apps` are in Home's order: the team's Oficina apps, the installed apps,
+ then Base's own pages (`store`, `people`, `settings`).
+- An Oficina app has `icon_url`, a path on Base's origin (content-hashed,
+ immutable), its `bundle_id` (`works.oficina.<id>`), and a `scheme` only
+ where its native app opens by one today (Calls, Equipo). The others open
+ on the web until their apps take the kit's `…://open`.
+- An installed app or own page has `tint` (a catalogue tint name: `amber`,
+ `teal`, `violet`, `rose`, `mist`, …) and `icon_svg`, line art drawn in
+ `currentColor`. Own pages' `url`s are Base's web pages.
+- Optional keys are absent, never `null` or `""`.
+
+## Ask Base
+
+No Ask route answers `401` while Base's session is good: Equipo refusing
+Ask's key is `409 {"state":"reconnect"}` (or `state` `reconnect` in a read).
+A `401` is only ever Base's own `{"code":"unauthenticated"}`.
+
+The web's own routes. Writes are **form-encoded**
+(`application/x-www-form-urlencoded`), not JSON, and must send
+`Accept: application/json` to get JSON back (without it they redirect, as
+for a form). Every answer is `no-store`.
+
+### The states
+
+`state` is one of:
+
+| state | meaning |
+|---|---|
+| `connect` | Ask isn't connected for this person (or a code ran out). |
+| `pending` | A sign-in code waits for approval in Equipo (web code flow). |
+| `ready` | Connected; the conversation shows. |
+| `norunner`, `oldrunner` | Connected, but the person has no runner that can answer (none, or too old). The conversation shows, with a note. |
+| `reconnect` | Equipo refused the key, or it expired. |
+| `unavailable` | Equipo didn't answer. |
+| `not_linked` | (Only from `POST /api/v1/ask/oficina`.) Equipo has no member linked to this Oficina ID. |
+
+### `GET /ask/state`
+
+```json
+{"state": "ready", "messages": [Message…], "jobs": [Job…], "cards": [Card…], "turn": Turn|null,
+ "status": "Thinking…", "cursor": 42, "renew_after": "2026-11-28T10:00:00Z", "equipo_origin": "https://equipo.acme.example",
+ "disconnected": false}
+```
+
+- `messages`, `jobs` and `cards` are never `null`. Outside `ready`,
+ `norunner` and `oldrunner` they are empty and `cursor` is `0`.
+- `turn` is the newest turn the person sees running (never a quiet
+ `team_update` one), or `null`. `status` is the line under the
+ conversation while it runs: `"Thinking…"`, `"Ask Base can't answer right
+ now. It will as soon as it can."` (turn `waiting`), or `""`.
+- `cursor` is where `/ask/events` starts.
+- `renew_after` (RFC 3339, UTC) is set when Ask was connected with Oficina
+ ID: from then on, the app sets Ask up again with a fresh assertion
+ (below), silently. `""` for a key from the web's code flow, or none.
+- `equipo_origin` is the Equipo instance Ask relays to: the audience of the
+ assertion for Ask set-up.
+- `disconnected` is `true` once the member has disconnected Ask, on any
+ device or the web, until a connection they make themselves is stored.
+ While it is, no client sets Ask up by itself; the app offers Connect
+ instead. `state` is then `connect`, as after any Disconnect, or `pending`
+ while a code from the web's Connect waits for approval (still `true`).
+
+**Message** `{"id", "role": "person"|"assistant", "text", "turn_id", "created_at"}`.
+An assistant's `text` may carry the little Markdown `ask.js` draws (lists,
+links to http(s) only, bold and italics).
+
+**Turn** `{"id", "kind", "state": "queued"|"running"|"waiting"|"replied"|"failed"|"cancelled", "reason"}`.
+
+**Card** `{"id", "revision", "kind", "state", "question", "options": [{"value","label"}], "links": [{"label","url","rel"?}], "result", "job"?, "detail"?, "started_at"?, "turn_id"?}`.
+- `kind` is `question`, `confirm`, `outcome`, `connect` or `job`; a card is
+ `open` while it waits for an answer. Every link is absolute http(s).
+- `rel` is `equipo` (a job's page in Equipo) or `oficina_connect` (Base's
+ own `/ask/oficina/connect`, a browser flow).
+- A job card has no options; its `state` is `working`, `asking`, `ready`,
+ `done` or `stopped`; `result` is its short status, `detail` one sentence
+ more and `started_at` when it began.
+- `job` names the job card a card belongs to; `turn_id`, on a connect card
+ from the stream, the turn that raised it.
+
+**Job** is a job Card plus `"cards": [Card…]`, the cards that belong to it,
+open and ended.
+
+### `GET /ask/events?after=<cursor>`
+
+Server-Sent Events, `text/event-stream`. On a reconnect, `Last-Event-ID`
+wins over `after`. The stream opens with `retry: 3000`, then:
+
+```
+id: 43
+event: message
+data: {"type":"message","data":Message}
+```
+
+| event | data |
+|---|---|
+| `message` | Message |
+| `turn` | Turn |
+| `card` | Card (a job card included: `kind` `job`) |
+| `delta` | `{"turn_id","offset","text"}`: a few of the reply's words; `offset` counts UTF-8 bytes |
+| `activity` | `{"turn_id","label"}`: what the Assistant is doing |
+| `glance` | `{"turn_id","text"}`: one line before the first words. **No `id` line**: it doesn't move the cursor. |
+| `state` | `{"state"}`: the stream can't start (not `ready`); it ends after this one event. |
+
+- `: ping` comments keep it alive. A stream lasts at most ten minutes;
+ reconnect with the last id.
+- Equipo not answering is `502`, and a bad `after` `400` (plain text):
+ reload `/ask/state` and start again from its cursor.
+
+### `POST /ask/messages`
+
+Form: `text` (1 to 16 KiB after trimming) and `key`, a fresh idempotency key
+per message (at most 128 bytes, not starting `reply:` or `card:`). A resend
+after a network error reuses the key: Equipo keeps one message per key.
+
+- `200 {"message": Message, "turn": Turn}`.
+- `422 {"state":"ready"}`: empty or too long.
+
+### `POST /ask/turns/{id}/cancel`
+
+Form: `key`. `200 {"state":"ready"}`; `409 {"state":"ready"}` when the turn
+has already ended.
+
+### `POST /ask/cards/{id}/answer`
+
+Form: `choice` (an option's `value`), `revision` (the card's, as seen) and
+`key`.
+
+- `200 {"card": Card, "message": Message|null, "turn": Turn|null}`. An
+ outcome card's answer starts no turn: both are `null`.
+- `409 {"state":"ready"}`: the card moved on (answered, or a newer
+ revision). Reload `/ask/state` to redraw it.
+
+### Every write's other answers
+
+| status | body | meaning |
+|---|---|---|
+| `409` | `{"state":"connect"\|"pending"\|"reconnect"\|"unavailable"}` | Not connected: nothing was sent. |
+| `409` | `{"state":"reconnect"}` | Equipo refused the key as it was used. Set Ask up again (with Oficina ID, below). |
+| `409` | `{"state":"norunner"\|"oldrunner"}` | No runner can answer; nothing was sent. |
+| `502` | `{"state":"unavailable"}` | Equipo didn't answer. Try again with the same key. |
+| `400` | plain text | The form couldn't be read. |
+
+### `POST /ask/disconnect`
+
+Ends the person's Ask connection, revoking the key in Equipo, whichever
+way it was made, and marks Ask disconnected by the member (`disconnected`
+in `/ask/state`), for every device and the web. It answers `303 /settings`.
+A Disconnect that fails changes nothing, the mark included.
+
+Only a connection the member makes clears the mark, in the same
+transaction that stores it:
+- the web's code flow once the code is approved and the key stored (pressing
+ Connect or Reconnect alone leaves it set; a code that expires, is refused
+ or is abandoned leaves it set);
+- `POST /api/v1/ask/oficina` without `"auto": true`, once its key is stored.
+
+Any set-up that fails leaves it set. An automatic set-up never clears it,
+and the save itself refuses while it is set.
+
+## Ask set-up with Oficina ID
+
+### `POST /api/v1/ask/oficina`
+
+JSON `{"assertion", "verifier", "auto"?}`: an assertion the kit fetched
+from Oficina ID addressed to `equipo_origin`, and its verifier. `auto` is
+`true` for a set-up the app starts by itself (after sign-in, or to renew
+after `renew_after`); leave it out, or send `false`, when the person asked
+to connect. `auto` must be exactly `true` or `false`: `null`, any other
+type, a repeated key or another spelling (`"AUTO"`) is `400 invalid`, as is
+any unknown or repeated name. Only a native session may
+call it (with `Origin`, as every POST). Base completes Equipo's own native
+sign-in for the person (Equipo's `POST /native/oficina-id`, then
+`POST /api/v1/auth/devices/native`), keeps the key it gets sealed where the
+web's code flow keeps one, and registers the Assistant's host with it.
+Two posts for the same person run one at a time, and a set-up yields to
+anything else that changes the person's connection meanwhile.
+
+| status | body | meaning |
+|---|---|---|
+| `200` | `{"state":"ready","renew_after":"<RFC 3339>"}` | Ask is ready. The key ends with Equipo's session, seven days after it was made; `renew_after` is five days after. After it, post a fresh assertion: that replaces the key and revokes the old one in Equipo. |
+| `409` | `{"state":"disconnected"}` | `auto` was `true`, and the member has disconnected Ask (also while a web code waits for approval). Nothing is stored; if the member disconnected while this set-up was at Equipo, the device Equipo made was revoked. Show Connect; post again without `auto` only when the person asks. |
+| `409` | `{"state":"not_linked"}` | Equipo has no member linked to this Oficina ID. Show Ask's "not set up for you yet" state, with the web's code flow; don't retry in a loop. |
+| `409` | `{"state":"superseded"}` | Ask's connection changed while Equipo answered (Disconnect, or a connection from the web): nothing was saved, and the device Equipo made was revoked. Reload `/ask/state`; don't retry at once. |
+| `422` | `{"state":"failed"}` | Equipo didn't accept the assertion (expired, wrong audience or verifier, already used). Get a fresh one and try once more. |
+| `400` | `{"state":"invalid"}` | Not JSON, an unknown, repeated or missing name, `auto` not exactly `true` or `false`, or Equipo couldn't read it. |
+| `403` | `{"state":"forbidden"}` | Not a native session: the web keeps its code flow. |
+| `502` | `{"state":"unavailable"}` | Equipo didn't answer, or refused the device. Try again later. |
+| `503` | `{"state":"unavailable"}` | Base couldn't read or store the connection. |
+
+Every failure stores nothing and leaves an existing connection as it was.
+The route answers `404` when Ask Base is off. It never answers `401` for
+Equipo's sake: a `401` is always Base's own session.
diff --git a/go.mod b/go.mod
index 960db01..72610f4 100644
--- a/go.mod
+++ b/go.mod
@@ -3,20 +3,21 @@ module amadan.net/carlos/base
go 1.26.0
require (
- amadan.net/oficina/home/connect v0.0.0-20261110233753-14c83d71b992
- amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489
- amadan.net/rastrillo/rastrillo v0.33.0
+ amadan.net/oficina/home/connect v0.0.0-20261122210203-8125a3ca6735
+ amadan.net/oficina/home/handoff v0.0.0-20261122210203-8125a3ca6735
+ amadan.net/rastrillo/rastrillo v0.38.0
github.com/chromedp/cdproto v0.158.6
github.com/chromedp/chromedp v0.21.0
github.com/go-chi/chi/v5 v5.3.2
+ github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3
)
require (
- amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d // indirect
+ amadan.net/oficina/estilo.git v0.0.0-20261120104604-487cadb03b88 // indirect
+ amadan.net/rastrillo/fiesta v1.5.0 // indirect
amadan.net/rastrillo/rastrillo/money v0.1.0 // indirect
github.com/BurntSushi/toml v1.6.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
- github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
diff --git a/go.sum b/go.sum
index 77b68c1..cff6f08 100644
--- a/go.sum
+++ b/go.sum
@@ -1,11 +1,13 @@
-amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d h1:p9+01xRdBD7s1viTINgQ6XoDD5ghOxYubD7FNcjhBTw=
-amadan.net/oficina/estilo.git v0.0.0-20261025200559-260f98c42e2d/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
-amadan.net/oficina/home/connect v0.0.0-20261110233753-14c83d71b992 h1:pyAvFStnIR6D/MSfMYpRQG+Lete8eYCF10nBdjtBbhA=
-amadan.net/oficina/home/connect v0.0.0-20261110233753-14c83d71b992/go.mod h1:7tsJ//7X4o5QkD068WoUGVDxj/e3ygZ2adF+PHhvBxE=
-amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 h1:RPKtyry/71i06o8L+gjAaUyexbmG56kO1YPs601URAM=
-amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k=
-amadan.net/rastrillo/rastrillo v0.33.0 h1:aYK33p7SIKOglr6rZM3EQLXdpz02Rnq9NB4Zhitz5yw=
-amadan.net/rastrillo/rastrillo v0.33.0/go.mod h1:IQnXick/ERWFvhqiQey87Zw1Td2aHlyloykFQB0g0pI=
+amadan.net/oficina/estilo.git v0.0.0-20261120104604-487cadb03b88 h1:wqpT3PmQQajULdOhtjJ/yENvdVB/NFG0QM7jlaEPS8s=
+amadan.net/oficina/estilo.git v0.0.0-20261120104604-487cadb03b88/go.mod h1:2UFIFrbTrhew8EFM0C94WmTo2OASM2pHEgT4jzeE/s8=
+amadan.net/oficina/home/connect v0.0.0-20261122210203-8125a3ca6735 h1:l2F7i47Y90p6BEnbvd354nh2r4+DWSpojiYh6k6Ye7s=
+amadan.net/oficina/home/connect v0.0.0-20261122210203-8125a3ca6735/go.mod h1:B45bHBZF5AtFJqy4d1qSDNDOqYcNkSz1qD20TLF1DI8=
+amadan.net/oficina/home/handoff v0.0.0-20261122210203-8125a3ca6735 h1:tWr0Xx1BpWNx/q/Bvbqdjj2PLX32YAiOuN8B51XZ9Vw=
+amadan.net/oficina/home/handoff v0.0.0-20261122210203-8125a3ca6735/go.mod h1:Mn5Rsm7Vcd6VZArBKMawza2yO+Fjo8KB1Ii6UcjcJHQ=
+amadan.net/rastrillo/fiesta v1.5.0 h1:wKfTsL5zRMofJBAqOxNlCY7aCtgHCtfwvTPBMA+ZA20=
+amadan.net/rastrillo/fiesta v1.5.0/go.mod h1:LpO391W1dIRUxOIKklHm+bGyWXtlFyBRRPQCysb9LjY=
+amadan.net/rastrillo/rastrillo v0.38.0 h1:q8aPnVtKt4q+uNjfxBRCTizhVvj+HdjDJh1MhlkBPOc=
+amadan.net/rastrillo/rastrillo v0.38.0/go.mod h1:0bufVMz8D4aWvxvJjehW70T8Jsvytrp1YEwoIzFTKm8=
amadan.net/rastrillo/rastrillo/money v0.1.0 h1:MxU4oqNrW8abxRTkgZBv24OYNpFnvonajNqeLIzmmaM=
amadan.net/rastrillo/rastrillo/money v0.1.0/go.mod h1:cmgkjBEIQh1pFSYvQk0UU6oPYS8kSDypdT9+t4Flx0U=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
diff --git a/internal/config/oficina.go b/internal/config/oficina.go
index 12c10cc..1f85810 100644
--- a/internal/config/oficina.go
+++ b/internal/config/oficina.go
@@ -20,6 +20,21 @@ var oficinaApps = []struct{ id, name string }{
{"memoria", "Memoria"}, {"calls", "Calls"}, {"fichas", "Fichas"}, {"equipo", "Equipo"},
}
+// BundleID is the app's native bundle ID on the Mac and iPhone: every
+// Oficina native app is works.oficina.<id> (ruled 2026-11-14). Base's own
+// native app opens the app by it when it is installed.
+func (o OficinaApp) BundleID() string { return "works.oficina." + o.ID }
+
+// oficinaSchemes are the URL schemes that open an Oficina app's native app
+// on the iPhone, for the apps whose app can be opened by one today. Docs,
+// Sheets, Calendar and Memoria answer only …://signin until their apps take
+// the kit's …://open, so they open on the web until then.
+var oficinaSchemes = map[string]string{"calls": "oficina-calls", "equipo": "works.oficina.equipo"}
+
+// Scheme is the URL scheme that opens the app's native app, or "" when it
+// opens on the web.
+func (o OficinaApp) Scheme() string { return oficinaSchemes[o.ID] }
+
// OficinaIDs is every app id BASE_OFICINA_APPS accepts.
func OficinaIDs() []string {
ids := make([]string, len(oficinaApps))
diff --git a/internal/equipo/equipotest/fake.go b/internal/equipo/equipotest/fake.go
index b3121e6..3169cc8 100644
--- a/internal/equipo/equipotest/fake.go
+++ b/internal/equipo/equipotest/fake.go
@@ -39,6 +39,9 @@ type device struct {
nonce, token string
revision int64
expires time.Time
+ // session is the native session cookie a device registered with
+ // Oficina ID ends with; "" for one from the code flow.
+ session string
}
// Fake is a running fake Equipo. URL is its origin.
@@ -61,12 +64,16 @@ type Fake struct {
failSend bool
// failBegin makes the next device sign-in start answer 503.
failBegin bool
+ // beginHold and revokeHold do for the next sign-in start and the next
+ // revocation what hold does for the next exchange.
+ beginHold, beginEntered, revokeHold, revokeEntered chan struct{}
// failSnapshot makes every snapshot answer 503.
failSnapshot bool
// snapHold and snapEntered do for the next snapshot what hold and
// entered do for the next exchange.
snapHold, snapEntered chan struct{}
chat
+ nativeState
}
// HoldNextExchange makes the next exchange wait, once it has arrived and
@@ -91,6 +98,39 @@ func (f *Fake) HoldNextSnapshot() (entered <-chan struct{}, release func()) {
return f.snapEntered, func() { close(hold) }
}
+// HoldNextBegin makes the next device sign-in start (POST
+// /api/v1/auth/devices) wait, once it has arrived and before it answers,
+// until release is called. entered is closed when it arrives.
+func (f *Fake) HoldNextBegin() (entered <-chan struct{}, release func()) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.beginHold, f.beginEntered = make(chan struct{}), make(chan struct{})
+ hold := f.beginHold
+ return f.beginEntered, func() { close(hold) }
+}
+
+// HoldNextRevoke does the same for the next device revocation (DELETE
+// /api/v1/auth/devices/{id}).
+func (f *Fake) HoldNextRevoke() (entered <-chan struct{}, release func()) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.revokeHold, f.revokeEntered = make(chan struct{}), make(chan struct{})
+ hold := f.revokeHold
+ return f.revokeEntered, func() { close(hold) }
+}
+
+// waitHeld waits at a hold taken from f, if there is one.
+func (f *Fake) waitHeld(hold, entered chan struct{}) {
+ if hold == nil {
+ return
+ }
+ close(entered)
+ select {
+ case <-hold:
+ case <-f.closing:
+ }
+}
+
// FailNextBegin makes the next device sign-in start (POST
// /api/v1/auth/devices) answer 503, as when Equipo is down.
func (f *Fake) FailNextBegin() {
@@ -120,6 +160,7 @@ func New(t testing.TB) *Fake {
f := &Fake{Instance: "TEAM1", closing: make(chan struct{}), devices: map[string]*device{},
Reply: func(string) string { return "Hello. What shall we work on?" }}
f.chat.init()
+ f.nativeState.init()
f.srv = httptest.NewServer(http.HandlerFunc(f.serve))
f.URL = f.srv.URL
t.Cleanup(func() {
@@ -197,6 +238,10 @@ func (f *Fake) serve(w http.ResponseWriter, r *http.Request) {
f.calls = append(f.calls, Call{r.Method, r.URL.Path, r.URL.RawQuery, r.Header.Clone(), string(body)})
f.mu.Unlock()
w.Header().Set("Cache-Control", "no-store")
+ // Equipo's native sign-in has rules of its own (native.go).
+ if f.serveNative(w, r) {
+ return
+ }
// Equipo refuses a request from another site, and any cookie on a
// device route; a server-to-server request carries neither.
if r.Header.Get("Origin") != "" || r.Header.Get("Cookie") != "" {
@@ -224,7 +269,10 @@ func (f *Fake) begin(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
fail := f.failBegin
f.failBegin = false
+ hold, entered := f.beginHold, f.beginEntered
+ f.beginHold, f.beginEntered = nil, nil
f.mu.Unlock()
+ f.waitHeld(hold, entered)
if fail {
writeError(w, r, 503, "unavailable")
return
@@ -333,6 +381,11 @@ func (f *Fake) Expire() {
}
func (f *Fake) revoke(w http.ResponseWriter, r *http.Request, id string) {
+ f.mu.Lock()
+ hold, entered := f.revokeHold, f.revokeEntered
+ f.revokeHold, f.revokeEntered = nil, nil
+ f.mu.Unlock()
+ f.waitHeld(hold, entered)
d, ok := f.bearer(r)
if !ok {
writeError(w, r, 401, "unauthenticated")
diff --git a/internal/equipo/equipotest/native.go b/internal/equipo/equipotest/native.go
new file mode 100644
index 0000000..3c914d7
--- /dev/null
+++ b/internal/equipo/equipotest/native.go
@@ -0,0 +1,283 @@
+package equipotest
+
+import (
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/base64"
+ "mime"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+ "unicode/utf8"
+)
+
+// Equipo's own native sign-in with Oficina ID, as Base completes it for a
+// person (Equipo's internal/equipo/oficinaid/native.go and
+// personapi/native_device.go):
+//
+// - POST /native/oficina-id trades an assertion Oficina ID made for
+// Equipo, and its verifier, for a seven-day native session, only for a
+// subject Equipo has linked to a roster member. It refuses anything a
+// browser sends (Origin, Sec-Fetch-Site), and answers
+// {name, value, expires_at}, or {"state": …} with 400, 401 failed,
+// 403 unknown or 503.
+// - POST /api/v1/auth/devices/native, with that session's cookie and
+// Equipo's own Origin, registers a device key and answers its person
+// credential, which ends with the session.
+//
+// The fake does not verify signatures: OficinaAssertion hands out an opaque
+// assertion and its verifier, as Oficina ID would for Equipo, and the
+// exchange accepts each once.
+
+// SessionCookie is the name of the fake's session cookie.
+const SessionCookie = "__Host-equipo_session"
+
+// nativeLifetime is how long Equipo's native session, and every device
+// registered with it, lasts.
+const nativeLifetime = 7 * 24 * time.Hour
+
+type nativeSession struct {
+ subject, address string
+ at time.Time
+ ended bool
+}
+
+type assertionGrant struct {
+ subject, verifier string
+ used bool
+}
+
+type nativeState struct {
+ nmu sync.Mutex
+ links map[string]string // Oficina subject → roster address
+ assertions map[string]*assertionGrant
+ sessions map[string]*nativeSession // cookie value → session
+ failNative int // the next exchange's status, once
+ // nativeHold, when set, stops the next exchange until it is closed;
+ // nativeEntered is closed when that exchange arrives.
+ nativeHold, nativeEntered chan struct{}
+}
+
+func (n *nativeState) init() {
+ n.links, n.assertions, n.sessions = map[string]string{}, map[string]*assertionGrant{}, map[string]*nativeSession{}
+}
+
+// LinkOficinaID links the Oficina ID subject to the roster member address,
+// as signing in to Equipo with Oficina ID once does.
+func (f *Fake) LinkOficinaID(subject, address string) {
+ f.nmu.Lock()
+ defer f.nmu.Unlock()
+ f.links[subject] = address
+}
+
+// OficinaAssertion is an assertion Oficina ID made for Equipo about
+// subject, and its verifier, as the native app fetches them.
+func (f *Fake) OficinaAssertion(subject string) (assertion, verifier string) {
+ f.nmu.Lock()
+ defer f.nmu.Unlock()
+ assertion, verifier = "oficina."+rand.Text()+rand.Text(), rand.Text()+rand.Text()
+ f.assertions[assertion] = &assertionGrant{subject: subject, verifier: verifier}
+ return assertion, verifier
+}
+
+// FailNextNativeExchange makes the next native exchange answer status
+// (with its state), as Equipo does when it is down (503).
+func (f *Fake) FailNextNativeExchange(status int) {
+ f.nmu.Lock()
+ defer f.nmu.Unlock()
+ f.failNative = status
+}
+
+// HoldNextNativeExchange makes the next native exchange wait, once it has
+// arrived and before it answers, until release is called: a test can act
+// in between. entered is closed when it arrives.
+func (f *Fake) HoldNextNativeExchange() (entered <-chan struct{}, release func()) {
+ f.nmu.Lock()
+ defer f.nmu.Unlock()
+ f.nativeHold, f.nativeEntered = make(chan struct{}), make(chan struct{})
+ hold := f.nativeHold
+ return f.nativeEntered, func() { close(hold) }
+}
+
+// NativeSessions is how many native sessions the fake has minted.
+func (f *Fake) NativeSessions() int {
+ f.nmu.Lock()
+ defer f.nmu.Unlock()
+ return len(f.sessions)
+}
+
+// EndNativeSession ends the native session whose cookie is value, as
+// signing out of Equipo does, and revokes every device registered with it.
+func (f *Fake) EndNativeSession(value string) {
+ f.nmu.Lock()
+ if s := f.sessions[value]; s != nil {
+ s.ended = true
+ }
+ f.nmu.Unlock()
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ for _, d := range f.devices {
+ if d.session == value {
+ d.revoked = true
+ }
+ }
+}
+
+// DeviceSession is the native session cookie the device with id was
+// registered with ("" for a device from the code flow).
+func (f *Fake) DeviceSession(id string) string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if d := f.devices[id]; d != nil {
+ return d.session
+ }
+ return ""
+}
+
+// LiveCredentials are the ids of the devices holding a credential Equipo
+// still takes: exchanged or registered, and not revoked.
+func (f *Fake) LiveCredentials() []string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ var out []string
+ for id, d := range f.devices {
+ if d.token != "" && !d.revoked {
+ out = append(out, id)
+ }
+ }
+ return out
+}
+
+// Devices are the ids of every device the fake knows.
+func (f *Fake) Devices() []string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ var out []string
+ for id := range f.devices {
+ out = append(out, id)
+ }
+ return out
+}
+
+func nativeAnswer(w http.ResponseWriter, status int, state string) {
+ writeJSON(w, status, map[string]string{"state": state})
+}
+
+// serveNative answers the two native routes, and reports whether r was
+// one of them.
+func (f *Fake) serveNative(w http.ResponseWriter, r *http.Request) bool {
+ switch {
+ case r.Method == http.MethodPost && r.URL.Path == "/native/oficina-id":
+ f.nativeExchange(w, r)
+ case r.Method == http.MethodPost && r.URL.Path == "/api/v1/auth/devices/native":
+ f.nativeDevice(w, r)
+ default:
+ return false
+ }
+ return true
+}
+
+func (f *Fake) nativeExchange(w http.ResponseWriter, r *http.Request) {
+ u, _ := url.Parse(f.URL)
+ media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ if r.Host != u.Host || r.URL.RawQuery != "" || len(r.Header.Values("Origin")) != 0 || len(r.Header.Values("Sec-Fetch-Site")) != 0 ||
+ len(r.Header.Values("Cookie")) != 0 || len(r.Header.Values("Authorization")) != 0 || err != nil || media != "application/json" {
+ nativeAnswer(w, 400, "invalid")
+ return
+ }
+ var in struct {
+ Assertion string `json:"assertion"`
+ Verifier string `json:"verifier"`
+ }
+ if strict(r, &in) != nil || in.Assertion == "" || in.Verifier == "" {
+ nativeAnswer(w, 400, "invalid")
+ return
+ }
+ f.nmu.Lock()
+ hold, entered := f.nativeHold, f.nativeEntered
+ f.nativeHold, f.nativeEntered = nil, nil
+ f.nmu.Unlock()
+ if hold != nil {
+ close(entered)
+ select {
+ case <-hold:
+ case <-f.closing:
+ return
+ }
+ }
+ f.nmu.Lock()
+ defer f.nmu.Unlock()
+ if status := f.failNative; status != 0 {
+ f.failNative = 0
+ state, ok := map[int]string{400: "invalid", 401: "failed", 403: "unknown"}[status]
+ if !ok {
+ state = "unavailable"
+ }
+ nativeAnswer(w, status, state)
+ return
+ }
+ g := f.assertions[in.Assertion]
+ if g == nil || g.used || g.verifier != in.Verifier {
+ nativeAnswer(w, 401, "failed")
+ return
+ }
+ address, linked := f.links[g.subject]
+ if !linked {
+ nativeAnswer(w, 403, "unknown")
+ return
+ }
+ g.used = true
+ value := rand.Text() + rand.Text()
+ now := time.Now().UTC().Truncate(time.Second)
+ f.sessions[value] = &nativeSession{subject: g.subject, address: address, at: now}
+ writeJSON(w, 200, map[string]any{"name": SessionCookie, "value": value, "expires_at": now.Add(nativeLifetime).Unix()})
+}
+
+func (f *Fake) nativeDevice(w http.ResponseWriter, r *http.Request) {
+ // A browser-style request: the session cookie, and Equipo's own
+ // Origin, which its CSRF check wants on a cookie mutation.
+ if r.Header.Get("Origin") != f.URL || len(r.Header.Values("Authorization")) != 0 || len(r.Header.Values("Idempotency-Key")) > 1 {
+ writeError(w, r, 403, "forbidden")
+ return
+ }
+ c, err := r.Cookie(SessionCookie)
+ if err != nil || len(r.Cookies()) != 1 {
+ writeError(w, r, 401, "unauthenticated")
+ return
+ }
+ var in struct {
+ PublicKey string `json:"public_key"`
+ Label string `json:"label"`
+ }
+ if strict(r, &in) != nil {
+ writeError(w, r, 422, "invalid_input")
+ return
+ }
+ raw, err := base64.RawURLEncoding.Strict().DecodeString(in.PublicKey)
+ if err != nil || len(raw) != ed25519.PublicKeySize || in.Label == "" || len(in.Label) > 128 || !utf8.ValidString(in.Label) || strings.ContainsAny(in.Label, "\x00\r\n") {
+ writeError(w, r, 422, "invalid_input")
+ return
+ }
+ f.nmu.Lock()
+ s := f.sessions[c.Value]
+ live := s != nil && !s.ended && time.Now().Before(s.at.Add(nativeLifetime))
+ var at time.Time
+ if live {
+ at = s.at
+ }
+ f.nmu.Unlock()
+ if !live {
+ writeError(w, r, 401, "unauthenticated")
+ return
+ }
+ d := &device{id: rand.Text(), publicKey: in.PublicKey, label: in.Label, approved: true, revision: 1,
+ token: personAudience + "." + rand.Text(), expires: at.Add(nativeLifetime), session: c.Value}
+ f.mu.Lock()
+ f.devices[d.id] = d
+ f.mu.Unlock()
+ w.Header().Set("ETag", `"1"`)
+ writeJSON(w, 200, map[string]any{"id": d.id, "token": d.token, "audience": personAudience,
+ "instance_id": f.Instance, "expires_at": d.expires})
+}
diff --git a/internal/equipo/native.go b/internal/equipo/native.go
new file mode 100644
index 0000000..7a15799
--- /dev/null
+++ b/internal/equipo/native.go
@@ -0,0 +1,127 @@
+package equipo
+
+import (
+ "bytes"
+ "context"
+ "crypto/ed25519"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// Equipo's own native sign-in with Oficina ID, which Base completes for a
+// member whose native app hands it an assertion addressed to Equipo
+// (Equipo's internal/equipo/oficinaid/native.go and
+// personapi/native_device.go). It ends in the same person credential the
+// code flow does, which lasts only as long as the Equipo session it was
+// registered with: seven days, or until the person signs out of Equipo, is
+// relinked or leaves the roster.
+
+var (
+ // ErrNotLinked: Equipo has no roster member linked to the assertion's
+ // Oficina ID (403 unknown).
+ ErrNotLinked = &Error{Status: http.StatusForbidden, Code: "unknown"}
+ // ErrAssertionFailed: Equipo did not accept the assertion (bad,
+ // expired, wrong audience or verifier, or already used): a fresh one
+ // may be tried (401 failed).
+ ErrAssertionFailed = &Error{Status: http.StatusUnauthorized, Code: "failed"}
+ // ErrAssertionInvalid: Equipo could not read the request (400 invalid).
+ ErrAssertionInvalid = &Error{Status: http.StatusBadRequest, Code: "invalid"}
+)
+
+// NativeSession is Equipo's native session: its cookie, and when it ends.
+type NativeSession struct {
+ Name string
+ Value string
+ ExpiresAt time.Time
+}
+
+// Cookie is the session as a Cookie header's value.
+func (s NativeSession) Cookie() string { return s.Name + "=" + s.Value }
+
+// NativeExchange trades an Oficina ID assertion addressed to Equipo, with
+// its verifier, for an Equipo native session. Like the native app it
+// stands in for, it sends no Origin and no cookie. A refusal is an *Error
+// whose Code is Equipo's state (ErrNotLinked, ErrAssertionFailed,
+// ErrAssertionInvalid, or a 503 "unavailable").
+func (c *Client) NativeExchange(ctx context.Context, assertion, verifier string) (NativeSession, error) {
+ ctx, cancel := context.WithTimeout(ctx, callTimeout)
+ defer cancel()
+ raw, err := json.Marshal(map[string]string{"assertion": assertion, "verifier": verifier})
+ if err != nil {
+ return NativeSession{}, err
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.origin+"/native/oficina-id", bytes.NewReader(raw))
+ if err != nil {
+ return NativeSession{}, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json")
+ res, err := c.http.Do(req)
+ if err != nil {
+ return NativeSession{}, err
+ }
+ defer res.Body.Close()
+ body, err := io.ReadAll(io.LimitReader(res.Body, 64<<10))
+ if err != nil {
+ return NativeSession{}, err
+ }
+ if res.StatusCode != http.StatusOK {
+ var e struct {
+ State string `json:"state"`
+ }
+ _ = json.Unmarshal(body, &e)
+ return NativeSession{}, &Error{Status: res.StatusCode, Code: e.State}
+ }
+ var out struct {
+ Name string `json:"name"`
+ Value string `json:"value"`
+ ExpiresAt int64 `json:"expires_at"`
+ }
+ if err := json.Unmarshal(body, &out); err != nil {
+ return NativeSession{}, fmt.Errorf("equipo: native exchange: %w", err)
+ }
+ if !cookieToken(out.Name) || !cookieToken(out.Value) || out.ExpiresAt <= 0 {
+ return NativeSession{}, fmt.Errorf("equipo: native exchange: an unusable session")
+ }
+ return NativeSession{Name: out.Name, Value: out.Value, ExpiresAt: time.Unix(out.ExpiresAt, 0).UTC()}, nil
+}
+
+// cookieToken reports whether s may stand in a Cookie header as a name or
+// value: 1 to 4096 printable ASCII characters, none of them a separator.
+func cookieToken(s string) bool {
+ if s == "" || len(s) > 4096 {
+ return false
+ }
+ for _, r := range s {
+ if r <= ' ' || r >= 0x7f || strings.ContainsRune(`";,\=`, r) {
+ return false
+ }
+ }
+ return true
+}
+
+// RegisterNative registers a device key pub, labelled label, with the
+// person's Equipo native session s, and returns its credential: the same
+// kind as the code flow's (audience equipo.person.v1), ending with s. It
+// sends s's cookie and Equipo's own Origin, as Equipo's CSRF check wants
+// on a cookie mutation, and nothing of Base's.
+func (c *Client) RegisterNative(ctx context.Context, s NativeSession, pub ed25519.PublicKey, label string) (Credential, error) {
+ var out Credential
+ h := http.Header{"Cookie": {s.Cookie()}, "Origin": {c.origin}}
+ in := map[string]string{"public_key": base64.RawURLEncoding.EncodeToString(pub), "label": label}
+ hdr, err := c.call(ctx, http.MethodPost, "/api/v1/auth/devices/native", "", NewKey(), h, in, &out)
+ if err != nil {
+ return Credential{}, err
+ }
+ if out.ID == "" || out.Token == "" {
+ return Credential{}, fmt.Errorf("equipo: native device: no credential")
+ }
+ out.Revision, _ = strconv.ParseInt(strings.Trim(hdr.Get("ETag"), `"`), 10, 64)
+ return out, nil
+}
diff --git a/internal/look/static/ask.js b/internal/look/static/ask.js
index 862b0cd..8a06515 100644
--- a/internal/look/static/ask.js
+++ b/internal/look/static/ask.js
@@ -1570,7 +1570,8 @@ function start(root) {
if (root.dataset.state !== "ready") show("ready");
return out;
}
- // Lost the connection: the panel says what to do. No runner that
+ // Lost the connection (a 409 saying so; Equipo refusing the key is
+ // 409 reconnect, never 401): the panel says what to do. No runner that
// can answer: the conversation stays, with a note saying so.
// Otherwise the conversation stays, with a line to try again (a 409
// is stale: the next events show how things are).
@@ -1620,7 +1621,7 @@ function start(root) {
for (const b of form.querySelectorAll("button")) b.disabled = false;
return;
}
- if (!out && lastStatus === 409) {
+ if (!out && lastStatus === 409 && lastState === "ready") {
// The card moved on (a new revision, or answered elsewhere): read the
// conversation afresh and let the person choose again. Never resend.
await load();
diff --git a/internal/store/disconnected_test.go b/internal/store/disconnected_test.go
new file mode 100644
index 0000000..7d5b6f7
--- /dev/null
+++ b/internal/store/disconnected_test.go
@@ -0,0 +1,64 @@
+package store
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+)
+
+// AskDisconnected is set by Disconnect and cleared only where a connection
+// is made: an explicit connected save, or an approval stored. A pending
+// code leaves it, and an automatic save refuses while it is set.
+func TestAskDisconnectedClearsOnlyOnAConnection(t *testing.T) {
+ ctx, db := context.Background(), open(t)
+ ana, _, err := Invite(ctx, db, "ana@example.com")
+ if err != nil {
+ t.Fatal(err)
+ }
+ flag := func() bool {
+ t.Helper()
+ v, err := AskDisconnected(ctx, db, ana.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return v
+ }
+ link := func(dev, state string) EquipoLink {
+ return EquipoLink{MemberID: ana.ID, Origin: "https://equipo.test", State: state, DeviceID: dev,
+ Sealed: []byte("s"), ExpiresAt: time.Now().Add(time.Hour)}
+ }
+ if err := DisconnectEquipo(ctx, db, ana.ID); err != nil || !flag() {
+ t.Fatalf("disconnect: %v, flag %v", err, flag())
+ }
+ // A pending code is not a connection.
+ if err := SaveEquipoLink(ctx, db, link("CODE", EquipoPending)); err != nil || !flag() {
+ t.Fatalf("pending code: %v, flag %v", err, flag())
+ }
+ // An automatic save refuses, writing nothing.
+ if err := SaveConnectedEquipoLink(ctx, db, link("AUTO", EquipoConnected), false); !errors.Is(err, ErrAskDisconnected) {
+ t.Fatalf("automatic save while disconnected: %v", err)
+ }
+ if l, _, _ := EquipoLinkFor(ctx, db, ana.ID); l.DeviceID != "CODE" || !flag() {
+ t.Fatalf("the refused automatic save wrote: %+v, flag %v", l, flag())
+ }
+ // The approval of the code is the connection.
+ if ok, err := ConnectEquipoLink(ctx, db, ana.ID, "CODE", []byte("b"), time.Now().Add(time.Hour), 3); !ok || err != nil || flag() {
+ t.Fatalf("approval: %v %v, flag %v", ok, err, flag())
+ }
+ // An approval that stores nothing clears nothing.
+ if err := DisconnectEquipo(ctx, db, ana.ID); err != nil {
+ t.Fatal(err)
+ }
+ if ok, _ := ConnectEquipoLink(ctx, db, ana.ID, "CODE", []byte("b"), time.Now().Add(time.Hour), 3); ok || !flag() {
+ t.Fatalf("a late approval: stored %v, flag %v", ok, flag())
+ }
+ // An explicit connected save clears it.
+ if err := SaveConnectedEquipoLink(ctx, db, link("NATIVE", EquipoConnected), true); err != nil || flag() {
+ t.Fatalf("explicit save: %v, flag %v", err, flag())
+ }
+ // And an automatic one, not disconnected, saves.
+ if err := SaveConnectedEquipoLink(ctx, db, link("RENEW", EquipoConnected), false); err != nil || flag() {
+ t.Fatalf("automatic renewal: %v, flag %v", err, flag())
+ }
+}
diff --git a/internal/store/equipo.go b/internal/store/equipo.go
index cf612b1..04b11b2 100644
--- a/internal/store/equipo.go
+++ b/internal/store/equipo.go
@@ -53,30 +53,62 @@ func EquipoLinkFor(ctx context.Context, db *sql.DB, memberID string) (l EquipoLi
return l, true, nil
}
+// ErrAskDisconnected: the member has disconnected Ask, so an automatic
+// save stores nothing (SaveConnectedEquipoLink).
+var ErrAskDisconnected = errors.New("store: Ask disconnected by the member")
+
// SaveEquipoLink stores l as the member's only link, replacing any other,
// and forgets the member's host token in the same transaction: a new
// connection may be another Equipo person, and gets its own once ready.
+// It leaves AskDisconnected as it is: a pending code is not a connection.
func SaveEquipoLink(ctx context.Context, db *sql.DB, l EquipoLink) error {
+ return inTx(ctx, db, func(tx *sql.Tx) error { return saveEquipoLink(ctx, tx, l) })
+}
+
+// SaveConnectedEquipoLink is SaveEquipoLink for a connected link, made in
+// one go (Ask set up with Oficina ID). An explicit one, which the member
+// asked for, clears AskDisconnected in the same transaction. An automatic
+// one leaves it, and while it is set stores nothing and answers
+// ErrAskDisconnected: the flag is checked where the link is written, not
+// only by the caller.
+func SaveConnectedEquipoLink(ctx context.Context, db *sql.DB, l EquipoLink, explicit bool) error {
+ return inTx(ctx, db, func(tx *sql.Tx) error {
+ if explicit {
+ if _, err := tx.ExecContext(ctx, `UPDATE members SET ask_disconnected = 0 WHERE id = ?`, l.MemberID); err != nil {
+ return err
+ }
+ } else {
+ var disconnected bool
+ if err := tx.QueryRowContext(ctx, `SELECT ask_disconnected FROM members WHERE id = ?`, l.MemberID).Scan(&disconnected); err != nil {
+ return err
+ }
+ if disconnected {
+ return ErrAskDisconnected
+ }
+ }
+ return saveEquipoLink(ctx, tx, l)
+ })
+}
+
+func saveEquipoLink(ctx context.Context, tx *sql.Tx, l EquipoLink) error {
var polled any
if l.PolledAt != nil {
polled = l.PolledAt.UTC()
}
- return inTx(ctx, db, func(tx *sql.Tx) error {
- if _, err := tx.ExecContext(ctx, `DELETE FROM host_tokens WHERE member_id = ?`, l.MemberID); err != nil {
- return err
- }
- _, err := tx.ExecContext(ctx, `INSERT INTO equipo_links (`+equipoCols+`, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- ON CONFLICT (member_id) DO UPDATE SET origin = excluded.origin, state = excluded.state,
- device_id = excluded.device_id, user_code = excluded.user_code,
- verification_uri = excluded.verification_uri, sealed = excluded.sealed,
- expires_at = excluded.expires_at, revision = excluded.revision,
- polled_at = excluded.polled_at, person = excluded.person,
- exchanging_until = NULL, updated_at = excluded.updated_at`,
- l.MemberID, l.Origin, l.State, l.DeviceID, l.UserCode, l.VerificationURI,
- l.Sealed, l.ExpiresAt.UTC(), l.Revision, polled, l.Person, time.Now().UTC())
+ if _, err := tx.ExecContext(ctx, `DELETE FROM host_tokens WHERE member_id = ?`, l.MemberID); err != nil {
return err
- })
+ }
+ _, err := tx.ExecContext(ctx, `INSERT INTO equipo_links (`+equipoCols+`, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT (member_id) DO UPDATE SET origin = excluded.origin, state = excluded.state,
+ device_id = excluded.device_id, user_code = excluded.user_code,
+ verification_uri = excluded.verification_uri, sealed = excluded.sealed,
+ expires_at = excluded.expires_at, revision = excluded.revision,
+ polled_at = excluded.polled_at, person = excluded.person,
+ exchanging_until = NULL, updated_at = excluded.updated_at`,
+ l.MemberID, l.Origin, l.State, l.DeviceID, l.UserCode, l.VerificationURI,
+ l.Sealed, l.ExpiresAt.UTC(), l.Revision, polled, l.Person, time.Now().UTC())
+ return err
}
func inTx(ctx context.Context, db *sql.DB, fn func(*sql.Tx) error) error {
@@ -116,12 +148,24 @@ func ReleaseEquipoPoll(ctx context.Context, db *sql.DB, memberID, dev string) er
// ConnectEquipoLink stores the bearer an exchange brought back, sealed, but
// only while the member's link is still that pending device. false means
// it is not (disconnected, or replaced by a newer Connect): the caller must
-// revoke the bearer instead.
-func ConnectEquipoLink(ctx context.Context, db *sql.DB, memberID, dev string, sealed []byte, expires time.Time, revision int64) (bool, error) {
- res, err := db.ExecContext(ctx, `UPDATE equipo_links SET state = ?, sealed = ?, expires_at = ?, revision = ?,
- user_code = '', exchanging_until = NULL, updated_at = ? WHERE member_id = ? AND device_id = ? AND state = ?`,
- EquipoConnected, sealed, expires.UTC(), revision, time.Now().UTC(), memberID, dev, EquipoPending)
- return affected(res, err)
+// revoke the bearer instead. Stored, it is the member's connection, made
+// with their approval in Equipo, so it clears AskDisconnected in the same
+// transaction.
+func ConnectEquipoLink(ctx context.Context, db *sql.DB, memberID, dev string, sealed []byte, expires time.Time, revision int64) (stored bool, err error) {
+ err = inTx(ctx, db, func(tx *sql.Tx) error {
+ res, err := tx.ExecContext(ctx, `UPDATE equipo_links SET state = ?, sealed = ?, expires_at = ?, revision = ?,
+ user_code = '', exchanging_until = NULL, updated_at = ? WHERE member_id = ? AND device_id = ? AND state = ?`,
+ EquipoConnected, sealed, expires.UTC(), revision, time.Now().UTC(), memberID, dev, EquipoPending)
+ if stored, err = affected(res, err); err != nil || !stored {
+ return err
+ }
+ _, err = tx.ExecContext(ctx, `UPDATE members SET ask_disconnected = 0 WHERE id = ?`, memberID)
+ return err
+ })
+ if err != nil {
+ stored = false
+ }
+ return stored, err
}
func affected(res sql.Result, err error) (bool, error) {
@@ -155,18 +199,30 @@ func LoseEquipoLink(ctx context.Context, db *sql.DB, memberID, dev string) error
})
}
-// DisconnectEquipo forgets the member's link, if it is still device dev,
-// and their host token, in one transaction: both go or neither does.
-func DisconnectEquipo(ctx context.Context, db *sql.DB, memberID, dev string) error {
+// DisconnectEquipo forgets the member's link, whichever device it is now,
+// and their host token, and marks Ask disconnected by the member
+// (AskDisconnected), in one transaction: all three or none.
+func DisconnectEquipo(ctx context.Context, db *sql.DB, memberID string) error {
return inTx(ctx, db, func(tx *sql.Tx) error {
- if _, err := tx.ExecContext(ctx, `DELETE FROM equipo_links WHERE member_id = ? AND device_id = ?`, memberID, dev); err != nil {
+ if _, err := tx.ExecContext(ctx, `DELETE FROM equipo_links WHERE member_id = ?`, memberID); err != nil {
+ return err
+ }
+ if _, err := tx.ExecContext(ctx, `DELETE FROM host_tokens WHERE member_id = ?`, memberID); err != nil {
return err
}
- _, err := tx.ExecContext(ctx, `DELETE FROM host_tokens WHERE member_id = ?`, memberID)
+ _, err := tx.ExecContext(ctx, `UPDATE members SET ask_disconnected = 1 WHERE id = ?`, memberID)
return err
})
}
+// AskDisconnected reports whether the member has disconnected Ask and not
+// connected it since.
+func AskDisconnected(ctx context.Context, q QueryRower, memberID string) (bool, error) {
+ var v bool
+ err := q.QueryRowContext(ctx, `SELECT ask_disconnected FROM members WHERE id = ?`, memberID).Scan(&v)
+ return v, err
+}
+
// SetEquipoPerson records the Equipo address the member's device dev
// speaks for, if the link is still that device.
func SetEquipoPerson(ctx context.Context, db *sql.DB, memberID, dev, person string) error {
diff --git a/internal/store/hosttokens_test.go b/internal/store/hosttokens_test.go
index 5055d05..5e04853 100644
--- a/internal/store/hosttokens_test.go
+++ b/internal/store/hosttokens_test.go
@@ -179,7 +179,7 @@ func TestHostTokenFollowsTheLink(t *testing.T) {
t.Fatal(err)
}
tok = mint()
- if err := DisconnectEquipo(ctx, db, ana.ID, "DEV1"); err != nil || names(tok) {
+ if err := DisconnectEquipo(ctx, db, ana.ID); err != nil || names(tok) {
t.Fatalf("disconnecting kept the token: %v", err)
}
link := func(dev, state string) error {
diff --git a/internal/store/members.go b/internal/store/members.go
index 3249d4e..04fdd58 100644
--- a/internal/store/members.go
+++ b/internal/store/members.go
@@ -24,9 +24,14 @@ type Member struct {
// AskClosed is true once the member has closed Ask Base, docked open
// beside Home on a wide screen, until they open it again.
AskClosed bool
+ // AskDisconnected is true once the member has disconnected Ask Base,
+ // until a connection they make themselves is stored (DisconnectEquipo,
+ // ConnectEquipoLink, SaveConnectedEquipoLink):
+ // no app sets it up again by itself meanwhile.
+ AskDisconnected bool
}
-const memberCols = `id, email, name, role, invited_at, joined_at, invite_sent_at, theme, ask_closed`
+const memberCols = `id, email, name, role, invited_at, joined_at, invite_sent_at, theme, ask_closed, ask_disconnected`
// memberColsOf is memberCols qualified by a table alias, for joins.
func memberColsOf(alias string) string {
@@ -42,7 +47,7 @@ type scanner interface{ Scan(...any) error }
func scanMember(s scanner) (Member, error) {
var m Member
var joined, sent sql.NullTime
- if err := s.Scan(&m.ID, &m.Email, &m.Name, &m.Role, &m.InvitedAt, &joined, &sent, &m.Theme, &m.AskClosed); err != nil {
+ if err := s.Scan(&m.ID, &m.Email, &m.Name, &m.Role, &m.InvitedAt, &joined, &sent, &m.Theme, &m.AskClosed, &m.AskDisconnected); err != nil {
return Member{}, err
}
if joined.Valid {
diff --git a/internal/store/migrations/0012_ask_disconnected.sql b/internal/store/migrations/0012_ask_disconnected.sql
new file mode 100644
index 0000000..a309682
--- /dev/null
+++ b/internal/store/migrations/0012_ask_disconnected.sql
@@ -0,0 +1,4 @@
+-- ask_disconnected: the member disconnected Ask Base, and no app connects
+-- it again by itself until they connect it themselves. Theirs, on every
+-- device.
+ALTER TABLE members ADD COLUMN ask_disconnected integer NOT NULL DEFAULT 0;
diff --git a/internal/store/oficina_links.go b/internal/store/oficina_links.go
new file mode 100644
index 0000000..e409e32
--- /dev/null
+++ b/internal/store/oficina_links.go
@@ -0,0 +1,30 @@
+package store
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+)
+
+// Oficina ID links are connect's rows (home_identity_links). connect checks
+// them, and Base reads and removes them only as connect asks an app to:
+// removing a member removes their links (RemoveMember), and a link connect
+// no longer resolves is removed before the member links again
+// (web.oficina.dropDeadLink). Nothing here writes one.
+
+// OficinaLinkSubject is the Oficina account (subject at issuer) linked to
+// member number n; ok is false when there is none.
+func OficinaLinkSubject(ctx context.Context, q QueryRower, issuer string, n int64) (subject string, ok bool, err error) {
+ err = q.QueryRowContext(ctx, `SELECT subject FROM home_identity_links WHERE issuer = ? AND person_id = ?`, issuer, n).Scan(&subject)
+ if errors.Is(err, sql.ErrNoRows) {
+ return "", false, nil
+ }
+ return subject, err == nil, err
+}
+
+// DeleteOficinaLink removes the link between subject at issuer and member
+// number n, if it is still that link.
+func DeleteOficinaLink(ctx context.Context, tx *sql.Tx, issuer, subject string, n int64) error {
+ _, err := tx.ExecContext(ctx, `DELETE FROM home_identity_links WHERE issuer = ? AND subject = ? AND person_id = ?`, issuer, subject, n)
+ return err
+}
diff --git a/internal/web/api.go b/internal/web/api.go
new file mode 100644
index 0000000..ffbe10a
--- /dev/null
+++ b/internal/web/api.go
@@ -0,0 +1,148 @@
+package web
+
+import (
+ "net/http"
+ "strings"
+
+ "amadan.net/carlos/base/internal/look"
+)
+
+// Base's small JSON API for its native app (docs/api/base-native-v1.md):
+// reads only, behind the member gate, with the session the native exchange
+// minted. Each answer is what the web page of the same name shows, from the
+// same builders.
+
+type apiMember struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ Initials string `json:"initials"`
+ Owner bool `json:"owner"`
+}
+
+type apiBase struct {
+ Name string `json:"name"`
+ Slug string `json:"slug"`
+ Origin string `json:"origin"`
+ Timezone string `json:"timezone"`
+}
+
+type apiMe struct {
+ Member apiMember `json:"member"`
+ Base apiBase `json:"base"`
+ // Appearance is "system", "light" or "dark".
+ Appearance string `json:"appearance"`
+ // EquipoOrigin is the Equipo instance Ask Base relays to, null with
+ // Ask off. The app asks Oficina ID for an assertion addressed to it.
+ EquipoOrigin *string `json:"equipo_origin"`
+}
+
+// apiMeRead is GET /api/v1/me.
+func (a *app) apiMeRead(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ name := displayName(me)
+ out := apiMe{
+ Member: apiMember{ID: me.ID, Name: name, Email: me.Email, Initials: initials(name), Owner: me.Role == "owner"},
+ Base: apiBase{Name: a.cfg.Name, Slug: a.cfg.Slug, Origin: a.cfg.Origin, Timezone: "UTC"},
+ Appearance: "system",
+ }
+ if a.cfg.Timezone != nil {
+ out.Base.Timezone = a.cfg.Timezone.String()
+ }
+ if me.Theme != "" {
+ out.Appearance = me.Theme
+ }
+ if a.ask != nil {
+ origin := a.cfg.EquipoOrigin
+ out.EquipoOrigin = &origin
+ }
+ writeJSON(w, http.StatusOK, out)
+}
+
+type apiStep struct {
+ Label string `json:"label"`
+ Done bool `json:"done"`
+}
+
+// apiApp is one app on Home. An Oficina app has its icon at IconURL, a
+// path on Base's origin, and its native bundle ID (and, when its native app
+// opens by one, a URL scheme); an installed app or one of Base's own pages
+// has line art (IconSVG, drawn in currentColor) on a tint, one of the
+// catalogue's tint names.
+type apiApp struct {
+ ID string `json:"id"`
+ Kind string `json:"kind"`
+ Name string `json:"name"`
+ URL string `json:"url"`
+ IconURL string `json:"icon_url,omitempty"`
+ Tint string `json:"tint,omitempty"`
+ IconSVG string `json:"icon_svg,omitempty"`
+ BundleID string `json:"bundle_id,omitempty"`
+ Scheme string `json:"scheme,omitempty"`
+}
+
+type apiHome struct {
+ Greeting string `json:"greeting"`
+ Lede string `json:"lede"`
+ Steps []apiStep `json:"steps"`
+ Apps []apiApp `json:"apps"`
+}
+
+// apiHomeRead is GET /api/v1/home: Home's steps and apps, in Home's order
+// (the team's Oficina apps, the installed apps, then Base's own pages).
+func (a *app) apiHomeRead(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ c, err := a.homeContent(r.Context(), me)
+ if err != nil {
+ a.logger.Error("api home", "err", err)
+ writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"})
+ return
+ }
+ out := apiHome{Greeting: c.Greeting, Lede: c.Lede, Steps: []apiStep{}, Apps: []apiApp{}}
+ for _, s := range c.Steps {
+ out.Steps = append(out.Steps, apiStep(s))
+ }
+ bundles := map[string]struct{ bundle, scheme string }{}
+ for _, o := range a.cfg.OficinaApps {
+ bundles[o.ID] = struct{ bundle, scheme string }{o.BundleID(), o.Scheme()}
+ }
+ for _, t := range append(append([]tile{}, c.Apps...), c.Dock...) {
+ app := apiApp{ID: t.ID, Kind: t.Kind, Name: t.Name, URL: t.Href}
+ switch t.Kind {
+ case "oficina":
+ app.IconURL = look.Assets.Path(t.Image)
+ app.BundleID, app.Scheme = bundles[t.ID].bundle, bundles[t.ID].scheme
+ case "own":
+ // Base's own pages open on the web.
+ app.URL = a.cfg.Origin + t.Href
+ fallthrough
+ default:
+ app.Tint, app.IconSVG = t.Tint, string(t.Icon)
+ }
+ out.Apps = append(out.Apps, app)
+ }
+ writeJSON(w, http.StatusOK, out)
+}
+
+// apiError is every JSON refusal's body.
+type apiError struct {
+ Code string `json:"code"`
+}
+
+// apiRequest reports whether a request is the native app's or a script's,
+// which hear a refusal as JSON, never as a redirect to /signin: everything
+// under /api/, and anything asking for JSON or an event stream.
+func apiRequest(r *http.Request) bool {
+ if strings.HasPrefix(r.URL.Path, "/api/") {
+ return true
+ }
+ accept := r.Header.Get("Accept")
+ return strings.Contains(accept, "application/json") || strings.Contains(accept, "text/event-stream")
+}
+
+// unauthenticated is the JSON refusal for a request with no session, or one
+// that names nobody who is a member now. The native app hears 401 and signs
+// in again.
+func unauthenticated(w http.ResponseWriter) {
+ writeJSON(w, http.StatusUnauthorized, apiError{Code: "unauthenticated"})
+}
diff --git a/internal/web/app.go b/internal/web/app.go
index 16fb289..986510c 100644
--- a/internal/web/app.go
+++ b/internal/web/app.go
@@ -10,6 +10,7 @@ import (
"html/template"
"io/fs"
"log/slog"
+ "mime"
"net/http"
"strings"
"time"
@@ -170,12 +171,17 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger
r.With(sess.Require).Get("/account/home", o.routes.Account)
r.With(sess.Require).Post("/account/home", o.routes.LinkStart)
r.With(sess.Require).Get("/account/home/confirm", o.bridge.ConfirmPage)
- r.With(sess.Require).Post("/account/home/confirm", o.routes.ConfirmPost)
+ r.With(sess.Require).Post("/account/home/confirm", a.oficinaConfirm)
r.Post("/auth/begin", o.routes.LocalGuard(a.auth.Begin))
r.Get("/auth/callback", o.routes.LocalGuard(a.auth.Callback))
r.Get("/auth/verify", o.routes.LocalGuard(a.auth.Verify))
r.Post("/auth/verify", o.routes.LocalGuard(a.auth.Verify))
r.Post("/auth/signout", o.routes.Signout)
+ // The native app's Oficina ID exchange. connect's Middleware lets
+ // this one path past the CSRF check: it refuses anything a browser
+ // sends, and reads and sets no cookies.
+ r.Post(connect.NativeExchangePath, o.bridge.NativeExchange)
+ r.Post("/signout", a.signout)
} else {
r.Get("/signin", a.signin)
r.Post("/auth/begin", a.auth.Begin)
@@ -200,6 +206,8 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger
r.Post("/store/{app}/uninstall", a.storeUninstall)
r.Get("/settings", a.settings)
r.Post("/settings/appearance", a.settingsAppearance)
+ r.Get("/api/v1/me", a.apiMeRead)
+ r.Get("/api/v1/home", a.apiHomeRead)
r.With(ownSignInOnly).Post(registerBeginPath, a.pk.RegisterBegin)
r.With(ownSignInOnly).Post(registerFinishPath, a.pk.RegisterFinish)
r.Method(http.MethodGet, "/authorize", authorize)
@@ -253,11 +261,14 @@ func CurrentMember(r *http.Request) (store.Member, bool) {
return m, ok
}
-// requireMember lets through only a browser session that belongs to a
-// current member, and puts that member on the request. A session from Base's
-// own sign-in names the member's address; one from Oficina ID names an
-// Oficina account, which counts only through a stored link to a member who
-// still exists. A signed-out page request goes to /signin.
+// requireMember lets through only a session that belongs to a current
+// member, and puts that member on the request. A session from Base's own
+// sign-in names the member's address; one from Oficina ID (a browser's or
+// the native app's) names an Oficina account, which counts only through a
+// stored link to a member who still exists. A signed-out page request goes
+// to /signin; the native app and scripts (apiRequest) hear
+// 401 {"code":"unauthenticated"} instead, for no session or a session that
+// names nobody.
func (a *app) requireMember(next http.Handler) http.Handler {
gate := a.auth.RequireSession
if a.oficina != nil {
@@ -265,7 +276,7 @@ func (a *app) requireMember(next http.Handler) http.Handler {
// /signin/local: a signed-out visitor is offered Oficina first.
gate = a.sess.Require
}
- return gate(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ member := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
s, ok := sessions.Current(r)
if !ok {
@@ -277,21 +288,40 @@ func (a *app) requireMember(next http.Handler) http.Handler {
case err != nil:
a.logger.Error("member gate", "err", err)
http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ case !found && apiRequest(r):
+ unauthenticated(w)
case !found:
http.Error(w, "forbidden", http.StatusForbidden)
default:
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, m)))
}
- }))
+ })
+ paged := gate(member)
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !apiRequest(r) {
+ paged.ServeHTTP(w, r)
+ return
+ }
+ s, ok := a.sess.From(r)
+ if !ok {
+ unauthenticated(w)
+ return
+ }
+ member.ServeHTTP(w, sessions.WithSession(r, s))
+ })
}
// memberFor is the member behind session s. found is false for a session
// that names nobody who is a member now.
func (a *app) memberFor(r *http.Request, s sessions.Session) (m store.Member, found bool, err error) {
- if s.Method == connect.HomeMethod {
- if a.oficina == nil {
- // Left over from when Oficina ID was on: it names an Oficina
- // account, never an address.
+ if connect.IsHomeDerived(s.Method) {
+ // A browser, native or native-to-web sign-in through Oficina. The
+ // native kinds end seven days after they were minted, however
+ // recently used; connect's ResolveSession refuses them too, but
+ // the age is checked here first so no path forgets it.
+ if a.oficina == nil || connect.Expired(connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, time.Now()) {
+ // Without Oficina ID on, one left over from when it was names
+ // an Oficina account, never an address.
return store.Member{}, false, nil
}
return a.oficina.member(r)
@@ -299,13 +329,13 @@ func (a *app) memberFor(r *http.Request, s sessions.Session) (m store.Member, fo
return store.MemberByEmail(r.Context(), a.db, s.Subject)
}
-// ownSignInOnly refuses a request whose session came from Oficina ID. A
-// passkey is filed under the session's subject, which for an Oficina session
-// is the Oficina account, not the member's address: a passkey added there
-// could never sign the member in.
+// ownSignInOnly refuses a request whose session came from Oficina ID, in a
+// browser or the native app. A passkey is filed under the session's subject,
+// which for an Oficina session is the Oficina account, not the member's
+// address: a passkey added there could never sign the member in.
func ownSignInOnly(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if s, ok := sessions.Current(r); !ok || s.Method == connect.HomeMethod {
+ if s, ok := sessions.Current(r); !ok || connect.IsHomeDerived(s.Method) {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
@@ -313,6 +343,28 @@ func ownSignInOnly(next http.Handler) http.Handler {
})
}
+// signout is POST /signout, the native app's sign-out: it ends the session
+// the request carries, whatever its method, and nothing else (Oficina's own
+// sign-out is the app's to do). The app hears 204; a browser form goes to
+// the signed-out page. It is mounted with Oficina ID on, inside the CSRF
+// check like every POST, which the app passes by sending Base's Origin.
+func (a *app) signout(w http.ResponseWriter, r *http.Request) {
+ a.sess.SignOut(w, r)
+ w.Header().Set("Cache-Control", "no-store")
+ if wantsJSON(r) || isJSONBody(r) {
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
+ http.Redirect(w, r, "/signed-out", http.StatusSeeOther)
+}
+
+// isJSONBody reports whether the request's body is JSON, as the native kit
+// sends it.
+func isJSONBody(r *http.Request) bool {
+ media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ return err == nil && media == "application/json"
+}
+
// signedInAt is when the request's session signed in: the credential's own
// verification time when the sign-in method records one (Keymail, and
// Oficina ID, which records when the person last proved who they are at
diff --git a/internal/web/ask.go b/internal/web/ask.go
index 2723ab3..ea02167 100644
--- a/internal/web/ask.go
+++ b/internal/web/ask.go
@@ -24,9 +24,13 @@ type asker struct {
seal equipo.Sealer
// label is the device name a member sees when approving Base in Equipo.
label string
- // hosts holds a *sync.Mutex per member id, held while their
- // connection changes or their host is registered (lockMember).
+ // hosts holds a *memberConn per member id: their lock, held while
+ // their connection changes or their host is registered (lockMember),
+ // and their connection's generation (changeLink).
hosts sync.Map
+ // oficina holds a *sync.Mutex per member id, held while Ask is set up
+ // with Oficina ID for them (askOficinaLock).
+ oficina sync.Map
}
// askRoutes mounts the chat, behind the member gate and Base's CSRF check.
@@ -44,6 +48,7 @@ func (a *app) askRoutes(r chi.Router) {
r.Post("/ask/dock", a.askDock)
r.Get("/ask/oficina/connect", a.askOficinaConnect)
r.Get("/ask/oficina/done", a.askOficinaDone)
+ r.Post(askOficinaPath, a.askOficina)
}
// askDock is POST /ask/dock: on a wide screen the X closes Ask Base, docked
@@ -105,13 +110,19 @@ func chatting(state string) bool {
// deviceSecrets is what Base keeps sealed for a member's Equipo device:
// the Ed25519 seed, the device secret, the challenge and the nonce it
// proves with (kept, so a lost exchange answer can be asked for again),
-// and the bearer once it has one.
+// and the bearer once it has one. A key set up with Oficina ID (Via
+// "oficina") has no secret, challenge or nonce; it keeps instead the
+// cookie of the Equipo session it ends with, which Base never sends
+// anywhere again and never signs out (signing out would end the key).
type deviceSecrets struct {
- Seed []byte `json:"seed"`
- Secret string `json:"secret"`
- Challenge string `json:"challenge"`
- Nonce string `json:"nonce"`
- Token string `json:"token,omitempty"`
+ Seed []byte `json:"seed"`
+ Secret string `json:"secret"`
+ Challenge string `json:"challenge"`
+ Nonce string `json:"nonce"`
+ Token string `json:"token,omitempty"`
+ Via string `json:"via,omitempty"`
+ SessionName string `json:"session_name,omitempty"`
+ SessionValue string `json:"session_value,omitempty"`
}
func (a *app) sealSecrets(memberID string, s deviceSecrets) ([]byte, error) {
@@ -543,15 +554,27 @@ func (a *app) askStateJSON(w http.ResponseWriter, r *http.Request) {
if state == askReady {
cursor = a.askSnapshot(r, me, l, sec.Token, &v)
}
+ // RenewAfter is when the native app should set Ask up again with a
+ // fresh Oficina ID assertion: "" for a key from the code flow.
+ renew := ""
+ if at := renewAfter(l, sec); !at.IsZero() && state != askConnect {
+ renew = at.Format(time.RFC3339)
+ }
out := struct {
- State string `json:"state"`
- Messages []equipo.Message `json:"messages"`
- Jobs []jobView `json:"jobs"`
- Cards []equipo.Card `json:"cards"`
- Turn *equipo.Turn `json:"turn"`
- Status string `json:"status"`
- Cursor int64 `json:"cursor"`
- }{v.State, append([]equipo.Message{}, v.Messages...), append([]jobView{}, v.Jobs...), append([]equipo.Card{}, v.Cards...), v.Turn, v.Status, cursor}
+ State string `json:"state"`
+ Messages []equipo.Message `json:"messages"`
+ Jobs []jobView `json:"jobs"`
+ Cards []equipo.Card `json:"cards"`
+ Turn *equipo.Turn `json:"turn"`
+ Status string `json:"status"`
+ Cursor int64 `json:"cursor"`
+ RenewAfter string `json:"renew_after"`
+ EquipoOrigin string `json:"equipo_origin"`
+ // Disconnected: the member disconnected Ask, so no app sets it up
+ // again by itself.
+ Disconnected bool `json:"disconnected"`
+ }{v.State, append([]equipo.Message{}, v.Messages...), append([]jobView{}, v.Jobs...), append([]equipo.Card{}, v.Cards...), v.Turn, v.Status, cursor,
+ renew, a.ask.client.Origin(), me.AskDisconnected}
writeJSON(w, http.StatusOK, out)
}
diff --git a/internal/web/ask_connect.go b/internal/web/ask_connect.go
index b170928..3dd4963 100644
--- a/internal/web/ask_connect.go
+++ b/internal/web/ask_connect.go
@@ -45,18 +45,24 @@ func (a *app) askConnectStart(w http.ResponseWriter, r *http.Request) {
me, _ := CurrentMember(r)
next := nextOf(r.PostFormValue("next"))
ctx := r.Context()
- if old, sec, state, err := a.askLink(ctx, me); err == nil && state == askReady {
- a.revoke(ctx, old, sec)
- // The old connection is over: its link is lost and its host token
- // goes with it, in one transaction, before anything below can fail.
- unlock := a.lockMember(me.ID)
- err = store.LoseEquipoLink(ctx, a.db, me.ID, old.DeviceID)
- unlock()
- if err != nil {
- a.fail(w, err)
- return
+ // Reconnecting ends the connection there is now, before anything below
+ // can fail: read and marked lost (its host token going with it) in one
+ // locked step, then its device revoked.
+ var ended store.EquipoLink
+ var endedSec deviceSecrets
+ err := a.changeLink(me.ID, func() error {
+ l, sec, state, e := a.askLink(ctx, me)
+ if e != nil || state != askReady {
+ return e
}
+ ended, endedSec = l, sec
+ return store.LoseEquipoLink(ctx, a.db, me.ID, l.DeviceID)
+ })
+ if err != nil {
+ a.fail(w, err)
+ return
}
+ a.revokeDisplaced(ctx, ended, endedSec, "")
pub, key, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
a.fail(w, err)
@@ -79,17 +85,25 @@ func (a *app) askConnectStart(w http.ResponseWriter, r *http.Request) {
if exp.IsZero() {
exp = time.Now().Add(10 * time.Minute)
}
- // Saving the new link forgets the host token with it: a new connection
- // may be another Equipo person.
- unlock := a.lockMember(me.ID)
- err = store.SaveEquipoLink(ctx, a.db, store.EquipoLink{MemberID: me.ID, Origin: a.ask.client.Origin(),
- State: store.EquipoPending, DeviceID: ch.ID, UserCode: ch.UserCode,
- VerificationURI: a.verifyURI(ch), Sealed: sealed, ExpiresAt: exp})
- unlock()
+ // The new link replaces whatever link there is now (a connection made
+ // with Oficina ID while Equipo answered, say), read in the same locked
+ // step, whose device is then revoked. Saving it forgets the host token
+ // with it: a new connection may be another Equipo person.
+ var old store.EquipoLink
+ var oldSec deviceSecrets
+ err = a.changeLink(me.ID, func() (e error) {
+ if old, oldSec, _, e = a.askLink(ctx, me); e != nil {
+ return e
+ }
+ return store.SaveEquipoLink(ctx, a.db, store.EquipoLink{MemberID: me.ID, Origin: a.ask.client.Origin(),
+ State: store.EquipoPending, DeviceID: ch.ID, UserCode: ch.UserCode,
+ VerificationURI: a.verifyURI(ch), Sealed: sealed, ExpiresAt: exp})
+ })
if err != nil {
a.fail(w, err)
return
}
+ a.revokeDisplaced(ctx, old, oldSec, ch.ID)
http.Redirect(w, r, "/ask/connect?next="+next, http.StatusSeeOther)
}
@@ -190,9 +204,9 @@ func (a *app) poll(ctx context.Context, me store.Member, l store.EquipoLink, sec
case errors.Is(err, equipo.ErrPending), errors.Is(err, equipo.ErrSlowDown):
return askPending, nil
case errors.Is(err, equipo.ErrExpired):
- return askExpired, store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID)
+ return askExpired, a.changeLink(me.ID, func() error { return store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID) })
case errors.As(err, &e) && e.Status == http.StatusForbidden:
- return askRefused, store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID)
+ return askRefused, a.changeLink(me.ID, func() error { return store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID) })
case err != nil:
return askPending, err
}
@@ -216,25 +230,32 @@ func (a *app) keep(ctx context.Context, me store.Member, l store.EquipoLink, sec
l.Revision = cred.Revision
sealed, err := a.sealSecrets(me.ID, sec)
if err == nil {
- var stored bool
- if stored, err = store.ConnectEquipoLink(ctx, a.db, me.ID, l.DeviceID, sealed, cred.ExpiresAt, cred.Revision); stored {
+ // Only while the link is still this pending device, as it is at
+ // that moment: after Disconnect, or once anything else replaced
+ // it, the bearer is this device's alone to give up.
+ var stored, duplicate bool
+ err = a.changeLink(me.ID, func() (e error) {
+ if stored, e = store.ConnectEquipoLink(ctx, a.db, me.ID, l.DeviceID, sealed, cred.ExpiresAt, cred.Revision); stored || e != nil {
+ return e
+ }
+ now, found, e := store.EquipoLinkFor(ctx, a.db, me.ID)
+ duplicate = found && now.DeviceID == l.DeviceID && now.State == store.EquipoConnected
+ return e
+ })
+ switch {
+ case stored:
a.hostFor(ctx, me, l.DeviceID, cred.Token, true)
return askReady
- }
- }
- if err == nil {
- now, found, e := store.EquipoLinkFor(ctx, a.db, me.ID)
- if e == nil && found && now.DeviceID == l.DeviceID && now.State == store.EquipoConnected {
+ case duplicate:
return askReady
- }
- if err = e; err == nil {
+ case err == nil:
a.revoke(ctx, l, sec)
return askConnect
}
}
a.logger.Error("ask: store bearer", "device", l.DeviceID, "err", err)
a.revoke(ctx, l, sec)
- if e := store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID); e != nil {
+ if e := a.changeLink(me.ID, func() error { return store.DeleteEquipoLink(ctx, a.db, me.ID, l.DeviceID) }); e != nil {
a.logger.Error("ask: forget device", "device", l.DeviceID, "err", e)
}
return askFailed
@@ -251,25 +272,35 @@ func (a *app) revoke(ctx context.Context, l store.EquipoLink, sec deviceSecrets)
}
}
+// revokeDisplaced revokes the device of link old, which a change to the
+// member's link has just replaced or removed, read in that change's locked
+// step: unless it is the device that replaced it (kept), or never had a
+// bearer (a code never approved, which Equipo lets lapse).
+func (a *app) revokeDisplaced(ctx context.Context, old store.EquipoLink, sec deviceSecrets, kept string) {
+ if old.DeviceID != "" && old.DeviceID != kept && sec.Token != "" {
+ a.revoke(ctx, old, sec)
+ }
+}
+
// askDisconnect is POST /ask/disconnect, from Settings.
func (a *app) askDisconnect(w http.ResponseWriter, r *http.Request) {
me, _ := CurrentMember(r)
- l, sec, state, err := a.askLink(r.Context(), me)
- if err != nil {
- a.fail(w, err)
- return
- }
- if state == askReady {
- a.revoke(r.Context(), l, sec)
- }
- // The link and the host token go together, or Disconnect fails.
- unlock := a.lockMember(me.ID)
- err = store.DisconnectEquipo(r.Context(), a.db, me.ID, l.DeviceID)
- unlock()
+ ctx := r.Context()
+ // Whatever link there is at that moment goes, with the host token, in
+ // one locked step, or Disconnect fails; then its device is revoked.
+ var old store.EquipoLink
+ var oldSec deviceSecrets
+ err := a.changeLink(me.ID, func() (e error) {
+ if old, oldSec, _, e = a.askLink(ctx, me); e != nil {
+ return e
+ }
+ return store.DisconnectEquipo(ctx, a.db, me.ID)
+ })
if err != nil {
a.fail(w, err)
return
}
+ a.revokeDisplaced(ctx, old, oldSec, "")
http.Redirect(w, r, "/settings", http.StatusSeeOther)
}
@@ -318,12 +349,49 @@ func (a *app) hostFor(ctx context.Context, me store.Member, dev, token string, f
}
}
-// lockMember takes the member's lock, held while their connection
-// changes or their host is registered, and returns its release.
+// memberConn is a member's lock, held while their connection changes or
+// their host is registered, and their connection's generation, which every
+// change to their link moves on (changeLink). The lock is not reentrant:
+// nothing holding it calls hostFor.
+type memberConn struct {
+ mu sync.Mutex
+ gen uint64
+}
+
+func (a *app) memberConn(id string) *memberConn {
+ c, _ := a.ask.hosts.LoadOrStore(id, &memberConn{})
+ return c.(*memberConn)
+}
+
+// lockMember takes the member's lock and returns its release.
func (a *app) lockMember(id string) func() {
- mu, _ := a.ask.hosts.LoadOrStore(id, &sync.Mutex{})
- mu.(*sync.Mutex).Lock()
- return mu.(*sync.Mutex).Unlock
+ c := a.memberConn(id)
+ c.mu.Lock()
+ return c.mu.Unlock
+}
+
+// changeLink runs change, which changes the member's link (Connect, its
+// approval or end, Disconnect, Ask set up with Oficina ID), under their
+// lock, and moves their connection's generation on: a set-up with Oficina
+// ID that began before it then yields (askOficina). Equipo refusing a key
+// (askLost) is not a change of this kind: a set-up may replace that key.
+func (a *app) changeLink(id string, change func() error) error {
+ c := a.memberConn(id)
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.gen++
+ return change()
+}
+
+// linkGenDisconnected is the member's connection generation now, and
+// whether they have disconnected Ask, read together under their lock:
+// Disconnect sets the one and moves the other in one locked step.
+func (a *app) linkGenDisconnected(ctx context.Context, id string) (uint64, bool, error) {
+ c := a.memberConn(id)
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ disconnected, err := store.AskDisconnected(ctx, a.db, id)
+ return c.gen, disconnected, err
}
func (a *app) renderConnect(w http.ResponseWriter, r *http.Request, status int, v connectView) {
diff --git a/internal/web/ask_oficina_native.go b/internal/web/ask_oficina_native.go
new file mode 100644
index 0000000..a65b868
--- /dev/null
+++ b/internal/web/ask_oficina_native.go
@@ -0,0 +1,246 @@
+package web
+
+import (
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "errors"
+ "io"
+ "net/http"
+ "sync"
+ "time"
+
+ jsonv2 "github.com/go-json-experiment/json"
+ "github.com/go-json-experiment/json/jsontext"
+
+ "amadan.net/oficina/home/connect"
+ "amadan.net/rastrillo/rastrillo/sessions"
+
+ "amadan.net/carlos/base/internal/equipo"
+ "amadan.net/carlos/base/internal/store"
+)
+
+// Ask set up with Oficina ID, for the native app: the app fetches an
+// assertion addressed to Equipo and posts it here, and Base completes
+// Equipo's own native sign-in for the member (equipo.NativeExchange, then
+// RegisterNative). The key it gets is the same kind the code flow gets and
+// is kept the same way, so the relay cannot tell the two apart. It ends with
+// the Equipo session it was registered with, seven days on (or when the
+// person signs out of Equipo, is relinked or leaves the roster), so Base
+// keeps that session's cookie sealed beside the key, never signs it out,
+// and tells the app when to send a fresh assertion (renewAfter).
+
+// askOficinaPath is where the native app posts the assertion.
+const askOficinaPath = "/api/v1/ask/oficina"
+
+// viaOficina marks a key set up with Oficina ID (deviceSecrets.Via).
+const viaOficina = "oficina"
+
+// renewBefore is how long before the Equipo session ends the app should
+// renew: five days after a seven-day session was minted.
+const renewBefore = 2 * 24 * time.Hour
+
+// askOficinaTimeout bounds the whole set-up, which carries on if the app
+// goes away: Equipo may already have made the device.
+const askOficinaTimeout = 45 * time.Second
+
+// askNotLinked is the answer for a person Equipo has not linked to their
+// Oficina ID. It is this route's alone: /ask/state never says it.
+const askNotLinked = "not_linked"
+
+// askSuperseded is the answer for a set-up that something else overtook
+// while Equipo answered (Disconnect, or a connection from the web): it
+// saved nothing, and revoked the device it made.
+const askSuperseded = "superseded"
+
+// askDisconnected is the answer to an automatic set-up after the member
+// disconnected Ask (store.Member.AskDisconnected): nothing was done.
+const askDisconnected = "disconnected"
+
+// renewAfter is when the app should send a fresh assertion for link l,
+// zero for a key from the code flow.
+func renewAfter(l store.EquipoLink, sec deviceSecrets) time.Time {
+ if sec.Via != viaOficina {
+ return time.Time{}
+ }
+ return l.ExpiresAt.Add(-renewBefore).UTC()
+}
+
+// askOficinaLock is the member's lock for setting Ask up with Oficina ID:
+// two posts for the same person run one at a time. It is not lockMember,
+// which is never held across a call to Equipo: the set-up takes that only
+// to compare its connection's generation and save (saveOficinaLink).
+func (a *app) askOficinaLock(id string) func() {
+ mu, _ := a.ask.oficina.LoadOrStore(id, &sync.Mutex{})
+ mu.(*sync.Mutex).Lock()
+ return mu.(*sync.Mutex).Unlock
+}
+
+// askOficina is POST /api/v1/ask/oficina, {assertion, verifier}, from a
+// native session only (docs/api/base-native-v1.md).
+func (a *app) askOficina(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ if s, ok := sessions.Current(r); !ok || s.Method != connect.NativeMethod {
+ writeJSON(w, http.StatusForbidden, map[string]string{"state": "forbidden"})
+ return
+ }
+ in, ok := readAskOficina(w, r)
+ if !ok {
+ writeJSON(w, http.StatusBadRequest, map[string]string{"state": "invalid"})
+ return
+ }
+ defer a.askOficinaLock(me.ID)()
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), askOficinaTimeout)
+ defer cancel()
+
+ // The connection as the set-up begins, and whether the member has
+ // disconnected Ask, read together. Anything that changes it while
+ // Equipo answers (Disconnect, the web's Connect or its approval) wins:
+ // the set-up then saves nothing.
+ gen, disconnected, err := a.linkGenDisconnected(ctx, me.ID)
+ if err != nil {
+ a.logger.Error("ask oficina: disconnected", "err", err)
+ writeJSON(w, http.StatusServiceUnavailable, map[string]string{"state": askUnavailable})
+ return
+ }
+ if in.Auto && disconnected {
+ writeJSON(w, http.StatusConflict, map[string]string{"state": askDisconnected})
+ return
+ }
+ sess, err := a.ask.client.NativeExchange(ctx, in.Assertion, in.Verifier)
+ if err != nil {
+ a.askOficinaRefused(w, "exchange", err)
+ return
+ }
+ pub, key, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ a.fail(w, err)
+ return
+ }
+ cred, err := a.ask.client.RegisterNative(ctx, sess, pub, a.ask.label)
+ if err != nil {
+ a.askOficinaRefused(w, "device", err)
+ return
+ }
+ exp := cred.ExpiresAt
+ if exp.IsZero() || exp.After(sess.ExpiresAt) {
+ exp = sess.ExpiresAt
+ }
+ sealed, err := a.sealSecrets(me.ID, deviceSecrets{Seed: key.Seed(), Token: cred.Token, Via: viaOficina,
+ SessionName: sess.Name, SessionValue: sess.Value})
+ l := store.EquipoLink{MemberID: me.ID, Origin: a.ask.client.Origin(), State: store.EquipoConnected,
+ DeviceID: cred.ID, Sealed: sealed, ExpiresAt: exp, Revision: cred.Revision}
+ var superseded bool
+ var old store.EquipoLink
+ var oldSec deviceSecrets
+ if err == nil {
+ superseded, old, oldSec, err = a.saveOficinaLink(ctx, me, gen, l, !in.Auto)
+ }
+ if err != nil || superseded {
+ // Nothing was saved: the device made for it goes.
+ a.revoke(ctx, l, deviceSecrets{Token: cred.Token})
+ switch {
+ case superseded:
+ writeJSON(w, http.StatusConflict, map[string]string{"state": askSuperseded})
+ return
+ case errors.Is(err, store.ErrAskDisconnected):
+ writeJSON(w, http.StatusConflict, map[string]string{"state": askDisconnected})
+ return
+ }
+ a.logger.Error("ask oficina: store", "device", cred.ID, "err", err)
+ writeJSON(w, http.StatusServiceUnavailable, map[string]string{"state": askUnavailable})
+ return
+ }
+ // The key it replaced is over, ready or not: revoke it in Equipo, as
+ // Connect does. A key Equipo already refused refuses this too.
+ a.revokeDisplaced(ctx, old, oldSec, cred.ID)
+ a.hostFor(ctx, me, cred.ID, cred.Token, true)
+ writeJSON(w, http.StatusOK, map[string]string{"state": askReady, "renew_after": renewAfter(l, deviceSecrets{Via: viaOficina}).Format(time.RFC3339)})
+}
+
+// saveOficinaLink stores l as the member's link, unless their connection
+// has changed since generation gen (superseded, and nothing is stored). It
+// answers the link it replaced, read under the member's lock as it saves.
+// Saving forgets the old host token with it. An explicit save clears the
+// member's Disconnect; an automatic one is refused while it stands
+// (store.ErrAskDisconnected), checked again in the save's own transaction.
+func (a *app) saveOficinaLink(ctx context.Context, me store.Member, gen uint64, l store.EquipoLink, explicit bool) (superseded bool, old store.EquipoLink, oldSec deviceSecrets, err error) {
+ c := a.memberConn(me.ID)
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.gen != gen {
+ return true, old, oldSec, nil
+ }
+ if old, oldSec, _, err = a.askLink(ctx, me); err != nil {
+ return false, store.EquipoLink{}, deviceSecrets{}, err
+ }
+ if err = store.SaveConnectedEquipoLink(ctx, a.db, l, explicit); err != nil {
+ return false, store.EquipoLink{}, deviceSecrets{}, err
+ }
+ c.gen++
+ return false, old, oldSec, nil
+}
+
+// askOficinaRefused answers for a step of Equipo's sign-in that failed,
+// having stored nothing. The app never hears a 401 here: that would read
+// as Base's own session ending.
+func (a *app) askOficinaRefused(w http.ResponseWriter, step string, err error) {
+ var e *equipo.Error
+ switch {
+ case step == "exchange" && errors.Is(err, equipo.ErrNotLinked):
+ writeJSON(w, http.StatusConflict, map[string]string{"state": askNotLinked})
+ case step == "exchange" && errors.Is(err, equipo.ErrAssertionFailed):
+ writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"state": "failed"})
+ case step == "exchange" && errors.Is(err, equipo.ErrAssertionInvalid):
+ writeJSON(w, http.StatusBadRequest, map[string]string{"state": "invalid"})
+ default:
+ if errors.As(err, &e) {
+ a.logger.Warn("ask oficina: equipo refused", "step", step, "status", e.Status, "code", e.Code)
+ } else {
+ a.logger.Warn("ask oficina: equipo", "step", step, "err", err)
+ }
+ writeJSON(w, http.StatusBadGateway, map[string]string{"state": askUnavailable})
+ }
+}
+
+// askOficinaIn is POST /api/v1/ask/oficina's body.
+type askOficinaIn struct {
+ Assertion, Verifier string
+ // Auto is a set-up the app starts by itself (after sign-in, or to
+ // renew), which yields to the member's Disconnect; without it the
+ // person asked, and it connects Ask again.
+ Auto bool
+}
+
+// readAskOficina reads the body strictly: one JSON object with exactly the
+// names assertion, verifier and, optionally, auto, each once and spelt so;
+// auto only true or false (never null, which a client might send for "not
+// set", and which must not read as the person asking).
+func readAskOficina(w http.ResponseWriter, r *http.Request) (askOficinaIn, bool) {
+ if !isJSONBody(r) {
+ return askOficinaIn{}, false
+ }
+ raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 16<<10))
+ if err != nil {
+ return askOficinaIn{}, false
+ }
+ var in struct {
+ Assertion string `json:"assertion"`
+ Verifier string `json:"verifier"`
+ Auto jsontext.Value `json:"auto"`
+ }
+ if jsonv2.Unmarshal(raw, &in, jsonv2.RejectUnknownMembers(true)) != nil ||
+ in.Assertion == "" || len(in.Assertion) > 8192 || in.Verifier == "" || len(in.Verifier) > 256 {
+ return askOficinaIn{}, false
+ }
+ out := askOficinaIn{Assertion: in.Assertion, Verifier: in.Verifier}
+ switch string(in.Auto) {
+ case "":
+ case "true":
+ out.Auto = true
+ case "false":
+ default:
+ return askOficinaIn{}, false
+ }
+ return out, true
+}
diff --git a/internal/web/ask_relay.go b/internal/web/ask_relay.go
index b6dab9e..92a5603 100644
--- a/internal/web/ask_relay.go
+++ b/internal/web/ask_relay.go
@@ -61,7 +61,8 @@ type askConn struct {
}
// askDone finishes a relayed write. A 401 from Equipo means the member must
-// reconnect; a 409 no_runner or runner_too_old means the person has no
+// reconnect: Base answers 409 reconnect, never 401, which is only ever
+// Base's own session ending (the native app signs in again on one); a 409 no_runner or runner_too_old means the person has no
// runner that can answer (norunner, oldrunner), and what they wrote stays
// unsent; any other 409 (a card already answered, a turn already ended) is
// stale, and the conversation as it is now says so; anything else is a
@@ -72,7 +73,7 @@ func (a *app) askDone(w http.ResponseWriter, r *http.Request, c askConn, err err
switch {
case errors.Is(err, equipo.ErrUnauthenticated):
a.askLost(r.Context(), c.me, c.device)
- status, state = http.StatusUnauthorized, askReconnect
+ status, state = http.StatusConflict, askReconnect
case errors.Is(err, equipo.ErrNoRunner):
status, state = http.StatusConflict, askNoRunner
case errors.Is(err, equipo.ErrRunnerTooOld):
diff --git a/internal/web/home.go b/internal/web/home.go
index bb793d4..f3b7e5d 100644
--- a/internal/web/home.go
+++ b/internal/web/home.go
@@ -1,6 +1,8 @@
package web
import (
+ "context"
+ "fmt"
"html/template"
"net/http"
"strings"
@@ -19,13 +21,17 @@ type step struct {
// pages. Its icon is an image (Image, a path in the static tree for
// {{asset}}: an Oficina app's) or line art on a tint (Icon and Tint).
type tile struct {
- Name string
- Href string
- Tint string
- Icon template.HTML
- Image string
- NewTab bool // an Oficina app, which opens in a new tab
- Own bool // one of Base's own pages, which start a row of their own
+ // ID names the app: an Oficina app's id, a catalogue app's, or the
+ // page's ("store", "people", "settings"). Kind is "oficina",
+ // "installed" or "own".
+ ID, Kind string
+ Name string
+ Href string
+ Tint string
+ Icon template.HTML
+ Image string
+ NewTab bool // an Oficina app, which opens in a new tab
+ Own bool // one of Base's own pages, which start a row of their own
}
type homePage struct {
@@ -98,29 +104,33 @@ func greeting(t time.Time, loc *time.Location, name string) string {
// chat's conversation before it draws the chat without it.
const homeSnapshotWait = 1500 * time.Millisecond
-func (a *app) home(w http.ResponseWriter, r *http.Request) {
- me, _ := CurrentMember(r)
- ms, err := store.Members(r.Context(), a.db)
+// homeContent is what Home shows a member, apart from the chat: the
+// greeting, the steps and every app in Home's order. Home and GET
+// /api/v1/home both draw from it, so they cannot disagree.
+type homeContent struct {
+ Greeting, Initials, Lede string
+ Steps []step
+ Apps, Dock []tile
+}
+
+func (a *app) homeContent(ctx context.Context, me store.Member) (homeContent, error) {
+ ms, err := store.Members(ctx, a.db)
if err != nil {
- a.logger.Error("home: members", "err", err)
- http.Error(w, "unavailable", http.StatusServiceUnavailable)
- return
+ return homeContent{}, fmt.Errorf("members: %w", err)
}
- installs, err := store.Installs(r.Context(), a.db)
+ installs, err := store.Installs(ctx, a.db)
if err != nil {
- a.logger.Error("home: installs", "err", err)
- http.Error(w, "unavailable", http.StatusServiceUnavailable)
- return
+ return homeContent{}, fmt.Errorf("installs: %w", err)
}
name := displayName(me)
- page := homePage{Name: a.cfg.Name, Greeting: greeting(time.Now(), a.cfg.Timezone, name), Initials: initials(name)}
- page.Dock = []tile{
- {Name: "Store", Href: "/store", Tint: "teal", Icon: iconStore, Own: true},
- {Name: "People", Href: "/people", Tint: "violet", Icon: iconPeople, Own: true},
- {Name: "Settings", Href: "/settings", Tint: "mist", Icon: iconSettings, Own: true},
+ c := homeContent{Greeting: greeting(time.Now(), a.cfg.Timezone, name), Initials: initials(name)}
+ c.Dock = []tile{
+ {ID: "store", Kind: "own", Name: "Store", Href: "/store", Tint: "teal", Icon: iconStore, Own: true},
+ {ID: "people", Kind: "own", Name: "People", Href: "/people", Tint: "violet", Icon: iconPeople, Own: true},
+ {ID: "settings", Kind: "own", Name: "Settings", Href: "/settings", Tint: "mist", Icon: iconSettings, Own: true},
}
for _, o := range a.cfg.OficinaApps {
- page.Apps = append(page.Apps, tile{Name: o.Name, Href: o.Origin + "/", Image: "static/oficina/" + o.ID + ".svg", NewTab: true})
+ c.Apps = append(c.Apps, tile{ID: o.ID, Kind: "oficina", Name: o.Name, Href: o.Origin + "/", Image: "static/oficina/" + o.ID + ".svg", NewTab: true})
}
installedOwn := false
for _, in := range installs {
@@ -129,30 +139,42 @@ func (a *app) home(w http.ResponseWriter, r *http.Request) {
continue
}
// The host the app was installed at: config may name another now.
- page.Apps = append(page.Apps, tile{Name: e.Name, Href: "https://" + in.Host + "/", Tint: e.Tint, Icon: template.HTML(e.Icon)})
+ c.Apps = append(c.Apps, tile{ID: in.App, Kind: "installed", Name: e.Name, Href: "https://" + in.Host + "/", Tint: e.Tint, Icon: template.HTML(e.Icon)})
if !e.Default {
installedOwn = true
}
}
- page.Steps = []step{
+ c.Steps = []step{
{"Signed in", true},
{"Invite your team", len(ms) > 1},
{"Install your first app", installedOwn},
}
left := 0
- for _, s := range page.Steps {
+ for _, s := range c.Steps {
if !s.Done {
left++
}
}
switch left {
case 0:
- page.Lede = a.cfg.Name + "'s Base is ready."
+ c.Lede = a.cfg.Name + "'s Base is ready."
case 1:
- page.Lede = "One step until " + a.cfg.Name + "'s Base is ready."
+ c.Lede = "One step until " + a.cfg.Name + "'s Base is ready."
default:
- page.Lede = "Two steps until " + a.cfg.Name + "'s Base is ready."
+ c.Lede = "Two steps until " + a.cfg.Name + "'s Base is ready."
+ }
+ return c, nil
+}
+
+func (a *app) home(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ c, err := a.homeContent(r.Context(), me)
+ if err != nil {
+ a.logger.Error("home", "err", err)
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ return
}
+ page := homePage{Name: a.cfg.Name, Greeting: c.Greeting, Initials: c.Initials, Lede: c.Lede, Steps: c.Steps, Apps: c.Apps, Dock: c.Dock}
if a.ask != nil {
l, sec, state, err := a.askLink(r.Context(), me)
if err != nil {
diff --git a/internal/web/oficina.go b/internal/web/oficina.go
index efdee32..7ee6b77 100644
--- a/internal/web/oficina.go
+++ b/internal/web/oficina.go
@@ -6,6 +6,7 @@ import (
"errors"
"net/http"
"net/url"
+ "time"
"amadan.net/oficina/home/connect"
"amadan.net/oficina/home/connect/linkstore"
@@ -30,6 +31,7 @@ type oficina struct {
bridge *connect.Bridge
routes *connect.Routes
db *sql.DB
+ issuer string
}
func (a *app) newOficina(home *connect.DecodedCredentials) (*oficina, error) {
@@ -72,6 +74,13 @@ func (a *app) newOficina(home *connect.DecodedCredentials) (*oficina, error) {
Render: a.oficinaPage,
MintHomeSession: func(w http.ResponseWriter, r *http.Request, s connect.Session) error {
return sess.SignIn(w, r, sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime})
+ },
+ // The native app's session (connect.NativeExchange, method
+ // NativeMethod): the same store and cookie name, minted without a
+ // cookie and handed back in the answer. The store records when it
+ // was made (At), which is what ends it after seven days.
+ MintNativeSession: func(_ context.Context, s connect.Session) (string, error) {
+ return sess.Mint(sessions.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime})
}}
b, err := connect.New(cfg)
if err != nil {
@@ -83,7 +92,7 @@ func (a *app) newOficina(home *connect.DecodedCredentials) (*oficina, error) {
if err != nil {
return nil, err
}
- return &oficina{bridge: b, routes: routes, db: a.db}, nil
+ return &oficina{bridge: b, routes: routes, db: a.db, issuer: home.Issuer}, nil
}
// formPolicy is the Content-Security-Policy rastrillo gives every Base
@@ -93,7 +102,8 @@ func (a *app) newOficina(home *connect.DecodedCredentials) (*oficina, error) {
// TestFormPolicyIsRastrillosWithTheIssuer keeps the two in step.
func formPolicy(issuer string) string {
return "default-src 'self'; " +
- "style-src 'self' 'unsafe-hashes' 'sha256-yJxAE4rjdcckohdlnvecSporPcqS9xOaA4hJxi87LMc='; " +
+ "style-src 'self' 'unsafe-hashes' 'sha256-yJxAE4rjdcckohdlnvecSporPcqS9xOaA4hJxi87LMc=' " +
+ "'sha256-81gZUb3tp60YCqhJ0dItBPh5hRQiGbfst4gpwCNPTfI='; " +
"img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action 'self' " + issuer
}
@@ -113,15 +123,87 @@ func (o *oficina) member(r *http.Request) (store.Member, bool, error) {
return m, true, nil
}
-// linked reports whether member m has an Oficina account connected. An
-// error counts as linked, so Settings offers nothing it cannot be sure of.
+// linked reports whether member m has an Oficina account connected: a
+// link connect resolves. A dead link (deadLink) is no connection. An error
+// counts as linked, so Settings offers nothing it cannot be sure of.
func (o *oficina) linked(ctx context.Context, m store.Member) bool {
n, err := store.MemberNumber(ctx, o.db, m.ID)
if err != nil {
return true
}
linked, err := o.bridge.Linked(ctx, n)
- return err != nil || linked
+ if err != nil || !linked {
+ return err != nil
+ }
+ _, dead, err := o.deadLink(ctx, o.db, n)
+ return err != nil || !dead
+}
+
+// deadLink reports whether member number n has a link connect no longer
+// resolves, and its subject. connect binds each link to Base's origin (and
+// the member's address), so every link made before BASE_ORIGIN changed is
+// one: it signs nobody in, yet it would stop the member linking again.
+// Asked only for a member who exists, so a refusal is the binding's.
+func (o *oficina) deadLink(ctx context.Context, q store.QueryRower, n int64) (subject string, dead bool, err error) {
+ subject, ok, err := store.OficinaLinkSubject(ctx, q, o.issuer, n)
+ if err != nil || !ok {
+ return "", false, err
+ }
+ switch _, err := o.bridge.ResolveOn(ctx, q, subject); {
+ case err == nil:
+ return subject, false, nil
+ case errors.Is(err, linkstore.ErrRefused):
+ return subject, true, nil
+ default:
+ return "", false, err
+ }
+}
+
+// dropDeadLink removes member m's dead link, if they have one, so that the
+// link they are confirming can take its place. connect's confirm refuses
+// while any link names the member or the subject, and offers no way to
+// replace one; connect asks the app to remove links itself (as
+// RemoveMember does). A link connect still resolves is never touched, nor
+// anyone else's.
+func (o *oficina) dropDeadLink(ctx context.Context, m store.Member) error {
+ tx, err := o.db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ n, err := store.MemberNumber(ctx, tx, m.ID)
+ if err != nil {
+ return err
+ }
+ subject, dead, err := o.deadLink(ctx, tx, n)
+ if err != nil || !dead {
+ return err
+ }
+ if err := store.DeleteOficinaLink(ctx, tx, o.issuer, subject, n); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+// oficinaConfirm is POST /account/home/confirm: connect's confirm, after
+// the member's dead link, if any, has made way. Only the member's own fresh
+// sign-in by email (connect.FreshLocal, what linking itself demands) clears
+// it; connect's confirm then checks that sign-in and the fresh Oficina
+// proof as always.
+func (a *app) oficinaConfirm(w http.ResponseWriter, r *http.Request) {
+ s, ok := sessions.Current(r)
+ if _, fresh := connect.FreshLocal(connect.Session{Subject: s.Subject, Method: s.Method, AuthTime: s.AuthTime, At: s.At}, time.Now()); ok && fresh {
+ m, found, err := store.MemberByEmail(r.Context(), a.db, s.Subject)
+ if err == nil && found {
+ err = a.oficina.dropDeadLink(r.Context(), m)
+ }
+ if err != nil {
+ a.logger.Error("oficina: dead link", "err", err)
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ return
+ }
+ }
+ a.oficina.routes.ConfirmPost(w, r)
}
// oficinaSignin is GET /signin with Oficina ID on. Someone signed in as a
diff --git a/internal/web/settings.go b/internal/web/settings.go
index 46771f7..045c1f7 100644
--- a/internal/web/settings.go
+++ b/internal/web/settings.go
@@ -50,7 +50,7 @@ var appearances = []struct{ value, label, stored string }{
func (a *app) settings(w http.ResponseWriter, r *http.Request) {
me, _ := CurrentMember(r)
s, _ := sessions.Current(r)
- viaOficina := s.Method == connect.HomeMethod
+ viaOficina := connect.IsHomeDerived(s.Method)
// Passkeys are filed under the address a member signs in with, which an
// Oficina session's subject is not.
subject := s.Subject
diff --git a/internal/webtest/api_test.go b/internal/webtest/api_test.go
new file mode 100644
index 0000000..2bd9ea9
--- /dev/null
+++ b/internal/webtest/api_test.go
@@ -0,0 +1,190 @@
+package webtest
+
+import (
+ "encoding/json"
+ "net/http"
+ "reflect"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/carlos/base/internal/config"
+ "amadan.net/carlos/base/internal/store"
+)
+
+// GET /api/v1/me and GET /api/v1/home: Base's reads for its native app
+// (docs/api/base-native-v1.md), with the session the native exchange mints.
+
+func decode[T any](t *testing.T, r Resp) T {
+ t.Helper()
+ var v T
+ if err := json.Unmarshal([]byte(r.Body), &v); err != nil {
+ t.Fatalf("%d %q: %v", r.Code, r.Body, err)
+ }
+ return v
+}
+
+func TestAPIMe(t *testing.T) {
+ dublin, _ := time.LoadLocation("Europe/Dublin")
+ a := newHomeAppWith(t, func(c *config.Config) { c.Timezone = dublin })
+ a.link(ownerAddress, "subject-owner")
+ app := a.nativeSignIn("subject-owner")
+ r := app.nativeGet("/api/v1/me")
+ if r.Code != 200 || r.Header.Get("Cache-Control") != "no-store" || r.Header.Get("Content-Type") != "application/json" {
+ t.Fatalf("me: %d %q %q", r.Code, r.Header.Get("Cache-Control"), r.Header.Get("Content-Type"))
+ }
+ got := decode[map[string]any](t, r)
+ want := map[string]any{
+ "member": map[string]any{"id": a.ownerID(), "name": "Owner", "email": ownerAddress, "initials": "O", "owner": true},
+ "base": map[string]any{"name": "Acme", "slug": "acme", "origin": homeOrigin, "timezone": "Europe/Dublin"},
+ "appearance": "system",
+ "equipo_origin": nil,
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("me:\n got %v\nwant %v", got, want)
+ }
+
+ // The member's Appearance, a member who is not the owner, and Ask on.
+ b := newHomeAppWith(t, func(c *config.Config) { c.EquipoOrigin = "https://equipo.acme.test" })
+ ana, _, err := store.Invite(t.Context(), b.DB, "ana.ruiz@acme.test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := store.SetTheme(t.Context(), b.DB, ana.ID, "dark"); err != nil {
+ t.Fatal(err)
+ }
+ b.link("ana.ruiz@acme.test", "subject-ana")
+ me := decode[apiMeShape](t, b.nativeSignIn("subject-ana").nativeGet("/api/v1/me"))
+ if me.Member.Owner || me.Member.Email != "ana.ruiz@acme.test" || me.Member.Name != "Ana.ruiz" || me.Appearance != "dark" ||
+ me.EquipoOrigin == nil || *me.EquipoOrigin != "https://equipo.acme.test" || me.Base.Timezone != "UTC" {
+ t.Fatalf("ana: %+v", me)
+ }
+}
+
+type apiMeShape struct {
+ Member struct {
+ ID, Name, Email, Initials string
+ Owner bool
+ }
+ Base struct{ Name, Slug, Origin, Timezone string }
+ Appearance string
+ EquipoOrigin *string `json:"equipo_origin"`
+}
+
+type apiAppShape struct {
+ ID string `json:"id"`
+ Kind string `json:"kind"`
+ Name string `json:"name"`
+ URL string `json:"url"`
+ IconURL string `json:"icon_url"`
+ Tint string `json:"tint"`
+ IconSVG string `json:"icon_svg"`
+ BundleID string `json:"bundle_id"`
+ Scheme string `json:"scheme"`
+}
+
+type apiHomeShape struct {
+ Greeting string `json:"greeting"`
+ Lede string `json:"lede"`
+ Steps []struct {
+ Label string `json:"label"`
+ Done bool `json:"done"`
+ } `json:"steps"`
+ Apps []apiAppShape `json:"apps"`
+}
+
+func TestAPIHome(t *testing.T) {
+ a := newHomeAppWith(t, func(c *config.Config) {
+ c.OficinaApps = []config.OficinaApp{
+ {ID: "docs", Name: "Docs", Origin: "https://docs.oficina.works"},
+ {ID: "calls", Name: "Calls", Origin: "https://calls.oficina.works"},
+ }
+ })
+ a.link(ownerAddress, "subject-owner")
+ a.setInstall("scratchpad", "installed", "")
+ app := a.nativeSignIn("subject-owner")
+ r := app.nativeGet("/api/v1/home")
+ if r.Code != 200 || r.Header.Get("Cache-Control") != "no-store" {
+ t.Fatalf("home: %d %q", r.Code, r.Header.Get("Cache-Control"))
+ }
+ var raw map[string]json.RawMessage
+ if err := json.Unmarshal([]byte(r.Body), &raw); err != nil || len(raw) != 4 {
+ t.Fatalf("home's keys: %v %s", err, r.Body)
+ }
+ h := decode[apiHomeShape](t, r)
+ if !regexp.MustCompile(`^(Hello|Good (morning|afternoon|evening)), Owner\.$`).MatchString(h.Greeting) {
+ t.Errorf("greeting %q", h.Greeting)
+ }
+ if h.Lede != "One step until Acme's Base is ready." {
+ t.Errorf("lede %q", h.Lede)
+ }
+ steps := []string{}
+ for _, s := range h.Steps {
+ steps = append(steps, s.Label+"="+map[bool]string{true: "done", false: "open"}[s.Done])
+ }
+ if got := strings.Join(steps, ", "); got != "Signed in=done, Invite your team=open, Install your first app=done" {
+ t.Errorf("steps: %s", got)
+ }
+ var order []string
+ for _, x := range h.Apps {
+ order = append(order, x.Kind+":"+x.ID)
+ }
+ if got := strings.Join(order, " "); got != "oficina:docs oficina:calls installed:scratchpad own:store own:people own:settings" {
+ t.Fatalf("apps in order: %s", got)
+ }
+ icon := regexp.MustCompile(`^/static/oficina/docs\.[0-9a-f]+\.svg$`)
+ docs, calls, scratch, store := h.Apps[0], h.Apps[1], h.Apps[2], h.Apps[3]
+ if docs.Name != "Docs" || docs.URL != "https://docs.oficina.works/" || !icon.MatchString(docs.IconURL) || docs.BundleID != "works.oficina.docs" ||
+ docs.Scheme != "" || docs.Tint != "" || docs.IconSVG != "" {
+ t.Errorf("docs: %+v", docs)
+ }
+ if calls.BundleID != "works.oficina.calls" || calls.Scheme != "oficina-calls" {
+ t.Errorf("calls: %+v", calls)
+ }
+ if scratch.Name != "Scratchpad" || scratch.URL != "https://acme-scratchpad.bab.oncarlos.com/" || scratch.Tint != "rose" ||
+ !strings.HasPrefix(scratch.IconSVG, "<svg") || scratch.IconURL != "" || scratch.BundleID != "" {
+ t.Errorf("scratchpad: %+v", scratch)
+ }
+ if store.Name != "Store" || store.URL != homeOrigin+"/store" || store.Tint != "teal" || !strings.HasPrefix(store.IconSVG, "<svg") {
+ t.Errorf("store: %+v", store)
+ }
+ // The icon is served where it says.
+ if r := app.get(docs.IconURL); r.Code != 200 || !strings.Contains(r.Body, "<svg") {
+ t.Errorf("GET %s: %d", docs.IconURL, r.Code)
+ }
+}
+
+// The native app and scripts hear a refusal as JSON, never as a redirect.
+func TestAPIRefusesWithoutSession(t *testing.T) {
+ a := newHomeAppWith(t, func(c *config.Config) { c.EquipoOrigin = "https://equipo.acme.test" })
+ a.link(ownerAddress, "subject-owner")
+ refused := func(where string, r Resp) {
+ t.Helper()
+ if r.Code != http.StatusUnauthorized || strings.TrimSpace(r.Body) != `{"code":"unauthenticated"}` ||
+ r.Header.Get("Cache-Control") != "no-store" || r.Location() != "" {
+ t.Errorf("%s: %d %q %q %q", where, r.Code, r.Body, r.Header.Get("Cache-Control"), r.Location())
+ }
+ }
+ none := a.newBrowser()
+ refused("no session, /api/v1/me", none.get("/api/v1/me"))
+ refused("no session, /api/v1/home", none.nativeGet("/api/v1/home"))
+ refused("no session, /ask/state as JSON", none.nativeGet("/ask/state"))
+ refused("no session, POST /ask/messages as JSON", none.nativePost("/ask/messages", ""))
+ // A session that names nobody: unlinked, or a native one past seven days.
+ refused("unlinked", a.storedSession("subject-stranger", "home-assertion-native", time.Now()).nativeGet("/api/v1/me"))
+ refused("expired", a.storedSession("subject-owner", "home-assertion-native", time.Now().Add(-8*24*time.Hour)).nativeGet("/api/v1/me"))
+ // A signed-out page still goes to /signin.
+ if r := none.get("/"); r.Code != http.StatusSeeOther || !strings.HasPrefix(r.Location(), "/signin") {
+ t.Errorf("signed-out page: %d %q", r.Code, r.Location())
+ }
+ // Without Oficina ID, the same.
+ b := newApp(t)
+ if r := b.get("/api/v1/me"); r.Code != http.StatusUnauthorized || strings.TrimSpace(r.Body) != `{"code":"unauthenticated"}` {
+ t.Errorf("Oficina off, /api/v1/me: %d %q", r.Code, r.Body)
+ }
+ b.signedInOwner()
+ if r := b.get("/api/v1/me"); r.Code != 200 {
+ t.Errorf("Oficina off, signed in: %d", r.Code)
+ }
+}
diff --git a/internal/webtest/ask_disconnect_test.go b/internal/webtest/ask_disconnect_test.go
new file mode 100644
index 0000000..0f26f1f
--- /dev/null
+++ b/internal/webtest/ask_disconnect_test.go
@@ -0,0 +1,304 @@
+package webtest
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "testing"
+
+ "amadan.net/carlos/base/internal/equipo/equipotest"
+ "amadan.net/carlos/base/internal/store"
+)
+
+// Disconnect is the member's, not a device's: once they disconnect Ask
+// anywhere, no app connects it again by itself. Only an explicit connect
+// (the web's Connect, or the app's set-up when the person asks) does.
+
+// connectAuto posts what the app posts when it sets Ask up by itself.
+func (a *testApp) connectAuto(f *equipotest.Fake, subject string) Resp {
+ a.t.Helper()
+ assertion, verifier := f.OficinaAssertion(subject)
+ body, _ := json.Marshal(map[string]any{"assertion": assertion, "verifier": verifier, "auto": true})
+ return a.nativePost("/api/v1/ask/oficina", string(body))
+}
+
+// askDisconnected is /ask/state's "disconnected".
+func (a *testApp) askDisconnected() bool {
+ a.t.Helper()
+ _, r := a.askState()
+ var s struct {
+ Disconnected *bool `json:"disconnected"`
+ }
+ if err := json.Unmarshal([]byte(r.Body), &s); err != nil || s.Disconnected == nil {
+ a.t.Fatalf("no disconnected in /ask/state: %s", r.Body)
+ }
+ return *s.Disconnected
+}
+
+// storedDisconnected is the flag as stored, read afresh: what a restarted
+// Base reads.
+func (a *testApp) storedDisconnected(email string) bool {
+ a.t.Helper()
+ m, ok, err := store.MemberByEmail(context.Background(), a.DB, email)
+ if err != nil || !ok {
+ a.t.Fatalf("member %s: %v", email, err)
+ }
+ return m.AskDisconnected
+}
+
+func TestDisconnectOnTheWebStopsAutomaticSetUp(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ if r := app.connectAuto(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("automatic set-up: %d %s", r.Code, r.Body)
+ }
+ if app.askDisconnected() {
+ t.Fatal("disconnected before any Disconnect")
+ }
+ if r := web.post("/ask/disconnect", nil); r.Code != 303 {
+ t.Fatalf("disconnect: %d", r.Code)
+ }
+ if !app.askDisconnected() || !app.storedDisconnected(ownerAddress) {
+ t.Fatal("Disconnect did not stick")
+ }
+ exchanges := len(f.Calls("/native/oficina-id"))
+ wantBody(t, "automatic set-up after Disconnect", app.connectAuto(f, "subject-owner"), 409, `{"state":"disconnected"}`)
+ if len(f.Calls("/native/oficina-id")) != exchanges || app.equipoLinks() != 0 {
+ t.Fatalf("an automatic set-up after Disconnect reached Equipo or stored a link")
+ }
+ if s, _ := app.askState(); s.State != "connect" {
+ t.Errorf("state: %s", s.State)
+ }
+ // The person asks for it: the explicit set-up connects and clears it.
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("explicit set-up: %d %s", r.Code, r.Body)
+ }
+ if app.askDisconnected() || app.storedDisconnected(ownerAddress) {
+ t.Fatal("an explicit connect left the flag set")
+ }
+ if r := app.connectAuto(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("automatic renewal after reconnecting: %d %s", r.Code, r.Body)
+ }
+}
+
+// "auto": false is explicit.
+func TestExplicitSetUpSaysSo(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ app.connectWithOficina(f, "subject-owner")
+ app.post("/ask/disconnect", nil)
+ assertion, verifier := f.OficinaAssertion("subject-owner")
+ body, _ := json.Marshal(map[string]any{"assertion": assertion, "verifier": verifier, "auto": false})
+ if r := app.nativePost("/api/v1/ask/oficina", string(body)); r.Code != 200 {
+ t.Fatalf("auto false: %d %s", r.Code, r.Body)
+ }
+ // Only absent, true or false: anything else is refused, whatever it
+ // might have meant, so no client undoes a Disconnect by accident.
+ app.post("/ask/disconnect", nil)
+ for _, auto := range []string{`"auto":null`, `"auto":"true"`, `"auto":1`, `"auto":{}`, `"auto":true,"auto":false`, `"auto":false,"auto":true`, `"AUTO":true`, `"Auto":false`} {
+ a, v := f.OficinaAssertion("subject-owner")
+ body := `{"assertion":"` + a + `","verifier":"` + v + `",` + auto + `}`
+ wantBody(t, auto, app.nativePost("/api/v1/ask/oficina", body), 400, `{"state":"invalid"}`)
+ }
+ if !app.storedDisconnected(ownerAddress) || app.equipoLinks() != 0 {
+ t.Fatal("a refused body connected Ask")
+ }
+}
+
+// The web's Connect clears the flag once the connection is made (its code
+// approved), not when the code is shown; an explicit set-up that fails
+// leaves the flag as it was.
+func TestWebConnectClearsDisconnected(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ web.approveEquipo(f)
+ web.post("/ask/disconnect", nil)
+ f.FailNextNativeExchange(503)
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 502 {
+ t.Fatalf("explicit set-up with Equipo down: %d %s", r.Code, r.Body)
+ }
+ if !app.askDisconnected() {
+ t.Fatal("a failed explicit set-up cleared the flag")
+ }
+ code := web.startWebConnect()
+ if !app.askDisconnected() || !app.storedDisconnected(ownerAddress) {
+ t.Fatal("pressing Connect cleared the flag before anything was connected")
+ }
+ if r := web.approveAndCheck(f, code); r.Code != 303 || r.Location() != "/settings" {
+ t.Fatalf("approval: %d %q", r.Code, r.Location())
+ }
+ if app.askDisconnected() || app.storedDisconnected(ownerAddress) {
+ t.Fatal("the web's approved connection left the flag set")
+ }
+}
+
+// Fable's P4: a code that is never approved (it expires, or Equipo refuses
+// it) leaves the member disconnected, and the app does not connect them.
+func TestUnapprovedWebCodeLeavesDisconnected(t *testing.T) {
+ for _, end := range []string{"expired", "refused"} {
+ t.Run(end, func(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ web.approveEquipo(f)
+ web.post("/ask/disconnect", nil)
+ web.startWebConnect()
+ if end == "expired" {
+ f.Expire()
+ } else {
+ f.RevokeAll()
+ }
+ web.pollable()
+ web.check("settings")
+ if s, _ := app.askState(); s.State != "connect" || !app.askDisconnected() {
+ t.Fatalf("after the code %s: state %s, disconnected %v", end, s.State, app.askDisconnected())
+ }
+ wantBody(t, "automatic set-up", app.connectAuto(f, "subject-owner"), 409, `{"state":"disconnected"}`)
+ wantLive(t, f)
+ })
+ }
+}
+
+// Fable's P4b: while the code waits, the app's automatic set-up does not
+// overtake it.
+func TestAutomaticSetUpLeavesAWaitingCode(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ web.approveEquipo(f)
+ web.post("/ask/disconnect", nil)
+ code := web.startWebConnect()
+ wantBody(t, "automatic set-up while a code waits", app.connectAuto(f, "subject-owner"), 409, `{"state":"disconnected"}`)
+ if s, _ := app.askState(); s.State != "pending" {
+ t.Fatalf("the waiting code went: %s", s.State)
+ }
+ if r := web.approveAndCheck(f, code); r.Code != 303 || r.Location() != "/settings" {
+ t.Fatalf("approval: %d %q", r.Code, r.Location())
+ }
+ if app.askDisconnected() || len(f.LiveCredentials()) != 1 {
+ t.Fatalf("after approval: disconnected %v, live %v", app.askDisconnected(), f.LiveCredentials())
+ }
+}
+
+// An automatic set-up waiting at Equipo when Disconnect lands: overtaken,
+// nothing live, the flag stored, and the next automatic set-up refused.
+func TestAutomaticSetUpOvertakenByDisconnect(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ if r := app.connectAuto(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("connect: %d %s", r.Code, r.Body)
+ }
+ entered, release := f.HoldNextNativeExchange()
+ done := background(func() Resp { return app.connectAuto(f, "subject-owner") })
+ arrived(t, entered, "the automatic set-up")
+ if r := app.post("/ask/disconnect", nil); r.Code != 303 {
+ t.Fatalf("disconnect: %d", r.Code)
+ }
+ release()
+ wantBody(t, "overtaken automatic set-up", <-done, 409, `{"state":"superseded"}`)
+ if n := app.equipoLinks(); n != 0 || !app.storedDisconnected(ownerAddress) {
+ t.Fatalf("links %d, flag %v", n, app.storedDisconnected(ownerAddress))
+ }
+ wantLive(t, f)
+ wantBody(t, "next automatic set-up", app.connectAuto(f, "subject-owner"), 409, `{"state":"disconnected"}`)
+}
+
+// The web's approval landing after Disconnect stores nothing and leaves
+// the flag set.
+func TestLateWebApprovalAfterDisconnect(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ code := web.startWebConnect()
+ if err := f.Approve(code); err != nil {
+ t.Fatal(err)
+ }
+ web.pollable()
+ entered, release := f.HoldNextExchange()
+ checked := background(func() Resp { return web.check("settings") })
+ arrived(t, entered, "the web's exchange")
+ if r := app.post("/ask/disconnect", nil); r.Code != 303 {
+ t.Fatalf("disconnect: %d", r.Code)
+ }
+ release()
+ <-checked
+ if n := app.equipoLinks(); n != 0 || !app.storedDisconnected(ownerAddress) {
+ t.Fatalf("links %d, flag %v", n, app.storedDisconnected(ownerAddress))
+ }
+ wantLive(t, f)
+}
+
+func TestDisconnectedIsPerMember(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ if _, _, err := store.Invite(context.Background(), web.DB, "ana@acme.test"); err != nil {
+ t.Fatal(err)
+ }
+ web.newBrowser().link("ana@acme.test", "subject-ana")
+ ana := web.nativeSignIn("subject-ana")
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ f.LinkOficinaID("subject-ana", "ana@acme.test")
+ app.connectWithOficina(f, "subject-owner")
+ if r := app.post("/ask/disconnect", nil); r.Code != 303 {
+ t.Fatalf("disconnect from the app: %d", r.Code)
+ }
+ if ana.askDisconnected() || web.storedDisconnected("ana@acme.test") {
+ t.Fatal("the owner's Disconnect reached Ana")
+ }
+ if r := ana.connectAuto(f, "subject-ana"); r.Code != 200 {
+ t.Fatalf("Ana's automatic set-up: %d %s", r.Code, r.Body)
+ }
+ wantBody(t, "the owner's", app.connectAuto(f, "subject-owner"), 409, `{"state":"disconnected"}`)
+}
+
+// A Disconnect that fails as it sets the flag, after the link and host
+// token were deleted, undoes all three: one transaction.
+func TestFailedDisconnectLeavesNoFlag(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ web.approveEquipo(f)
+ if web.hostRows() != 1 {
+ t.Fatalf("host tokens: %d", web.hostRows())
+ }
+ if _, err := web.DB.Exec(`CREATE TRIGGER keep_flag BEFORE UPDATE OF ask_disconnected ON members BEGIN SELECT RAISE(ABORT, 'injected'); END`); err != nil {
+ t.Fatal(err)
+ }
+ if r := web.post("/ask/disconnect", nil); r.Code == 303 {
+ t.Fatal("Disconnect reported success")
+ }
+ if app.askDisconnected() || web.storedDisconnected(ownerAddress) {
+ t.Fatal("a failed Disconnect set the flag")
+ }
+ if web.equipoLinks() != 1 || web.hostRows() != 1 {
+ t.Fatalf("a failed Disconnect removed the link (%d) or host token (%d)", web.equipoLinks(), web.hostRows())
+ }
+}
+
+// The web shows what it always showed after Disconnect: the connect state.
+func TestWebAfterDisconnectShowsConnect(t *testing.T) {
+ web, _, f := newNativeAskApp(t)
+ web.approveEquipo(f)
+ web.post("/ask/disconnect", nil)
+ page := web.get("/ask")
+ if page.Code != 200 || !strings.Contains(page.Body, `action="/ask/connect"`) {
+ t.Fatalf("/ask after Disconnect: %d\n%s", page.Code, page.Body)
+ }
+ if r := web.get("/settings"); r.Code != http.StatusOK || !strings.Contains(r.Body, `action="/ask/connect"`) {
+ t.Fatalf("Settings after Disconnect: %d", r.Code)
+ }
+}
+
+// The save's own transaction checks the flag, not only this process's
+// generation: a Disconnect another Base process stored while an automatic
+// set-up waited at Equipo (the generation here unmoved) still wins.
+func TestAutomaticSaveChecksTheStoredFlag(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ entered, release := f.HoldNextNativeExchange()
+ done := background(func() Resp { return app.connectAuto(f, "subject-owner") })
+ arrived(t, entered, "the automatic set-up")
+ if _, err := app.DB.Exec(`UPDATE members SET ask_disconnected = 1 WHERE email = ?`, ownerAddress); err != nil {
+ t.Fatal(err)
+ }
+ release()
+ wantBody(t, "automatic set-up", <-done, 409, `{"state":"disconnected"}`)
+ if n := app.equipoLinks(); n != 0 || !app.storedDisconnected(ownerAddress) {
+ t.Fatalf("links %d, flag %v", n, app.storedDisconnected(ownerAddress))
+ }
+ wantLive(t, f)
+}
diff --git a/internal/webtest/ask_link_race_test.go b/internal/webtest/ask_link_race_test.go
new file mode 100644
index 0000000..0b0a89a
--- /dev/null
+++ b/internal/webtest/ask_link_race_test.go
@@ -0,0 +1,232 @@
+package webtest
+
+import (
+ "net/url"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/carlos/base/internal/equipo/equipotest"
+)
+
+// Every change to a member's Ask link (the native set-up's save, the web's
+// Connect and its approval, Disconnect, a code that ends) reads the link as
+// it is at that moment, under the member's lock, changes it in that one
+// step, and only then revokes the device it displaced. Whichever of two
+// finishes first, Base ends with at most one live credential in Equipo, the
+// one it holds, and every credential it forgot is revoked. One test per
+// interleaving; the rest are elsewhere (see the commit that added this).
+
+// background runs call and returns where its answer will come.
+func background(call func() Resp) <-chan Resp {
+ out := make(chan Resp, 1)
+ go func() { out <- call() }()
+ return out
+}
+
+// arrived waits for a held call to reach Equipo.
+func arrived(t *testing.T, entered <-chan struct{}, what string) {
+ t.Helper()
+ select {
+ case <-entered:
+ case <-time.After(5 * time.Second):
+ t.Fatalf("%s never reached Equipo", what)
+ }
+}
+
+// startWebConnect presses Connect on the web and returns the code shown.
+func (a *testApp) startWebConnect() string {
+ a.t.Helper()
+ r := a.post("/ask/connect", url.Values{"next": {"settings"}})
+ if r.Code != 303 {
+ a.t.Fatalf("connect: %d %s", r.Code, r.Body)
+ }
+ m := codeRE.FindStringSubmatch(a.get(r.Location()).Body)
+ if m == nil {
+ a.t.Fatal("no code shown")
+ }
+ return m[1]
+}
+
+// approveAndCheck approves code in Equipo and presses Check again.
+func (a *testApp) approveAndCheck(f *equipotest.Fake, code string) Resp {
+ a.t.Helper()
+ if err := f.Approve(code); err != nil {
+ a.t.Fatal(err)
+ }
+ a.pollable()
+ return a.check("settings")
+}
+
+// wantLive fails unless exactly the devices in want hold a live credential.
+func wantLive(t *testing.T, f *equipotest.Fake, want ...string) {
+ t.Helper()
+ got := f.LiveCredentials()
+ sort.Strings(got)
+ sort.Strings(want)
+ if strings.Join(got, ",") != strings.Join(want, ",") {
+ t.Fatalf("live credentials %v, want %v", got, want)
+ }
+}
+
+// Astra's (a): the web's Connect, paused at Equipo, saves after a native
+// renewal did. It replaces the renewal's link and revokes its device.
+func TestRaceWebConnectSavesAfterNativeRenewal(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("connect: %d %s", r.Code, r.Body)
+ }
+ f.RevokeAll()
+ if s, _ := app.askState(); s.State != "reconnect" {
+ t.Fatalf("state: %s", s.State)
+ }
+ entered, release := f.HoldNextBegin()
+ started := background(func() Resp { return web.post("/ask/connect", url.Values{"next": {"settings"}}) })
+ arrived(t, entered, "the web's Connect")
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("renewal: %d %s", r.Code, r.Body)
+ }
+ renewed := f.LiveCredentials()
+ release()
+ if r := <-started; r.Code != 303 {
+ t.Fatalf("web connect: %d %s", r.Code, r.Body)
+ }
+ if len(renewed) != 1 || !f.Revoked(renewed[0]) {
+ t.Fatalf("the renewal's device %v is still live after the web replaced it", renewed)
+ }
+ m := codeRE.FindStringSubmatch(web.get("/ask/connect?next=settings").Body)
+ if m == nil {
+ t.Fatal("no code")
+ }
+ if r := web.approveAndCheck(f, m[1]); r.Code != 303 || r.Location() != "/settings" {
+ t.Fatalf("check: %d %q", r.Code, r.Location())
+ }
+ if live := f.LiveCredentials(); len(live) != 1 || live[0] == renewed[0] || web.equipoLinks() != 1 {
+ t.Fatalf("live %v, links %d", live, web.equipoLinks())
+ }
+}
+
+// Astra's (b): Disconnect, paused revoking the old device, and a native
+// renewal released meanwhile. Disconnect removed the link there was when it
+// ran; the renewal, overtaken, saves nothing and revokes its own device.
+func TestRaceDisconnectWhileNativeRenewalSaves(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("connect: %d %s", r.Code, r.Body)
+ }
+ renewal, releaseRenewal := startHeldSetup(t, app, f)
+ entered, releaseRevoke := f.HoldNextRevoke()
+ disconnected := background(func() Resp { return app.post("/ask/disconnect", nil) })
+ arrived(t, entered, "Disconnect's revocation")
+ releaseRenewal()
+ wantBody(t, "renewal", <-renewal, 409, `{"state":"superseded"}`)
+ releaseRevoke()
+ if r := <-disconnected; r.Code != 303 {
+ t.Fatalf("disconnect: %d", r.Code)
+ }
+ wantLive(t, f)
+ if n := app.equipoLinks(); n != 0 {
+ t.Fatalf("links: %d", n)
+ }
+ if hosts := f.Hosts(); len(hosts) != 1 {
+ t.Errorf("hosts registered: %d", len(hosts))
+ }
+}
+
+// A native set-up saves while the web's approval waits at Equipo's
+// exchange: the approval finds its code replaced and gives its bearer up.
+func TestRaceNativeSavesWhileWebApprovalExchanges(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ code := web.startWebConnect()
+ if err := f.Approve(code); err != nil {
+ t.Fatal(err)
+ }
+ web.pollable()
+ entered, release := f.HoldNextExchange()
+ checked := background(func() Resp { return web.check("settings") })
+ arrived(t, entered, "the web's exchange")
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("native: %d %s", r.Code, r.Body)
+ }
+ native := f.LiveCredentials()
+ release()
+ <-checked
+ wantLive(t, f, native...)
+ s, r := app.askState()
+ if s.State != "ready" || strings.Contains(r.Body, `"renew_after":""`) {
+ t.Fatalf("state: %s", r.Body)
+ }
+ // The old code ending later changes nothing.
+ f.Expire()
+ web.pollable()
+ web.check("settings")
+ wantLive(t, f, native...)
+}
+
+// Disconnect while the web's Connect waits at Equipo: the Connect, the
+// later of the two, saves its code; the connection Disconnect removed is
+// revoked, and nothing is live.
+func TestRaceDisconnectWhileWebConnectBegins(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("connect: %d %s", r.Code, r.Body)
+ }
+ entered, release := f.HoldNextBegin()
+ started := background(func() Resp { return web.post("/ask/connect", url.Values{"next": {"settings"}}) })
+ arrived(t, entered, "the web's Connect")
+ if r := app.post("/ask/disconnect", nil); r.Code != 303 {
+ t.Fatalf("disconnect: %d", r.Code)
+ }
+ release()
+ if r := <-started; r.Code != 303 {
+ t.Fatalf("web connect: %d", r.Code)
+ }
+ wantLive(t, f)
+ if s, _ := app.askState(); s.State != "pending" {
+ t.Errorf("state: %s", s.State)
+ }
+}
+
+// The web's code ends (expired) while a native set-up waits at Equipo:
+// the set-up, overtaken, saves nothing and revokes its device.
+func TestRaceCodeEndsWhileNativeSetupWaits(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ web.startWebConnect()
+ setup, release := startHeldSetup(t, app, f)
+ f.Expire()
+ web.pollable()
+ web.check("settings")
+ if n := web.equipoLinks(); n != 0 {
+ t.Fatalf("the expired code's link stays: %d", n)
+ }
+ release()
+ wantBody(t, "set-up", <-setup, 409, `{"state":"superseded"}`)
+ wantLive(t, f)
+}
+
+// A second Connect while the first's approval waits at Equipo: the
+// first's bearer is given up, and only the newer code stands.
+func TestRaceReconnectWhileWebApprovalExchanges(t *testing.T) {
+ web, _, f := newNativeAskApp(t)
+ code := web.startWebConnect()
+ if err := f.Approve(code); err != nil {
+ t.Fatal(err)
+ }
+ web.pollable()
+ entered, release := f.HoldNextExchange()
+ checked := background(func() Resp { return web.check("settings") })
+ arrived(t, entered, "the web's exchange")
+ web.startWebConnect()
+ release()
+ <-checked
+ wantLive(t, f)
+ if r := web.nativeGet("/ask/state"); !strings.Contains(r.Body, `"state":"pending"`) {
+ t.Errorf("state: %s", r.Body)
+ }
+}
diff --git a/internal/webtest/ask_native_contract_test.go b/internal/webtest/ask_native_contract_test.go
new file mode 100644
index 0000000..f7f92f0
--- /dev/null
+++ b/internal/webtest/ask_native_contract_test.go
@@ -0,0 +1,498 @@
+package webtest
+
+import (
+ "bufio"
+ "context"
+ "crypto/tls"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/url"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/carlos/base/internal/config"
+ "amadan.net/carlos/base/internal/equipo/equipotest"
+)
+
+// Ask's JSON contract (docs/api/base-native-v1.md), as the native app uses
+// it: every call carries the native session cookie, Origin and
+// Accept: application/json, and no Sec-Fetch-Site. These are the routes and
+// shapes ask.js relies on; a change to one breaks a test here.
+
+// newNativeAskApp is Base with Oficina ID and Ask on, the owner linked
+// (and signed in locally in the returned browser), and the owner's native
+// app signed in.
+func newNativeAskApp(t *testing.T) (web, app *testApp, f *equipotest.Fake) {
+ t.Helper()
+ f = equipotest.New(t)
+ web = newHomeAppWith(t, func(c *config.Config) { c.EquipoOrigin = f.URL })
+ web.link(ownerAddress, "subject-owner")
+ return web, web.nativeSignIn("subject-owner"), f
+}
+
+// nativeForm is a form POST as the native app makes one to Ask.
+func (a *testApp) nativeForm(target string, form url.Values) Resp {
+ a.t.Helper()
+ req, _ := http.NewRequest(http.MethodPost, a.base+target, strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Origin", homeOrigin)
+ req.Header.Set("Accept", "application/json")
+ return a.do(req)
+}
+
+// keysOf is the sorted keys of a JSON object.
+func keysOf(t *testing.T, raw string) []string {
+ t.Helper()
+ var m map[string]json.RawMessage
+ if err := json.Unmarshal([]byte(raw), &m); err != nil {
+ t.Fatalf("not an object: %q: %v", raw, err)
+ }
+ var out []string
+ for k := range m {
+ out = append(out, k)
+ }
+ sort.Strings(out)
+ return out
+}
+
+func wantKeys(t *testing.T, where, raw string, want ...string) {
+ t.Helper()
+ sort.Strings(want)
+ if got := keysOf(t, raw); !reflect.DeepEqual(got, want) {
+ t.Errorf("%s keys %v, want %v\n%s", where, got, want, raw)
+ }
+}
+
+func wantBody(t *testing.T, where string, r Resp, code int, body string) {
+ t.Helper()
+ if r.Code != code || strings.TrimSpace(r.Body) != body {
+ t.Errorf("%s: %d %s, want %d %s", where, r.Code, strings.TrimSpace(r.Body), code, body)
+ }
+}
+
+// askState is /ask/state's answer, its parts kept raw for their shapes.
+type askState struct {
+ State string `json:"state"`
+ Messages []json.RawMessage `json:"messages"`
+ Jobs []json.RawMessage `json:"jobs"`
+ Cards []json.RawMessage `json:"cards"`
+ Turn json.RawMessage `json:"turn"`
+ Status string `json:"status"`
+ Cursor int64 `json:"cursor"`
+}
+
+func (a *testApp) askState() (askState, Resp) {
+ a.t.Helper()
+ r := a.nativeGet("/ask/state")
+ if r.Code != 200 || r.Header.Get("Cache-Control") != "no-store" || r.Header.Get("Content-Type") != "application/json" {
+ a.t.Fatalf("/ask/state: %d %q %q %s", r.Code, r.Header.Get("Cache-Control"), r.Header.Get("Content-Type"), r.Body)
+ }
+ var s askState
+ if err := json.Unmarshal([]byte(r.Body), &s); err != nil {
+ a.t.Fatal(err)
+ }
+ return s, r
+}
+
+var stateKeys = []string{"state", "messages", "jobs", "cards", "turn", "status", "cursor", "renew_after", "equipo_origin", "disconnected"}
+
+func TestAskContractBeforeConnecting(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ s, r := app.askState()
+ wantKeys(t, "state", r.Body, stateKeys...)
+ if strings.TrimSpace(r.Body) != `{"state":"connect","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":0,"renew_after":"","equipo_origin":"`+f.URL+`","disconnected":false}` || s.State != "connect" {
+ t.Errorf("not connected: %s", r.Body)
+ }
+ wantBody(t, "send", app.nativeForm("/ask/messages", url.Values{"text": {"Hello"}, "key": {"k1"}}), 409, `{"state":"connect"}`)
+ wantBody(t, "cancel", app.nativeForm("/ask/turns/t_1/cancel", url.Values{"key": {"k2"}}), 409, `{"state":"connect"}`)
+ wantBody(t, "answer", app.nativeForm("/ask/cards/c_1/answer", url.Values{"choice": {"x"}, "revision": {"1"}, "key": {"k3"}}), 409, `{"state":"connect"}`)
+ frames := app.events(t, "0", func([]sseFrame) bool { return false })
+ if len(frames) != 1 || frames[0].Event != "state" || frames[0].Data != `{"state":"connect"}` || frames[0].ID != "" {
+ t.Errorf("events while not connected: %+v", frames)
+ }
+}
+
+func TestAskContractConversation(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ web.approveEquipo(f)
+ s, r := app.askState()
+ wantKeys(t, "state", r.Body, stateKeys...)
+ if s.State != "ready" || s.Messages == nil || s.Jobs == nil || s.Cards == nil || string(s.Turn) != "null" || s.Status != "" {
+ t.Fatalf("connected state: %s", r.Body)
+ }
+
+ // Send: the message and its turn; the same key again is the same message.
+ form := url.Values{"text": {"What can I do?"}, "key": {"native-1"}}
+ sent := app.nativeForm("/ask/messages", form)
+ if sent.Code != 200 || sent.Header.Get("Cache-Control") != "no-store" {
+ t.Fatalf("send: %d %s", sent.Code, sent.Body)
+ }
+ wantKeys(t, "send", sent.Body, "message", "turn")
+ var out struct {
+ Message, Turn json.RawMessage
+ }
+ _ = json.Unmarshal([]byte(sent.Body), &out)
+ wantKeys(t, "message", string(out.Message), "id", "role", "text", "turn_id", "created_at")
+ wantKeys(t, "turn", string(out.Turn), "id", "kind", "state", "reason")
+ var m struct{ ID, Role, Text string }
+ _ = json.Unmarshal(out.Message, &m)
+ if m.Role != "person" || m.Text != "What can I do?" {
+ t.Errorf("message: %s", out.Message)
+ }
+ again := app.nativeForm("/ask/messages", form)
+ var m2 struct{ Message struct{ ID string } }
+ if again.Code != 200 || json.Unmarshal([]byte(again.Body), &m2) != nil || m2.Message.ID != m.ID {
+ t.Errorf("resend with the same key: %d %s", again.Code, again.Body)
+ }
+ wantBody(t, "empty", app.nativeForm("/ask/messages", url.Values{"text": {" "}, "key": {"native-2"}}), 422, `{"state":"ready"}`)
+
+ // The reply is in the next read.
+ var after askState
+ for i := 0; i < 200; i++ {
+ if after, _ = app.askState(); len(after.Messages) == 2 && string(after.Turn) == "null" {
+ break
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ if len(after.Messages) != 2 || after.Cursor <= s.Cursor {
+ t.Fatalf("after the reply: %d messages, cursor %d (was %d)", len(after.Messages), after.Cursor, s.Cursor)
+ }
+ wantKeys(t, "state message", string(after.Messages[1]), "id", "role", "text", "turn_id", "created_at")
+}
+
+func TestAskContractEvents(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ web.approveEquipo(f)
+ s, _ := app.askState()
+ f.Hold = true
+ frames := app.events(t, strconv.FormatInt(s.Cursor, 10), func(got []sseFrame) bool {
+ if len(got) == 1 {
+ // The stream is open: send, glance, then answer.
+ go func() {
+ r := app.nativeForm("/ask/messages", url.Values{"text": {"Make a form"}, "key": {"ev-1"}})
+ var out struct{ Turn struct{ ID string } }
+ _ = json.Unmarshal([]byte(r.Body), &out)
+ for f.Turn(out.Turn.ID) != "running" {
+ time.Sleep(5 * time.Millisecond)
+ }
+ f.Glance(out.Turn.ID, "Looking at your **forms**")
+ time.Sleep(20 * time.Millisecond)
+ f.Answer(out.Turn.ID, "Here it is.", true)
+ }()
+ }
+ last := got[len(got)-1]
+ return last.Event == "turn" && strings.Contains(last.Data, `"state":"replied"`)
+ })
+ if frames[0].Retry != "3000" {
+ t.Errorf("first frame %+v, want retry: 3000", frames[0])
+ }
+ seen := map[string]bool{}
+ for _, fr := range frames[1:] {
+ if fr.Comment {
+ continue
+ }
+ seen[fr.Event] = true
+ var env struct {
+ Type string `json:"type"`
+ Data json.RawMessage `json:"data"`
+ }
+ if err := json.Unmarshal([]byte(fr.Data), &env); err != nil || env.Type != fr.Event {
+ t.Fatalf("frame %+v: %v", fr, err)
+ }
+ wantKeys(t, fr.Event+" frame", fr.Data, "type", "data")
+ switch fr.Event {
+ case "glance":
+ if fr.ID != "" {
+ t.Errorf("a glance carried an id: %+v", fr)
+ }
+ wantKeys(t, "glance event", string(env.Data), "turn_id", "text")
+ if !strings.Contains(string(env.Data), `"text":"Looking at your forms"`) {
+ t.Errorf("glance: %s", env.Data)
+ }
+ default:
+ if _, err := strconv.ParseUint(fr.ID, 10, 63); err != nil {
+ t.Errorf("%s frame without a numeric id: %+v", fr.Event, fr)
+ }
+ }
+ switch fr.Event {
+ case "message":
+ wantKeys(t, "message event", string(env.Data), "id", "role", "text", "turn_id", "created_at")
+ case "turn":
+ wantKeys(t, "turn event", string(env.Data), "id", "kind", "state", "reason")
+ case "delta":
+ wantKeys(t, "delta event", string(env.Data), "turn_id", "offset", "text")
+ }
+ }
+ for _, want := range []string{"message", "turn", "delta", "glance"} {
+ if !seen[want] {
+ t.Errorf("no %s event in %+v", want, frames)
+ }
+ }
+}
+
+func TestAskContractCancel(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ web.approveEquipo(f)
+ f.Hold = true
+ r := app.nativeForm("/ask/messages", url.Values{"text": {"Something long"}, "key": {"c-1"}})
+ var out struct{ Turn struct{ ID string } }
+ if json.Unmarshal([]byte(r.Body), &out) != nil || out.Turn.ID == "" {
+ t.Fatalf("send: %d %s", r.Code, r.Body)
+ }
+ for f.Turn(out.Turn.ID) != "running" {
+ time.Sleep(5 * time.Millisecond)
+ }
+ s, _ := app.askState()
+ if !strings.Contains(string(s.Turn), out.Turn.ID) || s.Status != "Thinking…" {
+ t.Errorf("running: turn %s status %q", s.Turn, s.Status)
+ }
+ wantBody(t, "cancel", app.nativeForm("/ask/turns/"+out.Turn.ID+"/cancel", url.Values{"key": {"c-2"}}), 200, `{"state":"ready"}`)
+ wantBody(t, "cancel again", app.nativeForm("/ask/turns/"+out.Turn.ID+"/cancel", url.Values{"key": {"c-3"}}), 409, `{"state":"ready"}`)
+}
+
+func TestAskContractCards(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ web.approveEquipo(f)
+ job := f.AskJob("Christmas order form")
+ f.AskKindFor("confirm", job, "Go ahead?", goOptions, nil)
+ q := f.AskQuestion("Which colour?", "red", "blue")
+ s, r := app.askState()
+ if len(s.Jobs) != 1 || len(s.Cards) != 1 {
+ t.Fatalf("jobs and cards: %s", r.Body)
+ }
+ wantKeys(t, "card", string(s.Cards[0]), "id", "revision", "kind", "state", "question", "options", "links", "result")
+ wantKeys(t, "job", string(s.Jobs[0]), "id", "revision", "kind", "state", "question", "options", "links", "result", "detail", "started_at", "cards")
+ var j struct {
+ Kind, State, Question string
+ Cards []json.RawMessage
+ }
+ if json.Unmarshal(s.Jobs[0], &j) != nil || j.Kind != "job" || j.Question != "Christmas order form" || len(j.Cards) != 1 {
+ t.Fatalf("job: %s", s.Jobs[0])
+ }
+ wantKeys(t, "job's card", string(j.Cards[0]), "id", "revision", "kind", "state", "question", "options", "links", "result", "job")
+
+ // Answer at the revision seen: the card, the message and turn it started.
+ a := app.nativeForm("/ask/cards/"+q+"/answer", url.Values{"choice": {"red"}, "revision": {"1"}, "key": {"a-1"}})
+ if a.Code != 200 {
+ t.Fatalf("answer: %d %s", a.Code, a.Body)
+ }
+ wantKeys(t, "answer", a.Body, "card", "message", "turn")
+ var ans struct {
+ Card struct{ ID, State, Result string }
+ Message *struct{ Text string }
+ Turn *struct{ ID string }
+ }
+ if json.Unmarshal([]byte(a.Body), &ans) != nil || ans.Card.ID != q || ans.Card.State != "answered" || ans.Message == nil || ans.Message.Text != "red" || ans.Turn == nil {
+ t.Errorf("answer: %s", a.Body)
+ }
+ // An outcome card's answer starts nothing.
+ o := f.AskOutcome("Publish it?", goOptions, nil)
+ wantBody(t, "outcome", app.nativeForm("/ask/cards/"+o+"/answer", url.Values{"choice": {"go"}, "revision": {"1"}, "key": {"a-2"}}), 200,
+ `{"card":{"id":"`+o+`","revision":2,"kind":"outcome","state":"answered","question":"Publish it?","options":[{"value":"go","label":"Go ahead"},{"value":"later","label":"Not yet"}],"links":[],"result":"Go ahead"},"message":null,"turn":null}`)
+ // Stale: the card moved on.
+ q2 := f.AskQuestion("Which size?", "S", "M")
+ f.SetCard(q2, "open", "")
+ wantBody(t, "stale", app.nativeForm("/ask/cards/"+q2+"/answer", url.Values{"choice": {"S"}, "revision": {"1"}, "key": {"a-3"}}), 409, `{"state":"ready"}`)
+}
+
+// Equipo refusing the key is Ask's 409 {"state":"reconnect"}, never a 401:
+// a 401 is always Base's own session ending ({"code":"unauthenticated"}),
+// and the kit signs in again on one.
+func TestAskContractLostKey(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ web.approveEquipo(f)
+ for i, call := range []func() Resp{
+ func() Resp { return app.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {"l-1"}}) },
+ func() Resp { return app.nativeForm("/ask/turns/t_0001/cancel", url.Values{"key": {"l-2"}}) },
+ func() Resp {
+ return app.nativeForm("/ask/cards/c_0001/answer", url.Values{"choice": {"go"}, "revision": {"1"}, "key": {"l-3"}})
+ },
+ } {
+ // Each time the key is refused afresh: reconnect, and Base's
+ // stored link is lost.
+ web.approveEquipo(f)
+ f.RevokeAll()
+ wantBody(t, "write "+strconv.Itoa(i), call(), 409, `{"state":"reconnect"}`)
+ }
+ if s, _ := app.askState(); s.State != "reconnect" {
+ t.Errorf("state after a refused key: %s", s.State)
+ }
+ if r := app.nativeGet("/api/v1/me"); r.Code != 200 {
+ t.Errorf("the session ended with the key: %d", r.Code)
+ }
+}
+
+// While Base's session is good, no Ask route answers 401, whatever Equipo
+// says of the key: connected, refused as it is used, or already lost.
+func TestAskNeverAnswers401WithASession(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ calls := map[string]func() Resp{
+ "state": func() Resp { return app.nativeGet("/ask/state") },
+ "send": func() Resp { return app.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {equipoKey()}}) },
+ "cancel": func() Resp { return app.nativeForm("/ask/turns/t_9999/cancel", url.Values{"key": {equipoKey()}}) },
+ "answer": func() Resp {
+ return app.nativeForm("/ask/cards/c_9999/answer", url.Values{"choice": {"x"}, "revision": {"1"}, "key": {equipoKey()}})
+ },
+ "check": func() Resp { return app.nativeForm("/ask/connect/check", url.Values{"next": {"ask"}}) },
+ "dock": func() Resp { return app.nativeForm("/ask/dock", url.Values{"open": {"1"}}) },
+ "page": func() Resp { return app.get("/ask") },
+ "oficina": func() Resp { return app.get("/ask/oficina/connect") },
+ "set-up": func() Resp { return app.connectWithOficina(f, "subject-owner") },
+ "replayed": func() Resp { return app.nativePost("/api/v1/ask/oficina", `{"assertion":"x","verifier":"y"}`) },
+ }
+ try := func(when string) {
+ t.Helper()
+ for name, call := range calls {
+ if name == "set-up" {
+ continue
+ }
+ if r := call(); r.Code == http.StatusUnauthorized {
+ t.Errorf("%s, %s: 401 %s", when, name, r.Body)
+ }
+ }
+ app.events(t, "0", func([]sseFrame) bool { return true })
+ }
+ try("not connected")
+ web.approveEquipo(f)
+ try("connected")
+ f.RevokeAll()
+ try("refused as used")
+ try("lost")
+ if r := calls["set-up"](); r.Code != 200 {
+ t.Fatalf("set-up: %d %s", r.Code, r.Body)
+ }
+ f.EndNativeSession(f.DeviceSession(liveDevice(t, f)))
+ try("Equipo's session ended")
+ if r := app.post("/ask/disconnect", nil); r.Code == http.StatusUnauthorized {
+ t.Errorf("disconnect: 401")
+ }
+}
+
+var keySeq int
+
+func equipoKey() string { keySeq++; return "never-401-" + strconv.Itoa(keySeq) }
+
+// After the member disconnects Ask, /ask/state says so and an automatic
+// set-up is refused with 409 disconnected.
+func TestAskContractDisconnected(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ web.approveEquipo(f)
+ web.post("/ask/disconnect", nil)
+ _, r := app.askState()
+ wantKeys(t, "state", r.Body, stateKeys...)
+ if !strings.Contains(r.Body, `"state":"connect"`) || !strings.Contains(r.Body, `"disconnected":true`) {
+ t.Fatalf("state after Disconnect: %s", r.Body)
+ }
+ wantBody(t, "automatic set-up", app.connectAuto(f, "subject-owner"), 409, `{"state":"disconnected"}`)
+}
+
+// sseFrame is one frame of an event stream, as the native client parses it.
+type sseFrame struct {
+ ID, Event, Data, Retry string
+ Comment bool
+}
+
+// events opens /ask/events?after= as the native app does and reads frames
+// until done says so or the stream ends. The first frame is the retry.
+func (a *testApp) events(t *testing.T, after string, done func([]sseFrame) bool) []sseFrame {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ req, _ := http.NewRequestWithContext(ctx, http.MethodGet, a.base+"/ask/events?after="+after, nil)
+ req.Header.Set("Origin", homeOrigin)
+ req.Header.Set("Accept", "text/event-stream")
+ for _, c := range a.client.Jar.Cookies(req.URL) {
+ req.AddCookie(c)
+ }
+ res := serveStreaming(a.client.Transport.(handlerTransport).h, req)
+ defer res.Body.Close()
+ if res.StatusCode != 200 || res.Header.Get("Content-Type") != "text/event-stream" || res.Header.Get("Cache-Control") != "no-store" {
+ t.Fatalf("events: %d %v", res.StatusCode, res.Header)
+ }
+ var frames []sseFrame
+ var cur sseFrame
+ sc := bufio.NewScanner(res.Body)
+ for sc.Scan() {
+ line := sc.Text()
+ switch {
+ case line == "":
+ frames = append(frames, cur)
+ cur = sseFrame{}
+ if done(frames) {
+ return frames
+ }
+ case strings.HasPrefix(line, ":"):
+ cur.Comment = true
+ default:
+ name, value, _ := strings.Cut(line, ": ")
+ switch name {
+ case "id":
+ cur.ID = value
+ case "event":
+ cur.Event = value
+ case "data":
+ cur.Data = value
+ case "retry":
+ cur.Retry = value
+ }
+ }
+ }
+ if ctx.Err() != nil {
+ t.Fatalf("the stream timed out after %+v", frames)
+ }
+ // Drop the retry frame for a stream that ends at once (a state event).
+ if len(frames) > 0 && frames[0].Retry != "" && frames[0].Event == "" {
+ return frames[1:]
+ }
+ return frames
+}
+
+// serveStreaming serves req with h in the background and answers as soon
+// as the headers are written, with a body that streams what h writes. The
+// in-process transport waits for the whole response, which a stream never
+// ends.
+func serveStreaming(h http.Handler, req *http.Request) *http.Response {
+ in := req.Clone(req.Context())
+ in.RequestURI, in.Host, in.RemoteAddr, in.TLS = req.URL.RequestURI(), req.URL.Host, "192.0.2.10:4321", &tls.ConnectionState{}
+ pr, pw := io.Pipe()
+ w := &pipeWriter{header: http.Header{}, pw: pw, ready: make(chan struct{})}
+ go func() {
+ h.ServeHTTP(w, in)
+ w.WriteHeader(http.StatusOK)
+ pw.Close()
+ }()
+ <-w.ready
+ return &http.Response{StatusCode: w.status, Header: w.sent, Body: pr, Request: req}
+}
+
+type pipeWriter struct {
+ header, sent http.Header
+ pw *io.PipeWriter
+ status int
+ once sync.Once
+ ready chan struct{}
+}
+
+func (p *pipeWriter) Header() http.Header { return p.header }
+
+func (p *pipeWriter) WriteHeader(code int) {
+ p.once.Do(func() {
+ p.status, p.sent = code, p.header.Clone()
+ close(p.ready)
+ })
+}
+
+func (p *pipeWriter) Write(b []byte) (int, error) {
+ p.WriteHeader(http.StatusOK)
+ return p.pw.Write(b)
+}
+
+func (p *pipeWriter) Flush() {}
diff --git a/internal/webtest/ask_oficina_native_test.go b/internal/webtest/ask_oficina_native_test.go
new file mode 100644
index 0000000..09b8f33
--- /dev/null
+++ b/internal/webtest/ask_oficina_native_test.go
@@ -0,0 +1,378 @@
+package webtest
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "amadan.net/carlos/base/internal/equipo/equipotest"
+)
+
+// Ask set up with Oficina ID (docs/api/base-native-v1.md): the native app
+// posts an assertion addressed to Equipo, and Base completes Equipo's own
+// native sign-in for the person, keeping the key where the code flow does.
+
+// connectWithOficina posts what the native app posts for subject.
+func (a *testApp) connectWithOficina(f *equipotest.Fake, subject string) Resp {
+ a.t.Helper()
+ assertion, verifier := f.OficinaAssertion(subject)
+ body, _ := json.Marshal(map[string]string{"assertion": assertion, "verifier": verifier})
+ return a.nativePost("/api/v1/ask/oficina", string(body))
+}
+
+type askReadyAnswer struct {
+ State string `json:"state"`
+ RenewAfter string `json:"renew_after"`
+}
+
+// equipoLinks is how many Equipo links Base holds.
+func (a *testApp) equipoLinks() int {
+ a.t.Helper()
+ var n int
+ if err := a.DB.QueryRow(`SELECT count(*) FROM equipo_links`).Scan(&n); err != nil {
+ a.t.Fatal(err)
+ }
+ return n
+}
+
+// liveDevice is the one device the fake holds that is not revoked.
+func liveDevice(t *testing.T, f *equipotest.Fake) string {
+ t.Helper()
+ var live []string
+ for _, id := range f.Devices() {
+ if !f.Revoked(id) {
+ live = append(live, id)
+ }
+ }
+ if len(live) != 1 {
+ t.Fatalf("live devices: %v", live)
+ }
+ return live[0]
+}
+
+func TestAskOficinaConnect(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ r := app.connectWithOficina(f, "subject-owner")
+ if r.Code != 200 || r.Header.Get("Cache-Control") != "no-store" {
+ t.Fatalf("connect: %d %s", r.Code, r.Body)
+ }
+ wantKeys(t, "connect", r.Body, "state", "renew_after")
+ out := decode[askReadyAnswer](t, r)
+ renew, err := time.Parse(time.RFC3339, out.RenewAfter)
+ if out.State != "ready" || err != nil || renew.Sub(time.Now().Add(5*24*time.Hour)).Abs() > time.Minute {
+ t.Fatalf("connect: %s", r.Body)
+ }
+
+ // Equipo's exchange: what a native app sends, no Origin, no cookie.
+ ex := f.Calls("/native/oficina-id")
+ if len(ex) != 1 || ex[0].Header.Get("Origin") != "" || ex[0].Header.Get("Cookie") != "" || ex[0].Header.Get("Authorization") != "" ||
+ ex[0].Header.Get("Content-Type") != "application/json" || len(keysOf(t, ex[0].Body)) != 2 {
+ t.Fatalf("exchange: %+v", ex)
+ }
+ // Then the device, with that session's cookie (and nothing of Base's),
+ // Equipo's own Origin, a fresh key and Base's label.
+ dev := f.Calls("/api/v1/auth/devices/native")
+ if len(dev) != 1 {
+ t.Fatalf("device calls: %d", len(dev))
+ }
+ h := dev[0].Header
+ if !strings.HasPrefix(h.Get("Cookie"), equipotest.SessionCookie+"=") || strings.Contains(h.Get("Cookie"), sessionCookie) ||
+ strings.Contains(h.Get("Cookie"), ";") || h.Get("Origin") != f.URL || h.Get("Authorization") != "" {
+ t.Fatalf("device headers: %v", h)
+ }
+ var in struct {
+ PublicKey string `json:"public_key"`
+ Label string `json:"label"`
+ }
+ _ = json.Unmarshal([]byte(dev[0].Body), &in)
+ if pub, err := base64.RawURLEncoding.DecodeString(in.PublicKey); err != nil || len(pub) != 32 || in.Label != "Base (Acme)" {
+ t.Fatalf("device body: %s", dev[0].Body)
+ }
+ device := liveDevice(t, f)
+ if f.DeviceSession(device) == "" {
+ t.Fatal("the key is not the native session's")
+ }
+ // The Assistant's host is registered with the new key, as Connect does.
+ hosts := f.Hosts()
+ if len(hosts) != 1 || !strings.HasPrefix(hosts[0].Header.Get("Authorization"), "Bearer equipo.person.v1.") {
+ t.Fatalf("hosts: %+v", hosts)
+ }
+ // Ask is ready, and the relay uses the key.
+ s, raw := app.askState()
+ if s.State != "ready" || !strings.Contains(raw.Body, `"renew_after":"`+out.RenewAfter+`"`) {
+ t.Fatalf("state: %s", raw.Body)
+ }
+ if sent := app.nativeForm("/ask/messages", url.Values{"text": {"Hello"}, "key": {"o-1"}}); sent.Code != 200 {
+ t.Fatalf("send: %d %s", sent.Code, sent.Body)
+ }
+ if c := f.Calls("/api/v1/assistant/messages"); len(c) != 1 || c[0].Header.Get("Authorization") != hosts[0].Header.Get("Authorization") {
+ t.Fatalf("relayed with: %+v", c)
+ }
+ // Neither the key nor Equipo's session ever reaches the app.
+ app.noLeak(strings.TrimPrefix(hosts[0].Header.Get("Authorization"), "Bearer "))
+ app.noLeak(f.DeviceSession(device))
+ // Base never signs Equipo's session out.
+ for _, c := range f.Calls("") {
+ if strings.Contains(c.Path, "signout") {
+ t.Errorf("Base called %s", c.Path)
+ }
+ }
+}
+
+// A person Equipo has not linked to their Oficina ID: not_linked, and
+// nothing is stored.
+func TestAskOficinaUnknown(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ wantBody(t, "unlinked", app.connectWithOficina(f, "subject-owner"), 409, `{"state":"not_linked"}`)
+ if n := app.equipoLinks(); n != 0 || len(f.Devices()) != 0 || len(f.Calls("/api/v1/auth/devices/native")) != 0 {
+ t.Fatalf("stored %d links, %d devices", n, len(f.Devices()))
+ }
+ if s, _ := app.askState(); s.State != "connect" {
+ t.Errorf("state: %s", s.State)
+ }
+}
+
+// Equipo's other refusals store nothing either, and never answer 401,
+// which the app would read as Base's own session ending.
+func TestAskOficinaEquipoRefusals(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ f.FailNextNativeExchange(503)
+ wantBody(t, "Equipo down", app.connectWithOficina(f, "subject-owner"), 502, `{"state":"unavailable"}`)
+ // An assertion Equipo refuses (here, one already used).
+ assertion, verifier := f.OficinaAssertion("subject-owner")
+ body, _ := json.Marshal(map[string]string{"assertion": assertion, "verifier": verifier})
+ if r := app.nativePost("/api/v1/ask/oficina", string(body)); r.Code != 200 {
+ t.Fatalf("first use: %d %s", r.Code, r.Body)
+ }
+ wantBody(t, "replayed", app.nativePost("/api/v1/ask/oficina", string(body)), 422, `{"state":"failed"}`)
+ if len(f.Devices()) != 1 {
+ t.Errorf("devices: %d", len(f.Devices()))
+ }
+ // What Base can't read.
+ for _, bad := range []string{``, `{}`, `{"assertion":"x"}`, `{"assertion":"x","verifier":"y","extra":1}`, `[1]`} {
+ wantBody(t, "body "+bad, app.nativePost("/api/v1/ask/oficina", bad), 400, `{"state":"invalid"}`)
+ }
+}
+
+// A second post replaces the key and Equipo session, and revokes the old
+// device in Equipo.
+func TestAskOficinaRenew(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("first: %d %s", r.Code, r.Body)
+ }
+ first := liveDevice(t, f)
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("renew: %d %s", r.Code, r.Body)
+ }
+ second := liveDevice(t, f)
+ if second == first || !f.Revoked(first) || f.DeviceSession(second) == f.DeviceSession(first) || f.NativeSessions() != 2 {
+ t.Fatalf("renew: first %s (revoked %v), second %s", first, f.Revoked(first), second)
+ }
+ if n := app.equipoLinks(); n != 1 {
+ t.Errorf("links: %d", n)
+ }
+ if hosts := f.Hosts(); len(hosts) != 2 {
+ t.Errorf("hosts registered: %d", len(hosts))
+ }
+ if s, _ := app.askState(); s.State != "ready" {
+ t.Errorf("state: %s", s.State)
+ }
+ // Two at once run one at a time: one device is left.
+ var wg sync.WaitGroup
+ for range 2 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Errorf("concurrent: %d %s", r.Code, r.Body)
+ }
+ }()
+ }
+ wg.Wait()
+ liveDevice(t, f)
+}
+
+// The web keeps its code flow: only a native session may post here.
+func TestAskOficinaRefusesWeb(t *testing.T) {
+ web, _, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ browser := web.newBrowser()
+ browser.signInWithOficina("subject-owner")
+ for name, b := range map[string]*testApp{"local": web, "Oficina in a browser": browser} {
+ wantBody(t, name, b.connectWithOficina(f, "subject-owner"), 403, `{"state":"forbidden"}`)
+ }
+ if len(f.Calls("/native/oficina-id")) != 0 {
+ t.Fatal("a browser session reached Equipo")
+ }
+ // From another site it never gets that far.
+ req, _ := http.NewRequest(http.MethodPost, homeOrigin+"/api/v1/ask/oficina", strings.NewReader(`{}`))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Origin", "https://evil.test")
+ if r := web.do(req); r.Code != http.StatusForbidden {
+ t.Errorf("cross-site: %d", r.Code)
+ }
+}
+
+func TestAskStateSaysWhenToRenew(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ // A key from the code flow: no renew_after.
+ web.approveEquipo(f)
+ _, r := app.askState()
+ if !strings.Contains(r.Body, `"renew_after":""`) || !strings.Contains(r.Body, `"equipo_origin":"`+f.URL+`"`) {
+ t.Fatalf("code flow: %s", r.Body)
+ }
+ // With Oficina ID: five days after Equipo's session began.
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ out := decode[askReadyAnswer](t, app.connectWithOficina(f, "subject-owner"))
+ _, r = app.askState()
+ if out.RenewAfter == "" || !strings.Contains(r.Body, `"renew_after":"`+out.RenewAfter+`"`) {
+ t.Fatalf("oficina: %s (answered %+v)", r.Body, out)
+ }
+ // It replaced the code flow's key, which is revoked: one key is live.
+ // Equipo ending its session ends the key: Ask asks to reconnect.
+ f.EndNativeSession(f.DeviceSession(liveDevice(t, f)))
+ if s, _ := app.askState(); s.State != "reconnect" {
+ t.Errorf("after Equipo's session ended: %s", s.State)
+ }
+}
+
+func TestDisconnectRevokesOficinaKey(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("connect: %d %s", r.Code, r.Body)
+ }
+ device := liveDevice(t, f)
+ if r := app.post("/ask/disconnect", nil); r.Code != 303 || r.Location() != "/settings" {
+ t.Fatalf("disconnect: %d %q", r.Code, r.Location())
+ }
+ if !f.Revoked(device) || app.equipoLinks() != 0 {
+ t.Fatalf("revoked %v, links %d", f.Revoked(device), app.equipoLinks())
+ }
+ if s, _ := app.askState(); s.State != "connect" {
+ t.Errorf("state: %s", s.State)
+ }
+}
+
+// startHeldSetup starts a native set-up that waits at Equipo's exchange,
+// and returns where its answer will come.
+func startHeldSetup(t *testing.T, app *testApp, f *equipotest.Fake) (done <-chan Resp, release func()) {
+ t.Helper()
+ entered, release := f.HoldNextNativeExchange()
+ out := make(chan Resp, 1)
+ go func() { out <- app.connectWithOficina(f, "subject-owner") }()
+ select {
+ case <-entered:
+ case r := <-out:
+ t.Fatalf("the set-up never reached Equipo: %d %s", r.Code, r.Body)
+ case <-time.After(5 * time.Second):
+ t.Fatal("the set-up never reached Equipo")
+ }
+ return out, release
+}
+
+// newDevice is the one device the fake holds that is not in before.
+func newDevice(t *testing.T, f *equipotest.Fake, before []string) string {
+ t.Helper()
+ old := map[string]bool{}
+ for _, id := range before {
+ old[id] = true
+ }
+ var made []string
+ for _, id := range f.Devices() {
+ if !old[id] {
+ made = append(made, id)
+ }
+ }
+ if len(made) != 1 {
+ t.Fatalf("new devices: %v", made)
+ }
+ return made[0]
+}
+
+// A renewal that Disconnect overtakes saves nothing, and revokes the
+// device it made: Disconnect stays done.
+func TestAskOficinaSetupOvertakenByDisconnect(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("connect: %d %s", r.Code, r.Body)
+ }
+ first := liveDevice(t, f)
+ done, release := startHeldSetup(t, app, f)
+ if r := app.post("/ask/disconnect", nil); r.Code != 303 {
+ t.Fatalf("disconnect: %d", r.Code)
+ }
+ release()
+ wantBody(t, "overtaken set-up", <-done, 409, `{"state":"superseded"}`)
+ made := newDevice(t, f, []string{first})
+ if n := app.equipoLinks(); n != 0 || !f.Revoked(first) || !f.Revoked(made) {
+ t.Fatalf("links %d, first revoked %v, new revoked %v", n, f.Revoked(first), f.Revoked(made))
+ }
+ if hosts := f.Hosts(); len(hosts) != 1 {
+ t.Errorf("hosts registered: %d", len(hosts))
+ }
+ if s, _ := app.askState(); s.State != "connect" {
+ t.Errorf("state: %s", s.State)
+ }
+}
+
+// A set-up that the web's code flow overtakes saves nothing and revokes
+// its device; the web's connection stays, the one live device.
+func TestAskOficinaSetupOvertakenByWebConnect(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ done, release := startHeldSetup(t, app, f)
+ web.approveEquipo(f)
+ webDevice := liveDevice(t, f)
+ release()
+ wantBody(t, "overtaken set-up", <-done, 409, `{"state":"superseded"}`)
+ made := newDevice(t, f, []string{webDevice})
+ if live := liveDevice(t, f); live != webDevice || !f.Revoked(made) {
+ t.Fatalf("live %s (web %s), new revoked %v", live, webDevice, f.Revoked(made))
+ }
+ if n := app.equipoLinks(); n != 1 {
+ t.Errorf("links: %d", n)
+ }
+ s, r := app.askState()
+ if s.State != "ready" || !strings.Contains(r.Body, `"renew_after":""`) {
+ t.Errorf("state: %s", r.Body)
+ }
+ if sent := app.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {"w-1"}}); sent.Code != 200 {
+ t.Errorf("send on the web's key: %d %s", sent.Code, sent.Body)
+ }
+}
+
+// A renewal revokes the device it replaces, read as it saves, ready or
+// not: here a key Base no longer uses (it expired here first) but Equipo
+// would still take.
+func TestAskOficinaRenewRevokesWhatItReplaces(t *testing.T) {
+ _, app, f := newNativeAskApp(t)
+ f.LinkOficinaID("subject-owner", ownerAddress)
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("connect: %d %s", r.Code, r.Body)
+ }
+ first := liveDevice(t, f)
+ if _, err := app.DB.Exec(`UPDATE equipo_links SET expires_at = ?`, time.Now().Add(-time.Minute).UTC()); err != nil {
+ t.Fatal(err)
+ }
+ if s, _ := app.askState(); s.State != "reconnect" {
+ t.Fatalf("state: %s", s.State)
+ }
+ if r := app.connectWithOficina(f, "subject-owner"); r.Code != 200 {
+ t.Fatalf("renew: %d %s", r.Code, r.Body)
+ }
+ if !f.Revoked(first) {
+ t.Fatal("the replaced device is still live in Equipo")
+ }
+ liveDevice(t, f)
+}
diff --git a/internal/webtest/native_test.go b/internal/webtest/native_test.go
new file mode 100644
index 0000000..1641167
--- /dev/null
+++ b/internal/webtest/native_test.go
@@ -0,0 +1,274 @@
+package webtest
+
+import (
+ "bytes"
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/home/connect"
+ "amadan.net/oficina/home/handoff"
+ "amadan.net/rastrillo/rastrillo/assertion"
+ "amadan.net/rastrillo/rastrillo/sessions"
+)
+
+// The native app's Oficina ID session (Home spec 2026-11-14-oficina-id-native.md
+// §7): connect's NativeMethod, minted without a browser and handed to the
+// app, which sends it as the session cookie with Origin set to Base's own.
+
+// sessionCookie is the name of Base's session cookie at homeOrigin.
+const sessionCookie = "__Host-rastrillo_session"
+
+// storedSession writes a session row as rastrillo's store would have,
+// created at, and returns a browser carrying its cookie. It stands in for a
+// session minted some time ago.
+func (a *testApp) storedSession(subject, method string, at time.Time) *testApp {
+ a.t.Helper()
+ token, hash, err := sessions.NewToken()
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ if _, err := a.DB.Exec(`INSERT INTO sessions (token_hash, subject, method, auth_time, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?)`,
+ hash, subject, method, at.UTC().Format(time.RFC3339), at.UTC().Format(time.RFC3339), time.Now().Add(30*24*time.Hour).UTC().Format(time.RFC3339)); err != nil {
+ a.t.Fatal(err)
+ }
+ return a.withSession(token)
+}
+
+// withSession is a fresh browser that holds only the session token, as the
+// native app does: it sends the cookie itself.
+func (a *testApp) withSession(token string) *testApp {
+ a.t.Helper()
+ b := a.newBrowser()
+ u, _ := url.Parse(homeOrigin + "/")
+ b.client.Jar.SetCookies(u, []*http.Cookie{{Name: sessionCookie, Value: token, Path: "/", Secure: true, HttpOnly: true}})
+ return b
+}
+
+// nativeGet is a GET as the native app makes it: the cookie, Origin and
+// Accept: application/json, and no Sec-Fetch-Site.
+func (a *testApp) nativeGet(target string) Resp {
+ a.t.Helper()
+ req, _ := http.NewRequest(http.MethodGet, a.base+target, nil)
+ req.Header.Set("Origin", homeOrigin)
+ req.Header.Set("Accept", "application/json")
+ return a.do(req)
+}
+
+// nativePost is a JSON POST as the native app makes it.
+func (a *testApp) nativePost(target, body string) Resp {
+ a.t.Helper()
+ req, _ := http.NewRequest(http.MethodPost, a.base+target, strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Origin", homeOrigin)
+ req.Header.Set("Accept", "application/json")
+ return a.do(req)
+}
+
+func TestNativeSessionIsAMember(t *testing.T) {
+ a := newHomeApp(t)
+ a.link(ownerAddress, "subject-owner")
+ b := a.storedSession("subject-owner", connect.NativeMethod, time.Now().Add(-time.Hour))
+ if r := b.get("/"); r.Code != 200 {
+ t.Fatalf("native session, GET /: %d %q", r.Code, r.Location())
+ }
+ if r := b.get("/settings"); r.Code != 200 || !strings.Contains(r.Body, ownerAddress) {
+ t.Fatalf("native session, GET /settings: %d", r.Code)
+ }
+ // A subject with no link names nobody.
+ if r := a.storedSession("subject-stranger", connect.NativeMethod, time.Now()).get("/"); r.Code != http.StatusForbidden {
+ t.Errorf("unlinked native session, GET /: %d", r.Code)
+ }
+}
+
+// Seven days after it was minted, however recently used, the native session
+// opens nothing (connect.Expired): the app mints a new one long before.
+func TestNativeSessionExpiresAfterSevenDays(t *testing.T) {
+ a := newHomeApp(t)
+ a.link(ownerAddress, "subject-owner")
+ if r := a.storedSession("subject-owner", connect.NativeMethod, time.Now().Add(-connect.NativeLifetime+time.Minute)).get("/"); r.Code != 200 {
+ t.Fatalf("a native session just short of seven days: %d", r.Code)
+ }
+ old := a.storedSession("subject-owner", connect.NativeMethod, time.Now().Add(-connect.NativeLifetime-time.Second))
+ for _, p := range []string{"/", "/settings"} {
+ if r := old.get(p); r.Code == 200 {
+ t.Errorf("a native session past seven days, GET %s: %d", p, r.Code)
+ }
+ }
+ // A browser Home session of the same age is the store's to expire.
+ if r := a.storedSession("subject-owner", connect.HomeMethod, time.Now().Add(-connect.NativeLifetime-time.Hour)).get("/"); r.Code != 200 {
+ t.Errorf("a browser Oficina session of eight days: %d", r.Code)
+ }
+}
+
+// A passkey is filed under the session's subject; for every Home-derived
+// session that is the Oficina account, so none may add one.
+func TestOwnSignInOnlyRefusesNativeSessions(t *testing.T) {
+ a := newHomeApp(t)
+ a.link(ownerAddress, "subject-owner")
+ b := a.storedSession("subject-owner", connect.NativeMethod, time.Now())
+ if r := b.nativePost("/passkey/register/begin", "{}"); r.Code != http.StatusForbidden {
+ t.Errorf("register from a native session: %d", r.Code)
+ }
+ // Settings offers no passkey to a native session, and lists the
+ // member's own by address.
+ if body := b.get("/settings").Body; strings.Contains(body, "data-passkey-add") {
+ t.Errorf("settings offers a passkey to a native session")
+ }
+}
+
+// nativeAnswer is POST /native/oficina-id's JSON answer.
+type nativeAnswer struct {
+ State string `json:"state"`
+ Name string `json:"name"`
+ Value string `json:"value"`
+ ExpiresAt int64 `json:"expires_at"`
+}
+
+// nativeAssertion is what id.oficina gives the native app for Base: an
+// assertion for subject whose nonce is derived from verifier's challenge.
+func (a *testApp) nativeAssertion(subject, audience string) (token, verifier string) {
+ a.t.Helper()
+ raw := make([]byte, 32)
+ if _, err := rand.Read(raw); err != nil {
+ a.t.Fatal(err)
+ }
+ verifier = base64.RawURLEncoding.EncodeToString(raw)
+ challenge, _ := handoff.NativeChallenge(verifier)
+ nonce, _ := handoff.NativeNonce(challenge)
+ now := time.Now().Unix()
+ jti, err := assertion.RandomID()
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ token, err = assertion.Sign(a.home.key, assertion.Claims{Version: 1, Issuer: homeIssuer, Audience: audience, Subject: subject,
+ KeyID: homeKeyID, ID: jti, Nonce: nonce, IssuedAt: now, ExpiresAt: now + 90, AuthTime: now - 60})
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ return token, verifier
+}
+
+// nativeExchange posts what the native app posts: JSON, no Origin, no
+// Sec-Fetch-Site, no cookies.
+func (a *testApp) nativeExchange(subject string) (Resp, nativeAnswer) {
+ a.t.Helper()
+ token, verifier := a.nativeAssertion(subject, homeOrigin)
+ body, _ := json.Marshal(map[string]string{"assertion": token, "verifier": verifier})
+ req, _ := http.NewRequest(http.MethodPost, homeOrigin+connect.NativeExchangePath, bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ r := a.newBrowser().do(req)
+ if len(r.Header.Values("Set-Cookie")) != 0 {
+ a.t.Fatalf("the native exchange set a cookie: %q", r.Header.Values("Set-Cookie"))
+ }
+ var answer nativeAnswer
+ if err := json.Unmarshal([]byte(r.Body), &answer); err != nil {
+ a.t.Fatalf("exchange answer %d %q: %v", r.Code, r.Body, err)
+ }
+ return r, answer
+}
+
+// nativeSignIn is a linked member's native app, signed in: a browser that
+// holds only the minted session.
+func (a *testApp) nativeSignIn(subject string) *testApp {
+ a.t.Helper()
+ r, answer := a.nativeExchange(subject)
+ if r.Code != 200 || answer.State != "ok" {
+ a.t.Fatalf("native exchange: %d %s", r.Code, r.Body)
+ }
+ return a.withSession(answer.Value)
+}
+
+func TestNativeExchangeMintsASession(t *testing.T) {
+ a := newHomeApp(t)
+ a.link(ownerAddress, "subject-owner")
+ r, answer := a.nativeExchange("subject-owner")
+ if r.Code != 200 || answer.State != "ok" || answer.Name != sessionCookie || answer.Value == "" {
+ t.Fatalf("exchange: %d %s", r.Code, r.Body)
+ }
+ if want := time.Now().Add(connect.NativeLifetime).Unix(); answer.ExpiresAt < want-60 || answer.ExpiresAt > want+60 {
+ t.Errorf("expires_at %d, want about %d", answer.ExpiresAt, want)
+ }
+ if r.Header.Get("Cache-Control") != "no-store" {
+ t.Errorf("Cache-Control %q", r.Header.Get("Cache-Control"))
+ }
+ var method string
+ if err := a.DB.QueryRow(`SELECT method FROM sessions WHERE token_hash = ?`, sessions.HashToken(answer.Value)).Scan(&method); err != nil || method != connect.NativeMethod {
+ t.Fatalf("stored session method %q, %v", method, err)
+ }
+ if home := a.withSession(answer.Value).get("/"); home.Code != 200 {
+ t.Fatalf("the minted session, GET /: %d %q", home.Code, home.Location())
+ }
+ if me := a.withSession(answer.Value).nativeGet("/api/v1/me"); me.Code != 200 || !strings.Contains(me.Body, ownerAddress) {
+ t.Fatalf("the minted session, GET /api/v1/me: %d %s", me.Code, me.Body)
+ }
+}
+
+func TestNativeExchangeUnknownPerson(t *testing.T) {
+ a := newHomeApp(t)
+ a.link(ownerAddress, "subject-owner")
+ r, _ := a.nativeExchange("subject-stranger")
+ if r.Code != http.StatusForbidden || r.Body != `{"state":"unknown"}` {
+ t.Fatalf("unlinked subject: %d %s", r.Code, r.Body)
+ }
+}
+
+// The exchange is not a browser route: a request carrying a browser's
+// Origin or Sec-Fetch-Site is refused by the exchange itself.
+func TestNativeExchangeRefusesBrowsers(t *testing.T) {
+ a := newHomeApp(t)
+ a.link(ownerAddress, "subject-owner")
+ for _, h := range [][2]string{{"Origin", homeOrigin}, {"Origin", "https://evil.test"}, {"Sec-Fetch-Site", "same-origin"}} {
+ token, verifier := a.nativeAssertion("subject-owner", homeOrigin)
+ body, _ := json.Marshal(map[string]string{"assertion": token, "verifier": verifier})
+ req, _ := http.NewRequest(http.MethodPost, homeOrigin+connect.NativeExchangePath, bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set(h[0], h[1])
+ if r := a.newBrowser().do(req); r.Code != http.StatusBadRequest || r.Body != `{"state":"invalid"}` {
+ t.Errorf("with %s: %s: %d %s", h[0], h[1], r.Code, r.Body)
+ }
+ }
+ // An assertion for another audience is not accepted.
+ token, verifier := a.nativeAssertion("subject-owner", "https://docs.acme.test")
+ body, _ := json.Marshal(map[string]string{"assertion": token, "verifier": verifier})
+ req, _ := http.NewRequest(http.MethodPost, homeOrigin+connect.NativeExchangePath, bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ if r := a.newBrowser().do(req); r.Code != http.StatusUnauthorized {
+ t.Errorf("another audience: %d %s", r.Code, r.Body)
+ }
+}
+
+// POST /signout is the native app's sign-out: it ends the session it
+// carries, whatever its method, and nothing else.
+func TestSignoutEndsTheNativeSession(t *testing.T) {
+ a := newHomeApp(t)
+ a.link(ownerAddress, "subject-owner")
+ app := a.nativeSignIn("subject-owner")
+ other := a.nativeSignIn("subject-owner")
+ if r := app.nativePost("/signout", "{}"); r.Code != http.StatusNoContent {
+ t.Fatalf("native signout: %d %q", r.Code, r.Body)
+ }
+ if r := app.get("/"); r.Code == 200 {
+ t.Fatalf("the signed-out native session still opens Home")
+ }
+ if r := other.get("/"); r.Code != 200 {
+ t.Errorf("another device's session ended too: %d", r.Code)
+ }
+ // From another site it is refused, as every POST is.
+ if r := other.postFrom("https://evil.test", "/signout", nil); r.Code != http.StatusForbidden {
+ t.Errorf("cross-site signout: %d", r.Code)
+ }
+ // A browser form lands on the signed-out page.
+ a.signedInOwner()
+ if r := a.post("/signout", nil); r.Code != http.StatusSeeOther || r.Location() != "/signed-out" {
+ t.Errorf("browser signout: %d %q", r.Code, r.Location())
+ }
+ if r := a.get("/"); r.Code == 200 {
+ t.Errorf("the browser session survived /signout")
+ }
+}
diff --git a/internal/webtest/oficina_harness_test.go b/internal/webtest/oficina_harness_test.go
index e4767f6..738d629 100644
--- a/internal/webtest/oficina_harness_test.go
+++ b/internal/webtest/oficina_harness_test.go
@@ -53,7 +53,10 @@ type oficina struct {
// newHomeApp builds Base exactly as main.go does with every BASE_HOME_*
// setting present, with an assertion key so it can hand off to apps too.
-func newHomeApp(t *testing.T) *testApp {
+func newHomeApp(t *testing.T) *testApp { return newHomeAppWith(t, nil) }
+
+// newHomeAppWith is newHomeApp with a last say over the configuration.
+func newHomeAppWith(t *testing.T, tweak func(*config.Config)) *testApp {
t.Helper()
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
d, err := db.Open(homeSchema.Path(t), logger)
@@ -83,6 +86,9 @@ func newHomeApp(t *testing.T) *testApp {
}
cfg := config.Config{Origin: homeOrigin, Name: "Acme", Owner: ownerAddress, InstanceKey: "test-instance-key", AllowLoggedMail: true,
Slug: "acme", AppsDomain: "bab.oncarlos.com", Timezone: time.UTC, AssertionKey: signing, Home: home}
+ if tweak != nil {
+ tweak(&cfg)
+ }
mailer := &capturingMailer{}
h, err := web.App(d, cfg, mailer, noInstaller{}, logger)
if err != nil {
diff --git a/internal/webtest/oficina_origin_test.go b/internal/webtest/oficina_origin_test.go
new file mode 100644
index 0000000..74c6fba
--- /dev/null
+++ b/internal/webtest/oficina_origin_test.go
@@ -0,0 +1,222 @@
+package webtest
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/home/connect/linkstore"
+
+ "amadan.net/carlos/base/internal/store"
+)
+
+// Moving Base to another BASE_ORIGIN. connect stamps each Oficina ID link
+// with Base's origin (its person binding), so a link made at the old origin
+// resolves nobody at the new one, and would block linking again. Base
+// treats such a link as gone: the member links again, proving who they are
+// by email as at first, and the dead link makes way for the new one.
+
+// oldOrigin is where Base ran before the move.
+const oldOrigin = "https://base.old.test"
+
+// linkAtOldOrigin stores the link connect would have made between email's
+// member and subject while Base ran at oldOrigin: the same key, issuer and
+// namespace, another origin. It is connect's own carry-over (Adopt), so the
+// row is exactly the one linking there wrote.
+func (a *testApp) linkAtOldOrigin(email, subject string) {
+ a.t.Helper()
+ ctx := context.Background()
+ old, err := linkstore.New(a.DB, bytes.Repeat([]byte{9}, 32), oldOrigin, homeIssuer, "carlos/base",
+ func(ctx context.Context, q linkstore.Queryer, n int64) (string, error) {
+ return store.MemberAddress(ctx, q, n)
+ })
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ m, ok, err := store.MemberByEmail(ctx, a.DB, email)
+ if err != nil || !ok {
+ a.t.Fatalf("member %s: %v", email, err)
+ }
+ n, err := store.MemberNumber(ctx, a.DB, m.ID)
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ tx, err := a.DB.BeginTx(ctx, nil)
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ defer tx.Rollback()
+ if err := old.Adopt(ctx, tx, homeIssuer, subject, n); err != nil {
+ a.t.Fatal(err)
+ }
+ if err := tx.Commit(); err != nil {
+ a.t.Fatal(err)
+ }
+ // At the old origin it resolves; here it does not.
+ if _, _, err := old.Resolve(ctx, homeIssuer, subject); err != nil {
+ a.t.Fatalf("the old link does not resolve at the old origin: %v", err)
+ }
+}
+
+// linkRows is how many Oficina ID links name email's member.
+func (a *testApp) linkRows(email string) int {
+ a.t.Helper()
+ var n int
+ if err := a.DB.QueryRow(`SELECT count(*) FROM home_identity_links l JOIN member_numbers n ON n.number = l.person_id
+ JOIN members m ON m.id = n.member_id WHERE m.email = ?`, email).Scan(&n); err != nil {
+ a.t.Fatal(err)
+ }
+ return n
+}
+
+// The move itself: the old link refuses Oficina sign-in, as it must, and
+// the member links again the way an unlinked member does (Oficina, then
+// email once), after which Oficina ID signs them in.
+func TestOficinaLinkFromAnOldOriginLinksAgain(t *testing.T) {
+ a := newHomeApp(t)
+ a.linkAtOldOrigin(ownerAddress, "subject-owner")
+
+ unknown := a.signInWithOficina("subject-owner")
+ if unknown.Code != http.StatusForbidden || !strings.Contains(unknown.Body, "Oficina account not connected") {
+ t.Fatalf("Oficina sign-in on a link from the old origin: %d\n%s", unknown.Code, unknown.Body)
+ }
+ r := a.signIn(ownerAddress)
+ resume := a.get(r.Location())
+ if resume.Code != 303 || !strings.HasPrefix(resume.Location(), "/auth/start") {
+ t.Fatalf("local sign-in did not resume the link: %d %q", resume.Code, resume.Location())
+ }
+ a.confirmLink(a.atOficina(a.get(resume.Location()), "subject-owner", 30*time.Second), ownerAddress)
+ if n := a.linkRows(ownerAddress); n != 1 {
+ t.Fatalf("links: %d", n)
+ }
+ b := a.newBrowser()
+ if fin := b.signInWithOficina("subject-owner"); fin.Code != 303 || fin.Location() != "/" {
+ t.Fatalf("Oficina sign-in after linking again: %d %q\n%s", fin.Code, fin.Location(), fin.Body)
+ }
+ if home := b.get("/"); home.Code != 200 {
+ t.Fatalf("Home: %d", home.Code)
+ }
+ if body := a.get("/settings").Body; strings.Contains(body, `href="/account/home"`) {
+ t.Errorf("Settings still offers Connect:\n%s", body)
+ }
+}
+
+// Settings no longer says the dead link is connected: it offers Connect,
+// and connecting from there works too.
+func TestOficinaLinkFromAnOldOriginConnectsFromSettings(t *testing.T) {
+ a := newHomeApp(t)
+ a.linkAtOldOrigin(ownerAddress, "subject-owner")
+ a.link(ownerAddress, "subject-owner") // fails unless Settings offers Connect and the confirm goes through
+ if n := a.linkRows(ownerAddress); n != 1 {
+ t.Fatalf("links: %d", n)
+ }
+ if fin := a.newBrowser().signInWithOficina("subject-owner"); fin.Code != 303 || fin.Location() != "/" {
+ t.Fatalf("Oficina sign-in: %d %q", fin.Code, fin.Location())
+ }
+}
+
+// A link that still resolves is never replaced: another Oficina ID can't
+// take a linked member over, even with their email.
+func TestOficinaLiveLinkIsNotReplaced(t *testing.T) {
+ a := newHomeApp(t)
+ a.link(ownerAddress, "subject-owner")
+ if body := a.get("/settings").Body; strings.Contains(body, `href="/account/home"`) {
+ t.Fatalf("Settings offers Connect to a linked member")
+ }
+ toIssuer := a.get(a.post("/account/home", nil).Location())
+ finish := a.atOficina(toIssuer, "subject-intruder", 30*time.Second)
+ if finish.Code != 303 || finish.Location() != "/account/home/confirm" {
+ t.Fatalf("link finish: %d %q", finish.Code, finish.Location())
+ }
+ if r := a.post("/account/home/confirm", nil); r.Code != http.StatusForbidden {
+ t.Fatalf("confirming a second Oficina ID: %d %q", r.Code, r.Location())
+ }
+ if fin := a.newBrowser().signInWithOficina("subject-owner"); fin.Code != 303 {
+ t.Errorf("the live link stopped working: %d", fin.Code)
+ }
+ if fin := a.newBrowser().signInWithOficina("subject-intruder"); fin.Code != http.StatusForbidden {
+ t.Errorf("the other Oficina ID signs in: %d", fin.Code)
+ }
+}
+
+// Linking again clears only the member's own dead link: another member's
+// dead link to the same Oficina ID stays, and the confirm is refused.
+func TestOficinaOldLinkOfAnotherMemberStays(t *testing.T) {
+ a := newHomeApp(t)
+ if _, _, err := store.Invite(context.Background(), a.DB, "ana@acme.test"); err != nil {
+ t.Fatal(err)
+ }
+ a.linkAtOldOrigin("ana@acme.test", "subject-shared")
+ a.signedInOwner()
+ toIssuer := a.get(a.post("/account/home", nil).Location())
+ a.atOficina(toIssuer, "subject-shared", 30*time.Second)
+ if r := a.post("/account/home/confirm", nil); r.Code != http.StatusForbidden {
+ t.Fatalf("the owner took Ana's Oficina ID: %d %q", r.Code, r.Location())
+ }
+ if a.linkRows("ana@acme.test") != 1 || a.linkRows(ownerAddress) != 0 {
+ t.Fatalf("links: ana %d, owner %d", a.linkRows("ana@acme.test"), a.linkRows(ownerAddress))
+ }
+}
+
+// Nothing but the member's own fresh email sign-in clears a dead link:
+// not a signed-out POST, nor a POST from another site, nor an old sign-in.
+func TestOficinaOldLinkClearedOnlyByTheMember(t *testing.T) {
+ a := newHomeApp(t)
+ a.linkAtOldOrigin(ownerAddress, "subject-owner")
+ before := a.linkRow(ownerAddress)
+ unchanged := func(what string) {
+ t.Helper()
+ if after := a.linkRow(ownerAddress); after != before {
+ t.Fatalf("%s changed the dead link: %q, was %q", what, after, before)
+ }
+ }
+ if r := a.postFrom(homeIssuer, "/account/home/confirm", url.Values{}); r.Code != http.StatusForbidden {
+ t.Fatalf("signed-out cross-site confirm: %d", r.Code)
+ }
+ unchanged("a signed-out cross-site confirm")
+ if r := a.post("/account/home/confirm", nil); r.Code == http.StatusOK {
+ t.Fatalf("signed-out confirm: %d", r.Code)
+ }
+ unchanged("a signed-out confirm")
+ // The owner freshly signed in by email, and a page on another site
+ // posting the confirm in their browser: refused before anything is
+ // cleared.
+ a.signedInOwner()
+ if r := a.postFrom(homeIssuer, "/account/home/confirm", url.Values{}); r.Code != http.StatusForbidden {
+ t.Fatalf("signed-in cross-site confirm: %d", r.Code)
+ }
+ unchanged("a signed-in cross-site confirm")
+}
+
+// linkRow is the Oficina ID link naming email's member, as stored.
+func (a *testApp) linkRow(email string) string {
+ a.t.Helper()
+ var subject, binding string
+ var person int64
+ if err := a.DB.QueryRow(`SELECT l.subject, l.person_id, l.person_binding FROM home_identity_links l
+ JOIN member_numbers n ON n.number = l.person_id JOIN members m ON m.id = n.member_id WHERE m.email = ?`, email).
+ Scan(&subject, &person, &binding); err != nil {
+ a.t.Fatalf("link row for %s: %v", email, err)
+ }
+ return fmt.Sprintf("%s/%d/%s", subject, person, binding)
+}
+
+// An email sign-in older than connect's five minutes clears nothing.
+func TestOficinaOldLinkNeedsAFreshSignIn(t *testing.T) {
+ a := newHomeApp(t)
+ a.linkAtOldOrigin(ownerAddress, "subject-owner")
+ a.signedInOwner()
+ old := time.Now().Add(-10 * time.Minute).UTC().Format(time.RFC3339)
+ if _, err := a.DB.Exec(`UPDATE sessions SET created_at = ?, auth_time = ?`, old, old); err != nil {
+ t.Fatal(err)
+ }
+ a.post("/account/home/confirm", nil)
+ if n := a.linkRows(ownerAddress); n != 1 {
+ t.Fatalf("an old sign-in cleared the link: %d", n)
+ }
+}