@flipstream/sdk 0.4.0 → 0.6.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.
Files changed (63) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +325 -20
  3. package/dist/auth/discovery.d.ts +2 -0
  4. package/dist/auth/discovery.js +4 -1
  5. package/dist/auth/discovery.js.map +1 -1
  6. package/dist/auth/signIn.d.ts +11 -2
  7. package/dist/auth/signIn.js +19 -27
  8. package/dist/auth/signIn.js.map +1 -1
  9. package/dist/auth/tokenEndpoint.d.ts +18 -0
  10. package/dist/auth/tokenEndpoint.js +36 -0
  11. package/dist/auth/tokenEndpoint.js.map +1 -0
  12. package/dist/core/fetch.d.ts +8 -0
  13. package/dist/core/fetch.js +36 -11
  14. package/dist/core/fetch.js.map +1 -1
  15. package/dist/core/result.d.ts +4 -2
  16. package/dist/core/result.js +3 -1
  17. package/dist/core/result.js.map +1 -1
  18. package/dist/flipstream.d.ts +7 -0
  19. package/dist/flipstream.js +14 -4
  20. package/dist/flipstream.js.map +1 -1
  21. package/dist/index.d.ts +2 -0
  22. package/dist/index.js +2 -0
  23. package/dist/index.js.map +1 -1
  24. package/dist/node/clientSecret.d.ts +41 -0
  25. package/dist/node/clientSecret.js +124 -0
  26. package/dist/node/clientSecret.js.map +1 -0
  27. package/dist/node/fileLock.d.ts +27 -0
  28. package/dist/node/fileLock.js +267 -0
  29. package/dist/node/fileLock.js.map +1 -0
  30. package/dist/node/fileStore.d.ts +19 -0
  31. package/dist/node/fileStore.js +135 -0
  32. package/dist/node/fileStore.js.map +1 -0
  33. package/dist/node/headless.d.ts +7 -2
  34. package/dist/node/headless.js +15 -2
  35. package/dist/node/headless.js.map +1 -1
  36. package/dist/node/index.d.ts +9 -0
  37. package/dist/node/index.js +9 -1
  38. package/dist/node/index.js.map +1 -1
  39. package/dist/node/keychainChild.d.ts +1 -0
  40. package/dist/node/keychainChild.js +100 -0
  41. package/dist/node/keychainChild.js.map +1 -0
  42. package/dist/node/keychainStore.d.ts +30 -0
  43. package/dist/node/keychainStore.js +150 -0
  44. package/dist/node/keychainStore.js.map +1 -0
  45. package/dist/node/loopback.d.ts +24 -5
  46. package/dist/node/loopback.js +80 -23
  47. package/dist/node/loopback.js.map +1 -1
  48. package/dist/node/session.d.ts +224 -0
  49. package/dist/node/session.js +622 -0
  50. package/dist/node/session.js.map +1 -0
  51. package/dist/node/store.d.ts +44 -0
  52. package/dist/node/store.js +91 -0
  53. package/dist/node/store.js.map +1 -0
  54. package/dist/query/health.d.ts +16 -0
  55. package/dist/query/health.js +18 -0
  56. package/dist/query/health.js.map +1 -0
  57. package/dist/query/query.d.ts +8 -0
  58. package/dist/query/query.js +12 -0
  59. package/dist/query/query.js.map +1 -1
  60. package/dist/version.gen.d.ts +2 -0
  61. package/dist/version.gen.js +4 -0
  62. package/dist/version.gen.js.map +1 -0
  63. package/package.json +18 -3
@@ -0,0 +1,622 @@
1
+ import { z } from 'zod';
2
+ import { call } from '../core/call.js';
3
+ import { discover } from '../auth/discovery.js';
4
+ import { tokenCall } from '../auth/tokenEndpoint.js';
5
+ import { authTransport, isHttpsUrl } from '../auth/transport.js';
6
+ import { clientAuthorization, vouched } from './clientSecret.js';
7
+ /** Thrown by `session.token()`; the default transport turns it into `no_token`, with this as its `cause`. */
8
+ export class SessionError extends Error {
9
+ failure;
10
+ constructor(failure) {
11
+ super(`no token: ${failure.kind}`);
12
+ this.name = 'SessionError';
13
+ this.failure = failure;
14
+ }
15
+ }
16
+ /** A caller waits this long for a refresh, then gets `unavailable` (the os's `refresh.ts`). */
17
+ const WAIT_MS = 15_000;
18
+ /** The refresh's own limit: past the callers' wait, so a slow answer is still saved. */
19
+ const REFRESH_DEADLINE_MS = 60_000;
20
+ /** A revocation's own limit, the lock's wait and the store's read included. */
21
+ const REVOKE_DEADLINE_MS = 10_000;
22
+ /** An access token with less left than this is refreshed first. */
23
+ const MARGIN_MS = 60_000;
24
+ /** An access token checked before and after a revocation needs this much left for both (D464). */
25
+ const CHECK_MARGIN_MS = 30_000;
26
+ /** A refresh with less than this left isn't sent: its answer could be cut off after the rotation (K6). */
27
+ const SEND_FLOOR_MS = 5_000;
28
+ /**
29
+ * A sign-out's turn waits at most this for the app's lock, counted from when it reaches the lock,
30
+ * and at most this for each of its store calls; then it gives up, touching nothing more (D487).
31
+ */
32
+ const SIGN_OUT_WAIT_MS = 60_000;
33
+ // A field set to undefined is read as left out, as a JavaScript store may well hand it back.
34
+ const zStored = z.object({
35
+ accessToken: z.string().min(1),
36
+ refreshToken: z.string().optional(),
37
+ expiresAt: z.number().optional(),
38
+ });
39
+ const SIGNED_OUT = { kind: 'signed-out' };
40
+ const UNAVAILABLE = { kind: 'unavailable' };
41
+ export function createSession(options) {
42
+ const { clientId, issuer } = options;
43
+ if ((options.server === undefined) === (issuer === undefined))
44
+ throw new TypeError('createSession: give exactly one of issuer and server');
45
+ if (issuer !== undefined && (typeof issuer !== 'string' || !isHttpsUrl(issuer)))
46
+ throw new TypeError('createSession: issuer must be an https URL');
47
+ // Made once: a TypeError here, at creation, for a secret that is given but blank.
48
+ const authorization = clientAuthorization('createSession', clientId, options.clientSecret);
49
+ const transport = authTransport({ fetch: options.fetch });
50
+ let inFlight = null;
51
+ let tail = Promise.resolve();
52
+ // A rotation whose save failed. Its refresh token is the session's only live one while the store
53
+ // still holds the token it replaced, which is spent (D456).
54
+ let unsaved = null;
55
+ // A refresh token whose last refresh got no answer the session could read: the server may have
56
+ // rotated it, so it may be spent (S5.B1). Cleared by the next answer for it.
57
+ let doubtful = null;
58
+ // The issuer's userinfo endpoint, once found: what a revocation is checked against.
59
+ let userinfo = null;
60
+ // The server, once known: given, or discovered by the first turn that needs it, then kept. A
61
+ // discovery that fails is tried again at the next need.
62
+ let known = options.server;
63
+ /**
64
+ * The server, discovered inside the turn that needs it (#130): only a refresh about to send, or
65
+ * a sign-out with something to revoke, asks the auth host for it. Held to that turn's deadline.
66
+ */
67
+ async function serverFor(limit) {
68
+ if (known !== undefined)
69
+ return { ok: true, data: known };
70
+ if (issuer === undefined)
71
+ return { ok: false, error: { kind: 'refused' } };
72
+ // By the clock too, as every send: a store that blocked the thread past the deadline returns
73
+ // before its timer has run (S1.F1).
74
+ const ended = limit.ended();
75
+ if (ended !== null)
76
+ return { ok: false, error: ended };
77
+ const found = await discover(issuer, { fetch: options.fetch, signal: limit.signal });
78
+ if (found.ok)
79
+ known = found.data;
80
+ return found;
81
+ }
82
+ async function read() {
83
+ try {
84
+ const stored = await options.tokens();
85
+ if (stored === null)
86
+ return { ok: true, tokens: null };
87
+ if (zStored.safeParse(stored).success)
88
+ return { ok: true, tokens: stored };
89
+ return { ok: false, failure: { kind: 'store_failed', step: 'read', cause: new TypeError('the stored tokens are not tokens') } };
90
+ }
91
+ catch (cause) {
92
+ return { ok: false, failure: { kind: 'store_failed', step: 'read', cause } };
93
+ }
94
+ }
95
+ /**
96
+ * The refresh token that is live now, and the stored one it stands for: an unsaved rotation's
97
+ * while the store still holds the token it replaced, else the store's. A store that moved on (a
98
+ * newer sign-in, a sign-out) lets the unsaved rotation go.
99
+ */
100
+ function liveOf(held) {
101
+ const stored = held?.refreshToken;
102
+ if (unsaved !== null && unsaved.replaces !== stored)
103
+ unsaved = null;
104
+ if (stored === undefined || stored === '')
105
+ return undefined;
106
+ return { token: unsaved?.refreshToken ?? stored, stored };
107
+ }
108
+ // Read and decided inside the one refresh, so two callers never spend the same refresh token,
109
+ // and a token another process refreshed meanwhile is used, not refreshed again (honest-typescript §5).
110
+ // Held to the refresh's deadline, up to the answer: the wait for its turn and the lock, the read
111
+ // and the request.
112
+ async function refresh(stale, limit) {
113
+ for (;;) {
114
+ // A lock that ran this only after the deadline: nothing is read, and nothing is sent.
115
+ if (limit.ended() !== null)
116
+ return UNAVAILABLE;
117
+ const now = await orAborted(read(), limit.signal);
118
+ if ('kind' in now)
119
+ return UNAVAILABLE;
120
+ if (!now.ok)
121
+ return now.failure;
122
+ const held = now.tokens;
123
+ const live = liveOf(held);
124
+ if (held === null)
125
+ return SIGNED_OUT;
126
+ if (held.accessToken !== stale && fresh(held))
127
+ return { kind: 'token', accessToken: held.accessToken };
128
+ if (live === undefined)
129
+ return SIGNED_OUT;
130
+ // The server, discovered now if this is the first turn that needs it (#130).
131
+ const found = await serverFor(limit);
132
+ if (!found.ok)
133
+ return discoveryFailure(found.error);
134
+ const server = found.data;
135
+ // By the clock, not only the timer (a store that blocks the thread returns before the timer
136
+ // runs), and never with under 5 s left: a request cut off after pulse-auth rotated loses the
137
+ // new token, and the next refresh then ends the session (K6). Unsent is better.
138
+ if (limit.left() < SEND_FLOOR_MS)
139
+ return UNAVAILABLE;
140
+ const sentAt = Date.now();
141
+ const form = { grant_type: 'refresh_token', refresh_token: live.token, client_id: clientId };
142
+ const answer = vouched(await call(transport, tokenCall('auth.refresh', server.tokenEndpoint, form, limit.left(), authorization)), authorization);
143
+ doubtful = !answer.ok && unanswered(answer.error) ? live.token : null;
144
+ if (!answer.ok) {
145
+ const failure = failureOf(answer.error);
146
+ if (failure.kind !== 'signed-out')
147
+ return failure;
148
+ // The server ended the session the token sent belongs to. The store's tokens are cleared,
149
+ // but only if they're still that session's: a newer sign-in another process saved
150
+ // meanwhile is kept, and used (D461).
151
+ const after = await read();
152
+ if (!after.ok)
153
+ return after.failure;
154
+ if (after.tokens?.refreshToken !== live.stored)
155
+ continue;
156
+ unsaved = null;
157
+ try {
158
+ await options.onTokens({ kind: 'cleared', replaces: live.stored });
159
+ }
160
+ catch (cause) {
161
+ return { kind: 'store_failed', step: 'save', cause };
162
+ }
163
+ return SIGNED_OUT;
164
+ }
165
+ const update = updateOf(answer.data, live.stored, sentAt);
166
+ // From here a rotation's refresh token is the only live one. So the re-read and the save are
167
+ // waited out, never cut short: until the save settles, the store may show tokens that may yet
168
+ // fail to save, and the refresh stays the one every caller takes. A rotation not saved is kept.
169
+ const keep = () => {
170
+ if (update.kind === 'rotated')
171
+ unsaved = { refreshToken: update.refreshToken, replaces: live.stored };
172
+ };
173
+ const before = await read();
174
+ if (!before.ok) {
175
+ keep();
176
+ return before.failure;
177
+ }
178
+ // The store moved on meanwhile, to a newer sign-in or a sign-out that this answer must not
179
+ // overwrite: the answer is let go, and the refresh starts over from the store as it is now.
180
+ if (before.tokens?.refreshToken !== live.stored)
181
+ continue;
182
+ try {
183
+ await options.onTokens(update);
184
+ }
185
+ catch (cause) {
186
+ keep();
187
+ return { kind: 'store_failed', step: 'save', cause };
188
+ }
189
+ if (update.kind === 'rotated')
190
+ unsaved = null;
191
+ return { kind: 'token', accessToken: update.accessToken };
192
+ }
193
+ }
194
+ /**
195
+ * Puts `work` at the end of the session's queue, inside the app's lock when there is one. The
196
+ * next turn waits for the work itself as well as for the lock's promise, so a lock that lets go
197
+ * at its signal while the work still runs (a mutex with a timeout) never lets a turn run beside
198
+ * it (K1).
199
+ */
200
+ function enqueue(work, signal) {
201
+ const run = {};
202
+ const begin = () => {
203
+ run.begun = work();
204
+ return run.begun;
205
+ };
206
+ const { lock } = options;
207
+ const turn = tail.then(() => (lock === undefined ? begin() : lock(begin, signal)));
208
+ tail = turn.then(noop, noop).then(() => run.begun?.then(noop, noop));
209
+ return { turn, run };
210
+ }
211
+ /**
212
+ * A sign-out's turn in the session's queue (#134, D487). Once it reaches the app's lock, it waits
213
+ * for it at most 60 s: the lock's signal fires then, and a lock that runs the work later anyway
214
+ * runs nothing. Past that, the turn gives up without touching the store (`late()`), and the
215
+ * queue moves on. The work, once begun, is bound by its own calls, each at most 60 s.
216
+ */
217
+ function enqueueSignOut(work, late) {
218
+ const run = {};
219
+ const { lock } = options;
220
+ const turn = tail.then(async () => {
221
+ const bound = createLimit(SIGN_OUT_WAIT_MS, undefined);
222
+ try {
223
+ const begin = () => {
224
+ run.begun = bound.ended() !== null ? Promise.resolve(late()) : work();
225
+ return run.begun;
226
+ };
227
+ const held = orAborted(lock === undefined ? begin() : lock(begin, bound.signal), bound.signal);
228
+ const first = await held;
229
+ return isAborted(first) ? await (run.begun ?? Promise.resolve(late())) : first;
230
+ }
231
+ finally {
232
+ bound.dispose();
233
+ }
234
+ });
235
+ // As every turn: the next waits for the work itself too, not only for the lock's promise (K1),
236
+ // and the work is bound by its own calls (D487).
237
+ tail = turn.then(noop, noop).then(() => run.begun?.then(noop, noop));
238
+ return { turn, run };
239
+ }
240
+ /**
241
+ * One at a time within this session, a refresh or a revocation, each inside the app's lock when
242
+ * there is one, so a revocation never sends a token a refresh is spending, nor a refresh one a
243
+ * revocation is ending. The wait for a turn and for the lock ends at `limit`, and then the work
244
+ * never begins (`late()`), by its timer or by the clock; once begun, its outcome stands,
245
+ * whenever it settles.
246
+ */
247
+ function serial(work, limit, late, lockFailed) {
248
+ if (limit.ended() !== null)
249
+ return Promise.resolve(late());
250
+ const { turn, run } = enqueue(() => (limit.ended() !== null ? Promise.resolve(late()) : work()), limit.signal);
251
+ return orAborted(turn, limit.signal).then((first) => (isAborted(first) ? (run.begun ?? late()) : first), (cause) => run.begun ?? (limit.signal.aborted ? late() : lockFailed(cause)));
252
+ }
253
+ function shared(stale) {
254
+ if (inFlight !== null)
255
+ return inFlight;
256
+ const limit = createLimit(REFRESH_DEADLINE_MS, undefined);
257
+ const lockFailed = (cause) => ({ kind: 'store_failed', step: 'lock', cause });
258
+ const attempt = serial(() => refresh(stale, limit), limit, () => UNAVAILABLE, lockFailed).finally(limit.dispose);
259
+ inFlight = attempt;
260
+ const clear = () => {
261
+ if (inFlight === attempt)
262
+ inFlight = null;
263
+ };
264
+ attempt.then(clear, clear);
265
+ return attempt;
266
+ }
267
+ // A caller's whole wait, the store's read included, so a store that stalls can't hold it longer.
268
+ // While a refresh runs, every caller takes its outcome, not the store's: the store may already
269
+ // show tokens whose save hasn't settled, or a token the server just refused (a 401).
270
+ async function acquire(ask) {
271
+ if (inFlight !== null)
272
+ return inFlight;
273
+ const now = await read();
274
+ if (!now.ok)
275
+ return now.failure;
276
+ if (inFlight !== null)
277
+ return inFlight;
278
+ const held = now.tokens;
279
+ if (held === null)
280
+ return SIGNED_OUT;
281
+ if (held.accessToken !== ask.rejected && fresh(held))
282
+ return { kind: 'token', accessToken: held.accessToken };
283
+ return shared(held.accessToken);
284
+ }
285
+ // RFC 7009 on the tokens as they are once no refresh is spending them. pulse-auth answers 200
286
+ // whatever it is sent, a spent refresh token or an access token that has run out included, and
287
+ // revokes nothing for those: so the answer is checked against the server, never taken on trust.
288
+ /**
289
+ * A sign-out's turn (#134): the revocation, then the store's clear, in one hold of the app's lock,
290
+ * so nothing can rotate the session in between. The turn's one read of the store serves both:
291
+ * the revocation waits for it only within its 10 s, the clear for as long as it takes. The
292
+ * revocation's result goes to `answer` as soon as it's known. The clear runs whatever the
293
+ * revocation did: in time or too late to send anything, aborted (D478), failed, or with any
294
+ * result.
295
+ */
296
+ async function signOut(limit, answer) {
297
+ const reading = waitedAtMost(read());
298
+ // Whatever the revocation half does, throwing included, the clear below still runs (rev140's
299
+ // P3.2): a throw is the revocation's own failure, outside the contract.
300
+ const result = await revokeWith(reading, limit).catch((cause) => ({ kind: 'unconfirmed', reason: { kind: 'invalid', issues: `the revocation failed: ${cause instanceof Error ? cause.message : String(cause)}` } }));
301
+ answer(result);
302
+ // The session the turn read, while the store still holds it: a sign-in saved since is kept.
303
+ const now = await reading;
304
+ if (!isAborted(now) && now.ok)
305
+ await clearIfStill(keyOf(now.tokens));
306
+ return result;
307
+ }
308
+ /** A store call, given up on after 60 s (D487): the turn then touches nothing more. */
309
+ function waitedAtMost(call) {
310
+ const bound = createLimit(SIGN_OUT_WAIT_MS, undefined);
311
+ return orAborted(call, bound.signal).finally(bound.dispose);
312
+ }
313
+ async function revokeWith(reading, limit) {
314
+ // A turn that came after the 10 s, by the timer or the clock: nothing is sent.
315
+ if (limit.ended() !== null)
316
+ return limit.unconfirmed();
317
+ const now = await orAborted(reading, limit.signal);
318
+ if (isAborted(now))
319
+ return limit.unconfirmed();
320
+ if (!now.ok)
321
+ return { kind: 'unconfirmed', reason: now.failure };
322
+ const held = now.tokens;
323
+ const live = liveOf(held);
324
+ // Nothing to send, so the auth host isn't asked (#130): nothing stored, or no refresh token and
325
+ // an access token that has run out, which ends nothing at pulse-auth.
326
+ if (held === null || (live === undefined && !unexpired(held)))
327
+ return { kind: 'unconfirmed', reason: { kind: 'no_tokens' } };
328
+ const found = await serverFor(limit);
329
+ if (!found.ok)
330
+ return { kind: 'unconfirmed', reason: limit.ended() ?? found.error };
331
+ const server = found.data;
332
+ const endpoint = server.revocationEndpoint;
333
+ if (endpoint === undefined)
334
+ return { kind: 'unconfirmed', reason: { kind: 'no_endpoint' } };
335
+ // D464: a 200 from the issuer just before, then a 401 for the same token just after, is a
336
+ // difference only the revocation explains. A 401 on its own isn't: pulse-auth answers every
337
+ // failure of a token with the same 401 (expired, another audience, an ended session).
338
+ // A known expiry only: a token that could run out between the two checks would revoke nothing,
339
+ // and still be refused after (S6.B1).
340
+ if (held.expiresAt !== undefined && held.expiresAt - Date.now() >= CHECK_MARGIN_MS) {
341
+ const before = await taken(server, held.accessToken, limit);
342
+ if (before.kind === 'taken') {
343
+ const sent = await revocation(endpoint, held.accessToken, 'access_token', limit);
344
+ if (!sent.ok)
345
+ return { kind: 'unconfirmed', reason: sent.error };
346
+ const after = await taken(server, held.accessToken, limit);
347
+ if (after.kind === 'taken')
348
+ return { kind: 'unconfirmed', reason: { kind: 'still_live' } };
349
+ if (after.kind === 'failed')
350
+ return { kind: 'unconfirmed', reason: { kind: 'check_failed', error: after.error } };
351
+ unsaved = null;
352
+ doubtful = null;
353
+ return { kind: 'revoked' };
354
+ }
355
+ // Nothing to compare the answer after with: the session is still ended as best it can be,
356
+ // and the result says why it can't be confirmed.
357
+ const sent = await revocation(endpoint, live?.token ?? held.accessToken, live === undefined ? 'access_token' : 'refresh_token', limit);
358
+ return { kind: 'unconfirmed', reason: sent.ok ? { kind: 'check_failed', error: before.error } : sent.error };
359
+ }
360
+ // No access token to check with: the live refresh token goes, or, with none, the access token.
361
+ const sent = await revocation(endpoint, live?.token ?? held.accessToken, live === undefined ? 'access_token' : 'refresh_token', limit);
362
+ if (!sent.ok)
363
+ return { kind: 'unconfirmed', reason: sent.error };
364
+ return { kind: 'unconfirmed', reason: { kind: live !== undefined && doubtful === live.token ? 'maybe_spent' : 'unconfirmable' } };
365
+ }
366
+ /**
367
+ * Clears the store, as C2 does after `invalid_grant`: read again, and `cleared` only while the
368
+ * store's key is still `key`, so a sign-in another process saved meanwhile is kept. Waited out,
369
+ * the read as well as the write, however slow the store (rev140's P2.1): nobody but the queue
370
+ * waits for it. A clear that fails leaves the tokens: the result is about the server, and the next
371
+ * refresh of an ended session clears them (C2).
372
+ */
373
+ async function clearIfStill(key) {
374
+ if (key === undefined)
375
+ return;
376
+ const now = await waitedAtMost(read());
377
+ if (isAborted(now) || !now.ok || keyOf(now.tokens) !== key)
378
+ return;
379
+ unsaved = null;
380
+ await waitedAtMost(Promise.resolve().then(() => options.onTokens({ kind: 'cleared', replaces: key }))).catch(noop);
381
+ }
382
+ function revocation(endpoint, token, hint, limit) {
383
+ // Nothing is sent once the turn's 10 s are up, not even with no time left (S6.F1).
384
+ const ended = limit.ended();
385
+ if (ended !== null)
386
+ return Promise.resolve({ ok: false, error: ended });
387
+ const body = new URLSearchParams({ token, token_type_hint: hint, client_id: clientId }).toString();
388
+ const headers = { 'content-type': 'application/x-www-form-urlencoded', ...(authorization === undefined ? {} : { authorization }) };
389
+ return call(withoutBody(transport), {
390
+ effect: 'write',
391
+ service: 'auth',
392
+ endpoint: 'auth.revoke',
393
+ makeRequest: () => new Request(endpoint, { method: 'POST', headers, body }),
394
+ schema: z.null(),
395
+ deadlineMs: limit.left(),
396
+ retry: 'never',
397
+ }, limit.caller).then((sent) => vouched(sent, authorization));
398
+ }
399
+ /**
400
+ * Whether the issuer takes `accessToken` now, asked at its userinfo endpoint. pulse-auth checks
401
+ * there that the token's session (`sid`) is still active (tokens/automatic.py `verify`), needs no
402
+ * scope, and answers every refusal with the same 401, an ended session or an expired token alike.
403
+ * Resource servers trust the signature alone, so only the issuer can say.
404
+ */
405
+ async function taken(server, accessToken, limit) {
406
+ const found = await userinfoEndpoint(server, limit);
407
+ if (!found.ok)
408
+ return { kind: 'failed', error: found.error };
409
+ const ended = limit.ended();
410
+ if (ended !== null)
411
+ return { kind: 'failed', error: ended };
412
+ const asked = await call(transport, {
413
+ effect: 'read',
414
+ service: 'auth',
415
+ endpoint: 'auth.userinfo',
416
+ makeRequest: () => new Request(found.data, { headers: { accept: 'application/json', authorization: `Bearer ${accessToken}` } }),
417
+ schema: z.unknown(),
418
+ deadlineMs: limit.left(),
419
+ retry: 'never',
420
+ }, limit.caller);
421
+ if (asked.ok)
422
+ return { kind: 'taken' };
423
+ return { kind: asked.error.kind === 'unauthorized' ? 'refused' : 'failed', error: asked.error };
424
+ }
425
+ /**
426
+ * pulse-auth names its userinfo endpoint only in its OpenID configuration (OIDC Discovery §4),
427
+ * not in the RFC 8414 metadata `discover` reads: so it is read there, once, and held to what
428
+ * discovery holds an endpoint to: the same issuer, https, and here the issuer's own origin. Once
429
+ * pulse-auth names it in its RFC 8414 metadata too (flipstream-io/pulse-auth#83), read it there
430
+ * first.
431
+ */
432
+ async function userinfoEndpoint(server, limit) {
433
+ if (userinfo !== null)
434
+ return { ok: true, data: userinfo };
435
+ const ended = limit.ended();
436
+ if (ended !== null)
437
+ return { ok: false, error: ended };
438
+ const read = await call(transport, {
439
+ effect: 'read',
440
+ service: 'auth',
441
+ endpoint: 'auth.openid_configuration',
442
+ makeRequest: () => new Request(`${server.issuer.replace(/\/+$/, '')}/.well-known/openid-configuration`, { headers: { accept: 'application/json' } }),
443
+ schema: zOpenIdConfiguration,
444
+ deadlineMs: limit.left(),
445
+ retry: 'read',
446
+ }, limit.caller);
447
+ if (!read.ok)
448
+ return read;
449
+ const { issuer, userinfo_endpoint: found } = read.data;
450
+ if (issuer !== server.issuer)
451
+ return { ok: false, error: { kind: 'invalid', issues: 'the OpenID configuration names another issuer', status: 200 } };
452
+ if (found === undefined || !isHttpsUrl(found) || new URL(found).origin !== new URL(server.issuer).origin) {
453
+ return { ok: false, error: { kind: 'invalid', issues: 'the OpenID configuration names no userinfo endpoint on the issuer', status: 200 } };
454
+ }
455
+ userinfo = found;
456
+ return { ok: true, data: found };
457
+ }
458
+ return {
459
+ async token(ask = {}) {
460
+ const outcome = await within(acquire(ask), WAIT_MS);
461
+ if (outcome.kind === 'token')
462
+ return outcome.accessToken;
463
+ throw new SessionError(outcome);
464
+ },
465
+ revoke(revokeOptions = {}) {
466
+ const limit = createLimit(REVOKE_DEADLINE_MS, revokeOptions.signal);
467
+ // A sign-out asked with a signal that has already fired does nothing at all.
468
+ if (limit.signal.aborted) {
469
+ limit.dispose();
470
+ return Promise.resolve(limit.unconfirmed());
471
+ }
472
+ let answer = noop;
473
+ const answered = new Promise((resolve) => (answer = resolve));
474
+ // Queued now, before anything is awaited, so neither an abort nor a stalled read can keep the
475
+ // turn from coming, and a refresh asked after the sign-out comes after it (K1).
476
+ const { turn, run } = enqueueSignOut(() => signOut(limit, answer), limit.unconfirmed);
477
+ return new Promise((resolve) => {
478
+ // The revocation's result, once the clear is done, so a token() just after finds the store
479
+ // cleared; but never past the 10 s, so a clear that stalls holds the queue, not the caller.
480
+ answered.then(async (result) => {
481
+ await orAborted(turn.then(noop, noop), limit.signal);
482
+ resolve(result);
483
+ }, noop);
484
+ // At the 10 s, a turn that hasn't begun is `timeout` (or `aborted`); one that has begun
485
+ // answers soon, every step of it being bound to the same 10 s. A lock that fails after the
486
+ // work began leaves the work's own result standing (rev140's P3.1).
487
+ void orAborted(turn, limit.signal).then((first) => {
488
+ if (isAborted(first) && run.begun === undefined)
489
+ resolve(limit.unconfirmed());
490
+ }, (cause) => {
491
+ if (run.begun === undefined)
492
+ resolve({ kind: 'unconfirmed', reason: { kind: 'store_failed', step: 'lock', cause } });
493
+ // A turn whose own work failed, without an answer: the caller still gets one (K6), not
494
+ // a wait for an answer that won't come (rev140's round-3 P3.5).
495
+ else
496
+ void run.begun.catch((failed) => resolve({ kind: 'unconfirmed', reason: { kind: 'invalid', issues: `the sign-out failed: ${failed instanceof Error ? failed.message : String(failed)}` } }));
497
+ });
498
+ }).finally(limit.dispose);
499
+ },
500
+ };
501
+ }
502
+ const fresh = (held) => held.expiresAt === undefined || held.expiresAt - Date.now() > MARGIN_MS;
503
+ const unexpired = (held) => held.expiresAt === undefined || held.expiresAt > Date.now();
504
+ /** What a store compares on (D472): its refresh token, or its access token when it has none (`||`). */
505
+ const keyOf = (held) => (held === null ? undefined : held.refreshToken || held.accessToken);
506
+ /**
507
+ * A refresh the server may have carried out without the session learning of it: no answer, past
508
+ * the deadline, a server error, or a success it couldn't read. A 4xx answer, or a request never
509
+ * sent, rotated nothing.
510
+ */
511
+ const unanswered = (error) => error.kind === 'timeout' || error.kind === 'unavailable' || error.kind === 'invalid';
512
+ // OIDC Discovery §3, what a revocation's check needs and nothing more.
513
+ const zOpenIdConfiguration = z.looseObject({ issuer: z.string(), userinfo_endpoint: z.string().exactOptional() });
514
+ const noop = () => undefined;
515
+ const ABORTED = { kind: 'aborted' };
516
+ const isAborted = (value) => value === ABORTED;
517
+ function createLimit(ms, caller) {
518
+ const stop = new AbortController();
519
+ const end = Date.now() + ms;
520
+ let reason = 'timeout';
521
+ const timer = setTimeout(() => {
522
+ stop.abort();
523
+ }, ms);
524
+ const onAbort = () => {
525
+ reason = 'aborted';
526
+ stop.abort();
527
+ };
528
+ if (caller?.aborted === true)
529
+ onAbort();
530
+ else
531
+ caller?.addEventListener('abort', onAbort, { once: true });
532
+ return {
533
+ signal: stop.signal,
534
+ caller,
535
+ left: () => Math.max(0, end - Date.now()),
536
+ unconfirmed: () => ({ kind: 'unconfirmed', reason: { kind: reason } }),
537
+ // The clock as well as the timer: a store that blocks the thread past the deadline returns
538
+ // before the timer has had a chance to run (S7.F1).
539
+ ended: () => (stop.signal.aborted || Date.now() >= end ? { kind: reason } : null),
540
+ dispose: () => {
541
+ clearTimeout(timer);
542
+ caller?.removeEventListener('abort', onAbort);
543
+ },
544
+ };
545
+ }
546
+ /** `work`, or ABORTED as soon as `signal` fires; the work itself goes on. */
547
+ function orAborted(work, signal) {
548
+ if (signal === undefined)
549
+ return work;
550
+ if (signal.aborted) {
551
+ // Let go, but observed: a rejection nobody handles would end a Node process.
552
+ work.then(() => undefined, () => undefined);
553
+ return Promise.resolve(ABORTED);
554
+ }
555
+ return new Promise((resolve, reject) => {
556
+ const onAbort = () => {
557
+ resolve(ABORTED);
558
+ };
559
+ signal.addEventListener('abort', onAbort, { once: true });
560
+ work.then((value) => {
561
+ signal.removeEventListener('abort', onAbort);
562
+ resolve(value);
563
+ }, (error) => {
564
+ signal.removeEventListener('abort', onAbort);
565
+ reject(error instanceof Error ? error : new Error(String(error)));
566
+ });
567
+ });
568
+ }
569
+ /** The refresh, or `unavailable` once `ms` have passed; the refresh itself goes on. */
570
+ function within(work, ms) {
571
+ return new Promise((resolve, reject) => {
572
+ const timer = setTimeout(() => {
573
+ resolve(UNAVAILABLE);
574
+ }, ms);
575
+ work.then((outcome) => {
576
+ clearTimeout(timer);
577
+ resolve(outcome);
578
+ }, (error) => {
579
+ clearTimeout(timer);
580
+ reject(error instanceof Error ? error : new Error(String(error)));
581
+ });
582
+ });
583
+ }
584
+ // RFC 6749 §6: a new refresh token replaces the old; none (pulse-auth sends "") means keep it.
585
+ function updateOf(answer, replaces, sentAt) {
586
+ const expiry = answer.expires_in === undefined ? {} : { expiresAt: sentAt + answer.expires_in * 1000 };
587
+ return answer.refresh_token !== undefined && answer.refresh_token !== ''
588
+ ? { kind: 'rotated', accessToken: answer.access_token, refreshToken: answer.refresh_token, ...expiry, replaces }
589
+ : { kind: 'access-only', accessToken: answer.access_token, ...expiry, replaces };
590
+ }
591
+ /** A discovery that failed in a refresh's turn: no answer is `unavailable`; anything else, a refresh that failed. */
592
+ function discoveryFailure(error) {
593
+ return error.kind === 'unavailable' || error.kind === 'timeout' || error.kind === 'aborted' ? UNAVAILABLE : { kind: 'refresh_failed', error };
594
+ }
595
+ function failureOf(error) {
596
+ switch (error.kind) {
597
+ case 'unavailable':
598
+ case 'timeout':
599
+ return UNAVAILABLE;
600
+ // pulse-auth answers a refresh token it doesn't know with 400 invalid_grant, and the reuse of
601
+ // a spent one with 401 invalid_grant (it then revokes the session).
602
+ case 'rejected':
603
+ case 'unauthorized':
604
+ return error.code === 'invalid_grant' ? SIGNED_OUT : { kind: 'refresh_failed', error };
605
+ default:
606
+ return { kind: 'refresh_failed', error };
607
+ }
608
+ }
609
+ /**
610
+ * RFC 7009 §2.2: a 200 says the token is revoked, and its body means nothing (pulse-auth's is
611
+ * empty, which `readJson` can't read). So a success's body is let go and read as `null`.
612
+ */
613
+ function withoutBody(transport) {
614
+ return async (request) => {
615
+ const sent = await transport(request);
616
+ if (sent.kind !== 'response' || !sent.response.ok)
617
+ return sent;
618
+ void sent.response.body?.cancel().catch(() => undefined);
619
+ return { kind: 'response', response: new Response('null', { status: 200 }) };
620
+ };
621
+ }
622
+ //# sourceMappingURL=session.js.map