oficina / home Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package connect adapts the Home handoff to an application's existing identity.
2// It grants no membership and never creates local accounts or sample content.
3package connect
4
5import (
6 "context"
7 "database/sql"
8 "errors"
9 "net/http"
10 "time"
11
12 "amadan.net/oficina/home/connect/linkstore"
13)
14
15const HomeMethod = "home-assertion"
16
17// NativeMethod is a session minted by NativeExchange for a native app, from
18// an assertion Home made for a device grant (Home spec
19// 2026-11-14-oficina-id-native.md §7). NativeWebMethod is the browser
20// session "Open on the web" mints (§12, slice D); connect does not mint it
21// yet, but resolves and ages it like any Home-derived session.
22const (
23 NativeMethod = "home-assertion-native"
24 NativeWebMethod = "home-native-web"
25)
26
27// NativeLifetime is how long after its creation (Session.At) connect accepts
28// a NativeMethod or NativeWebMethod session: absolute, never sliding (Paul,
29// 2026-11-14). The app re-mints after a day and on any 401; this bounds what
30// an offline device keeps after its grant is revoked.
31const NativeLifetime = 7 * 24 * time.Hour
32
33// IsHomeDerived reports whether a session method names a person by their
34// Home subject: a browser sign-in through Home, a native exchange, or a
35// native-to-web handoff. Every check that used to compare a method with
36// HomeMethod asks this instead, so the three are one kind of session.
37func IsHomeDerived(method string) bool {
38 switch method {
39 case HomeMethod, NativeMethod, NativeWebMethod:
40 return true
41 }
42 return false
43}
44
45// Expired reports whether connect refuses a session by its age: a native or
46// native-web session more than NativeLifetime after its At, or one with no
47// At at all (fail closed). Browser and local sessions keep the session
48// store's own expiry. Apps that resolve sessions themselves, rather than
49// through ResolveSession, must refuse what this refuses.
50func Expired(s Session, now time.Time) bool {
51 if s.Method != NativeMethod && s.Method != NativeWebMethod {
52 return false
53 }
54 return s.At.IsZero() || s.At.After(now.Add(time.Minute)) || now.Sub(s.At) > NativeLifetime
55}
56
57// Session times must come from the verified stored session, never request or last-seen time.
58// AuthTime is the method verification time; At is immutable session creation time.
59type Session struct {
60 Subject, Method string
61 AuthTime, At time.Time
62}
63
64// Person.Label is the canonical verified local address, never a display name.
65// Local IDs must never be reused, including for a new account with the same address.
66type Person struct {
67 ID int64
68 Label string
69}
70
71type Config struct {
72 DB *sql.DB
73 Origin, Issuer, ConsumerID, Namespace, SessionCookie string
74 Keys map[string][]byte
75 DEK []byte
76 // ReadSession must resolve the actual verified session, never a supplied subject.
77 ReadSession func(*http.Request) (*Session, error)
78 // MintHomeSession stores the browser session for a Home sign-in
79 // (Method HomeMethod, the assertion's AuthTime) and sets its cookie.
80 // It is called only where a Home sign-in becomes a session: a finished
81 // exchange (Finish) and a Member's "I'm new here" (ChoosePost). Never
82 // for linking, the choose page, "unknown" or "failed".
83 //
84 // That makes it the one place an app remembers "Continue with Oficina
85 // ID" for its smart door (Home spec 2026-11-19-smart-door.md, "The
86 // cookie"), and connect leaves it to the app: connect imports no
87 // lastsignin or auth. (Its go.mod requires rastrillo v0.38.0, so a
88 // bump still moves an app there.)
89 // Once the session is stored, the app records the federated way in
90 // with the address of the person who just signed in, or with none:
91 //
92 // p, _ := connect.MintedPerson(r)
93 // auth.RememberJar().Remember(w, lastsignin.Record{
94 // Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina,
95 // Address: p.Label, // "" for a Home-only person
96 // })
97 //
98 // MintedPerson is the person connect resolved for this sign-in. Never
99 // carry an address over from the record already in the jar: it may be
100 // somebody else's. A failure to remember must not fail the sign-in.
101 // NativeExchange mints through MintNativeSession, never this hook, and
102 // a native client has no browser jar to remember in.
103 MintHomeSession func(http.ResponseWriter, *http.Request, Session) error
104 // Both lookup hooks must read current existing, admitted local accounts.
105 // They never create accounts or infer a Home link from an email address.
106 LookupLocalSession func(context.Context, Session) (Person, error)
107 LookupPerson linkstore.LookupPerson
108 Render func(http.ResponseWriter, *http.Request, string, string, int)
109 ReturnPath func(*http.Request) string
110 Now func() time.Time
111
112 // Admit, Unlinked and HomeOnly are optional and set together, or not
113 // at all; New refuses any one without the others. With all three nil,
114 // connect behaves exactly as it always has: an ordinary sign-in whose
115 // subject has no account link here is refused with the "unknown" page
116 // and the resume-linking marker. They exist for team mode
117 // (home/teammode), where a roster member who has never had a local
118 // account must be able to enter on their Home identity alone, as an
119 // addressless person. No hook is ever called with a transaction open.
120 //
121 // Admit is the roster decision, and it comes first (Home spec
122 // 2026-11-14-oficina-id-native.md §8): asked only for a verified
123 // subject with neither an account link nor a HomeOnly person, it
124 // allocates nothing. nil means a roster Member (in team mode, a Member
125 // decision whose lease is valid: teammode.Runtime.AdmitUnlinked);
126 // ErrNoPerson means a non-member, answered exactly as an unlinked
127 // subject on an instance without the hooks; any other error is "cannot
128 // decide now", a 503. A Member is not allocated: they are asked whether
129 // they already have an account here (the choose page, or 409 "choose"
130 // natively), so a guest's local account never blocks a new member.
131 // It must never ask whether the team has local or email accounts.
132 Admit func(ctx context.Context, issuer, subject string) error
133 // Unlinked may create the Home-only person for a subject. Connect asks
134 // it only after a Member chose "I'm new here" (the choose POST, or a
135 // native exchange with choice "new"), never in the link flow, never
136 // with an app session present, and only after re-checking Admit and
137 // that the subject still has no person. It must re-check before it
138 // creates, open its own writer transaction, and create only on a
139 // current decision that the subject may enter. ErrNoPerson or any
140 // other error makes connect resolve the subject again: a person found
141 // then (a racing choice made one) is used; otherwise ErrNoPerson is
142 // "unknown" and any other error a 503.
143 Unlinked func(ctx context.Context, issuer, subject string) (Person, error)
144 // HomeOnly reads, never creates, the person Unlinked gave a subject;
145 // ErrNoPerson when there is none. Connect asks it after the account
146 // link in ordinary resolution (Resolve, ResolveSession,
147 // completion), so the same-person rules hold for Home-only people too.
148 // ResolveOn is explicitly linked-only: this hook has no transaction input.
149 // A HomeOnly person has a positive ID and an empty Label: there is no
150 // address to give, and connect refuses a Home-only person with one.
151 HomeOnly func(ctx context.Context, issuer, subject string) (Person, error)
152
153 // MintNativeSession is optional and turns NativeExchange on. It stores
154 // a session for s (Method NativeMethod, the assertion's AuthTime) and
155 // returns its cookie value, which the app's native client then sends
156 // as SessionCookie. It must set no cookie, and it is called with no
157 // transaction open. connect refuses the session NativeLifetime after
158 // its At (Expired), so the store must record At at creation, and its
159 // own lifetime must be at least NativeLifetime: the answer promises the
160 // app expires_at = now + NativeLifetime.
161 MintNativeSession func(ctx context.Context, s Session) (string, error)
162}
163
164// MintedPerson is the person a Home sign-in resolved to, on the request
165// MintHomeSession is called with, and false on any other request. Label is
166// their canonical verified local address, or "" for a Home-only person.
167func MintedPerson(r *http.Request) (Person, bool) {
168 p, ok := r.Context().Value(mintedKey{}).(Person)
169 return p, ok
170}
171
172type mintedKey struct{}
173
174// mint is MintHomeSession for person, who must be the one connect resolved
175// for this sign-in.
176func (b *Bridge) mint(w http.ResponseWriter, r *http.Request, s Session, person Person) error {
177 return b.mintSession(w, r.WithContext(context.WithValue(r.Context(), mintedKey{}, person)), s)
178}
179
180// ErrNoPerson is what a Config.Unlinked or Config.HomeOnly hook returns for
181// "no person here for this subject", as distinct from a storage failure.
182var ErrNoPerson = errors.New("home connect: no person for this subject")
183
184// Resolve is the person a Home subject signs in as: an account link first,
185// then, when Config.HomeOnly is set, a Home-only person. It never creates
186// either. Its errors are linkstore's: ErrRefused for neither, ErrStorage
187// when that cannot be read.
188func (b *Bridge) Resolve(ctx context.Context, subject string) (Person, error) {
189 id, label, err := b.links.Resolve(ctx, b.issuer, subject)
190 if err == nil || b.homeOnly == nil || !errors.Is(err, linkstore.ErrRefused) {
191 return Person{ID: id, Label: label}, err
192 }
193 p, err := b.homeOnly(ctx, b.issuer, subject)
194 return homeOnlyPerson(p, err)
195}
196
197// homeOnlyPerson holds a hook's answer to the Home-only contract: a
198// positive ID and no address, ErrNoPerson for none, anything else storage.
199func homeOnlyPerson(p Person, err error) (Person, error) {
200 switch {
201 case err == nil && p.ID > 0 && p.Label == "":
202 return p, nil
203 case err == nil || errors.Is(err, ErrNoPerson):
204 return Person{}, linkstore.ErrRefused
205 }
206 return Person{}, linkstore.ErrStorage
207}
208
209// Linked reports whether the local person already has a stored link to an
210// Oficina identity. The account menu offers "Connect your Oficina account"
211// only when it does not, however this session signed in: someone linked who
212// signed in with the app's own email link is still linked. One indexed
213// lookup; an error means "unknown", and callers should offer nothing.
214func (b *Bridge) Linked(ctx context.Context, person int64) (bool, error) {
215 return b.links.Linked(ctx, person)
216}
217
218// Adopt carries one link from an app's own link table into connect's, inside
219// the app's transaction, so the row resolves exactly as one made by linking
220// here would. It exists for moving an app onto connect, once, at boot and
221// before serving; see linkstore.Store.Adopt for what it refuses.
222func (b *Bridge) Adopt(ctx context.Context, tx *sql.Tx, issuer, subject string, person int64) error {
223 return b.links.Adopt(ctx, tx, issuer, subject, person)
224}
225
226// ResolveOn resolves an existing account link at the fixed Home issuer on the
227// caller's transaction, including the keyed person binding and current local
228// admission. Unlike Resolve, it does not fall back to Config.HomeOnly: that
229// hook cannot read through the caller's transaction. A Home-only identity is
230// refused rather than resolved outside the transaction's authority checks.
231func (b *Bridge) ResolveOn(ctx context.Context, q linkstore.Queryer, subject string) (Person, error) {
232 id, label, err := b.links.ResolveOn(ctx, q, b.issuer, subject)
233 return Person{ID: id, Label: label}, err
234}
235
236func (b *Bridge) ResolveSession(r *http.Request) (Person, error) {
237 session, err := b.actualSession(r)
238 if err != nil || session == nil {
239 return Person{}, errIdentityRefused
240 }
241 return b.existingPerson(r, *session)
242}
243
244// FreshLocal accepts only independent local verification. A Keymail session
245// without auth_time cannot borrow its local session creation time.
246func FreshLocal(s Session, now time.Time) (time.Time, bool) {
247 if s.Subject == "" || (s.Method != "magiclink" && s.Method != "keymail") {
248 return time.Time{}, false
249 }
250 at := s.AuthTime
251 if at.IsZero() && s.Method == "magiclink" {
252 at = s.At
253 }
254 if at.IsZero() || at.After(now) || now.Sub(at) > 5*time.Minute {
255 return time.Time{}, false
256 }
257 return at, true
258}
259