| 1 | # Connect an app to Home |
| 2 | |
| 3 | `connect` lets an app keep its existing local accounts and accept Home sign-in |
| 4 | after the person explicitly links both identities. The app still decides who |
| 5 | may enter and what they may access. |
| 6 | |
| 7 | Load optional settings with `CredentialsFromEnv("SHEETS")`, then validate them |
| 8 | with `DecodeCredentials(settings, origin)` once you know the app's origin. |
| 9 | The variables end in `_HOME_ISSUER`, `_HOME_CONSUMER_ID`, `_HOME_KEYS_BASE64` |
| 10 | and `_HOME_DEK_BASE64`. All empty means disabled; a partial configuration fails. |
| 11 | `HOME_DIRECTORY_ORIGIN` (unprefixed, the name Home itself reads) optionally |
| 12 | supplies the hub directory origin as `Credentials.Directory`, for an app switcher |
| 13 | and "All apps" link. It enables nothing on its own and must be a bare https origin. |
| 14 | Use a dedicated random 32-byte storage key and a distinct namespace per app. |
| 15 | Keep this key stable: it protects proof state and keyed local-person bindings. |
| 16 | Replacing it without a migration makes existing links unusable; rotation requires |
| 17 | an explicit migration with both keys, which this package does not yet provide. |
| 18 | |
| 19 | Apply `handoff.Migrations` and `linkstore.Migrations` using your framework's |
| 20 | migration package. The latter's namespace is `linkstore.SchemaNamespace`. |
| 21 | This package imports neither framework session nor migration types, so old |
| 22 | and new Rastrillo apps can share the same protocol. |
| 23 | |
| 24 | Construct `Bridge` with the hooks in `Config`. Read the actual session cookie; |
| 25 | `MintHomeSession` stores the opaque Home subject with method `HomeMethod` and |
| 26 | the supplied authentication time. `LookupLocalSession` reads an existing |
| 27 | local account. `LookupPerson` uses its supplied SQL query object and rechecks |
| 28 | current admission; return `sql.ErrNoRows` for missing or disallowed accounts. |
| 29 | Neither hook creates accounts, samples or identity mappings. The returned label |
| 30 | must be the canonical verified local address, never an editable display name. |
| 31 | Local IDs must never be reused, even for a new account with the same address. |
| 32 | Delete the account's `home_identity_links` rows in the same transaction as the |
| 33 | local account. The shared schema cannot impose a foreign key on app-owned tables. |
| 34 | A keyed binding detects reuse with a different address at every proof stage and |
| 35 | resolution. Address changes require explicit removal and fresh linking; old or |
| 36 | unbound links fail closed, rather than adopting the current account. |
| 37 | |
| 38 | Session cookie values must be exactly 43 characters of canonical unpadded |
| 39 | base64url encoding of 32 bytes. `Session.AuthTime` is the method's actual |
| 40 | verification time. `Session.At` is immutable verified-session creation time, |
| 41 | never 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 | |
| 44 | On every authenticated app request, resolve Home sessions through |
| 45 | `Bridge.ResolveSession`. Use the returned local ID for ownership and grants. |
| 46 | Never pass an opaque Home subject through a helper that treats subjects as |
| 47 | email addresses or creates a local account. Keep ordinary local sign-in's |
| 48 | existing behavior in the app's local authentication path. |
| 49 | |
| 50 | `Routes` supplies shared navigation, local reauthentication markers and the |
| 51 | narrow callback exception to your app's CSRF middleware. Mount its methods |
| 52 | alongside `Bridge.Start`, `Callback`, `Finish` and `ConfirmPage`. The local |
| 53 | plugin's successful return must be `LocalCompletePath`. Its pending cookie must |
| 54 | be `__Host-rastrillo_pending`, and the local entry is `/signin/local` |
| 55 | (`Routes.SigninLocal`; see "The sign-in door" below). |
| 56 | Mount exactly `Bridge.Callback` at `POST /auth/assertion`: this path alone bypasses |
| 57 | CSRF protection because the bridge verifies its browser-bound assertion. |
| 58 | `LocalLandingPath` optionally sets a validated local destination after ordinary |
| 59 | local sign-in (default `/`); explicit account-link navigation takes precedence. Render shared pages |
| 60 | inside the app's existing Estilo layout; all paths work without JavaScript. |
| 61 | Apps with additional content-security directives must supply their existing |
| 62 | policy with the validated Home issuer added to `form-action`. |
| 63 | |
| 64 | Offer "Connect your Oficina account" in the account menu only when |
| 65 | `Bridge.Linked` reports no stored link for the signed-in local person, however |
| 66 | the session signed in: one indexed lookup per render. Render the shared pages |
| 67 | with `PageFor(r, ...)` so "Accounts connected" leads back to the page the link |
| 68 | began from. An assertion with no link here leaves a sealed, ten-minute |
| 69 | navigation marker: the next fresh local sign-in begins the link at once and |
| 70 | lands, after Home's freshness check, on the confirm step. An expired marker is |
| 71 | ignored. The confirm POST ends on `GET /account/home/confirm?connected=1`, |
| 72 | which shows "Accounts connected" only to a person whose link is stored. |
| 73 | |
| 74 | Wrap the trusted local plugin's Begin handler with `OAuthContinuation` when it |
| 75 | can redirect to Keymail. Render the supplied destination with `OAuthPage` and the |
| 76 | shared `home-oauth-head` and `home-oauth` templates inside your existing layout. |
| 77 | The helper validates the client origin, `/auth/callback`, scope and PKCE method, |
| 78 | then ends the POST with a no-store continuation page so Safari does not apply |
| 79 | form-action to Keymail's redirect chain. It does not discover or trust arbitrary |
| 80 | request-provided destinations. Keep the existing local plugin callback route. |
| 81 | |
| 82 | ## The sign-in door |
| 83 | |
| 84 | Three GET routes (Home spec `2026-11-19-smart-door.md`, "Routes, and every |
| 85 | state 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 | |
| 103 | In 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, |
| 107 | because linking needs `FreshLocal`, which no Home sign-in gives. |
| 108 | |
| 109 | ```go |
| 110 | st := app.auth.SigninState(r) // app.auth is the app's *rauth.Auth |
| 111 | if 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 | |
| 117 | Set rastrillo's `auth.Config.SigninPath` to `connect.SigninPath`. rastrillo |
| 118 | sends 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. |
| 120 | A step-up stays local on `/signin` too, because `reauth=1` rides every one of |
| 121 | those links. |
| 122 | |
| 123 | **Wrap `SigninDoor` and `SigninOficina` in the app's admission check.** They |
| 124 | read the session cookie and nothing else, so a session the app's signed-in |
| 125 | routes refuse (a removed member, a revoked share) counts as signed in. Unless |
| 126 | the app ends or hides it first, `/signin` and the refusing page redirect to |
| 127 | each other forever. |
| 128 | |
| 129 | Bumping connect is a compile break (`Routes.Signin` is gone). `MIGRATING.md` |
| 130 | has the per-app changes, including an interim that keeps today's behaviour |
| 131 | until an app moves to the new door. |
| 132 | |
| 133 | **Remembering Oficina ID** is the app's job, in `Config.MintHomeSession`. |
| 134 | connect imports no `lastsignin` or `auth` (its go.mod still requires |
| 135 | rastrillo v0.38.0, so a bump moves you there). |
| 136 | After 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 |
| 139 | address over from the record already in the jar. connect calls the hook only |
| 140 | where a Home sign-in becomes a session (a finished exchange, and "I'm new |
| 141 | here"), never on link, choose, unknown or failed. |
| 142 | |
| 143 | **Signed out.** Set `RoutesConfig.ForgetPath` to where you mounted rastrillo |
| 144 | auth's `Forget`. `PageFor(r, "signedout", …)` on the request `Routes.SignedOut` |
| 145 | renders then carries it as `PageData.ForgetAction`. Draw it with estilo's |
| 146 | `estilo-signed-out`: `chrome.SignInNotice{…}.SignedOut(p.Action).Forgetting(p.ForgetAction, "")`. |
| 147 | It is a plain same-origin POST, which `csrf.SameOrigin` admits, so it stays |
| 148 | inside `Middleware`'s CSRF check with no token. It forgets this host only; |
| 149 | id.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 |
| 154 | Home sign-in session too and returns the browser to the app's `/signed-out`. Home |
| 155 | admits 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 |
| 158 | the issuer in `form-action`. |
| 159 | |
| 160 | ## Home-only people (team mode) |
| 161 | |
| 162 | `Config.Admit`, `Config.Unlinked` and `Config.HomeOnly` are optional and set |
| 163 | together; `New` refuses any one without the others. Without them nothing above |
| 164 | changes. With them, a roster member with no account link here can still sign |
| 165 | in, as an addressless person the app creates, which is what team mode needs |
| 166 | for 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 |
| 169 | called with a transaction open: Docs has a single writer connection, and a |
| 170 | hook 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 | |
| 222 | A native app holding an Oficina ID grant asks Home for an assertion for this |
| 223 | origin (`POST https://id.oficina.works/native/v1/assert {aud, challenge}`) |
| 224 | and trades it here, with no browser, for a session. Set |
| 225 | `Config.MintNativeSession` (store the session, return its cookie value, set |
| 226 | no cookie) and mount `Bridge.NativeExchange` at `POST /native/oficina-id` |
| 227 | (`NativeExchangePath`). `Routes.Middleware` lets that one path past the CSRF |
| 228 | check: the exchange itself refuses any request carrying `Origin` or |
| 229 | `Sec-Fetch-Site`, any query, and anything but `application/json`. |
| 230 | |
| 231 | The request is `{"assertion", "verifier", "target"?, "choice"?}`. The |
| 232 | verifier is 32 random bytes; Home sets the assertion's nonce from its |
| 233 | challenge, 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 |
| 236 | cookies: |
| 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 |
| 248 | default browser. The exchange writes the assertion's `jti` only once it is |
| 249 | about 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 |
| 251 | the app one fresh assertion. |
| 252 | |
| 253 | The session's method is `NativeMethod`, `home-assertion-native`. Every check |
| 254 | on a Home sign-in uses `IsHomeDerived(method)`, true for `HomeMethod`, |
| 255 | `NativeMethod` and `NativeWebMethod`. `Expired` refuses a native or |
| 256 | native-web session more than seven days after its `At`, absolute; an app that |
| 257 | resolves sessions itself rather than through `ResolveSession` must refuse |
| 258 | what it refuses. The app re-mints after a day and on any 401. |
| 259 | |
| 260 | ## Moving existing links onto connect |
| 261 | |
| 262 | An app that already links Home identities in its own table (Docs' |
| 263 | `docs_identity_links`) carries them over with `Bridge.Adopt(ctx, tx, issuer, |
| 264 | subject, personID)`. A plain SQL copy does not work. Every |
| 265 | `home_identity_links` row carries `person_binding`, a keyed hash of the |
| 266 | person's address under the storage key, and `Resolve` refuses a row whose |
| 267 | binding does not match. Copied rows would stop resolving at once. `Adopt` |
| 268 | asks `LookupPerson` for the address inside your transaction and writes the |
| 269 | row that linking here would have written. The address is hashed and never |
| 270 | stored. `Adopt` checks nothing about the subject: your table vouches for it. |
| 271 | |
| 272 | Do it once, at boot, after the migrations and `New` and before serving: |
| 273 | |
| 274 | 1. Begin a transaction on `Config.DB`. |
| 275 | 2. Read your old rows and call `Adopt` for each. |
| 276 | 3. Retire the old table in the same transaction, then commit. |
| 277 | |
| 278 | If the old table is absent, there is nothing to do. A repeat of an identical |
| 279 | row 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 | |
| 290 | The app decides whether a refusal aborts the move or drops that row, and |
| 291 | should say which. `ErrStorage` means roll back. |
| 292 | |
| 293 | `LookupPerson` must read through the `Queryer` it is given, as it must |
| 294 | already. A lookup on its own connection deadlocks against the open |
| 295 | transaction on a single-connection pool. |
| 296 | |
| 297 | Carry the old link clock in the same transaction with |
| 298 | `UPDATE home_link_clock SET high_water = MAX(high_water, ?) WHERE id = 1`. |
| 299 | Do not carry in-flight link flows. They last five minutes, and a person |
| 300 | mid-link starts again. |
| 301 | |
| 302 | `Adopt` does not consult `Config.HomeOnly`. An app with Home-only people |
| 303 | keeps their subjects disjoint from links itself, as Docs does with triggers. |
| 304 | |
| 305 | ## Extraction record |
| 306 | |
| 307 | The link proof protocol, bridge, freshness rules and navigation originate in |
| 308 | Oficina Docs commit `3fffd1be535ec87ab6e92da753046a4f1e4c754c`, whose tree |
| 309 | matches reviewed deployment `a8f5c0e1d67ad042e89793aa941135eacd98aa23`. |
| 310 | The original files live under `internal/docs/home_*` and `internal/docs/linkstore`. |
| 311 | This extraction preserves the consumed proof stages, nonce/session binding, |
| 312 | clock watermark, freshness windows and encrypted flow purpose strings. |
| 313 | |
| 314 | Changes are the neutral session DTO and app lookup hooks, new `home_*` link |
| 315 | tables, app-selected encryption namespace, and shared rendering/navigation. |
| 316 | The local-person foreign key becomes a transaction-scoped existence/admission |
| 317 | lookup, because apps use different local identity tables. Every link write |
| 318 | and subsequent resolution still checks the current local account. Additive |
| 319 | migration 0002 adds a keyed person binding; earlier unbound rows fail closed. |
| 320 | OAuth continuation also derives from Docs `internal/docs/auth_navigation.go`. |
| 321 | |
| 322 | The original Docs state-machine tests were ported with synthetic session and |
| 323 | local-account hooks. The app-owned content-preservation test now checks an |
| 324 | unchanged content row; framework CSRF coverage belongs to the shared Routes |
| 325 | and each app's router integration tests. Existing Docs tables and bytes are |
| 326 | untouched. 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 |
| 329 | links. 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. |
| 332 | An addressless identity is refused by this method. Ordinary `Resolve`, session |
| 333 | resolution and browser completion retain their Home-only behavior. Agent |
| 334 | consumers that require linked local accounts must apply that restriction to |
| 335 | reads and response checks as well as writes. |
| 336 | |