oficina / home Public

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

Plain git — no account needed to clone.

Download

Download this file

Connect an app to Home

connect lets an app keep its existing local accounts and accept Home sign-in after the person explicitly links both identities. The app still decides who may enter and what they may access.

Load optional settings with CredentialsFromEnv("SHEETS"), then validate them with DecodeCredentials(settings, origin) once you know the app's origin. The variables end in _HOME_ISSUER, _HOME_CONSUMER_ID, _HOME_KEYS_BASE64 and _HOME_DEK_BASE64. All empty means disabled; a partial configuration fails. HOME_DIRECTORY_ORIGIN (unprefixed, the name Home itself reads) optionally supplies the hub directory origin as Credentials.Directory, for an app switcher and "All apps" link. It enables nothing on its own and must be a bare https origin. Use a dedicated random 32-byte storage key and a distinct namespace per app. Keep this key stable: it protects proof state and keyed local-person bindings. Replacing it without a migration makes existing links unusable; rotation requires an explicit migration with both keys, which this package does not yet provide.

Apply handoff.Migrations and linkstore.Migrations using your framework's migration package. The latter's namespace is linkstore.SchemaNamespace. This package imports neither framework session nor migration types, so old and new Rastrillo apps can share the same protocol.

Construct Bridge with the hooks in Config. Read the actual session cookie; MintHomeSession stores the opaque Home subject with method HomeMethod and the supplied authentication time. LookupLocalSession reads an existing local account. LookupPerson uses its supplied SQL query object and rechecks current admission; return sql.ErrNoRows for missing or disallowed accounts. Neither hook creates accounts, samples or identity mappings. The returned label must be the canonical verified local address, never an editable display name. Local IDs must never be reused, even for a new account with the same address. Delete the account's home_identity_links rows in the same transaction as the local account. The shared schema cannot impose a foreign key on app-owned tables. A keyed binding detects reuse with a different address at every proof stage and resolution. Address changes require explicit removal and fresh linking; old or unbound links fail closed, rather than adopting the current account.

Session cookie values must be exactly 43 characters of canonical unpadded base64url encoding of 32 bytes. Session.AuthTime is the method's actual verification time. Session.At is immutable verified-session creation time, never last-seen time or request time: legacy magic-link sessions can use it when AuthTime is absent. Keymail sessions cannot use that fallback.

On every authenticated app request, resolve Home sessions through Bridge.ResolveSession. Use the returned local ID for ownership and grants. Never pass an opaque Home subject through a helper that treats subjects as email addresses or creates a local account. Keep ordinary local sign-in's existing behavior in the app's local authentication path.

Routes supplies shared navigation, local reauthentication markers and the narrow callback exception to your app's CSRF middleware. Mount its methods alongside Bridge.Start, Callback, Finish and ConfirmPage. The local plugin's successful return must be LocalCompletePath. Its pending cookie must be __Host-rastrillo_pending, and the local entry is /signin/local (Routes.SigninLocal; see "The sign-in door" below). Mount exactly Bridge.Callback at POST /auth/assertion: this path alone bypasses CSRF protection because the bridge verifies its browser-bound assertion. LocalLandingPath optionally sets a validated local destination after ordinary local sign-in (default /); explicit account-link navigation takes precedence. Render shared pages inside the app's existing Estilo layout; all paths work without JavaScript. Apps with additional content-security directives must supply their existing policy with the validated Home issuer added to form-action.

Offer "Connect your Oficina account" in the account menu only when Bridge.Linked reports no stored link for the signed-in local person, however the session signed in: one indexed lookup per render. Render the shared pages with PageFor(r, ...) so "Accounts connected" leads back to the page the link began from. An assertion with no link here leaves a sealed, ten-minute navigation marker: the next fresh local sign-in begins the link at once and lands, after Home's freshness check, on the confirm step. An expired marker is ignored. The confirm POST ends on GET /account/home/confirm?connected=1, which shows "Accounts connected" only to a person whose link is stored.

Wrap the trusted local plugin's Begin handler with OAuthContinuation when it can redirect to Keymail. Render the supplied destination with OAuthPage and the shared home-oauth-head and home-oauth templates inside your existing layout. The helper validates the client origin, /auth/callback, scope and PKCE method, then ends the POST with a no-store continuation page so Safari does not apply form-action to Keymail's redirect chain. It does not discover or trust arbitrary request-provided destinations. Keep the existing local plugin callback route.

The sign-in door

Three GET routes (Home spec 2026-11-19-smart-door.md, "Routes, and every state the door must answer"):

  • SigninPath (/signin) at Routes.SigninDoor: always the door, which the app draws in its RoutesConfig.LocalSignin. It never starts a Home exchange. A browser with a live session goes straight to the validated return_to (or /), unless the query names a state of the door (sent, err, force, reauth, continue).
  • SigninLocalPath (/signin/local) at Routes.SigninLocal: the same door with email as the one way in. connect sends people here when Oficina ID cannot help them: unknown, failed, a link to resume, "Connect my existing account", and a session too old to link (as /signin/local?reauth=1). It has no signed-in shortcut. Mount it at SigninLocal, never at the app's door handler directly, or that door offers Oficina ID.
  • SigninOficinaPath (/signin/oficina?return_to=…) at Routes.SigninOficina: "Continue with Oficina ID". It remembers the validated return_to in the sealed return cookie and redirects to handoff.StartPath. A live session goes straight to the page instead; a reauth is sent to /signin/local.

In the door, OficinaHref(r) is the href for rastrillo's auth.FederatedDoor.Href. It is "" on /signin/local, on any step-up (reauth in the query), and on any request that did not come through SigninDoor. Set no FederatedDoor then: a step-up offers local ways only, because linking needs FreshLocal, which no Home sign-in gives.

st := app.auth.SigninState(r) // app.auth is the app's *rauth.Auth
if href := connect.OficinaHref(r); href != "" {
	st.Federated = &rauth.FederatedDoor{Provider: lastsignin.ProviderOficina,
		Href: href, Label: "Oficina ID", Icon: chrome.OficinaGlyph}
}

Set rastrillo's auth.Config.SigninPath to connect.SigninPath. rastrillo sends every outcome, chooser link and Forget there. Apps with Home set it to /signin/local today, and left there the chooser never has an Oficina ID row. A step-up stays local on /signin too, because reauth=1 rides every one of those links.

Wrap SigninDoor and SigninOficina in the app's admission check. They read the session cookie and nothing else, so a session the app's signed-in routes refuse (a removed member, a revoked share) counts as signed in. Unless the app ends or hides it first, /signin and the refusing page redirect to each other forever.

Bumping connect is a compile break (Routes.Signin is gone). MIGRATING.md has the per-app changes, including an interim that keeps today's behaviour until an app moves to the new door.

Remembering Oficina ID is the app's job, in Config.MintHomeSession. connect imports no lastsignin or auth (its go.mod still requires rastrillo v0.38.0, so a bump moves you there). After storing the session, call RememberJar().Remember with lastsignin.MethodFederated, ProviderOficina and the address of connect.MintedPerson(r) (empty for a Home-only person). Never carry an address over from the record already in the jar. connect calls the hook only where a Home sign-in becomes a session (a finished exchange, and "I'm new here"), never on link, choose, unknown or failed.

Signed out. Set RoutesConfig.ForgetPath to where you mounted rastrillo auth's Forget. PageFor(r, "signedout", …) on the request Routes.SignedOut renders then carries it as PageData.ForgetAction. Draw it with estilo's estilo-signed-out: chrome.SignInNotice{…}.SignedOut(p.Action).Forgetting(p.ForgetAction, ""). It is a plain same-origin POST, which csrf.SameOrigin admits, so it stays inside Middleware's CSRF check with no token. It forgets this host only; id.oficina.works keeps and forgets its own record.

Signing out

Routes.Signout ends the app session and then answers 307 to {Issuer}/signout, which ends the Home sign-in session too and returns the browser to the app's /signed-out. Home admits that hop only from an origin registered in its HOME_CONSUMERS, by Referer when the browser nulls Origin, so a page showing Sign out must not send Referrer-Policy: no-referrer (use strict-origin), and a custom policy must keep the issuer in form-action.

Home-only people (team mode)

Config.Admit, Config.Unlinked and Config.HomeOnly are optional and set together; New refuses any one without the others. Without them nothing above changes. With them, a roster member with no account link here can still sign in, as an addressless person the app creates, which is what team mode needs for a member who has never had a local account (home/teammode, implementation/teammode-package.md). Home spec 2026-11-14-oficina-id-native.md §8 governs what follows. No hook is ever called with a transaction open: Docs has a single writer connection, and a hook waiting on it from inside connect's own transaction would wedge it.

  • HomeOnly(ctx, issuer, subject) reads, never creates, the person a subject was given. Connect asks it after the account link in ordinary resolution: Resolve, ResolveSession, completion and the native exchange, so the same-person rules hold for Home-only people too. It returns ErrNoPerson for none. The person has a positive ID and an empty Label; connect refuses one with a label, because there is no address to give. It may be asked about any subject linkstore refused, including one that is not a person ref, so it must not assume the subject's shape.
  • Admit(ctx, issuer, subject) is the roster decision, and it comes first: asked only for a verified subject with neither a link nor a Home-only person, and only when no app session is present, it allocates nothing. nil is a Member (teammode.Runtime.AdmitUnlinked), ErrNoPerson a non-member, any other error "cannot decide now". It must never ask whether the team has local or email accounts.
  • A non-member gets today's "unknown" answer byte for byte (403, with the resume-linking marker), the same as an instance without the hooks. An unavailable roster is a 503. A Member gets a sealed, single-use, ten-minute choice proof bound to the browser by __Host-oficina-home-choice (linkstore migration 0003) and a 303 to ChoosePath, /account/home/choose. Nothing is created yet, so a guest's local account never blocks a new member's first sign-in.
  • Mount Bridge.ChoosePage at GET and Bridge.ChoosePost at POST /account/home/choose, outside the session guards and inside the app's CSRF middleware. Render state "choose" with your own template from ChoiceFor(r) (the form's action and token) and the choose_* strings: title "Welcome to the team", and two buttons that POST choice=connect or choice=new with the token. The token is an HMAC of the proof cookie and the POST requires this exact Origin. - "Connect my existing account" consumes the proof and goes to /signin/local with the resume-linking marker, then slice 1's linking. - "I'm new here — continue with Oficina ID" refuses while any app session is present; otherwise it consumes the proof in its own short transaction, re-checks the link and Admit with none open, allocates through Unlinked, resolves again and mints. The person lands on /.
  • Unlinked(ctx, issuer, subject) may create that person, and is asked only after a Member's explicit "I'm new here" (the choose POST, or a native choice:"new"). It opens its own writer transaction and re-checks before it creates. Whatever it answers, connect resolves the subject again: a person found then (a racing choice made one) is used; otherwise ErrNoPerson is "unknown" and any other error a 503.
  • A subject arriving over a live session is never allocated and no proof is issued: an unknown one is refused as "unknown", and a known one that is not the signed-in person is refused as "failed", leaving that session in place. Every cookie shape check stays connect's.

Bridge.Linked knows nothing of Home-only people, so an app should not offer "Connect your Oficina account" to one: there is no local account to connect.

Native apps: NativeExchange

A native app holding an Oficina ID grant asks Home for an assertion for this origin (POST https://id.oficina.works/native/v1/assert {aud, challenge}) and trades it here, with no browser, for a session. Set Config.MintNativeSession (store the session, return its cookie value, set no cookie) and mount Bridge.NativeExchange at POST /native/oficina-id (NativeExchangePath). Routes.Middleware lets that one path past the CSRF check: the exchange itself refuses any request carrying Origin or Sec-Fetch-Site, any query, and anything but application/json.

The request is {"assertion", "verifier", "target"?, "choice"?}. The verifier is 32 random bytes; Home sets the assertion's nonce from its challenge, and the exchange recomputes it (handoff.NativeChallenge, handoff.NativeNonce; the derivation and a test vector are in handoff/native.go). Answers are JSON {"state": …}, no-store, with no cookies:

| Status | state | Meaning | |---|---|---| | 200 | ok | name (the session cookie), value, expires_at (unix, 7 days), target echoed if sent | | 400 | invalid | malformed request | | 401 | failed | assertion not accepted (signature, audience, expiry, verifier, already used): get a fresh one | | 403 | unknown | no person here and none may be made; identical for every such subject and instance | | 409 | choose | a roster Member with no person here: offer both routes; send choice:"new" only from "I'm new here" | | 503 | unavailable | try again shortly |

"Connect my existing account" in the app opens <origin>/account/home in the default browser. The exchange writes the assertion's jti only once it is about to mint, in its own committed transaction (handoff.Store.Reserve); a jti burned with no session (a crash, or the final recheck refusing) costs the app one fresh assertion.

The session's method is NativeMethod, home-assertion-native. Every check on a Home sign-in uses IsHomeDerived(method), true for HomeMethod, NativeMethod and NativeWebMethod. Expired refuses a native or native-web session more than seven days after its At, absolute; an app that resolves sessions itself rather than through ResolveSession must refuse what it refuses. The app re-mints after a day and on any 401.

Moving existing links onto connect

An app that already links Home identities in its own table (Docs' docs_identity_links) carries them over with Bridge.Adopt(ctx, tx, issuer, subject, personID). A plain SQL copy does not work. Every home_identity_links row carries person_binding, a keyed hash of the person's address under the storage key, and Resolve refuses a row whose binding does not match. Copied rows would stop resolving at once. Adopt asks LookupPerson for the address inside your transaction and writes the row that linking here would have written. The address is hashed and never stored. Adopt checks nothing about the subject: your table vouches for it.

Do it once, at boot, after the migrations and New and before serving:

  1. Begin a transaction on Config.DB.
  2. Read your old rows and call Adopt for each.
  3. Retire the old table in the same transaction, then commit.

If the old table is absent, there is nothing to do. A repeat of an identical row is not an error, so a boot that stops partway can simply run again. ErrRefused means nothing was written. Its causes are:

  • a foreign issuer;
  • an invalid subject;
  • a person LookupPerson does not return now (that link could not resolve anyway);
  • the subject already linked to another person;
  • the person already linked under another subject;
  • an existing row with a stale or missing binding. Adopt never repairs one.

The app decides whether a refusal aborts the move or drops that row, and should say which. ErrStorage means roll back.

LookupPerson must read through the Queryer it is given, as it must already. A lookup on its own connection deadlocks against the open transaction on a single-connection pool.

Carry the old link clock in the same transaction with UPDATE home_link_clock SET high_water = MAX(high_water, ?) WHERE id = 1. Do not carry in-flight link flows. They last five minutes, and a person mid-link starts again.

Adopt does not consult Config.HomeOnly. An app with Home-only people keeps their subjects disjoint from links itself, as Docs does with triggers.

Extraction record

The link proof protocol, bridge, freshness rules and navigation originate in Oficina Docs commit 3fffd1be535ec87ab6e92da753046a4f1e4c754c, whose tree matches reviewed deployment a8f5c0e1d67ad042e89793aa941135eacd98aa23. The original files live under internal/docs/home_* and internal/docs/linkstore. This extraction preserves the consumed proof stages, nonce/session binding, clock watermark, freshness windows and encrypted flow purpose strings.

Changes are the neutral session DTO and app lookup hooks, new home_* link tables, app-selected encryption namespace, and shared rendering/navigation. The local-person foreign key becomes a transaction-scoped existence/admission lookup, because apps use different local identity tables. Every link write and subsequent resolution still checks the current local account. Additive migration 0002 adds a keyed person binding; earlier unbound rows fail closed. OAuth continuation also derives from Docs internal/docs/auth_navigation.go.

The original Docs state-machine tests were ported with synthetic session and local-account hooks. The app-owned content-preservation test now checks an unchanged content row; framework CSRF coverage belongs to the shared Routes and each app's router integration tests. Existing Docs tables and bytes are untouched. This is not a migration path for an already deployed Docs instance.

Bridge.ResolveOn(ctx, q, subject) is explicitly limited to existing account links. It verifies the complete keyed binding and current local lookup through q, including while the caller holds SQLite's writer. It never invokes HomeOnly or Unlinked: those hooks cannot use the caller's transaction. An addressless identity is refused by this method. Ordinary Resolve, session resolution and browser completion retain their Home-only behavior. Agent consumers that require linked local accounts must apply that restriction to reads and response checks as well as writes.