@phibac/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/auth.ts ADDED
@@ -0,0 +1,371 @@
1
+ // Signing the user in: the authorization code flow with PKCE (S256) in a
2
+ // popup on the server's domain, the code handed back with postMessage
3
+ // (response_mode web_message), and DPoP-bound tokens. The access token
4
+ // lives in memory only; the refresh token is kept in IndexedDB. Nothing is
5
+ // written to localStorage or sessionStorage, and no token is put in a URL
6
+ // or logged.
7
+ import { BRAND } from "./brand.js";
8
+ import { createProof, getOrCreateKey, openPbDB, randomToken, sha256, type StoredTokens } from "./dpop.js";
9
+ import { PbError, SIGN_IN_HINT } from "./errors.js";
10
+ import { attempt, clockError, readJSON, type ProofSigner } from "./http.js";
11
+
12
+ /** Refresh the access token when it has less than this left. */
13
+ const REFRESH_MARGIN_MS = 60_000;
14
+ /** How often to check whether the user closed the sign-in popup. */
15
+ const POPUP_POLL_MS = 500;
16
+ export const POPUP_NAME = `${BRAND}-sign-in`;
17
+ export const POPUP_FEATURES = "popup,width=480,height=720";
18
+ /** The type of the message the server's done page posts (server/internal/auth/oauth.go). */
19
+ const AUTH_MESSAGE_TYPE = "pb:auth";
20
+
21
+ /** popupBlocked is the error for a sign-in popup the browser did not open. */
22
+ export function popupBlocked(): PbError {
23
+ return new PbError(
24
+ "popup_blocked",
25
+ `The browser blocked the ${BRAND} sign-in popup.`,
26
+ "Call connect() (or signIn()) directly from a click or key handler, not on page load or after an await, so the browser allows the popup.",
27
+ );
28
+ }
29
+
30
+ interface TokenResponse {
31
+ access_token: string;
32
+ refresh_token: string;
33
+ token_type: string;
34
+ expires_in: number;
35
+ user_id: string;
36
+ }
37
+
38
+ export interface AuthOptions {
39
+ /** The app ID (app_...). */
40
+ app: string;
41
+ /** The server, e.g. "https://pb.example.com". */
42
+ baseUrl: string;
43
+ }
44
+
45
+ export class Auth implements ProofSigner {
46
+ /**
47
+ * Resolves once the stored sign-in (if any) has been loaded from
48
+ * IndexedDB. Read signedIn and userId after `await auth.ready`; until
49
+ * then they are false and null. signIn, accessToken and signOut wait for
50
+ * it themselves.
51
+ */
52
+ readonly ready: Promise<void>;
53
+ /**
54
+ * Milliseconds to add to the device clock for DPoP proofs, learnt from
55
+ * the server's serverTime when it refuses a proof's iat.
56
+ */
57
+ clockOffsetMs = 0;
58
+
59
+ private readonly app: string;
60
+ private readonly base: string;
61
+ private readonly origin: string;
62
+ private readonly tokenKey: string;
63
+ private readonly lockName: string;
64
+ private _signedIn = false;
65
+ private _userId: string | null = null;
66
+ private access: { token: string; expiresAt: number } | null = null;
67
+ private refreshing: Promise<string> | null = null;
68
+ private signingIn: Promise<void> | null = null;
69
+ private signInPopup: Window | null = null;
70
+ private keys: Promise<CryptoKeyPair> | null = null;
71
+ private localTail: Promise<unknown> = Promise.resolve();
72
+
73
+ constructor(opts: AuthOptions) {
74
+ this.app = opts.app;
75
+ this.base = opts.baseUrl.replace(/\/+$/, "");
76
+ this.origin = new URL(this.base).origin;
77
+ this.tokenKey = `${this.origin} ${this.app}`;
78
+ this.lockName = `pb:refresh ${this.origin} ${this.app}`;
79
+ this.ready = this.load();
80
+ }
81
+
82
+ /** Whether a refresh token is stored for this app and server (after ready). */
83
+ get signedIn(): boolean {
84
+ return this._signedIn;
85
+ }
86
+
87
+ /** The signed-in user's ID (u_...), or null. */
88
+ get userId(): string | null {
89
+ return this._userId;
90
+ }
91
+
92
+ private async load(): Promise<void> {
93
+ const stored = await this.readStored();
94
+ this._signedIn = stored !== undefined;
95
+ this._userId = stored?.userId ?? null;
96
+ }
97
+
98
+ // ---- sign-in ----
99
+
100
+ /**
101
+ * signIn opens the sign-in popup on the server and resolves once the user
102
+ * has signed in and connected the app. Call it directly from a click or
103
+ * key handler: the popup is opened before anything is awaited so the
104
+ * browser still sees the user's gesture, as a blank window that is sent
105
+ * to the authorization page once the PKCE challenge (an async SHA-256) is
106
+ * ready. Rejects with popup_blocked, access_denied or sign_in_cancelled.
107
+ * A call while a sign-in is in flight returns that sign-in's promise.
108
+ * popup, when given, is a blank window the caller already opened inside
109
+ * the gesture (connect() does this); it is used instead of opening one.
110
+ */
111
+ signIn(popup?: Window): Promise<void> {
112
+ // A second call while a sign-in is in flight shares it: both would
113
+ // otherwise drive the same named popup and the first would fail.
114
+ if (this.signingIn) {
115
+ if (popup && popup !== this.signInPopup) popup.close();
116
+ return this.signingIn;
117
+ }
118
+ const run = this.runSignIn(popup);
119
+ this.signingIn = run;
120
+ const clear = () => {
121
+ if (this.signingIn === run) this.signingIn = null;
122
+ };
123
+ run.then(clear, clear);
124
+ return run;
125
+ }
126
+
127
+ private async runSignIn(given?: Window): Promise<void> {
128
+ // No await before this line: window.open must run inside the gesture.
129
+ const popup = given ?? window.open("", POPUP_NAME, POPUP_FEATURES);
130
+ if (!popup || popup.closed) throw popupBlocked();
131
+ this.signInPopup = popup;
132
+ let code: string;
133
+ const verifier = randomToken(32);
134
+ try {
135
+ const state = randomToken(16);
136
+ const challenge = await sha256(verifier);
137
+ const q = new URLSearchParams({
138
+ client_id: this.app,
139
+ origin: window.location.origin,
140
+ code_challenge: challenge,
141
+ code_challenge_method: "S256",
142
+ state,
143
+ response_mode: "web_message",
144
+ });
145
+ try {
146
+ popup.location.href = `${this.base}/oauth/authorize?${q}`;
147
+ } catch {
148
+ throw new PbError(
149
+ "popup_blocked",
150
+ `The ${BRAND} sign-in popup could not be sent to the sign-in page.`,
151
+ "Close any other sign-in window and call connect() again from a click or key handler.",
152
+ );
153
+ }
154
+ // The waiter starts only after navigation succeeded, so no waiter is
155
+ // left behind when it fails. The page's message is delivered as a
156
+ // later task, so it cannot arrive before the listener below exists.
157
+ code = await this.waitForCode(popup, state);
158
+ } catch (e) {
159
+ popup.close();
160
+ throw e;
161
+ } finally {
162
+ this.signInPopup = null;
163
+ }
164
+ await this.ready;
165
+ const t = await this.tokenRequest({
166
+ grant_type: "authorization_code",
167
+ code,
168
+ code_verifier: verifier,
169
+ client_id: this.app,
170
+ });
171
+ await this.withLock(() => this.save(t));
172
+ }
173
+
174
+ /**
175
+ * waitForCode resolves with the code from the first message that comes
176
+ * from the popup, from the server's origin, of the sign-in type and with
177
+ * our state; every other message is ignored. It rejects when the user
178
+ * closes the popup first. The listener and timer are always removed.
179
+ */
180
+ private waitForCode(popup: Window, state: string): Promise<string> {
181
+ return new Promise((resolve, reject) => {
182
+ let closedPolls = 0;
183
+ const onMessage = (ev: MessageEvent) => {
184
+ if (ev.origin !== this.origin || ev.source !== popup) return;
185
+ const d: unknown = ev.data;
186
+ if (typeof d !== "object" || d === null) return;
187
+ const m = d as { type?: unknown; state?: unknown; code?: unknown; error?: unknown };
188
+ if (m.type !== AUTH_MESSAGE_TYPE || m.state !== state) return;
189
+ cleanup();
190
+ if (m.error === "access_denied") {
191
+ reject(new PbError("access_denied", `The user did not connect this app to ${BRAND}.`, "Let the user try again from a click when they are ready."));
192
+ } else if (typeof m.code === "string" && m.code !== "") {
193
+ resolve(m.code);
194
+ } else {
195
+ reject(new PbError(typeof m.error === "string" ? m.error : "invalid_request", `${BRAND} sign-in did not return a code.`, SIGN_IN_HINT));
196
+ }
197
+ };
198
+ // A finished sign-in posts its message and closes the popup at once,
199
+ // so "closed" counts only when seen on two polls in a row: a message
200
+ // already on its way is handled first.
201
+ const timer = setInterval(() => {
202
+ if (!popup.closed) return;
203
+ if (++closedPolls < 2) return;
204
+ cleanup();
205
+ reject(new PbError("sign_in_cancelled", `The ${BRAND} sign-in window was closed before sign-in finished.`, SIGN_IN_HINT));
206
+ }, POPUP_POLL_MS);
207
+ const cleanup = () => {
208
+ window.removeEventListener("message", onMessage);
209
+ clearInterval(timer);
210
+ };
211
+ window.addEventListener("message", onMessage);
212
+ });
213
+ }
214
+
215
+ // ---- tokens ----
216
+
217
+ /**
218
+ * accessToken returns an access token valid for at least another 60
219
+ * seconds, refreshing it first when needed. Rejects with unauthorized
220
+ * when the user is not (or no longer) signed in.
221
+ */
222
+ async accessToken(): Promise<string> {
223
+ await this.ready;
224
+ const a = this.access;
225
+ if (a && Date.now() < a.expiresAt - REFRESH_MARGIN_MS) return a.token;
226
+ return this.refresh();
227
+ }
228
+
229
+ /**
230
+ * refresh gets a new access token with the stored refresh token. Callers
231
+ * in this tab share one refresh in flight. When stale (the token a
232
+ * request was refused with) is given and this tab already holds a
233
+ * different valid token, that token is returned instead.
234
+ */
235
+ refresh(stale?: string): Promise<string> {
236
+ const a = this.access;
237
+ if (stale !== undefined && a && a.token !== stale && Date.now() < a.expiresAt - REFRESH_MARGIN_MS) {
238
+ return Promise.resolve(a.token);
239
+ }
240
+ if (!this.refreshing) {
241
+ this.refreshing = this.withLock(() => this.refreshLocked()).finally(() => {
242
+ this.refreshing = null;
243
+ });
244
+ }
245
+ return this.refreshing;
246
+ }
247
+
248
+ /**
249
+ * refreshLocked runs while holding the cross-tab lock. It re-reads the
250
+ * refresh token from IndexedDB, because another tab may have rotated it
251
+ * since: presenting a used refresh token revokes the whole session.
252
+ */
253
+ private async refreshLocked(): Promise<string> {
254
+ await this.ready;
255
+ const stored = await this.readStored();
256
+ if (!stored) {
257
+ this.forget();
258
+ throw new PbError("unauthorized", `Not signed in to ${BRAND}.`, SIGN_IN_HINT);
259
+ }
260
+ let t: TokenResponse;
261
+ try {
262
+ t = await this.tokenRequest({ grant_type: "refresh_token", refresh_token: stored.refreshToken, client_id: this.app });
263
+ } catch (e) {
264
+ // A refused refresh token (no DPoP reason) means the session is over.
265
+ // A refused proof leaves the refresh token unused, so it is kept.
266
+ if (e instanceof PbError && e.code === "unauthorized" && e.extra.reason === undefined) {
267
+ await this.deleteStored();
268
+ this.forget();
269
+ throw new PbError("unauthorized", `Signed out of ${BRAND}: ${e.message}`, SIGN_IN_HINT, e.extra);
270
+ }
271
+ throw e;
272
+ }
273
+ await this.save(t);
274
+ return t.access_token;
275
+ }
276
+
277
+ /**
278
+ * signOut forgets this app's tokens (in memory and IndexedDB). The DPoP
279
+ * key and other apps' sign-ins are kept.
280
+ */
281
+ async signOut(): Promise<void> {
282
+ await this.ready;
283
+ await this.withLock(() => this.deleteStored());
284
+ this.forget();
285
+ }
286
+
287
+ /** tokenRequest calls the token endpoint, correcting the clock once on dpop_iat. */
288
+ private async tokenRequest(body: Record<string, string>): Promise<TokenResponse> {
289
+ const url = `${this.base}/oauth/token`;
290
+ let out = await attempt(this, "POST", url, body);
291
+ const serverTime = out.ok ? undefined : clockError(out.err);
292
+ if (serverTime) {
293
+ this.setServerTime(serverTime);
294
+ out = await attempt(this, "POST", url, body);
295
+ }
296
+ if (!out.ok) throw out.err;
297
+ const t = (await readJSON(out.res)) as Partial<TokenResponse> | undefined;
298
+ if (!t || typeof t !== "object" || typeof t.access_token !== "string" || typeof t.refresh_token !== "string" ||
299
+ typeof t.expires_in !== "number" || typeof t.user_id !== "string") {
300
+ throw new PbError("internal", `${BRAND} returned an incomplete token response.`, "Check that baseUrl points at the server.");
301
+ }
302
+ return t as TokenResponse;
303
+ }
304
+
305
+ private async save(t: TokenResponse): Promise<void> {
306
+ const db = await openPbDB();
307
+ try {
308
+ await db.put("tokens", { refreshToken: t.refresh_token, userId: t.user_id }, this.tokenKey);
309
+ } finally {
310
+ db.close();
311
+ }
312
+ this.access = { token: t.access_token, expiresAt: Date.now() + t.expires_in * 1000 };
313
+ this._signedIn = true;
314
+ this._userId = t.user_id;
315
+ }
316
+
317
+ private forget(): void {
318
+ this.access = null;
319
+ this._signedIn = false;
320
+ this._userId = null;
321
+ }
322
+
323
+ private async readStored(): Promise<StoredTokens | undefined> {
324
+ const db = await openPbDB();
325
+ try {
326
+ return await db.get("tokens", this.tokenKey);
327
+ } finally {
328
+ db.close();
329
+ }
330
+ }
331
+
332
+ private async deleteStored(): Promise<void> {
333
+ const db = await openPbDB();
334
+ try {
335
+ await db.delete("tokens", this.tokenKey);
336
+ } finally {
337
+ db.close();
338
+ }
339
+ }
340
+
341
+ /**
342
+ * withLock runs fn while holding the refresh lock for this app and
343
+ * server, shared by every tab of the browser through Web Locks.
344
+ */
345
+ private withLock<T>(fn: () => Promise<T>): Promise<T> {
346
+ const locks = typeof navigator === "undefined" ? undefined : navigator.locks;
347
+ if (locks) return locks.request(this.lockName, fn);
348
+ // Without Web Locks (very old browsers) refreshes are serialised in
349
+ // this tab only; two tabs refreshing at the same moment could then
350
+ // present the same refresh token and end the session.
351
+ const run = this.localTail.then(fn, fn);
352
+ this.localTail = run.catch(() => undefined);
353
+ return run;
354
+ }
355
+
356
+ // ---- DPoP ----
357
+
358
+ /** proof returns a DPoP proof signed with this browser's key for the server. */
359
+ async proof(method: string, url: string, accessToken?: string): Promise<string> {
360
+ if (!this.keys) {
361
+ this.keys = getOrCreateKey(this.base);
362
+ this.keys.catch(() => (this.keys = null));
363
+ }
364
+ return createProof(await this.keys, method, url, accessToken, this.clockOffsetMs);
365
+ }
366
+
367
+ /** setServerTime sets the clock offset from the server's serverTime (RFC 3339). */
368
+ setServerTime(serverTime: string): void {
369
+ this.clockOffsetMs = Date.parse(serverTime) - Date.now();
370
+ }
371
+ }
package/src/brand.ts ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * BRAND is the product name shown in user-facing SDK text (error messages
3
+ * and hints). Change it here; never write the name anywhere else.
4
+ */
5
+ export const BRAND = "pb";
6
+
7
+ /** DEFAULT_BASE_URL is the local development server. */
8
+ export const DEFAULT_BASE_URL = "http://localhost:8787";