Line data Source code
1 : import { z } from 'zod'
2 :
3 : import { CredentialResponseSchema } from './exchange'
4 : import type { AccountCredential } from './sessionContracts'
5 :
6 : /**
7 : * Raw string storage for the credential cache. Hosts wrap their medium —
8 : * per-tab browser storage today, a cookie-backed session tomorrow. Each client
9 : * instance sees only its own storage: signing out in one tab leaves another
10 : * tab's session live until the server revokes it and the next remint 401s.
11 : */
12 : export interface CredentialStorage {
13 : read: () => string | null
14 : write: (value: string) => void
15 : clear: () => void
16 : }
17 :
18 : /** The generated contract for POST /api/auth/token, never a local copy of it. */
19 2356 : const CachedCredentialSchema = CredentialResponseSchema.omit({
20 : expires_at: true,
21 : user_id: true
22 : }).extend({
23 : // Storage and broadcast are untrusted boundaries: an empty token can never
24 : // authorize and a non-finite expiry can never lapse, so neither is a session.
25 : token: z.string().min(1),
26 : expiresAt: z.number().finite(),
27 : uid: z.string(),
28 : /** The workspace target the credential was minted for; absent = personal. */
29 : target: z.string().optional()
30 : })
31 :
32 : interface CachedCredential {
33 : readonly credential: AccountCredential
34 : readonly target: string | undefined
35 : }
36 :
37 0 : function toCredential(
38 : data: z.infer<typeof CachedCredentialSchema>
39 : ): AccountCredential {
40 0 : return {
41 : token: data.token,
42 : expiresAt: data.expiresAt,
43 : uid: data.uid,
44 : workspace: data.workspace,
45 : role: data.role,
46 : permissions: data.permissions
47 : }
48 : }
49 :
50 0 : export function encodeCached(
51 : session: AccountCredential,
52 : target: string | undefined
53 : ): string {
54 0 : return JSON.stringify({ ...session, target })
55 : }
56 :
57 0 : export function decodeCached(
58 : raw: string,
59 : uid: string
60 : ): CachedCredential | undefined {
61 0 : let parsed: unknown
62 0 : try {
63 0 : parsed = JSON.parse(raw)
64 : } catch {
65 0 : return undefined
66 : }
67 0 : const result = CachedCredentialSchema.safeParse(parsed)
68 0 : if (!result.success || result.data.uid !== uid) return undefined
69 0 : return { credential: toCredential(result.data), target: result.data.target }
70 : }
71 :
72 0 : export function decodeAdopted(message: unknown): AccountCredential | undefined {
73 0 : const parsed = CachedCredentialSchema.safeParse(message)
74 0 : return parsed.success ? toCredential(parsed.data) : undefined
75 : }
76 :
77 : interface CredentialCache {
78 : read: (uid: string) => CachedCredential | undefined
79 : write: (session: AccountCredential, target: string | undefined) => void
80 : clear: () => void
81 : }
82 :
83 2356 : export const DEFAULT_FRESH_MARGIN_MS = 5 * 60 * 1000
84 :
85 0 : export function isCredentialFresh(
86 : session: AccountCredential,
87 : now: number,
88 : freshMarginMs: number = DEFAULT_FRESH_MARGIN_MS
89 : ): boolean {
90 0 : return session.expiresAt - now > freshMarginMs
91 : }
92 :
93 : interface CredentialCandidate {
94 : readonly credential: AccountCredential | undefined
95 : readonly target: string | undefined
96 : }
97 :
98 : /**
99 : * The live credential is authoritative; storage is recovery state, not a
100 : * competing source. Candidates are consulted in the order given (memory
101 : * first, then storage) for this exact uid and target, and the first fresh one
102 : * wins — expiry must not override this (a rejected token can outlive its
103 : * shorter-lived replacement), and a target-less read must never adopt a team
104 : * session.
105 : */
106 0 : export function selectFreshCredential(
107 : candidates: readonly (() => CredentialCandidate | undefined)[],
108 : uid: string,
109 : target: string | undefined,
110 : now: number,
111 : freshMarginMs: number
112 : ): AccountCredential | undefined {
113 0 : for (const supply of candidates) {
114 0 : const candidate = supply()
115 0 : if (
116 : candidate?.credential?.uid === uid &&
117 : candidate.target === target &&
118 : isCredentialFresh(candidate.credential, now, freshMarginMs)
119 : ) {
120 0 : return candidate.credential
121 : }
122 : }
123 : return undefined
124 : }
125 :
126 2355 : export function createCredentialCache(
127 : storage: CredentialStorage
128 : ): CredentialCache {
129 2355 : return {
130 : read(uid) {
131 0 : let raw: string | null
132 0 : try {
133 0 : raw = storage.read()
134 : } catch {
135 0 : return undefined
136 : }
137 0 : return raw === null ? undefined : decodeCached(raw, uid)
138 : },
139 : write(session, target) {
140 0 : try {
141 0 : storage.write(encodeCached(session, target))
142 : } catch {
143 : void 0
144 : }
145 : },
146 : clear() {
147 4699 : try {
148 4699 : storage.clear()
149 : } catch {
150 : void 0
151 : }
152 : }
153 : }
154 : }
|