oficina / home Public

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

Plain git — no account needed to clone.

Download

Download this file

1package home
2
3import (
4 "crypto/elliptic"
5 "crypto/hmac"
6 "crypto/rand"
7 "crypto/sha256"
8 "database/sql"
9 "encoding/base64"
10 "encoding/hex"
11 "encoding/json"
12 "errors"
13 "io"
14 "mime"
15 "net/http"
16 "strings"
17 "time"
18
19 assertioncrypto "amadan.net/rastrillo/rastrillo/crypto"
20 "github.com/go-chi/chi/v5"
21 strictjson "github.com/go-json-experiment/json"
22)
23
24// The native half of Oficina ID (docs/superpowers/specs/2026-11-14-oficina-id-native.md).
25//
26// Every endpoint here lives under nativePrefix on the credential origin. They
27// take JSON only, answer no-store, send no CORS headers, render nothing and
28// refuse any request carrying Origin or Sec-Fetch-Site: a browser has no
29// business here, and refusing its evidence headers keeps every one of these
30// endpoints out of reach of a page (§4).
31const nativePrefix = "/native/v1"
32
33const (
34 // nativeProofContext domain-separates the device-key proof (§3).
35 nativeProofContext = "oficina-id/native-proof/v1"
36
37 nativeProofSkew = 30 // |iat − now| allowed, seconds
38 nativeReplayHold = 61 // seconds a jti stays in the replay table: see below
39 nativeReplayPerMin = 120 // accepted calls per grant per minute
40 nativePersonPerMin = 300 // and per person, across all their grants
41 nativeGrantIdleDays = 90 // a grant unused this long has expired
42 nativeGrantLife = 365 * day // absolute grant lifetime
43 nativeGrantKeep = 365 * day // how long an ended grant keeps its device key
44 nativeGrantsPerID = 20 // live grants per person; a 21st ends the LRU
45 nativeBodyLimit = 64 << 10
46 day = 24 * 3600
47)
48
49// nativeReplayCap is how many replay rows the table holds before it fails
50// closed. A variable only so a test can fill it without 250,000 inserts.
51var nativeReplayCap = 250000
52
53// nativePlatforms is the closed set a device may report. It is self-reported
54// and decides nothing; it exists so A2's Devices page can draw a fixed label.
55var nativePlatforms = map[string]bool{"macos": true, "ios": true, "ipados": true}
56
57// mountNative mounts the native endpoints on the credential role. They sit
58// outside csrf.Protect: they refuse every browser evidence header instead.
59func (a *App) mountNative(r chi.Router) {
60 r.Group(func(r chi.Router) {
61 r.Use(a.credentialOnly)
62 r.Post(nativePrefix+"/code/start", a.nativeCodeStart)
63 r.Post(nativePrefix+"/code/resend", a.nativeCodeResend)
64 r.Post(nativePrefix+"/code/verify", a.nativeCodeVerify)
65 r.Post(nativePrefix+"/passkey/begin", a.nativePasskeyBegin)
66 r.Post(nativePrefix+"/passkey/finish", a.nativePasskeyFinish)
67 r.Post(nativePrefix+"/assert", a.nativeAuthed(a.nativeAssert))
68 r.Post(nativePrefix+"/signout", a.nativeAuthed(a.nativeSignout))
69 r.Get(aasaPath, a.serveAASA)
70 })
71}
72
73// nativeReply is every native answer. Date is set explicitly because the
74// client corrects its clock from it (§3); net/http would add one, but a
75// header the protocol depends on should not rest on a server default.
76func nativeReply(w http.ResponseWriter, status int, v any) {
77 h := w.Header()
78 h.Set("Cache-Control", "no-store")
79 h.Set("Content-Type", "application/json")
80 h.Set("X-Content-Type-Options", "nosniff")
81 h.Set("Date", time.Now().UTC().Format(http.TimeFormat))
82 w.WriteHeader(status)
83 _ = json.NewEncoder(w).Encode(v)
84}
85
86func nativeFail(w http.ResponseWriter, status int, code string) {
87 nativeReply(w, status, map[string]string{"error": code})
88}
89
90// The two 401 answers. The client wipes the device's identity only on
91// nativeGrantEnded: the grant is gone (never existed, revoked, signed out,
92// expired, replaced or swept by an enrolment). Every other refusal — a bad
93// signature, a skewed iat, a wrong htu or body, a replayed jti, a malformed
94// header — is nativeProofRejected, which the client may retry once after
95// correcting its clock from "now".
96const (
97 nativeGrantEnded = "grant_ended"
98 nativeProofRejected = "proof_rejected"
99)
100
101// nativeUnauthorized carries the server's clock, so a client whose proof
102// failed on iat can correct its offset and retry once (§3).
103func nativeUnauthorized(w http.ResponseWriter, code string) {
104 nativeReply(w, http.StatusUnauthorized, map[string]any{"error": code, "now": time.Now().Unix()})
105}
106
107// nativeIntake applies the transport rules every native endpoint shares and
108// returns the raw body, which the proof's bh covers byte for byte.
109func nativeIntake(w http.ResponseWriter, r *http.Request) ([]byte, bool) {
110 if _, ok := r.Header["Origin"]; ok {
111 nativeFail(w, http.StatusForbidden, "browser")
112 return nil, false
113 }
114 if _, ok := r.Header["Sec-Fetch-Site"]; ok {
115 nativeFail(w, http.StatusForbidden, "browser")
116 return nil, false
117 }
118 if r.URL.RawQuery != "" {
119 nativeFail(w, http.StatusBadRequest, "request")
120 return nil, false
121 }
122 media, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
123 if err != nil || media != "application/json" {
124 nativeFail(w, http.StatusUnsupportedMediaType, "json")
125 return nil, false
126 }
127 body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, nativeBodyLimit))
128 if err != nil {
129 nativeFail(w, http.StatusRequestEntityTooLarge, "request")
130 return nil, false
131 }
132 return body, true
133}
134
135// decodeNative is strict: unknown members, duplicates and trailing data are
136// all refusals, so two parsers can never read one body two ways.
137func decodeNative(body []byte, v any) bool {
138 return strictjson.Unmarshal(body, v, strictjson.RejectUnknownMembers(true)) == nil
139}
140
141// b64 is the one encoding on the native wire: base64url without padding.
142var nb64 = base64.RawURLEncoding
143
144func decodeB64(s string, n int) ([]byte, bool) {
145 b, err := nb64.Strict().DecodeString(s)
146 if err != nil || (n > 0 && len(b) != n) || nb64.EncodeToString(b) != s {
147 return nil, false
148 }
149 return b, true
150}
151
152// decodeDeviceKey accepts a 65-byte uncompressed P-256 point, base64url, and
153// nothing else — the shape rastrillo/crypto.Verify takes.
154func decodeDeviceKey(s string) ([]byte, bool) {
155 if len(s) != 87 {
156 return nil, false
157 }
158 b, ok := decodeB64(s, 65)
159 if !ok {
160 return nil, false
161 }
162 if x, _ := elliptic.Unmarshal(elliptic.P256(), b); x == nil {
163 return nil, false
164 }
165 return b, true
166}
167
168// nativeProof is the Oficina-Proof payload (§3). No JWT, no algorithm field.
169type nativeProof struct {
170 V int `json:"v"`
171 HTM string `json:"htm"`
172 HTU string `json:"htu"`
173 IAT int64 `json:"iat"`
174 JTI string `json:"jti"`
175 BH string `json:"bh"`
176}
177
178var errNativeProof = errors.New("home: native proof refused")
179
180// parseNativeProof reads the header without trusting any of it yet.
181func parseNativeProof(r *http.Request) (nativeProof, []byte, []byte, error) {
182 var p nativeProof
183 values := r.Header.Values("Oficina-Proof")
184 if len(values) != 1 || len(values[0]) > 2048 {
185 return p, nil, nil, errNativeProof
186 }
187 enc, sigEnc, ok := strings.Cut(values[0], ".")
188 if !ok || strings.Contains(sigEnc, ".") {
189 return p, nil, nil, errNativeProof
190 }
191 payload, ok := decodeB64(enc, 0)
192 if !ok {
193 return p, nil, nil, errNativeProof
194 }
195 sig, ok := decodeB64(sigEnc, 64)
196 if !ok {
197 return p, nil, nil, errNativeProof
198 }
199 if !decodeNative(payload, &p) {
200 return p, nil, nil, errNativeProof
201 }
202 if p.V != 1 || p.HTM == "" || p.HTU == "" || p.IAT <= 0 || !nativeJTI(p.JTI) || len(p.BH) != 43 {
203 return p, nil, nil, errNativeProof
204 }
205 return p, payload, sig, nil
206}
207
208func nativeJTI(s string) bool {
209 if len(s) < 16 || len(s) > 64 {
210 return false
211 }
212 for i := 0; i < len(s); i++ {
213 if !alphaNumeric(s[i]) && s[i] != '-' && s[i] != '_' {
214 return false
215 }
216 }
217 return true
218}
219func alphaNumeric(b byte) bool {
220 return b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b >= '0' && b <= '9'
221}
222
223// verifyNativeProof is the whole check except the jti, which the caller
224// records only after this passes (§3: no jti row before the grant and the
225// signature verify).
226func (a *App) verifyNativeProof(r *http.Request, body, key []byte, p nativeProof, payload, sig []byte, now int64) bool {
227 if !assertioncrypto.Verify(key, nativeProofContext, payload, sig) {
228 return false
229 }
230 bh := sha256.Sum256(body)
231 skew := p.IAT - now
232 return p.HTM == r.Method &&
233 p.HTU == a.origins.Credential+r.URL.Path &&
234 skew <= nativeProofSkew && skew >= -nativeProofSkew &&
235 hmac.Equal([]byte(p.BH), []byte(nb64.EncodeToString(bh[:])))
236}
237
238// nativeKey derives one purpose's Home-only key from the pepper:
239// HKDF-SHA256 (rastrillo crypto.Derive, salt nil) with the info label
240// "oficina-id/<purpose>/v1". The purposes are identity-id, native-code,
241// native-address, native-ip and native-bucket; distinct labels give
242// independent keys, none equal to the pepper the people index uses (§3:
243// identity_id is an HMAC under a dedicated key). Paul accepted deriving them
244// from HOME_PEPPER on 2026-11-14, on that domain separation.
245//
246// What rotating HOME_PEPPER would invalidate here, beyond the people index
247// it already orphans: every identity_id changes (a device's stored ID no
248// longer matches what a mint returns, so "Already signed in" detection
249// breaks until each device signs in again, and home_id_grants.identity_id
250// goes stale); every live code stops verifying (code_mac); and the native
251// rate-limit buckets and start uniqueness reset, because their keys are
252// blinded under it. Grants themselves survive: grant_hash is a plain
253// SHA-256 of the token.
254func (a *App) nativeKey(purpose string) []byte {
255 return assertioncrypto.Derive(a.secrets.Pepper, "oficina-id/"+purpose+"/v1")
256}
257
258func (a *App) nativeMAC(purpose string, parts ...string) string {
259 m := hmac.New(sha256.New, a.nativeKey(purpose))
260 for _, p := range parts {
261 m.Write([]byte(p))
262 m.Write([]byte{0})
263 }
264 return hex.EncodeToString(m.Sum(nil))
265}
266
267// identityID is what a device keys an identity by; it never holds the ref.
268func (a *App) identityID(person string) string {
269 m := hmac.New(sha256.New, a.nativeKey("identity-id"))
270 m.Write([]byte(person))
271 return nb64.EncodeToString(m.Sum(nil))
272}
273
274func nativeHash(s string) string { h := sha256.Sum256([]byte(s)); return hex.EncodeToString(h[:]) }
275
276func nativeToken() (string, error) {
277 b := make([]byte, 32)
278 if _, err := rand.Read(b); err != nil {
279 return "", err
280 }
281 return nb64.EncodeToString(b), nil
282}
283
284// nativeGrant is a live grant as loaded for one authenticated call.
285type nativeGrant struct {
286 hash, person, identityID, deviceKey, platform, method string
287 authTime int64
288}
289
290func dayOf(unix int64) string { return time.Unix(unix, 0).UTC().Format(dayFormat) }
291
292// idleCutoff is the newest last_used_day that has already expired: a grant
293// last used on day D lapses at the start of D+91, whatever hour it was used.
294func idleCutoff(now int64) string { return dayOf(now - (nativeGrantIdleDays+1)*day) }
295
296// nativeAuthed authenticates a grant-holding call (§3) and hands the handler
297// an open writer transaction. The handler's answer is committed together
298// with the jti, so a refused handler still spends its jti.
299func (a *App) nativeAuthed(handle func(tx *sql.Tx, g nativeGrant, body []byte, now int64) (int, any)) http.HandlerFunc {
300 return func(w http.ResponseWriter, r *http.Request) {
301 body, ok := nativeIntake(w, r)
302 if !ok {
303 return
304 }
305 auth := r.Header.Values("Authorization")
306 token, found := "", false
307 if len(auth) == 1 {
308 token, found = strings.CutPrefix(auth[0], "OficinaID ")
309 }
310 if !found || len(token) != 43 {
311 nativeUnauthorized(w, nativeProofRejected)
312 return
313 }
314 if _, ok := decodeB64(token, 32); !ok {
315 nativeUnauthorized(w, nativeProofRejected)
316 return
317 }
318 p, payload, sig, err := parseNativeProof(r)
319 if err != nil {
320 nativeUnauthorized(w, nativeProofRejected)
321 return
322 }
323 tx, now, err := a.idTransaction(r.Context())
324 if err != nil {
325 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
326 return
327 }
328 defer tx.Rollback()
329 var g nativeGrant
330 var expires int64
331 var lastUsed string
332 var ended sql.NullInt64
333 g.hash = nativeHash(token)
334 var created int64
335 err = tx.QueryRow("SELECT person_ref,identity_id,device_key,platform,method,auth_time,expires_at,last_used_day,ended_at,created_at FROM home_id_grants WHERE grant_hash=?", g.hash).
336 Scan(&g.person, &g.identityID, &g.deviceKey, &g.platform, &g.method, &g.authTime, &expires, &lastUsed, &ended, &created)
337 if errors.Is(err, sql.ErrNoRows) || (err == nil && ended.Valid) {
338 nativeUnauthorized(w, nativeGrantEnded)
339 return
340 }
341 if err != nil {
342 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
343 return
344 }
345 // Belt and braces: "Sign out all devices" ends every grant in the
346 // same transaction as its mark, so none created at or before the
347 // mark should be live; if one is, it is not honoured.
348 if before, err := signedOutBefore(r.Context(), tx, "home_id_signed_out_all", g.person, created); err != nil || before {
349 if err != nil {
350 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
351 } else {
352 nativeUnauthorized(w, nativeGrantEnded)
353 }
354 return
355 }
356 if expires <= now || lastUsed <= idleCutoff(now) {
357 if _, err = tx.Exec("UPDATE home_id_grants SET ended_at=?,end_reason='expiry' WHERE grant_hash=? AND ended_at IS NULL", now, g.hash); err != nil || tx.Commit() != nil {
358 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
359 return
360 }
361 nativeUnauthorized(w, nativeGrantEnded)
362 return
363 }
364 key, ok := decodeDeviceKey(g.deviceKey)
365 if !ok || !a.verifyNativeProof(r, body, key, p, payload, sig, now) {
366 nativeUnauthorized(w, nativeProofRejected)
367 return
368 }
369 // Only now, with the grant live and the signature good, does the jti
370 // touch the table. A row lives 61 seconds, not 60: iat may be 30
371 // seconds ahead of now and is accepted until 30 seconds behind, so
372 // the last second a replay could pass is now+60, and the row must
373 // still be there then.
374 if _, err = tx.Exec("DELETE FROM home_id_native_replay WHERE expires_at<=?", now); err != nil {
375 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
376 return
377 }
378 var total, mine int
379 if tx.QueryRow("SELECT count(*) FROM home_id_native_replay").Scan(&total) != nil {
380 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
381 return
382 }
383 if total >= nativeReplayCap {
384 // Fails closed: a full table refuses every proof rather than
385 // forgetting the oldest ones and readmitting their replays.
386 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
387 return
388 }
389 if tx.QueryRow("SELECT count(*) FROM home_id_native_replay WHERE grant_hash=?", g.hash).Scan(&mine) != nil {
390 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
391 return
392 }
393 if mine >= nativeReplayPerMin {
394 nativeFail(w, http.StatusTooManyRequests, "rate_limited")
395 return
396 }
397 // Per person as well, so one account's twenty grants cannot spend a
398 // fifth of the table between them: filling it takes hundreds of
399 // accounts, each behind its own mailbox.
400 var theirs int
401 if tx.QueryRow("SELECT count(*) FROM home_id_native_replay WHERE person_ref=?", g.person).Scan(&theirs) != nil {
402 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
403 return
404 }
405 if theirs >= nativePersonPerMin {
406 nativeFail(w, http.StatusTooManyRequests, "rate_limited")
407 return
408 }
409 res, err := tx.Exec("INSERT INTO home_id_native_replay(jti_hash,grant_hash,person_ref,expires_at) VALUES(?,?,?,?) ON CONFLICT DO NOTHING", nativeHash(g.hash+"\x00"+p.JTI), g.hash, g.person, now+nativeReplayHold)
410 if err != nil {
411 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
412 return
413 }
414 if n, err := res.RowsAffected(); err != nil || n != 1 {
415 nativeUnauthorized(w, nativeProofRejected)
416 return
417 }
418 if today := dayOf(now); lastUsed != today {
419 if _, err = tx.Exec("UPDATE home_id_grants SET last_used_day=? WHERE grant_hash=?", today, g.hash); err != nil {
420 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
421 return
422 }
423 }
424 status, reply := handle(tx, g, body, now)
425 if status == 0 || tx.Commit() != nil {
426 nativeFail(w, http.StatusServiceUnavailable, "unavailable")
427 return
428 }
429 nativeReply(w, status, reply)
430 }
431}
432
433// nativePreGrant verifies a proof-only call (§3): one made before a grant
434// exists, signed by the key the call is bound to. These never touch the jti
435// table; their single-use start or challenge is their replay protection.
436func (a *App) nativePreGrant(r *http.Request, body []byte, deviceKey string, now int64) bool {
437 key, ok := decodeDeviceKey(deviceKey)
438 if !ok {
439 return false
440 }
441 p, payload, sig, err := parseNativeProof(r)
442 return err == nil && a.verifyNativeProof(r, body, key, p, payload, sig, now)
443}
444
445// mintGrant issues a grant to one device. It is called inside the writer
446// transaction that consumed the sign-in's proof, so a grant exists only if
447// that proof is gone.
448func (a *App) mintGrant(tx *sql.Tx, person, deviceKey, platform, method string, authTime, now int64) (map[string]any, error) {
449 if err := sweepGrants(tx, now); err != nil {
450 return nil, err
451 }
452 // A 21st live grant ends the least recently used one.
453 for {
454 var live int
455 if err := tx.QueryRow("SELECT count(*) FROM home_id_grants WHERE person_ref=? AND ended_at IS NULL", person).Scan(&live); err != nil {
456 return nil, errIDProof
457 }
458 if live < nativeGrantsPerID {
459 break
460 }
461 if _, err := tx.Exec("UPDATE home_id_grants SET ended_at=?,end_reason='lru' WHERE grant_hash=(SELECT grant_hash FROM home_id_grants WHERE person_ref=? AND ended_at IS NULL ORDER BY last_used_day,created_at LIMIT 1)", now, person); err != nil {
462 return nil, errIDProof
463 }
464 }
465 token, err := nativeToken()
466 if err != nil {
467 return nil, errIDProof
468 }
469 id := a.identityID(person)
470 if _, err = tx.Exec("INSERT INTO home_id_grants(grant_hash,person_ref,identity_id,device_key,platform,method,auth_time,created_at,last_used_day,expires_at) VALUES(?,?,?,?,?,?,?,?,?,?)",
471 nativeHash(token), person, id, deviceKey, platform, method, authTime, now, dayOf(now), now+nativeGrantLife); err != nil {
472 return nil, errIDProof
473 }
474 return map[string]any{"grant": token, "identity_id": id, "auth_time": authTime}, nil
475}
476
477// sweepGrants marks lapsed grants as expired and forgets ended ones once
478// their device key is no longer needed to recognise a returning device.
479func sweepGrants(tx *sql.Tx, now int64) error {
480 if _, err := tx.Exec("UPDATE home_id_grants SET ended_at=?,end_reason='expiry' WHERE ended_at IS NULL AND (expires_at<=? OR last_used_day<=?)", now, now, idleCutoff(now)); err != nil {
481 return errIDProof
482 }
483 if _, err := tx.Exec("DELETE FROM home_id_grants WHERE ended_at IS NOT NULL AND ended_at<=?", now-nativeGrantKeep); err != nil {
484 return errIDProof
485 }
486 return nil
487}
488
489// endGrants ends every live grant a person holds, for one reason: "all_devices"
490// and "replacement" (§3, §10).
491func endGrants(tx *sql.Tx, person, reason string, now int64) error {
492 _, err := tx.Exec("UPDATE home_id_grants SET ended_at=?,end_reason=? WHERE person_ref=? AND ended_at IS NULL", now, reason, person)
493 if err != nil {
494 return errIDProof
495 }
496 return nil
497}
498
499// endPasskeylessGrants is a first passkey enrolment's revocation (§3): every
500// live grant whose method has no passkey ends, except the enrolling grant. A
501// web enrolment has none, so it passes "".
502func endPasskeylessGrants(tx *sql.Tx, person, except string, now int64) error {
503 _, err := tx.Exec("UPDATE home_id_grants SET ended_at=?,end_reason='enrolment' WHERE person_ref=? AND ended_at IS NULL AND instr(method,'passkey')=0 AND grant_hash<>?", now, person, except)
504 if err != nil {
505 return errIDProof
506 }
507 return nil
508}
509
510// returningKey reports §4's exemption. Any live grant for this (person,
511// key) makes it returning. Otherwise the most recently ENDED grant decides:
512// returning if it ended by expiry, lru or enrolment; not if by "Sign out all
513// devices", Revoke or recovery replacement — those are how a lost device is
514// cut off, and a later-created grant that happened to end earlier must not
515// undo that.
516func returningKey(tx *sql.Tx, person, deviceKey string) (bool, error) {
517 if person == "" {
518 return false, nil
519 }
520 var live int
521 if err := tx.QueryRow("SELECT count(*) FROM home_id_grants WHERE person_ref=? AND device_key=? AND ended_at IS NULL", person, deviceKey).Scan(&live); err != nil {
522 return false, errIDProof
523 }
524 if live > 0 {
525 return true, nil // live, or lapsed and not yet swept: lapsing is expiry
526 }
527 var reason sql.NullString
528 err := tx.QueryRow("SELECT end_reason FROM home_id_grants WHERE person_ref=? AND device_key=? ORDER BY ended_at DESC, created_at DESC LIMIT 1", person, deviceKey).Scan(&reason)
529 if errors.Is(err, sql.ErrNoRows) {
530 return false, nil
531 }
532 if err != nil {
533 return false, errIDProof
534 }
535 switch reason.String {
536 case "expiry", "lru", "enrolment":
537 return true, nil
538 }
539 return false, nil
540}
541