oficina / base Public

Merge branch 'native/slice-1-server' into main

Merge branch 'native/slice-1-server' into main

Base native slice 1, server half (plan Tasks 3-7): native Oficina ID
sessions, POST /native/oficina-id and /signout, GET /api/v1/me and
/api/v1/home, Ask's JSON contract pinned (docs/api/base-native-v1.md),
and Ask set up with Oficina ID through Equipo's own native sign-in.
Brings the native design spec and plan with it.

Reviewed by Codex Astra in three rounds (approved at bffe609); make ci
green at each round.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 3f8e6d1e3165573bf9289586af48ebb53b76796f parent d8700cfparent bffe609
28 files changed, +3,593 −130
  • README.md +18 −0
  • docs/api/base-native-v1.md +240 −0
  • docs/superpowers/plans/2026-11-23-base-native-slice1.md +370 −0
  • docs/superpowers/specs/2026-11-23-base-native-design.md +278 −0
  • go.mod +5 −4
  • 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/equipo.go +3 −3
  • internal/store/hosttokens_test.go +1 −1
  • internal/web/api.go +148 −0
  • internal/web/app.go +68 −16
  • internal/web/ask.go +36 −16
  • internal/web/ask_connect.go +111 −46
  • internal/web/ask_oficina_native.go +196 −0
  • internal/web/ask_relay.go +3 −2
  • internal/web/home.go +51 −29
  • internal/web/oficina.go +9 −1
  • internal/web/settings.go +1 −1
  • internal/webtest/api_test.go +190 −0
  • internal/webtest/ask_link_race_test.go +232 −0
  • internal/webtest/ask_native_contract_test.go +483 −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
diff --git a/README.md b/README.md
index 876de92..9eeabb7 100644
--- a/README.md
+++ b/README.md
@@ -88,6 +88,24 @@ 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.
+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..9bc4f88
--- /dev/null
+++ b/docs/api/base-native-v1.md
@@ -0,0 +1,240 @@
+# 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"}
+```
+
+- `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.
+
+**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. It answers `303 /settings`.
+
+## Ask set-up with Oficina ID
+
+### `POST /api/v1/ask/oficina`
+
+JSON `{"assertion", "verifier"}`: an assertion the kit fetched from Oficina
+ID addressed to `equipo_origin`, and its verifier. 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":"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 or missing field, 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/docs/superpowers/plans/2026-11-23-base-native-slice1.md b/docs/superpowers/plans/2026-11-23-base-native-slice1.md
new file mode 100644
index 0000000..7c0aa72
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-23-base-native-slice1.md
@@ -0,0 +1,370 @@
+# Base on the Mac and iPhone, slice 1: Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** A person signs in to Base on a Mac or an iPhone with Oficina ID, going straight in when another Oficina app holds the ID. Ask Base works at once, with no code to approve in Equipo. They talk to the Assistant, see and answer their jobs, and open their apps. On the Mac, Ask is also a menu-bar panel and an optional global shortcut.
+
+**Architecture:**
+- **Base's server** becomes a native Oficina ID consumer. It mounts connect's `NativeExchange`, mints the 7-day native session, and accepts it everywhere a Home session is accepted. It also gains two small JSON reads, `GET /api/v1/me` and `GET /api/v1/home`. Ask's routes already answer JSON and SSE for `ask.js`, so the native app uses them as they are.
+- **Ask set-up uses Oficina ID.** The app fetches a second Home assertion addressed to Equipo and posts it to Base. Base's server completes Equipo's own native sign-in on the person's behalf: `POST /native/oficina-id`, then `POST /api/v1/auth/devices/native`. It seals the resulting Equipo key exactly where the code flow puts it today. No Equipo change.
+- **The native app** lives in `native/` and is built on RastrilloApple, like Equipo's. It has one SwiftUI package, `BaseKit` (look, API client, Ask, Home), a SwiftPM Mac executable, and an xcodegen iPhone project.
+
+**Tech Stack:**
+- Server: Go (`GOTOOLCHAIN=go1.26.11`, `CGO_ENABLED=0`), chi, rastrillo, Home's `connect` module.
+- Native: Swift 6.2 / SwiftUI, macOS 26 and iOS 26, RastrilloApple (Oficina ID, NativeHTTP, quiet Sparkle updates), swift-cmark, and KeyboardShortcuts (MIT) for the Mac shortcut.
+
+**Spec:** `docs/superpowers/specs/2026-11-23-base-native-design.md` (binding, with Paul's picks of 2026-11-23: Mac window B, iPhone Ask first, Ask set up at sign-in). Approved look: `.superpowers/mockups/native/` (git-ignored; `python3 build.py`).
+
+**Repositories and branches:**
+
+| Repo | Tasks | Branch |
+|---|---|---|
+| **rastrillo/native** | 1 | `base-kit` from `origin/main` `0254817` |
+| **Home** (oficina/home) | 2 | `base-native-app-id` from `origin/main` `8125a3c` |
+| **Base** (this repo) | 3 to 16 | `native/slice-1` from `origin/main` `d8700cf` |
+| Controller | 17 | copy review, operator steps with Paul, live check, release |
+
+**Equipo** needs no change (checked at `00d09aa7`; see P1).
+
+## Plan decisions
+
+- **P1. Equipo's key from Oficina ID lasts 7 days.**
+ - **How it's minted:** Equipo's native exchange (`oficinaid/native.go:56-104`) and `POST /api/v1/auth/devices/native` (`native_device.go`).
+ - **What it is:** the same `PersonCredential` (audience `equipo.person.v1`) as the code flow, so the relay and `PUT /api/v1/assistant/host` work unchanged.
+ - **The catch:** it ends with the Equipo native session, 7 days after minting, and with any Equipo sign-out, relink or roster removal. The code flow's key lasts 30 days.
+ - **The rule:** Base stores the Equipo session cookie sealed beside the key, and never signs it out. Base tells the app `renew_after` (minted + 5 days). The app sends a fresh assertion the next time it starts or comes forward after that time, silently.
+ - **Web-only people** keep the code flow. Whichever key is newest is used.
+ - A 30-day Oficina ID key would need an Equipo policy change that `devices.go:280-284` deliberately rules out, so slice 1 doesn't ask for one.
+- **P2. Only people Equipo already links get Ask this way.** Equipo's exchange answers `403 unknown` for an Oficina ID it hasn't linked to a roster member. Base then shows Ask's existing "Ask Base isn't set up for you yet" state, with the code flow's button.
+- **P3. Base admits only people already linked in Base** (slice 1).
+ - `Admit`, `Unlinked` and `HomeOnly` stay unset, as on the web today.
+ - A person who has never signed in to Base with Oficina ID on the web gets the kit's "unknown" answer. Its copy points them to Base on the web once.
+ - Admitting an invited person straight from native is slice 2, with the team-mode hooks Docs uses.
+- **P4. Ask routes are reused, not copied.**
+ - The native client calls `/ask/state`, `/ask/events`, `/ask/messages`, `/ask/turns/{id}/cancel` and `/ask/cards/{id}/answer` with `Accept: application/json`. That's the same contract `ask.js` uses; the kit's `NativeHTTP` sends the session cookie and `Origin`, so CSRF passes.
+ - Task 6 writes the contract down (`docs/api/base-native-v1.md`) and pins it with tests. The web and native then can't drift apart.
+ - Unauthenticated JSON requests get `401 {"code":"unauthenticated"}`, never a redirect to `/signin`. The kit calls `sessionRejected()` on 401.
+- **P5. `/api/v1` is reads only:** `me` and `home`. Store, People and Settings changes stay on the web in slice 1 (spec 3.3, Paul 11-23). The Mac sidebar's Store and People rows open Base's web pages in the browser.
+- **P6. App metadata the API serves.** `GET /api/v1/home` gives each Oficina app its native bundle ID (`works.oficina.<id>`; Calls is `works.oficina.calls`) and, where the app has one, its URL scheme. Installed apps carry their tint and line-art SVG (the catalog's own); Oficina apps carry their icon's URL (`/static/oficina/<id>.svg`). The client never hard-codes an app.
+- **P7. One palette.** `BaseKit/Look/Palette.swift` holds Base's tokens (sky, fog, glass, sheet, pill, states, text) for light and dark. A test parses `internal/look/static/app.css` (`:root` and `:root[data-theme="light"]`) and fails if any mirrored token differs. The web and native look can't drift.
+- **P8. Timeless Sans in the app.** `hack/fonts.sh` already fetches the pinned file (git-ignored). The native build copies it into the bundle.
+ - **Release builds** refuse to run without it (`hack/fonts.sh check`).
+ - **Dev builds** fall back to DM Sans (committed, OFL), as the web does.
+ - The face is registered at launch, before the first frame, so nothing ever paints in a fallback face when the file is there. The Grotesk cut is the `STYL` axis at 0 (headings, wordmark); the Sans cut is `STYL` 100.
+- **P9. The sky** is a `TimelineView`-driven `Canvas`.
+ - **Light and fog:** two blurred beams and four blurred fog ellipses on the same paths and periods as `app.css` (`sway` 9 s and 13 s, `breathe` 6 s, `path-a/b/c` 10 to 17 s, `tint` 18 s), and the same sky gradient.
+ - **Reduce Motion** freezes it at the CSS's reduced-motion pose.
+ - **Performance:** it pauses when the window is hidden or the app inactive, and draws at 30 fps.
+- **P10. Glass** is a `.background` of the sheet or glass gradient over `.ultraThinMaterial`, with a 1 px top edge (`--glass-shine`) and a hairline border (`--glass-edge`). Text sits only on glass, never straight on the sky (spec 6, WCAG AA).
+- **P11. The shortcut** uses `KeyboardShortcuts` (sindresorhus, MIT; it's in the Colophon). It is off until the person records one (Paul 11-23). The menu-bar item is on by default, and Settings can switch it off.
+- **P12. Opening an Oficina app:**
+ - **Mac:** if `NSWorkspace.urlForApplication(withBundleIdentifier:)` finds the app and Settings says "The app", open it there. Otherwise open the app's web URL.
+ - **iPhone:** Calls by `oficina-calls://`, Equipo by its scheme (in `LSApplicationQueriesSchemes`), everything else on the web. Opening Docs, Sheets, Calendar and Memoria natively waits for the kit's `open` URL (Task 1) to reach their repins. Until then they open on the web.
+- **P13. Bundle ID `works.oficina.base`** (Paul 11-23), shown as "Oficina Base" in Finder, the Dock and Spotlight and as "Base" inside the app (D2). The app is version `0.1.0`.
+
+## File map (Base, new)
+
+```
+native/
+ .gitignore *.xcodeproj, generated Info.plists, Resources/Fonts/Timeless*
+ PrivacyInfo.xcprivacy
+ mac-updates.json Sparkle: bundle_id, feed_url …/native-releases/main/base/appcast.xml
+ apple/Package.swift BaseKit (library), BaseMac (executable)
+ apple/Sources/BaseKit/
+ Look/Palette.swift Look/Sky.swift Look/Glass.swift Look/Type.swift Look/Marks.swift
+ API/Client.swift API/Models.swift API/Events.swift
+ Ask/AskModel.swift Ask/Thread.swift Ask/Pill.swift Ask/Card.swift Ask/Composer.swift Ask/Markdown*.swift
+ Home/HomeModel.swift Home/AppIcon.swift Home/Opener.swift
+ Session/BaseSession.swift Session/AskSetup.swift
+ SignIn/BaseOnboarding.swift
+ apple/Sources/BaseMac/ BaseMacApp.swift MainWindow.swift Sidebar.swift MenuPanel.swift Settings*.swift Colophon.swift
+ apple/Sources/BasePhone/ (compiled by the xcodegen project) BasePhoneApp.swift AskScreen.swift AppsSheet.swift
+ apple/Tests/BaseKitTests/ PaletteTests ClientTests EventsTests AskModelTests AskSetupTests OpenerTests
+ ios/project.yml ios/BasePhone.entitlements ios/Assets.xcassets
+ macos/DeveloperID.entitlements
+ scripts/build-mac.sh scripts/build-iphone.sh scripts/check-native.sh scripts/snapshots.sh scripts/fonts-into-bundle.sh
+.amadan/ci.d/20-native check-native.sh on Darwin, --core-only elsewhere
+docs/api/base-native-v1.md
+```
+
+## Task 1 (rastrillo/native): the kit's three additions
+
+**Files:**
+- `Sources/RastrilloApple/OficinaID/OficinaIDModel.swift`
+- `Sources/RastrilloApple/OficinaID/OficinaAppearance.swift`
+- `Sources/RastrilloApple/NativeConnection.swift`
+- their tests
+
+- [ ] **Step 1: tests first.**
+ - `OficinaIDModelAssertionTests`: `assertion(for:)` returns an assertion and its verifier for any audience; it uses the model's own service (shared clock-skew); a `grantEnded` error ends the grant through `grantEnded()` exactly as `mint` does.
+ - `OficinaAppTests`: `.base` has its symbol and accents.
+ - `NativeConnectionOpenURLTests`: `handleOpenURL` accepts `<scheme>://open` (and `…://open?path=/x` where `path` is a relative path on the app's own origin), and still ignores anything else.
+- [ ] **Step 2: implement.**
+ - `public func assertion(for audience: URL) async throws -> (assertion: String, verifier: String)` on `OficinaIDModel`, reusing `service` and the signed-in identity's credential.
+ - The `OficinaApp.base` case: symbol `square.fill` (`circle.grid.2x2` if that reads better at 16 pt); accent `#2FC6C0`, accentSoft `#6EE7DC` (Base's lagoon and signal).
+ - The `open` action on `NativeConnection.handleOpenURL`. It brings the app forward and, with `path`, hands the path to a new optional `onOpen` closure.
+- [ ] **Step 3:** run `swift test`; check that the snapshot gate is unchanged (nothing iterates `OficinaApp`). Push, ask for review, and merge on the hub with `amadan branch merge`. Record the merge commit for Task 7's pin.
+
+## Task 2 (Home): Base's app ID can use passkeys
+
+**Files:**
+- `internal/home/native_passkey.go:287-294` (`nativeAppIDs`)
+- its test
+
+- [ ] Add `9U4A84C4WK.works.oficina.base` to `nativeAppIDs`. The test asserts the AASA `webcredentials.apps` list contains it.
+- [ ] `make ci`, push, review, merge. Deploying waits for the controller (Task 17), with Home's usual promote and restart (see Home's deploy notes).
+
+## Task 3 (Base): connect bump and native sessions recognised
+
+**Files:**
+- `go.mod`, `go.sum`
+- `internal/web/app.go:261-310` (`requireMember`, `memberFor`, `ownSignInOnly`)
+- `internal/web/oficina.go`
+- tests in `internal/webtest`
+
+- [ ] **Step 1:** bump `amadan.net/oficina/home/connect` (and `handoff`) to Home `origin/main`. Fix any compile changes. `make ci` green before going on.
+- [ ] **Step 2: tests.**
+ - `TestNativeSessionIsAMember`: a session with method `connect.NativeMethod` for a linked member reaches `/`.
+ - `TestNativeSessionExpiresAfterSevenDays`: the same session 7 days and 1 second after `At` is refused.
+ - `TestOwnSignInOnlyRefusesNativeSessions`: passkey registration refuses a native session, as it refuses a Home one.
+- [ ] **Step 3:** replace every `s.Method == connect.HomeMethod` with `connect.IsHomeDerived(s.Method)`, and check `connect.Expired(s, now)` wherever Base resolves a Home-derived session itself.
+
+## Task 4 (Base): the native exchange and `/signout`
+
+**Files:**
+- `internal/web/oficina.go`, `internal/web/app.go`
+- tests in `internal/webtest`
+
+- [ ] **Step 1: tests,** driving the exchange with connect's test helpers (a signed assertion for Base's origin, as Docs' `home_native_test.go` does):
+ - `TestNativeExchangeMintsASession`: the answer is `200 {state:"ok", name:"__Host-rastrillo_session", value, expires_at}`, and the value opens `/api/v1/me`.
+ - `TestNativeExchangeUnknownPerson`: `403 {state:"unknown"}` for an unlinked subject.
+ - `TestNativeExchangeRefusesBrowsers`: `Origin` or `Sec-Fetch-Site` gets a 400.
+ - `TestSignoutEndsTheNativeSession`: `POST /signout` with the cookie and `Origin: <base origin>` ends the session, and the cookie no longer opens anything.
+- [ ] **Step 2: implement.**
+ - Set `Config.MintNativeSession` to `sess.Mint` with `NativeMethod`; the store keeps `At`.
+ - Mount `r.Post(connect.NativeExchangePath, o.bridge.NativeExchange)` outside CSRF; connect's Middleware already exempts it.
+ - Mount `r.Post("/signout", …)`, which ends the current session (any method) and answers 204 to JSON, or a 303 to `/signed-out`.
+ - Don't mount `/native/web/end` (Home slice D). The kit treats its failure as harmless.
+
+## Task 5 (Base): `GET /api/v1/me` and `GET /api/v1/home`
+
+**Files:**
+- `internal/web/api.go` (new), `internal/web/app.go`
+- `internal/config/oficina.go` (bundle IDs, schemes)
+- tests
+
+- [ ] **Step 1: tests.**
+ - `TestAPIMe`: `{member:{id,name,email,initials,owner}, base:{name,slug,origin,timezone}, appearance:"system|light|dark", equipo_origin:"…"|null}`.
+ - `TestAPIHome`: `{greeting, lede, steps:[{label,done}], apps:[{id,kind:"oficina"|"installed"|"own",name,url,icon_url?,tint?,icon_svg?,bundle_id?,scheme?}]}`, in Home's order. Own pages carry Base's web URLs.
+ - `TestAPIRefusesWithoutSession`: `401 {"code":"unauthenticated"}`, `Cache-Control: no-store`, no redirect.
+- [ ] **Step 2: implement**, reusing `home.go`'s builders (move the tile and step building into one function both use, so Home and the API can't disagree). Mount under `requireMember`. Make `requireMember` answer 401 JSON for `/api/` paths and for any request with `Accept: application/json` (this covers the Ask routes).
+
+## Task 6 (Base): Ask's JSON contract, written down and pinned
+
+**Files:**
+- `docs/api/base-native-v1.md` (new)
+- `internal/webtest/ask_native_contract_test.go` (new)
+
+- [ ] **Step 1:** document what `ask.js` already relies on. Read it from `ask.js`, `ask.go`, `ask_relay.go` and `ask_cards.go`; don't invent anything. Cover:
+ - `/ask/state` (`state`, `messages`, `jobs`, `cards`, `turn`, `status`, `cursor`);
+ - `/ask/events?after=` (SSE event types and their `data`);
+ - `/ask/messages` (`text`, `key`);
+ - cancel and answer (`choice`, `revision`, `key`), their status codes and error bodies.
+- [ ] **Step 2:** contract tests that make each call the way the native client will. Each carries the native session cookie, `Origin`, and `Accept: application/json`, and no `Sec-Fetch-Site`. Each asserts the documented shape against `equipotest`'s fake Equipo. Any shape `ask.js` changes later now breaks a test.
+
+## Task 7 (Base): Ask set up with Oficina ID
+
+**Files:**
+- `internal/equipo/equipo.go`: add `NativeExchange(ctx, assertion, verifier) (cookie, expires, error)` and `RegisterNative(ctx, cookie, pub, label) (Credential, error)`
+- `internal/web/ask_oficina_native.go` (new)
+- `internal/store` (columns for the sealed Equipo session cookie, its expiry, and how the key was minted)
+- `internal/equipo/equipotest` (fake the two Equipo routes)
+- README
+
+- [ ] **Step 1: tests,** against `equipotest`.
+ - `TestAskOficinaConnect`: `POST /api/v1/ask/oficina {assertion, verifier}` from a native session:
+ - Base calls Equipo's `POST /native/oficina-id`, with Host set to Equipo's origin and no `Origin` header;
+ - then `POST /api/v1/auth/devices/native` with that cookie, `Origin: <equipo origin>`, a new Ed25519 key pair for the member (as the code flow makes one, `ask_connect.go:60`) and Base's device label;
+ - then seals the key and cookie, registers the Assistant host as the code flow does, and answers `200 {state:"ready", renew_after}`;
+ - `/ask/state` is `ready`.
+ - `TestAskOficinaUnknown`: Equipo's 403 becomes `409 {state:"not_linked"}`, and nothing is stored.
+ - `TestAskOficinaRenew`: a second post replaces the key and cookie, revoking the old device in Equipo.
+ - `TestAskOficinaRefusesWeb`: a browser session (not native) gets 403; the web keeps its code flow.
+ - `TestAskStateSaysWhenToRenew`: `/ask/state` gains `renew_after` (RFC 3339, empty for code-flow keys) and `equipo_origin`.
+ - `TestDisconnectRevokesOficinaKey`: Settings' Disconnect revokes it as it does a code-flow key.
+- [ ] **Step 2: implement**, reusing the code flow's storage and host registration, so the relay can't tell the two kinds of key apart. Rules:
+ - A failure from Equipo stores nothing.
+ - Two posts for the same person run one at a time (a per-member lock).
+ - Never send Base's own cookie or session to Equipo.
+- [ ] **Step 3:** README. Explain that the native app connects Ask with Oficina ID; that this key lasts 7 days and the app renews it; and that the person must be linked in Equipo.
+
+## Task 8 (Base): native skeleton builds and is gated
+
+**Files:** `native/` as in the file map (empty views); `.amadan/ci.d/20-native`; `Makefile` (`native-check`).
+
+- [ ] Copy and adapt Equipo's `native/apple/Package.swift`, `ios/project.yml`, entitlements, `PrivacyInfo.xcprivacy`, `.gitignore` and `scripts/build-mac.sh`, `build-iphone.sh` and `check-native.sh`, all at Equipo `00d09aa7`. Use:
+ - bundle `works.oficina.base`;
+ - keychain groups `9U4A84C4WK.works.oficina.base`, then `9U4A84C4WK.works.oficina.id` (in that order);
+ - App Group `group.works.oficina` (iOS) and `9U4A84C4WK.works.oficina` (Mac);
+ - `webcredentials:id.oficina.works`;
+ - rastrillo/native pinned at Task 1's merge commit, and swift-cmark at Equipo's pin;
+ - KeyboardShortcuts at its latest tagged release.
+- [ ] `scripts/fonts-into-bundle.sh` copies `internal/look/static/fonts/timeless/1.094/TimelessSansVF.woff2` and DM Sans into `BaseKit` resources. `check-native.sh --release` runs `hack/fonts.sh check` first.
+- [ ] `mac-updates.json` follows Equipo's, with `feed_url https://raw.amadan.net/oficina/native-releases/main/base/appcast.xml` and profile `~/private_keys/oficina/profiles/Oficina-Base-macOS-Developer-ID.provisionprofile`.
+- [ ] The icon: Base's mark (the rounded square, `--mark-1` to `--mark-2`) on the indigo sky, one 1024 px PNG, with the Mac icon made by the kit's `mac-icon.swift`. Show it to Paul in Task 17.
+- [ ] `check-native.sh` passes: `swift test`, the BaseMac build, and an iPhone simulator build.
+
+## Task 9 (Base): the look
+
+**Files:** `BaseKit/Look/*`, `Tests/BaseKitTests/PaletteTests.swift`.
+
+- [ ] **Step 1: tests.**
+ - `PaletteTests`: parses `app.css`, comparing the light and dark values of every token `Palette` mirrors (P7).
+ - `TypeTests`: Timeless registers before first use, and the Grotesk and Sans cuts resolve; with the file absent, DM Sans and no crash.
+- [ ] **Step 2: implement**
+ - `Palette`, keyed by `ColorScheme`;
+ - `Sky` (P9);
+ - `.glass()`, `.sheet()` and `.solid()` modifiers (P10);
+ - `BaseFont.heading(size)` and `.body(size)`;
+ - `Marks`: the state marks (asking, ready, done, stopped paths from `ask.js`; working is a turning arc round a breathing dot).
+ - The member's Appearance from `/api/v1/me` overrides the system's (`preferredColorScheme`).
+- [ ] **Step 3:** snapshot the sky (frozen pose), a glass card and the type scale in light and dark (`scripts/snapshots.sh`, RastrilloSnapshots; out of CI, as in Docs).
+
+## Task 10 (Base): session, client and events
+
+**Files:** `Session/*`, `API/*`, tests.
+
+- [ ] **Step 1: tests.**
+ - `ClientTests`: requests carry the kit's cookie and `Origin`; a 401 calls `sessionRejected()`; a JSON error body becomes a typed error.
+ - `EventsTests`: the SSE reader handles `id`, `event`, multi-line `data`, `retry`, pings, and a reconnect with `after=<last id>`; a `410 cursor_expired` reloads `/ask/state`.
+ - `AskModelTests`: applying `message`, `turn`, `delta`, `glance`, `card` and `activity` events to a snapshot gives the same thread `ask.js` would draw (fixtures from Task 6's contract tests).
+- [ ] **Step 2: implement.**
+ - `BaseSession` wraps `OficinaIDModel.live(configuration: .init(app: "base", appName: "Base"), appGroup:)` and its `client()`.
+ - The client and models.
+ - `AskModel`, an `@Observable` holding the thread, jobs, cards and turn.
+ - The SSE reader, adapted from EquipoKit's `URLSessionTransport.lines()`.
+ - On foreground: `renewIfNeeded()`, then reload state and resume events.
+
+## Task 11 (Base): Ask, drawn
+
+**Files:** `Ask/*`, `Ask/Markdown*.swift` (copied from EquipoKit's `ChatMarkdown`, `MarkdownStreamRenderer` and `MarkdownDraft`, at `00d09aa7`, with the source noted in each file), snapshot tests.
+
+- [ ] Draw, matching the approved mockups:
+ - the thread: person and Assistant bubbles; the streaming draft and caret; the thinking line, with glance text (dots, then the words);
+ - job pills: state mark, title and stage, the Try it link, and the open cards hanging under the pill;
+ - cards: question, connect and outcome, with choices as ghost buttons;
+ - "Jump to latest";
+ - the composer: Send and Stop inside the field, and the luminous focus edge;
+ - Ask's non-ready states (`connect`, `pending`, `reconnect`, `unavailable`, `norunner`, `oldrunner`, `not_linked`), with the web's approved copy.
+- [ ] **Behaviour:**
+ - Sending uses a fresh idempotency key per message; a resend after a network error reuses it.
+ - Answering posts the card's revision, and a 409 `card_stale` redraws the card.
+ - Stop cancels the turn.
+ - A pill opens its job view: a popover on the Mac, a sheet on the iPhone. It shows the job's title (linking to Equipo, as on the web), status, detail, ended cards and start time. The jobs design (11-20) adds decisions to it later.
+- [ ] **Accessibility:** VoiceOver labels (a pill reads "Christmas order form, One question for you"), Dynamic Type up to accessibility sizes, and Reduce Motion stopping the working arc and the caret.
+- [ ] Snapshots of the mockups' thread on Mac and iPhone, light and dark, and at large text.
+
+## Task 12 (Base): sign-in and Ask set-up, without a step
+
+**Files:** `SignIn/BaseOnboarding.swift`, `Session/AskSetup.swift`, tests.
+
+- [ ] **Step 1: tests (`AskSetupTests`, fake client and fake kit).**
+ - After sign-in, if `/ask/state` is `connect` or `reconnect`, or `renew_after` has passed:
+ 1. call `assertion(for: equipo_origin)`;
+ 2. `POST /api/v1/ask/oficina`;
+ 3. reload the state.
+ - `not_linked` shows the non-ready state, with no loop.
+ - A failure leaves the state as Base reports it and retries on the next foreground, never more than once a minute.
+- [ ] **Step 2: implement.**
+ - `BaseOnboarding` is the kit's `OficinaOnboardingView` in Base's look (the sky behind; wordmark; copy per the mockup: "Sign in to Base", "Use your Oficina ID, the same one as Docs, Sheets and Calls."). The kit's straight-in means most people never see it.
+ - The `unknown` answer (P3): "Sign in to Base on the web once with your Oficina ID, then come back." It has a button that opens Base's `/signin` in the browser.
+
+## Task 13 (Base): the Mac app
+
+**Files:** `BaseMac/*`.
+
+- [ ] **The window (B):**
+ - The sky, with a floating glass sidebar and the Ask pane as a sheet (mockup `mac-main-b`).
+ - **Sidebar:**
+ - Ask Base, with a badge counting jobs in `asking` or `stopped`;
+ - Getting started, while any step is open;
+ - Apps: each opens through `Opener` (P12);
+ - the team's name, with Store and People (opening the web);
+ - at the foot, the person and team, with a menu (Switch team, Sign out, Open Base on the web).
+ - The sidebar toggle in the pane's bar.
+ - Window state restores.
+ - One window; ⌘N does nothing new.
+- [ ] **The menu-bar panel:** `MenuBarExtra(isInserted:)` with `.window` style, showing the compact Ask (mockup `mac-menubar`).
+ - The field has focus when the panel opens.
+ - Jobs waiting on the person sit at the top.
+ - Open Base brings the window forward.
+ - The foot shows the team and the shortcut, if one is set.
+- [ ] **Settings (⌘,),** three tabs (mockup `mac-settings`):
+ - **General:** Appearance (writes the member's Appearance on the web through the existing `POST /settings/appearance`, with the native session); Show Base in the menu bar; Shortcut for Ask Base (KeyboardShortcuts recorder, empty by default); Open Base when you log in (`SMAppService.mainApp`); Open Oficina apps in (The app / The browser); and Notifications (opens System Settings; there are no notifications until slice 2, so the row is hidden in slice 1).
+ - **Account:** the Oficina ID, the team, Switch team and Sign out.
+ - **Ask Base:** connected or not, and Disconnect.
+- [ ] **Chrome:**
+ - `PlainAppNameCommands()` first, `NativeUpdater(policy: .quiet)`, `NativeUpdateCommands`;
+ - a Colophon under Help (estilo's catalog plus KeyboardShortcuts, swift-cmark, Sparkle, Timeless Sans and DM Sans, each with its licence);
+ - an offline banner from the kit, with Base's copy.
+- [ ] **Snapshots:** window B, the menu panel and Settings, in light and dark.
+
+## Task 14 (Base): the iPhone app
+
+**Files:** `BasePhone/*`, `ios/project.yml`.
+
+- [ ] **Ask first** (mockup `phone-ask`): round glass buttons for Apps (left) and the person (right, a menu: Switch team, Sign out, Open Base on the web), the title "Ask Base" with the team under it, then the thread and composer.
+- [ ] **The Apps sheet** (`phone-apps`): steps and a 4-column grid, opening each app through `Opener` (P12).
+- [ ] **The job sheet** (`phone-job`), with today's content (Task 11).
+- [ ] **The keyboard:** the composer rides above it, the thread keeps its newest message in view, and there's no zoom on focus.
+- [ ] **Snapshots:** the iPhone 18 Pro simulator ("Rastrillo Snapshots"), light and dark, at large text.
+
+## Task 15 (Base): release tooling
+
+**Files:**
+- `native/scripts/release-mac.sh` (Equipo's `release-equipo-0.1.5.sh` steps: build-mac, then `release_mac.py`, a smoke check, and `publish_mac_update.py`)
+- `native/scripts/testflight.sh` (a copy of `agent-tools/equipo-tf/testflight.sh` with Base's paths, profiles and bundle ID)
+
+- [ ] Both scripts plan by default and act only with `--publish` / `--upload`.
+- [ ] Dry runs pass locally up to the signing step. Real signing waits on Paul's portal steps (Task 17).
+
+## Task 16 (Base): gates and hand-over
+
+- [ ] **Gates:** `make ci` green; `native/scripts/check-native.sh` green; snapshots recorded and reviewed by eye against the mockups.
+- [ ] **Review:** ask for a review of the server half (Tasks 3 to 7) and the native half (8 to 15), by a reviewer of another model family. Record findings and fixes in `.superpowers/sdd/2026-11-23-base-native/progress.md`.
+- [ ] **Hand-over** to the controller: branch, commits, gates, the new strings for copy review, and the operator steps.
+
+## Task 17 (controller, with Paul)
+
+1. **Copy review** (the `copy-review` skill) of every new string:
+ - the onboarding and `unknown` copy;
+ - Settings labels;
+ - the sidebar's headings;
+ - menu-panel and offline copy;
+ - VoiceOver labels.
+2. **Paul's portal steps:**
+ - App ID `works.oficina.base`, with Associated Domains and App Groups;
+ - iOS development and App Store profiles, and a macOS Developer ID profile, saved to `~/private_keys/oficina/profiles/`;
+ - the App Store Connect app record, "Oficina Base".
+3. **Operator steps:**
+ - Home: deploy Task 2. Confirm that Base's staging origin and Equipo's staging origin are registered consumers (`HOME_CONSUMERS` or the table), and that the directory lists a `base` app with Base's origin for team `oficina` (the kit opens `team.origin(for: "base")`).
+ - Base staging: deploy `native/slice-1`; check `/api/version`; check `BASE_EQUIPO_ORIGIN`.
+ - Make `native-releases/base/`.
+4. **Live check on staging,** Mac first, then iPhone through TestFlight:
+ - straight-in sign-in;
+ - Ask connects with no code;
+ - send, stream, cancel and answer a card;
+ - open Docs natively and Store on the web;
+ - the menu-bar panel and a recorded shortcut;
+ - sign out;
+ - the 7-day renewal, simulated by moving `renew_after`.
+5. **Merge** `native/slice-1` on the hub. Release Mac 0.1.0 through Sparkle and iPhone 0.1.0 to TestFlight.
+
+## Not in this plan
+
+- Notifications.
+- Store and People drawn natively.
+- Admitting an invited person straight from native.
+- Siri, Shortcuts and the share extension.
+- Live Activities.
+- Decisions on job pills: the 11-20 jobs design, built for web and native together when it lands.
diff --git a/docs/superpowers/specs/2026-11-23-base-native-design.md b/docs/superpowers/specs/2026-11-23-base-native-design.md
new file mode 100644
index 0000000..8b8fdc0
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-23-base-native-design.md
@@ -0,0 +1,278 @@
+# Base on the Mac and iPhone
+
+Status: draft for Paul's review, 2026-11-23. Read against Base main `d8700cf`,
+rastrillo/native `0254817`, Home `8125a3c`, Docs `d5a328a`, Equipo `a697cde9`.
+
+Decided by Paul so far:
+
+- The native "launcher" we once discussed for Oficina is **Base**, not a
+ native Oficina Home (2026-11-23).
+- Base's branches land on main first (done: `d8700cf`).
+- **Native Base follows Base's look**, not Oficina's Calma (2026-11-23).
+- **Mac main window: B**, Ask in the middle with the apps in a floating
+ sidebar, "for now" (2026-11-23, from the slice 1 mockups).
+- **iPhone first screen: A**, Ask first, with the apps one tap away
+ (2026-11-23).
+- **Ask is set up during sign-in, in slice 1** (2026-11-23): nobody approves
+ a code in Equipo before Ask works (3.8).
+
+Mockups: `.superpowers/mockups/native/` (git-ignored: it holds the licensed
+font; `python3 build.py` draws it), shown to Paul on 2026-11-23.
+
+## 1. What native Base is for
+
+Base's direction is "all about doing work and giving the user something to see
+very quickly" (Paul, 2026-11-20, jobs design). The native app serves that,
+not app launching. On a Mac the Dock and Spotlight already launch apps, and on
+an iPhone the Home Screen does. A grid of icons in a window would only copy them.
+
+What only a native Base can do:
+
+1. **Ask Base from anywhere.** One keystroke on the Mac, or Siri and Shortcuts
+ on the iPhone, opens Ask without finding a browser tab first.
+2. **Tell you when a job needs you.** It sends a notification when a job is
+ ready, done, stuck or waiting on your decision. The answer's buttons sit on
+ the notification where the platform allows it.
+3. **Sign in once.** It uses the same Oficina ID as Docs, Sheets, Calls and
+ Equipo, and goes straight in if one of them already holds it.
+4. **Open your apps.** It opens the native app when one is installed, and the
+ web app otherwise.
+
+*My call:* the order of importance is 1, 2, 3, 4, and the first slice is
+built to match (section 6).
+
+## 2. What exists today (audit)
+
+### 2.1 Base's server
+
+- **Every screen is a server-rendered page behind a browser cookie**
+ (`internal/web/app.go:160-208`). There is no JSON API for a person. The one
+ bearer API, `/api/v1/operations`, is for Equipo's Assistant
+ (`internal/operations`).
+- **Sign-in is either Base's own** (email link or passkey) **or Oficina ID**,
+ through Home's browser handoff (`internal/web/oficina.go`). There is no
+ native exchange.
+- **Ask runs through Base.** Base enrols with Equipo as a device for each
+ person (`internal/equipo/equipo.go:168-208`). It keeps that person's Equipo
+ key sealed with `BASE_INSTANCE_KEY`, and relays the snapshot, events,
+ messages, cancel and card answers (`internal/web/ask*.go`).
+ - **Connecting Equipo is a one-time code** the person approves in Equipo
+ (`ask_connect.go:41-135`).
+ - **Connecting Oficina apps to the Assistant** goes through
+ oficina-connect (`ask_oficina.go`).
+- **Home's apps come from two places.** The team's Oficina apps come from
+ `BASE_OFICINA_APPS` (`internal/config/oficina.go`) and open in a new tab.
+ The rest are apps installed from the Store. Base's own pages (Store,
+ People, Settings) form the dock (`internal/web/home.go:21-50`).
+- **Appearance** is System, Light or Dark, stored for each member
+ (`internal/web/settings.go:44-47`).
+- **The jobs design** (`2026-11-20-jobs-that-keep-moving-design.md`, direction
+ approved) is not built yet. Until it is, job cards can't carry their own
+ decision, on the web or in a native app.
+
+### 2.2 The shared native kit (RastrilloApple)
+
+- **Oficina ID sign-in:** an email code or a passkey, with straight-in when
+ another app holds the ID and a chooser when there are two or more IDs
+ (`OficinaID/OficinaIDModel.swift`).
+- **Keychain and App Group:** identities go in the shared group
+ `9U4A84C4WK.works.oficina.id`. Sessions go in each app's own group. The App
+ Group is `group.works.oficina` on iOS and `9U4A84C4WK.works.oficina` on the
+ Mac.
+- **Also in the kit:** several accounts, a team step, an offline banner, and
+ quiet Sparkle updates.
+- **Not in the kit:** an account or team menu (Equipo built its own), the
+ Colophon (each app has its own) and a string catalog.
+- **`OficinaApp` has no `base` case** (`OficinaAppearance.swift:7-8`).
+
+### 2.3 Equipo's native app
+
+- **Chat:** `EquipoKit` has public chat pieces: `ConversationScreen`,
+ `ChatMarkdownView`, `ThinkingLine` and an SSE reader. They are bound to the
+ Coordinator's routes and `EquipoSession`, and nothing calls the Assistant
+ routes. Base can adapt them, not drop them in.
+- **Push:** registrations, an outbox and payloads are built. Sending is a stub
+ until the CARLOS `/v1/push` verb and rastrillo's push client exist. Paul
+ has still to rule who holds the Apple push key (Equipo native slice 2 plan).
+- **Live Activities** exist in Equipo's iOS widget extension.
+
+### 2.4 Opening other apps
+
+- **Bundle IDs:** every Oficina native app is `works.oficina.<app>` on every
+ build (D1, ruled 11-14). D2 puts "Oficina <Name>" in Finder and the plain
+ name inside the app.
+- **Docs, Sheets, Calendar and Memoria** only handle `…://signin`. Opening
+ their scheme with anything else just launches them.
+- **Calls** handles `oficina-calls://join`, and **Equipo** handles
+ `works.oficina.equipo://task/<id>`.
+- **Missing:** universal links, and opening a given document by link. "Open
+ on the web, already signed in" is spec'd as Home slice D but not built.
+
+## 3. How it works
+
+### 3.1 Signing in
+
+- **Oficina ID only, with the kit's flow** (email code, passkey, straight-in).
+- **Base becomes a Home consumer.** Its origin is added to `HOME_CONSUMERS`,
+ and it mounts `connect.Bridge.NativeExchange` at `POST /native/oficina-id`,
+ as Docs did in `9de84e4`. The exchange mints a native session (method
+ `home-assertion-native`, seven days). The answer is `ok`, `failed`,
+ `unknown`, `choose` or `unavailable`, with the kit's handling of each.
+- **Also mounted:** `POST /signout`, `POST /native/web/end` and the choose
+ page at `/account/home/choose`.
+- **A Base without Oficina ID** (self-hosted, Base's own sign-in only) gets a
+ "Use the browser instead" path in a later slice, not in slice 1 (*my
+ call*). Every Base Paul runs has Oficina ID.
+
+### 3.2 A small JSON API for people
+
+Under `/api/v1`, with the native session. The routes are the web pages'
+reads and writes, not new behaviour:
+
+- `GET me`: the member, the Base's name and the appearance.
+- `GET home`: the steps and the apps in Home's order. Each app carries:
+ - `kind`: `oficina`, `installed` or `own`;
+ - its name and web address;
+ - its tint and icon;
+ - for Oficina apps, the native bundle ID.
+- `ask/*`: the same relay as today's `/ask/*` (state, events, messages, turn
+ cancel, card answer, connect, check and disconnect), returning JSON and
+ SSE.
+
+*My call:* the native app talks **only to Base**, never to Equipo directly.
+Base already holds each person's Equipo key, registers itself as the
+Assistant's host and translates cards. A second, native path to Equipo would
+fork all of that.
+
+### 3.3 Ask
+
+- **Mac:** one window (B, chosen). Ask fills it. A floating glass sidebar
+ holds Ask Base (with a badge counting jobs waiting on the person), Getting
+ started while any step is open, every app (Oficina apps, then installed
+ ones), then Store and People, and the person and team at its foot.
+ Settings is the app's Settings window (⌘,). The web's layout, Home and Ask
+ side by side (A), was the alternative.
+ - A **menu-bar item and a global shortcut** open a small Ask panel from
+ anywhere. Its text field has focus, and the reply streams in.
+ - The native-levelup audit says to ask before adding a menu-bar item: this
+ is that ask (Q3).
+- **iPhone:** Ask is the first screen (A, chosen). Home's apps sit behind one
+ button, top left, in a sheet. Home first, as the web's phone layout, was
+ the alternative.
+- **Cards:** they draw what Base's web draws today: question, confirm,
+ outcome, connect and job cards, with jobs as pills. When the jobs design
+ lands, the job pill carries its decision on both web and native at once,
+ because both read the same JSON.
+- **Code:** adapted from `EquipoKit`'s chat views and SSE reader, pointed at
+ Base's `ask/*`.
+
+### 3.4 Opening apps
+
+- **Mac:** if the Oficina app's bundle ID is installed, open it with
+ `NSWorkspace`. Otherwise open its web address in the default browser.
+- **iPhone:** an app can't be opened by bundle ID, so the kit's
+ `handleOpenURL` gains `…://open`, a small kit change that every app picks up
+ at its next repin. Until then, the web address.
+- **Store apps** always open on the web.
+- **When Home slice D lands**, "open on the web" arrives already signed in.
+ Until then the browser may ask once.
+
+### 3.5 Notifications (slice 2)
+
+- **Equipo sends them**, to the Base app's device registrations, through
+ Equipo's existing outbox. *My call:* Equipo knows every job's state the
+ moment it changes, and Base only sees it while relaying a chat.
+- **Blocked on** the CARLOS push verb and the ruling on who holds the Apple
+ push key, the same blockers as Equipo's own push.
+
+### 3.6 The look
+
+Base's approved look (first-slice spec section 6), translated:
+
+- **Sky and fog:** the deep indigo sky with teal, violet, rose and mist fog,
+ and the swaying amber beam. Drawn with SwiftUI `MeshGradient` and `Canvas`.
+ Fog loops of 10 to 17 seconds, still when Reduce Motion is on.
+- **Glass:** system materials with Base's dark tint (`--glass-base`
+ `rgba(14,17,42,.40)`) and a thin bright top edge. Text keeps WCAG AA on
+ every frame.
+- **Accent and buttons:** teal `#6EE7DC` only for finished steps and progress.
+ Primary buttons are frost white with dark text.
+- **Type:** Timeless Sans, the Grotesk cut for headings, bundled through a
+ fetch step with a pinned checksum. Never committed. No FOUT: the font is in
+ the bundle, so nothing paints in a fallback face.
+- **Appearance:** System, Light and Dark, from the member's setting.
+- **Platform rules:** standard platform controls (menus, sheets, toolbars,
+ Settings), with Base's colours and type. The Mac window is a real window;
+ nothing in it pretends to be an operating system.
+
+### 3.7 Where it lives
+
+- **Code:** `native/` in this repo, laid out like Equipo's: `apple/`
+ (BaseKit), `ios/` and `macos/`, on RastrilloApple.
+- **Kit changes:** a `base` case on `OficinaApp`, and the `open` URL.
+- **Distribution:** Mac through Sparkle and the Mac release assets, iPhone
+ through TestFlight.
+
+### 3.8 Ask set up during sign-in
+
+Today a person connects Equipo once from Base's web: Base enrols a device key
+with Equipo (`internal/equipo/equipo.go:168-208`), the person approves its
+code in Equipo, and Base keeps the resulting Equipo key sealed. In the native
+app that step disappears: signing in to Base with Oficina ID also connects
+Ask, the first time, with nothing to approve.
+
+Both ends already know the person through Oficina ID, so the approval can be
+an Oficina ID proof in place of the code. Two shapes, to settle in the plan
+with Equipo's owner:
+
+- **Base asks for it.** Base's server gets a short-lived Oficina ID assertion
+ for the person addressed to Equipo (a Home consumer change: Base may ask
+ for another app's audience only for the person it holds a session for) and
+ presents it with its device proof. Equipo checks the assertion and the
+ person's membership, and issues the person's key to Base. The native app
+ does nothing extra.
+- **The app carries it.** At sign-in the native app fetches a second
+ assertion from Home with Equipo's audience, as it fetched Base's, and
+ hands it to Base with the exchange. Base presents it to Equipo as above.
+ No change to Home's rules about audiences, one more round trip for the app.
+
+*My call:* the second, because it keeps Home's rule that an assertion is
+fetched by the person's own device for one app. Either way the web keeps its
+code as a fallback, and a person whose Equipo membership is missing sees
+Ask's existing "isn't set up for you yet" state.
+
+## 4. Questions for Paul
+
+1. **Base and Oficina Home.** Does Base eventually replace Home as Oficina's
+ front door, or do they live side by side? This spec works either way. The
+ answer decides whether Home's directory should ever become Base's.
+2. **Bundle ID and name.** Base isn't only Oficina's: it fronts Keymail,
+ Sporran and the rest. Recommended: `works.oficina.base`, named "Base". It
+ lives at base.oficina.works and shares Oficina ID's keychain group. The
+ alternative is a CARLOS ID such as `com.carloku.base`.
+3. **Mac menu-bar item and global shortcut** for Ask. Recommended: yes, with
+ the shortcut off until the person sets one.
+4. **Store, People and Settings in slice 1?** Recommended: Settings natively
+ (account, appearance, sign out, Equipo connection). Store and People open
+ Base on the web in slice 1 and go native in slice 2.
+5. **Notifications:** sent by Equipo (recommended) or by Base.
+
+## 5. Not doing
+
+- A grid-of-icons launcher as the main screen.
+- Base's own sign-in in the native app (slice 1).
+- Installing Oficina, Keymail or Sporran from the Store. That is the web
+ Store's later slice; native follows it.
+- Widgets and Live Activities before notifications.
+
+## 6. Slices
+
+1. **Sign in, Ask, Home.**
+ - Server: native exchange, JSON API.
+ - Native: Mac window with menu-bar Ask, iPhone with Ask first, Home's apps
+ opening as in 3.4, Settings.
+ - Mockups first, for Paul to approve. Then the plan.
+2. **Notifications, Store and People native, and the jobs design's
+ decisions on cards** (if not already built for the web).
+3. **Siri and Shortcuts** ("Ask Base"), a share extension ("Send to Base"),
+ and Live Activities for running jobs.
diff --git a/go.mod b/go.mod
index 960db01..d416e8a 100644
--- a/go.mod
+++ b/go.mod
@@ -3,16 +3,17 @@ 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
)
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
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/equipo.go b/internal/store/equipo.go
index cf612b1..b00579b 100644
--- a/internal/store/equipo.go
+++ b/internal/store/equipo.go
@@ -155,11 +155,11 @@ func LoseEquipoLink(ctx context.Context, db *sql.DB, memberID, dev string) error
})
}
-// DisconnectEquipo forgets the member's link, if it is still device dev,
+// DisconnectEquipo forgets the member's link, whichever device it is now,
// and their host token, in one transaction: both go or neither does.
-func DisconnectEquipo(ctx context.Context, db *sql.DB, memberID, dev string) error {
+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
}
_, err := tx.ExecContext(ctx, `DELETE FROM host_tokens WHERE member_id = ?`, memberID)
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/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..945d507 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"
@@ -176,6 +177,11 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger
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..7b06cf4 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,24 @@ 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"`
+ }{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()}
writeJSON(w, http.StatusOK, out)
}
diff --git a/internal/web/ask_connect.go b/internal/web/ask_connect.go
index b170928..5cded9b 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,46 @@ 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()
+}
+
+// linkGen is the member's connection generation now.
+func (a *app) linkGen(id string) uint64 {
+ c := a.memberConn(id)
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.gen
}
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..f489495
--- /dev/null
+++ b/internal/web/ask_oficina_native.go
@@ -0,0 +1,196 @@
+package web
+
+import (
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "sync"
+ "time"
+
+ "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"
+
+// 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
+ }
+ var in struct {
+ Assertion string `json:"assertion"`
+ Verifier string `json:"verifier"`
+ }
+ if !isJSONBody(r) || decodeStrict(http.MaxBytesReader(w, r.Body, 16<<10), &in) != nil ||
+ in.Assertion == "" || len(in.Assertion) > 8192 || in.Verifier == "" || len(in.Verifier) > 256 {
+ 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. Anything that changes it while
+ // Equipo answers (Disconnect, the web's Connect or its approval) wins:
+ // the set-up then saves nothing.
+ gen := a.linkGen(me.ID)
+ 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)
+ }
+ if err != nil || superseded {
+ // Nothing was saved: the device made for it goes.
+ a.revoke(ctx, l, deviceSecrets{Token: cred.Token})
+ if superseded {
+ writeJSON(w, http.StatusConflict, map[string]string{"state": askSuperseded})
+ 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.
+func (a *app) saveOficinaLink(ctx context.Context, me store.Member, gen uint64, l store.EquipoLink) (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
+ }
+ c.gen++
+ return false, old, oldSec, store.SaveEquipoLink(ctx, a.db, l)
+}
+
+// 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})
+ }
+}
+
+// decodeStrict decodes exactly one JSON object with no unknown fields.
+func decodeStrict(r io.Reader, v any) error {
+ d := json.NewDecoder(r)
+ d.DisallowUnknownFields()
+ if err := d.Decode(v); err != nil {
+ return err
+ }
+ if d.Decode(new(json.RawMessage)) != io.EOF {
+ return errors.New("trailing JSON")
+ }
+ return nil
+}
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..c602275 100644
--- a/internal/web/oficina.go
+++ b/internal/web/oficina.go
@@ -72,6 +72,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 {
@@ -93,7 +100,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
}
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_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..be42266
--- /dev/null
+++ b/internal/webtest/ask_native_contract_test.go
@@ -0,0 +1,483 @@
+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"}
+
+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+`"}` || 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) }
+
+// 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 {