oficina / home Public

Clone
git clone https://amadan.net/oficina/home

Plain git — no account needed to clone.

Download

Download this file

1# Connect an app to Home
2
3`connect` lets an app keep its existing local accounts and accept Home sign-in
4after the person explicitly links both identities. The app still decides who
5may enter and what they may access.
6
7Load optional settings with `CredentialsFromEnv("SHEETS")`, then validate them
8with `DecodeCredentials(settings, origin)` once you know the app's origin.
9The variables end in `_HOME_ISSUER`, `_HOME_CONSUMER_ID`, `_HOME_KEYS_BASE64`
10and `_HOME_DEK_BASE64`. All empty means disabled; a partial configuration fails.
11`HOME_DIRECTORY_ORIGIN` (unprefixed, the name Home itself reads) optionally
12supplies the hub directory origin as `Credentials.Directory`, for an app switcher
13and "All apps" link. It enables nothing on its own and must be a bare https origin.
14Use a dedicated random 32-byte storage key and a distinct namespace per app.
15Keep this key stable: it protects proof state and keyed local-person bindings.
16Replacing it without a migration makes existing links unusable; rotation requires
17an explicit migration with both keys, which this package does not yet provide.
18
19Apply `handoff.Migrations` and `linkstore.Migrations` using your framework's
20migration package. The latter's namespace is `linkstore.SchemaNamespace`.
21This package imports neither framework session nor migration types, so old
22and new Rastrillo apps can share the same protocol.
23
24Construct `Bridge` with the hooks in `Config`. Read the actual session cookie;
25`MintHomeSession` stores the opaque Home subject with method `HomeMethod` and
26the supplied authentication time. `LookupLocalSession` reads an existing
27local account. `LookupPerson` uses its supplied SQL query object and rechecks
28current admission; return `sql.ErrNoRows` for missing or disallowed accounts.
29Neither hook creates accounts, samples or identity mappings. The returned label
30must be the canonical verified local address, never an editable display name.
31Local IDs must never be reused, even for a new account with the same address.
32Delete the account's `home_identity_links` rows in the same transaction as the
33local account. The shared schema cannot impose a foreign key on app-owned tables.
34A keyed binding detects reuse with a different address at every proof stage and
35resolution. Address changes require explicit removal and fresh linking; old or
36unbound links fail closed, rather than adopting the current account.
37
38Session cookie values must be exactly 43 characters of canonical unpadded
39base64url encoding of 32 bytes. `Session.AuthTime` is the method's actual
40verification time. `Session.At` is immutable verified-session creation time,
41never last-seen time or request time: legacy magic-link sessions can use it when
42`AuthTime` is absent. Keymail sessions cannot use that fallback.
43
44On every authenticated app request, resolve Home sessions through
45`Bridge.ResolveSession`. Use the returned local ID for ownership and grants.
46Never pass an opaque Home subject through a helper that treats subjects as
47email addresses or creates a local account. Keep ordinary local sign-in's
48existing behavior in the app's local authentication path.
49
50`Routes` supplies shared navigation, local reauthentication markers and the
51narrow callback exception to your app's CSRF middleware. Mount its methods
52alongside `Bridge.Start`, `Callback`, `Finish` and `ConfirmPage`. The local
53plugin's successful return must be `LocalCompletePath`. Its pending cookie must
54be `__Host-rastrillo_pending`, and the local entry is `/signin/local`
55(`Routes.SigninLocal`; see "The sign-in door" below).
56Mount exactly `Bridge.Callback` at `POST /auth/assertion`: this path alone bypasses
57CSRF protection because the bridge verifies its browser-bound assertion.
58`LocalLandingPath` optionally sets a validated local destination after ordinary
59local sign-in (default `/`); explicit account-link navigation takes precedence. Render shared pages
60inside the app's existing Estilo layout; all paths work without JavaScript.
61Apps with additional content-security directives must supply their existing
62policy with the validated Home issuer added to `form-action`.
63
64Offer "Connect your Oficina account" in the account menu only when
65`Bridge.Linked` reports no stored link for the signed-in local person, however
66the session signed in: one indexed lookup per render. Render the shared pages
67with `PageFor(r, ...)` so "Accounts connected" leads back to the page the link
68began from. An assertion with no link here leaves a sealed, ten-minute
69navigation marker: the next fresh local sign-in begins the link at once and
70lands, after Home's freshness check, on the confirm step. An expired marker is
71ignored. The confirm POST ends on `GET /account/home/confirm?connected=1`,
72which shows "Accounts connected" only to a person whose link is stored.
73
74Wrap the trusted local plugin's Begin handler with `OAuthContinuation` when it
75can redirect to Keymail. Render the supplied destination with `OAuthPage` and the
76shared `home-oauth-head` and `home-oauth` templates inside your existing layout.
77The helper validates the client origin, `/auth/callback`, scope and PKCE method,
78then ends the POST with a no-store continuation page so Safari does not apply
79form-action to Keymail's redirect chain. It does not discover or trust arbitrary
80request-provided destinations. Keep the existing local plugin callback route.
81
82## The sign-in door
83
84Three GET routes (Home spec `2026-11-19-smart-door.md`, "Routes, and every
85state the door must answer"):
86
87- `SigninPath` (`/signin`) at `Routes.SigninDoor`: **always the door**, which
88 the app draws in its `RoutesConfig.LocalSignin`. It never starts a Home
89 exchange. A browser with a live session goes straight to the validated
90 `return_to` (or `/`), unless the query names a state of the door (`sent`,
91 `err`, `force`, `reauth`, `continue`).
92- `SigninLocalPath` (`/signin/local`) at `Routes.SigninLocal`: the same door
93 with **email as the one way in**. connect sends people here when Oficina ID
94 cannot help them: unknown, failed, a link to resume, "Connect my existing
95 account", and a session too old to link (as `/signin/local?reauth=1`). It
96 has no signed-in shortcut. Mount it at `SigninLocal`, never at the app's
97 door handler directly, or that door offers Oficina ID.
98- `SigninOficinaPath` (`/signin/oficina?return_to=…`) at `Routes.SigninOficina`:
99 "Continue with Oficina ID". It remembers the validated `return_to` in the
100 sealed return cookie and redirects to `handoff.StartPath`. A live session
101 goes straight to the page instead; a `reauth` is sent to `/signin/local`.
102
103In the door, `OficinaHref(r)` is the href for rastrillo's
104`auth.FederatedDoor.Href`. It is `""` on `/signin/local`, on any step-up
105(`reauth` in the query), and on any request that did not come through
106`SigninDoor`. Set no `FederatedDoor` then: a step-up offers local ways only,
107because linking needs `FreshLocal`, which no Home sign-in gives.
108
109```go
110st := app.auth.SigninState(r) // app.auth is the app's *rauth.Auth
111if href := connect.OficinaHref(r); href != "" {
112 st.Federated = &rauth.FederatedDoor{Provider: lastsignin.ProviderOficina,
113 Href: href, Label: "Oficina ID", Icon: chrome.OficinaGlyph}
114}
115```
116
117Set rastrillo's `auth.Config.SigninPath` to `connect.SigninPath`. rastrillo
118sends every outcome, chooser link and Forget there. Apps with Home set it to
119`/signin/local` today, and left there the chooser never has an Oficina ID row.
120A step-up stays local on `/signin` too, because `reauth=1` rides every one of
121those links.
122
123**Wrap `SigninDoor` and `SigninOficina` in the app's admission check.** They
124read the session cookie and nothing else, so a session the app's signed-in
125routes refuse (a removed member, a revoked share) counts as signed in. Unless
126the app ends or hides it first, `/signin` and the refusing page redirect to
127each other forever.
128
129Bumping connect is a compile break (`Routes.Signin` is gone). `MIGRATING.md`
130has the per-app changes, including an interim that keeps today's behaviour
131until an app moves to the new door.
132
133**Remembering Oficina ID** is the app's job, in `Config.MintHomeSession`.
134connect imports no `lastsignin` or `auth` (its go.mod still requires
135rastrillo v0.38.0, so a bump moves you there).
136After storing the session, call `RememberJar().Remember` with
137`lastsignin.MethodFederated`, `ProviderOficina` and the address of
138`connect.MintedPerson(r)` (empty for a Home-only person). Never carry an
139address over from the record already in the jar. connect calls the hook only
140where a Home sign-in becomes a session (a finished exchange, and "I'm new
141here"), never on link, choose, unknown or failed.
142
143**Signed out.** Set `RoutesConfig.ForgetPath` to where you mounted rastrillo
144auth's `Forget`. `PageFor(r, "signedout", …)` on the request `Routes.SignedOut`
145renders then carries it as `PageData.ForgetAction`. Draw it with estilo's
146`estilo-signed-out`: `chrome.SignInNotice{…}.SignedOut(p.Action).Forgetting(p.ForgetAction, "")`.
147It is a plain same-origin POST, which `csrf.SameOrigin` admits, so it stays
148inside `Middleware`'s CSRF check with no token. It forgets this host only;
149id.oficina.works keeps and forgets its own record.
150
151## Signing out
152
153`Routes.Signout` ends the app session and then answers `307` to `{Issuer}/signout`, which ends the
154Home sign-in session too and returns the browser to the app's `/signed-out`. Home
155admits that hop only from an origin registered in its `HOME_CONSUMERS`, by
156`Referer` when the browser nulls `Origin`, so a page showing Sign out must not send
157`Referrer-Policy: no-referrer` (use `strict-origin`), and a custom policy must keep
158the issuer in `form-action`.
159
160## Home-only people (team mode)
161
162`Config.Admit`, `Config.Unlinked` and `Config.HomeOnly` are optional and set
163together; `New` refuses any one without the others. Without them nothing above
164changes. With them, a roster member with no account link here can still sign
165in, as an addressless person the app creates, which is what team mode needs
166for a member who has never had a local account (`home/teammode`,
167`implementation/teammode-package.md`). Home spec
168`2026-11-14-oficina-id-native.md` §8 governs what follows. No hook is ever
169called with a transaction open: Docs has a single writer connection, and a
170hook waiting on it from inside connect's own transaction would wedge it.
171
172- `HomeOnly(ctx, issuer, subject)` reads, never creates, the person a subject
173 was given. Connect asks it after the account link in ordinary resolution:
174 `Resolve`, `ResolveSession`, completion and the native exchange, so the
175 same-person rules hold for Home-only people too. It returns `ErrNoPerson`
176 for none. The person has a positive ID and an empty `Label`; connect
177 refuses one with a label, because there is no address to give.
178 It may be asked about any subject linkstore refused, including one that is
179 not a person ref, so it must not assume the subject's shape.
180- `Admit(ctx, issuer, subject)` is the roster decision, and it comes first:
181 asked only for a verified subject with neither a link nor a Home-only person,
182 and only when no app session is present, it allocates nothing. `nil` is a
183 Member (`teammode.Runtime.AdmitUnlinked`), `ErrNoPerson` a non-member, any
184 other error "cannot decide now". It must never ask whether the team has
185 local or email accounts.
186- **A non-member** gets today's "unknown" answer byte for byte (403, with the
187 resume-linking marker), the same as an instance without the hooks. **An
188 unavailable roster** is a 503. **A Member** gets a sealed, single-use,
189 ten-minute choice proof bound to the browser by `__Host-oficina-home-choice`
190 (linkstore migration 0003) and a 303 to `ChoosePath`,
191 `/account/home/choose`. Nothing is created yet, so a guest's local account
192 never blocks a new member's first sign-in.
193- Mount `Bridge.ChoosePage` at `GET` and `Bridge.ChoosePost` at `POST`
194 `/account/home/choose`, outside the session guards and inside the app's
195 CSRF middleware. Render state `"choose"` with your own template from
196 `ChoiceFor(r)` (the form's action and token) and the `choose_*` strings:
197 title "Welcome to the team", and two buttons that POST `choice=connect` or
198 `choice=new` with the token. The token is an HMAC of the proof cookie and
199 the POST requires this exact `Origin`.
200 - "Connect my existing account" consumes the proof and goes to
201 `/signin/local` with the resume-linking marker, then slice 1's linking.
202 - "I'm new here — continue with Oficina ID" refuses while any app session
203 is present; otherwise it consumes the proof in its own short
204 transaction, re-checks the link and `Admit` with none open, allocates
205 through `Unlinked`, resolves again and mints. The person lands on `/`.
206- `Unlinked(ctx, issuer, subject)` may create that person, and is asked only
207 after a Member's explicit "I'm new here" (the choose POST, or a native
208 `choice:"new"`). It opens its own writer transaction and re-checks before
209 it creates. Whatever it answers, connect resolves the subject again: a
210 person found then (a racing choice made one) is used; otherwise
211 `ErrNoPerson` is "unknown" and any other error a 503.
212- A subject arriving over a live session is never allocated and no proof is
213 issued: an unknown one is refused as "unknown", and a known one that is not
214 the signed-in person is refused as "failed", leaving that session in
215 place. Every cookie shape check stays connect's.
216
217`Bridge.Linked` knows nothing of Home-only people, so an app should not offer
218"Connect your Oficina account" to one: there is no local account to connect.
219
220## Native apps: NativeExchange
221
222A native app holding an Oficina ID grant asks Home for an assertion for this
223origin (`POST https://id.oficina.works/native/v1/assert {aud, challenge}`)
224and trades it here, with no browser, for a session. Set
225`Config.MintNativeSession` (store the session, return its cookie value, set
226no cookie) and mount `Bridge.NativeExchange` at `POST /native/oficina-id`
227(`NativeExchangePath`). `Routes.Middleware` lets that one path past the CSRF
228check: the exchange itself refuses any request carrying `Origin` or
229`Sec-Fetch-Site`, any query, and anything but `application/json`.
230
231The request is `{"assertion", "verifier", "target"?, "choice"?}`. The
232verifier is 32 random bytes; Home sets the assertion's nonce from its
233challenge, and the exchange recomputes it (`handoff.NativeChallenge`,
234`handoff.NativeNonce`; the derivation and a test vector are in
235`handoff/native.go`). Answers are JSON `{"state": …}`, `no-store`, with no
236cookies:
237
238| Status | state | Meaning |
239|---|---|---|
240| 200 | `ok` | `name` (the session cookie), `value`, `expires_at` (unix, 7 days), `target` echoed if sent |
241| 400 | `invalid` | malformed request |
242| 401 | `failed` | assertion not accepted (signature, audience, expiry, verifier, already used): get a fresh one |
243| 403 | `unknown` | no person here and none may be made; identical for every such subject and instance |
244| 409 | `choose` | a roster Member with no person here: offer both routes; send `choice:"new"` only from "I'm new here" |
245| 503 | `unavailable` | try again shortly |
246
247"Connect my existing account" in the app opens `<origin>/account/home` in the
248default browser. The exchange writes the assertion's `jti` only once it is
249about to mint, in its own committed transaction (`handoff.Store.Reserve`); a
250`jti` burned with no session (a crash, or the final recheck refusing) costs
251the app one fresh assertion.
252
253The session's method is `NativeMethod`, `home-assertion-native`. Every check
254on a Home sign-in uses `IsHomeDerived(method)`, true for `HomeMethod`,
255`NativeMethod` and `NativeWebMethod`. `Expired` refuses a native or
256native-web session more than seven days after its `At`, absolute; an app that
257resolves sessions itself rather than through `ResolveSession` must refuse
258what it refuses. The app re-mints after a day and on any 401.
259
260## Moving existing links onto connect
261
262An app that already links Home identities in its own table (Docs'
263`docs_identity_links`) carries them over with `Bridge.Adopt(ctx, tx, issuer,
264subject, personID)`. A plain SQL copy does not work. Every
265`home_identity_links` row carries `person_binding`, a keyed hash of the
266person's address under the storage key, and `Resolve` refuses a row whose
267binding does not match. Copied rows would stop resolving at once. `Adopt`
268asks `LookupPerson` for the address inside your transaction and writes the
269row that linking here would have written. The address is hashed and never
270stored. `Adopt` checks nothing about the subject: your table vouches for it.
271
272Do it once, at boot, after the migrations and `New` and before serving:
273
2741. Begin a transaction on `Config.DB`.
2752. Read your old rows and call `Adopt` for each.
2763. Retire the old table in the same transaction, then commit.
277
278If the old table is absent, there is nothing to do. A repeat of an identical
279row is not an error, so a boot that stops partway can simply run again.
280`ErrRefused` means nothing was written. Its causes are:
281
282- a foreign issuer;
283- an invalid subject;
284- a person `LookupPerson` does not return now (that link could not resolve
285 anyway);
286- the subject already linked to another person;
287- the person already linked under another subject;
288- an existing row with a stale or missing binding. Adopt never repairs one.
289
290The app decides whether a refusal aborts the move or drops that row, and
291should say which. `ErrStorage` means roll back.
292
293`LookupPerson` must read through the `Queryer` it is given, as it must
294already. A lookup on its own connection deadlocks against the open
295transaction on a single-connection pool.
296
297Carry the old link clock in the same transaction with
298`UPDATE home_link_clock SET high_water = MAX(high_water, ?) WHERE id = 1`.
299Do not carry in-flight link flows. They last five minutes, and a person
300mid-link starts again.
301
302`Adopt` does not consult `Config.HomeOnly`. An app with Home-only people
303keeps their subjects disjoint from links itself, as Docs does with triggers.
304
305## Extraction record
306
307The link proof protocol, bridge, freshness rules and navigation originate in
308Oficina Docs commit `3fffd1be535ec87ab6e92da753046a4f1e4c754c`, whose tree
309matches reviewed deployment `a8f5c0e1d67ad042e89793aa941135eacd98aa23`.
310The original files live under `internal/docs/home_*` and `internal/docs/linkstore`.
311This extraction preserves the consumed proof stages, nonce/session binding,
312clock watermark, freshness windows and encrypted flow purpose strings.
313
314Changes are the neutral session DTO and app lookup hooks, new `home_*` link
315tables, app-selected encryption namespace, and shared rendering/navigation.
316The local-person foreign key becomes a transaction-scoped existence/admission
317lookup, because apps use different local identity tables. Every link write
318and subsequent resolution still checks the current local account. Additive
319migration 0002 adds a keyed person binding; earlier unbound rows fail closed.
320OAuth continuation also derives from Docs `internal/docs/auth_navigation.go`.
321
322The original Docs state-machine tests were ported with synthetic session and
323local-account hooks. The app-owned content-preservation test now checks an
324unchanged content row; framework CSRF coverage belongs to the shared Routes
325and each app's router integration tests. Existing Docs tables and bytes are
326untouched. This is not a migration path for an already deployed Docs instance.
327
328`Bridge.ResolveOn(ctx, q, subject)` is explicitly limited to existing account
329links. It verifies the complete keyed binding and current local lookup through
330`q`, including while the caller holds SQLite's writer. It never invokes
331`HomeOnly` or `Unlinked`: those hooks cannot use the caller's transaction.
332An addressless identity is refused by this method. Ordinary `Resolve`, session
333resolution and browser completion retain their Home-only behavior. Agent
334consumers that require linked local accounts must apply that restriction to
335reads and response checks as well as writes.
336