@flipstream/sdk 0.4.0 → 0.5.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 (47) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +229 -18
  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 +1 -0
  22. package/dist/index.js.map +1 -1
  23. package/dist/node/clientSecret.d.ts +41 -0
  24. package/dist/node/clientSecret.js +124 -0
  25. package/dist/node/clientSecret.js.map +1 -0
  26. package/dist/node/fileLock.d.ts +27 -0
  27. package/dist/node/fileLock.js +248 -0
  28. package/dist/node/fileLock.js.map +1 -0
  29. package/dist/node/headless.d.ts +7 -2
  30. package/dist/node/headless.js +15 -2
  31. package/dist/node/headless.js.map +1 -1
  32. package/dist/node/index.d.ts +5 -0
  33. package/dist/node/index.js +7 -1
  34. package/dist/node/index.js.map +1 -1
  35. package/dist/node/loopback.d.ts +24 -5
  36. package/dist/node/loopback.js +80 -23
  37. package/dist/node/loopback.js.map +1 -1
  38. package/dist/node/session.d.ts +192 -0
  39. package/dist/node/session.js +480 -0
  40. package/dist/node/session.js.map +1 -0
  41. package/dist/query/health.d.ts +16 -0
  42. package/dist/query/health.js +18 -0
  43. package/dist/query/health.js.map +1 -0
  44. package/dist/query/query.d.ts +8 -0
  45. package/dist/query/query.js +12 -0
  46. package/dist/query/query.js.map +1 -1
  47. package/package.json +10 -1
@@ -0,0 +1,192 @@
1
+ import type { TokenAsk } from '../core/fetch.js';
2
+ import type { ApiError } from '../core/result.js';
3
+ import type { AuthServer } from '../auth/discovery.js';
4
+ import type { Tokens } from '../auth/signIn.js';
5
+ import { type AuthCallOptions } from '../auth/transport.js';
6
+ /** What the app's store holds: `finishSignIn`'s tokens fit. */
7
+ export type SessionTokens = Pick<Tokens, 'accessToken' | 'refreshToken' | 'expiresAt'>;
8
+ /**
9
+ * New tokens from a refresh, for the app to save before anything uses them, or the end of the
10
+ * session. `replaces` is the store's key when the refresh began (D472): its refresh token, or its
11
+ * access token when it has none or an empty one, as `refreshToken || accessToken`. Write only while
12
+ * the store's key is still `replaces` (compare and set, or delete), so a refresh of an old session
13
+ * never overwrites a newer sign-in that another process saved meanwhile.
14
+ */
15
+ export type TokenUpdate =
16
+ /** A new refresh token came: save both. The one sent is spent. */
17
+ {
18
+ readonly kind: 'rotated';
19
+ readonly accessToken: string;
20
+ readonly refreshToken: string;
21
+ readonly expiresAt?: number;
22
+ readonly replaces: string;
23
+ }
24
+ /**
25
+ * This refresh crossed another one, perhaps another process's, and only the access token is
26
+ * new. Keep the refresh token that is stored now: the other refresh may already have saved its
27
+ * new one, and writing back the one this refresh sent would end the session.
28
+ */
29
+ | {
30
+ readonly kind: 'access-only';
31
+ readonly accessToken: string;
32
+ readonly expiresAt?: number;
33
+ readonly replaces: string;
34
+ }
35
+ /**
36
+ * The server ended the session (`invalid_grant`): delete the stored tokens, only while the
37
+ * store's key is still `replaces`, so a newer sign-in is kept.
38
+ */
39
+ | {
40
+ readonly kind: 'cleared';
41
+ readonly replaces: string;
42
+ };
43
+ export interface SessionOptions extends Pick<AuthCallOptions, 'fetch'> {
44
+ /** The server, as `discover` gave it. */
45
+ readonly server: AuthServer;
46
+ /** The app's own OAuth client ID (D421). */
47
+ readonly clientId: string;
48
+ /**
49
+ * The app's client secret, as a confidential client (#123): sent only in the Authorization header
50
+ * of the refresh and the revocation, to `server`'s own endpoints, and their failures then keep
51
+ * no server text (`finishSignIn`'s rule). Left out, the session is a public client's. Never log it.
52
+ */
53
+ readonly clientSecret?: string | undefined;
54
+ /**
55
+ * The tokens as the store holds them now, or null when nobody is signed in. Read again before
56
+ * every refresh, so the refresh token sent is the current one, even after another process
57
+ * rotated it, and again just before a refresh's answer is saved.
58
+ *
59
+ * The store's contract (D457): this returns only what `onTokens` has durably saved. Write first,
60
+ * make visible second, so no reader, in this process or another, ever sees tokens whose save
61
+ * may still fail. For example:
62
+ * - the system keychain, whose write is one step that is visible once it has succeeded;
63
+ * - a file, written in full to a temporary name in the same folder, flushed to disk (fsync),
64
+ * renamed over the old one, and the folder flushed too (fsync on the directory, where the
65
+ * platform has one): a reader sees it whole or not at all, and a power cut can't bring back
66
+ * the old file with its spent token.
67
+ */
68
+ readonly tokens: () => SessionTokens | null | Promise<SessionTokens | null>;
69
+ /**
70
+ * Saves a refresh's tokens, or clears them once the server has ended the session, only while the
71
+ * store's key (`refreshToken || accessToken`) is still `update.replaces`. The session reads the
72
+ * store again just before, and lets the answer go when the store has moved on (a newer sign-in,
73
+ * or a sign-out); comparing and setting on `replaces` closes the moment between that read and
74
+ * this write, and a store that refuses then throws. A refresh's answer is used only once this has
75
+ * settled. When a save fails, the session keeps a rotation's refresh token in memory, the only
76
+ * live one, for its next refresh and for `revoke()` (D456).
77
+ */
78
+ readonly onTokens: (update: TokenUpdate) => void | Promise<void>;
79
+ /**
80
+ * Runs `work` while holding off every other process's refresh, for a store several Node
81
+ * processes share: `fileLock(path)` from this entry, or the app's own lock on its store. With
82
+ * `fileLock`, keep `tokens` and `onTokens` asynchronous: a holder whose thread is blocked for 10 s
83
+ * loses the lock. A refresh runs inside it (the reads, the request and the save), and so does a
84
+ * revocation.
85
+ * `signal` fires at the refresh's deadline: a lock still held then ends the refresh on time, as
86
+ * `unavailable`, and `work` never sends anything, even if the lock runs it late. A lock that
87
+ * ignores `signal` still holds off the others for as long as it waits.
88
+ *
89
+ * The lock's promise must settle only once `work` has settled, as Web Locks does with its
90
+ * signal: a lock that lets go while `work` still runs (a mutex with a timeout) lets another
91
+ * process in beside a pending save. The session itself waits for `work` before its next turn.
92
+ *
93
+ * Without one, there must be one session per store, shared by everything that uses it: two
94
+ * sessions on one store, in one process (a backend making one per request) or in two, refresh
95
+ * as two processes do. A refresh whose answer takes longer than pulse-auth's 10 s grace can then
96
+ * cross another's refresh of the same token, which pulse-auth reads as reuse, and the session
97
+ * ends.
98
+ */
99
+ readonly lock?: <T>(work: () => Promise<T>, signal: AbortSignal) => Promise<T>;
100
+ }
101
+ /** Why a session has no token to give. */
102
+ export type SessionFailure =
103
+ /**
104
+ * Nobody is signed in: no tokens, no refresh token, or the server ended the session
105
+ * (`invalid_grant`), after which the stored tokens are cleared (`onTokens`, `cleared`).
106
+ */
107
+ {
108
+ readonly kind: 'signed-out';
109
+ }
110
+ /** No token within 15 s, or no answer at all: offline, or the server is down. A refresh goes on, and its answer is still saved. */
111
+ | {
112
+ readonly kind: 'unavailable';
113
+ }
114
+ /** The app's store failed: reading the tokens, saving a refresh's, or taking its lock. */
115
+ | {
116
+ readonly kind: 'store_failed';
117
+ readonly step: 'read' | 'save' | 'lock';
118
+ readonly cause: unknown;
119
+ }
120
+ /** The refresh failed any other way: the server refused the client, or answered outside the contract. */
121
+ | {
122
+ readonly kind: 'refresh_failed';
123
+ readonly error: ApiError;
124
+ };
125
+ /** Thrown by `session.token()`; the default transport turns it into `no_token`, with this as its `cause`. */
126
+ export declare class SessionError extends Error {
127
+ readonly failure: SessionFailure;
128
+ constructor(failure: SessionFailure);
129
+ }
130
+ /**
131
+ * How a revocation came out (RFC 7009). pulse-auth answers a revocation 200 whatever it was sent,
132
+ * so that answer proves nothing: `revoked` rests on the issuer taking the session's access token
133
+ * just before and refusing it just after (D461, D464). Either way, what the app clears locally is
134
+ * its own call.
135
+ */
136
+ export type RevokeResult = {
137
+ readonly kind: 'revoked';
138
+ } | {
139
+ readonly kind: 'unconfirmed';
140
+ /**
141
+ * Why it isn't known to be over:
142
+ * - the revocation's own failure (an `ApiError`, `aborted` and `timeout` included);
143
+ * - `still_live`: the issuer still takes the access token after its revocation;
144
+ * - `check_failed`: the revocation went, but the check before or after it couldn't be made,
145
+ * or the issuer didn't take the access token before it (`error` says how);
146
+ * - `unconfirmable`: no access token known to have 30 s left to check with, so the refresh
147
+ * token went (or a last access token), and nothing can tell whether it ended the session;
148
+ * - `maybe_spent`: as `unconfirmable`, and the refresh token's last refresh got no answer, so
149
+ * the server may have rotated it, and it may end nothing;
150
+ * - `no_endpoint`, `no_tokens` (nothing to send), or the store failing.
151
+ */
152
+ readonly reason: ApiError | {
153
+ readonly kind: 'still_live';
154
+ } | {
155
+ readonly kind: 'check_failed';
156
+ readonly error: ApiError;
157
+ } | {
158
+ readonly kind: 'unconfirmable';
159
+ } | {
160
+ readonly kind: 'maybe_spent';
161
+ } | {
162
+ readonly kind: 'no_endpoint';
163
+ } | {
164
+ readonly kind: 'no_tokens';
165
+ } | Extract<SessionFailure, {
166
+ readonly kind: 'store_failed';
167
+ }>;
168
+ };
169
+ export interface Session {
170
+ /**
171
+ * The token function for `createFlipstream` (or `fetchTransport`): the access token while it has
172
+ * more than a minute left, or else a refreshed one. Callers arriving while a refresh runs share
173
+ * it. After a 401 (`rejected`), the token is refreshed, unless another refresh already replaced
174
+ * it. Rejects with a `SessionError`.
175
+ */
176
+ token(ask?: TokenAsk): Promise<string>;
177
+ /**
178
+ * Ends the session at the server (RFC 7009), with the tokens read once no refresh is spending
179
+ * them, inside the app's `lock` when there is one, all within 10 s, with nothing sent after. An
180
+ * access token known to have at least 30 s left is checked at the issuer, revoked (pulse-auth
181
+ * ends the whole session by it, whatever became of the refresh token) and checked again: only
182
+ * taken before and refused after is `revoked`. Without such a token, or when the check before
183
+ * fails, the live refresh token goes (the store's, or a rotation's whose save failed, D456), and
184
+ * the result is `unconfirmed`.
185
+ *
186
+ * It doesn't touch the store: after it, whatever the result, the app clears its own (D473). A
187
+ * clear with no `replaces` can be undone by a refresh's slow save that lands afterwards; #134
188
+ * would have the session do the clear instead.
189
+ */
190
+ revoke(options?: Pick<AuthCallOptions, 'signal'>): Promise<RevokeResult>;
191
+ }
192
+ export declare function createSession(options: SessionOptions): Session;
@@ -0,0 +1,480 @@
1
+ import { z } from 'zod';
2
+ import { call } from '../core/call.js';
3
+ import { tokenCall } from '../auth/tokenEndpoint.js';
4
+ import { authTransport, isHttpsUrl } from '../auth/transport.js';
5
+ import { clientAuthorization, vouched } from './clientSecret.js';
6
+ /** Thrown by `session.token()`; the default transport turns it into `no_token`, with this as its `cause`. */
7
+ export class SessionError extends Error {
8
+ failure;
9
+ constructor(failure) {
10
+ super(`no token: ${failure.kind}`);
11
+ this.name = 'SessionError';
12
+ this.failure = failure;
13
+ }
14
+ }
15
+ /** A caller waits this long for a refresh, then gets `unavailable` (the os's `refresh.ts`). */
16
+ const WAIT_MS = 15_000;
17
+ /** The refresh's own limit: past the callers' wait, so a slow answer is still saved. */
18
+ const REFRESH_DEADLINE_MS = 60_000;
19
+ /** A revocation's own limit, the lock's wait and the store's read included. */
20
+ const REVOKE_DEADLINE_MS = 10_000;
21
+ /** An access token with less left than this is refreshed first. */
22
+ const MARGIN_MS = 60_000;
23
+ /** An access token checked before and after a revocation needs this much left for both (D464). */
24
+ const CHECK_MARGIN_MS = 30_000;
25
+ /** A refresh with less than this left isn't sent: its answer could be cut off after the rotation (K6). */
26
+ const SEND_FLOOR_MS = 5_000;
27
+ // A field set to undefined is read as left out, as a JavaScript store may well hand it back.
28
+ const zStored = z.object({
29
+ accessToken: z.string().min(1),
30
+ refreshToken: z.string().optional(),
31
+ expiresAt: z.number().optional(),
32
+ });
33
+ const SIGNED_OUT = { kind: 'signed-out' };
34
+ const UNAVAILABLE = { kind: 'unavailable' };
35
+ export function createSession(options) {
36
+ const { server, clientId } = options;
37
+ // Made once: a TypeError here, at creation, for a secret that is given but blank.
38
+ const authorization = clientAuthorization('createSession', clientId, options.clientSecret);
39
+ const transport = authTransport({ fetch: options.fetch });
40
+ let inFlight = null;
41
+ let tail = Promise.resolve();
42
+ // A rotation whose save failed. Its refresh token is the session's only live one while the store
43
+ // still holds the token it replaced, which is spent (D456).
44
+ let unsaved = null;
45
+ // A refresh token whose last refresh got no answer the session could read: the server may have
46
+ // rotated it, so it may be spent (S5.B1). Cleared by the next answer for it.
47
+ let doubtful = null;
48
+ // The issuer's userinfo endpoint, once found: what a revocation is checked against.
49
+ let userinfo = null;
50
+ async function read() {
51
+ try {
52
+ const stored = await options.tokens();
53
+ if (stored === null)
54
+ return { ok: true, tokens: null };
55
+ if (zStored.safeParse(stored).success)
56
+ return { ok: true, tokens: stored };
57
+ return { ok: false, failure: { kind: 'store_failed', step: 'read', cause: new TypeError('the stored tokens are not tokens') } };
58
+ }
59
+ catch (cause) {
60
+ return { ok: false, failure: { kind: 'store_failed', step: 'read', cause } };
61
+ }
62
+ }
63
+ /**
64
+ * The refresh token that is live now, and the stored one it stands for: an unsaved rotation's
65
+ * while the store still holds the token it replaced, else the store's. A store that moved on (a
66
+ * newer sign-in, a sign-out) lets the unsaved rotation go.
67
+ */
68
+ function liveOf(held) {
69
+ const stored = held?.refreshToken;
70
+ if (unsaved !== null && unsaved.replaces !== stored)
71
+ unsaved = null;
72
+ if (stored === undefined || stored === '')
73
+ return undefined;
74
+ return { token: unsaved?.refreshToken ?? stored, stored };
75
+ }
76
+ // Read and decided inside the one refresh, so two callers never spend the same refresh token,
77
+ // and a token another process refreshed meanwhile is used, not refreshed again (honest-typescript §5).
78
+ // Held to the refresh's deadline, up to the answer: the wait for its turn and the lock, the read
79
+ // and the request.
80
+ async function refresh(stale, limit) {
81
+ for (;;) {
82
+ // A lock that ran this only after the deadline: nothing is read, and nothing is sent.
83
+ if (limit.ended() !== null)
84
+ return UNAVAILABLE;
85
+ const now = await orAborted(read(), limit.signal);
86
+ if ('kind' in now)
87
+ return UNAVAILABLE;
88
+ if (!now.ok)
89
+ return now.failure;
90
+ const held = now.tokens;
91
+ const live = liveOf(held);
92
+ if (held === null)
93
+ return SIGNED_OUT;
94
+ if (held.accessToken !== stale && fresh(held))
95
+ return { kind: 'token', accessToken: held.accessToken };
96
+ if (live === undefined)
97
+ return SIGNED_OUT;
98
+ // By the clock, not only the timer (a store that blocks the thread returns before the timer
99
+ // runs), and never with under 5 s left: a request cut off after pulse-auth rotated loses the
100
+ // new token, and the next refresh then ends the session (K6). Unsent is better.
101
+ if (limit.left() < SEND_FLOOR_MS)
102
+ return UNAVAILABLE;
103
+ const sentAt = Date.now();
104
+ const form = { grant_type: 'refresh_token', refresh_token: live.token, client_id: clientId };
105
+ const answer = vouched(await call(transport, tokenCall('auth.refresh', server.tokenEndpoint, form, limit.left(), authorization)), authorization);
106
+ doubtful = !answer.ok && unanswered(answer.error) ? live.token : null;
107
+ if (!answer.ok) {
108
+ const failure = failureOf(answer.error);
109
+ if (failure.kind !== 'signed-out')
110
+ return failure;
111
+ // The server ended the session the token sent belongs to. The store's tokens are cleared,
112
+ // but only if they're still that session's: a newer sign-in another process saved
113
+ // meanwhile is kept, and used (D461).
114
+ const after = await read();
115
+ if (!after.ok)
116
+ return after.failure;
117
+ if (after.tokens?.refreshToken !== live.stored)
118
+ continue;
119
+ unsaved = null;
120
+ try {
121
+ await options.onTokens({ kind: 'cleared', replaces: live.stored });
122
+ }
123
+ catch (cause) {
124
+ return { kind: 'store_failed', step: 'save', cause };
125
+ }
126
+ return SIGNED_OUT;
127
+ }
128
+ const update = updateOf(answer.data, live.stored, sentAt);
129
+ // From here a rotation's refresh token is the only live one. So the re-read and the save are
130
+ // waited out, never cut short: until the save settles, the store may show tokens that may yet
131
+ // fail to save, and the refresh stays the one every caller takes. A rotation not saved is kept.
132
+ const keep = () => {
133
+ if (update.kind === 'rotated')
134
+ unsaved = { refreshToken: update.refreshToken, replaces: live.stored };
135
+ };
136
+ const before = await read();
137
+ if (!before.ok) {
138
+ keep();
139
+ return before.failure;
140
+ }
141
+ // The store moved on meanwhile, to a newer sign-in or a sign-out that this answer must not
142
+ // overwrite: the answer is let go, and the refresh starts over from the store as it is now.
143
+ if (before.tokens?.refreshToken !== live.stored)
144
+ continue;
145
+ try {
146
+ await options.onTokens(update);
147
+ }
148
+ catch (cause) {
149
+ keep();
150
+ return { kind: 'store_failed', step: 'save', cause };
151
+ }
152
+ if (update.kind === 'rotated')
153
+ unsaved = null;
154
+ return { kind: 'token', accessToken: update.accessToken };
155
+ }
156
+ }
157
+ /**
158
+ * Puts `work` at the end of the session's queue, inside the app's lock when there is one. The
159
+ * next turn waits for the work itself as well as for the lock's promise, so a lock that lets go
160
+ * at its signal while the work still runs (a mutex with a timeout) never lets a turn run beside
161
+ * it (K1).
162
+ */
163
+ function enqueue(work, signal) {
164
+ const run = {};
165
+ const begin = () => {
166
+ run.begun = work();
167
+ return run.begun;
168
+ };
169
+ const { lock } = options;
170
+ const turn = tail.then(() => (lock === undefined ? begin() : lock(begin, signal)));
171
+ tail = turn.then(noop, noop).then(() => run.begun?.then(noop, noop));
172
+ return { turn, run };
173
+ }
174
+ /**
175
+ * One at a time within this session, a refresh or a revocation, each inside the app's lock when
176
+ * there is one, so a revocation never sends a token a refresh is spending, nor a refresh one a
177
+ * revocation is ending. The wait for a turn and for the lock ends at `limit`, and then the work
178
+ * never begins (`late()`), by its timer or by the clock; once begun, its outcome stands,
179
+ * whenever it settles.
180
+ */
181
+ function serial(work, limit, late, lockFailed) {
182
+ if (limit.ended() !== null)
183
+ return Promise.resolve(late());
184
+ const { turn, run } = enqueue(() => (limit.ended() !== null ? Promise.resolve(late()) : work()), limit.signal);
185
+ return orAborted(turn, limit.signal).then((first) => (isAborted(first) ? (run.begun ?? late()) : first), (cause) => run.begun ?? (limit.signal.aborted ? late() : lockFailed(cause)));
186
+ }
187
+ function shared(stale) {
188
+ if (inFlight !== null)
189
+ return inFlight;
190
+ const limit = createLimit(REFRESH_DEADLINE_MS, undefined);
191
+ const lockFailed = (cause) => ({ kind: 'store_failed', step: 'lock', cause });
192
+ const attempt = serial(() => refresh(stale, limit), limit, () => UNAVAILABLE, lockFailed).finally(limit.dispose);
193
+ inFlight = attempt;
194
+ const clear = () => {
195
+ if (inFlight === attempt)
196
+ inFlight = null;
197
+ };
198
+ attempt.then(clear, clear);
199
+ return attempt;
200
+ }
201
+ // A caller's whole wait, the store's read included, so a store that stalls can't hold it longer.
202
+ // While a refresh runs, every caller takes its outcome, not the store's: the store may already
203
+ // show tokens whose save hasn't settled, or a token the server just refused (a 401).
204
+ async function acquire(ask) {
205
+ if (inFlight !== null)
206
+ return inFlight;
207
+ const now = await read();
208
+ if (!now.ok)
209
+ return now.failure;
210
+ if (inFlight !== null)
211
+ return inFlight;
212
+ const held = now.tokens;
213
+ if (held === null)
214
+ return SIGNED_OUT;
215
+ if (held.accessToken !== ask.rejected && fresh(held))
216
+ return { kind: 'token', accessToken: held.accessToken };
217
+ return shared(held.accessToken);
218
+ }
219
+ // RFC 7009 on the tokens as they are once no refresh is spending them. pulse-auth answers 200
220
+ // whatever it is sent, a spent refresh token or an access token that has run out included, and
221
+ // revokes nothing for those: so the answer is checked against the server, never taken on trust.
222
+ async function revokeNow(endpoint, limit) {
223
+ if (limit.signal.aborted)
224
+ return limit.unconfirmed();
225
+ const now = await orAborted(read(), limit.signal);
226
+ if ('kind' in now)
227
+ return limit.unconfirmed();
228
+ if (!now.ok)
229
+ return { kind: 'unconfirmed', reason: now.failure };
230
+ const held = now.tokens;
231
+ const live = liveOf(held);
232
+ if (held === null)
233
+ return { kind: 'unconfirmed', reason: { kind: 'no_tokens' } };
234
+ // D464: a 200 from the issuer just before, then a 401 for the same token just after, is a
235
+ // difference only the revocation explains. A 401 on its own isn't: pulse-auth answers every
236
+ // failure of a token with the same 401 (expired, another audience, an ended session).
237
+ // A known expiry only: a token that could run out between the two checks would revoke nothing,
238
+ // and still be refused after (S6.B1).
239
+ if (held.expiresAt !== undefined && held.expiresAt - Date.now() >= CHECK_MARGIN_MS) {
240
+ const before = await taken(held.accessToken, limit);
241
+ if (before.kind === 'taken') {
242
+ const sent = await revocation(endpoint, held.accessToken, 'access_token', limit);
243
+ if (!sent.ok)
244
+ return { kind: 'unconfirmed', reason: sent.error };
245
+ const after = await taken(held.accessToken, limit);
246
+ if (after.kind === 'taken')
247
+ return { kind: 'unconfirmed', reason: { kind: 'still_live' } };
248
+ if (after.kind === 'failed')
249
+ return { kind: 'unconfirmed', reason: { kind: 'check_failed', error: after.error } };
250
+ unsaved = null;
251
+ doubtful = null;
252
+ return { kind: 'revoked' };
253
+ }
254
+ // Nothing to compare the answer after with: the session is still ended as best it can be,
255
+ // and the result says why it can't be confirmed.
256
+ const sent = await revocation(endpoint, live?.token ?? held.accessToken, live === undefined ? 'access_token' : 'refresh_token', limit);
257
+ return { kind: 'unconfirmed', reason: sent.ok ? { kind: 'check_failed', error: before.error } : sent.error };
258
+ }
259
+ // No access token to check with: the live refresh token goes, or, with none, an access token
260
+ // that hasn't run out yet (pulse-auth ends a session by either).
261
+ if (live === undefined && !unexpired(held))
262
+ return { kind: 'unconfirmed', reason: { kind: 'no_tokens' } };
263
+ const sent = await revocation(endpoint, live?.token ?? held.accessToken, live === undefined ? 'access_token' : 'refresh_token', limit);
264
+ if (!sent.ok)
265
+ return { kind: 'unconfirmed', reason: sent.error };
266
+ return { kind: 'unconfirmed', reason: { kind: live !== undefined && doubtful === live.token ? 'maybe_spent' : 'unconfirmable' } };
267
+ }
268
+ function revocation(endpoint, token, hint, limit) {
269
+ // Nothing is sent once the turn's 10 s are up, not even with no time left (S6.F1).
270
+ const ended = limit.ended();
271
+ if (ended !== null)
272
+ return Promise.resolve({ ok: false, error: ended });
273
+ const body = new URLSearchParams({ token, token_type_hint: hint, client_id: clientId }).toString();
274
+ const headers = { 'content-type': 'application/x-www-form-urlencoded', ...(authorization === undefined ? {} : { authorization }) };
275
+ return call(withoutBody(transport), {
276
+ effect: 'write',
277
+ service: 'auth',
278
+ endpoint: 'auth.revoke',
279
+ makeRequest: () => new Request(endpoint, { method: 'POST', headers, body }),
280
+ schema: z.null(),
281
+ deadlineMs: limit.left(),
282
+ retry: 'never',
283
+ }, limit.caller).then((sent) => vouched(sent, authorization));
284
+ }
285
+ /**
286
+ * Whether the issuer takes `accessToken` now, asked at its userinfo endpoint. pulse-auth checks
287
+ * there that the token's session (`sid`) is still active (tokens/automatic.py `verify`), needs no
288
+ * scope, and answers every refusal with the same 401, an ended session or an expired token alike.
289
+ * Resource servers trust the signature alone, so only the issuer can say.
290
+ */
291
+ async function taken(accessToken, limit) {
292
+ const found = await userinfoEndpoint(limit);
293
+ if (!found.ok)
294
+ return { kind: 'failed', error: found.error };
295
+ const ended = limit.ended();
296
+ if (ended !== null)
297
+ return { kind: 'failed', error: ended };
298
+ const asked = await call(transport, {
299
+ effect: 'read',
300
+ service: 'auth',
301
+ endpoint: 'auth.userinfo',
302
+ makeRequest: () => new Request(found.data, { headers: { accept: 'application/json', authorization: `Bearer ${accessToken}` } }),
303
+ schema: z.unknown(),
304
+ deadlineMs: limit.left(),
305
+ retry: 'never',
306
+ }, limit.caller);
307
+ if (asked.ok)
308
+ return { kind: 'taken' };
309
+ return { kind: asked.error.kind === 'unauthorized' ? 'refused' : 'failed', error: asked.error };
310
+ }
311
+ /**
312
+ * pulse-auth names its userinfo endpoint only in its OpenID configuration (OIDC Discovery §4),
313
+ * not in the RFC 8414 metadata `discover` reads: so it is read there, once, and held to what
314
+ * discovery holds an endpoint to: the same issuer, https, and here the issuer's own origin. Once
315
+ * pulse-auth names it in its RFC 8414 metadata too (flipstream-io/pulse-auth#83), read it there
316
+ * first.
317
+ */
318
+ async function userinfoEndpoint(limit) {
319
+ if (userinfo !== null)
320
+ return { ok: true, data: userinfo };
321
+ const ended = limit.ended();
322
+ if (ended !== null)
323
+ return { ok: false, error: ended };
324
+ const read = await call(transport, {
325
+ effect: 'read',
326
+ service: 'auth',
327
+ endpoint: 'auth.openid_configuration',
328
+ makeRequest: () => new Request(`${server.issuer.replace(/\/+$/, '')}/.well-known/openid-configuration`, { headers: { accept: 'application/json' } }),
329
+ schema: zOpenIdConfiguration,
330
+ deadlineMs: limit.left(),
331
+ retry: 'read',
332
+ }, limit.caller);
333
+ if (!read.ok)
334
+ return read;
335
+ const { issuer, userinfo_endpoint: found } = read.data;
336
+ if (issuer !== server.issuer)
337
+ return { ok: false, error: { kind: 'invalid', issues: 'the OpenID configuration names another issuer', status: 200 } };
338
+ if (found === undefined || !isHttpsUrl(found) || new URL(found).origin !== new URL(server.issuer).origin) {
339
+ return { ok: false, error: { kind: 'invalid', issues: 'the OpenID configuration names no userinfo endpoint on the issuer', status: 200 } };
340
+ }
341
+ userinfo = found;
342
+ return { ok: true, data: found };
343
+ }
344
+ return {
345
+ async token(ask = {}) {
346
+ const outcome = await within(acquire(ask), WAIT_MS);
347
+ if (outcome.kind === 'token')
348
+ return outcome.accessToken;
349
+ throw new SessionError(outcome);
350
+ },
351
+ async revoke(revokeOptions = {}) {
352
+ const endpoint = server.revocationEndpoint;
353
+ if (endpoint === undefined)
354
+ return { kind: 'unconfirmed', reason: { kind: 'no_endpoint' } };
355
+ const limit = createLimit(REVOKE_DEADLINE_MS, revokeOptions.signal);
356
+ const lockFailed = (cause) => ({ kind: 'unconfirmed', reason: { kind: 'store_failed', step: 'lock', cause } });
357
+ try {
358
+ return await serial(() => revokeNow(endpoint, limit), limit, limit.unconfirmed, lockFailed);
359
+ }
360
+ finally {
361
+ limit.dispose();
362
+ }
363
+ },
364
+ };
365
+ }
366
+ const fresh = (held) => held.expiresAt === undefined || held.expiresAt - Date.now() > MARGIN_MS;
367
+ const unexpired = (held) => held.expiresAt === undefined || held.expiresAt > Date.now();
368
+ /**
369
+ * A refresh the server may have carried out without the session learning of it: no answer, past
370
+ * the deadline, a server error, or a success it couldn't read. A 4xx answer, or a request never
371
+ * sent, rotated nothing.
372
+ */
373
+ const unanswered = (error) => error.kind === 'timeout' || error.kind === 'unavailable' || error.kind === 'invalid';
374
+ // OIDC Discovery §3, what a revocation's check needs and nothing more.
375
+ const zOpenIdConfiguration = z.looseObject({ issuer: z.string(), userinfo_endpoint: z.string().exactOptional() });
376
+ const noop = () => undefined;
377
+ const ABORTED = { kind: 'aborted' };
378
+ const isAborted = (value) => value === ABORTED;
379
+ function createLimit(ms, caller) {
380
+ const stop = new AbortController();
381
+ const end = Date.now() + ms;
382
+ let reason = 'timeout';
383
+ const timer = setTimeout(() => {
384
+ stop.abort();
385
+ }, ms);
386
+ const onAbort = () => {
387
+ reason = 'aborted';
388
+ stop.abort();
389
+ };
390
+ if (caller?.aborted === true)
391
+ onAbort();
392
+ else
393
+ caller?.addEventListener('abort', onAbort, { once: true });
394
+ return {
395
+ signal: stop.signal,
396
+ caller,
397
+ left: () => Math.max(0, end - Date.now()),
398
+ unconfirmed: () => ({ kind: 'unconfirmed', reason: { kind: reason } }),
399
+ // The clock as well as the timer: a store that blocks the thread past the deadline returns
400
+ // before the timer has had a chance to run (S7.F1).
401
+ ended: () => (stop.signal.aborted || Date.now() >= end ? { kind: reason } : null),
402
+ dispose: () => {
403
+ clearTimeout(timer);
404
+ caller?.removeEventListener('abort', onAbort);
405
+ },
406
+ };
407
+ }
408
+ /** `work`, or ABORTED as soon as `signal` fires; the work itself goes on. */
409
+ function orAborted(work, signal) {
410
+ if (signal === undefined)
411
+ return work;
412
+ if (signal.aborted) {
413
+ // Let go, but observed: a rejection nobody handles would end a Node process.
414
+ work.then(() => undefined, () => undefined);
415
+ return Promise.resolve(ABORTED);
416
+ }
417
+ return new Promise((resolve, reject) => {
418
+ const onAbort = () => {
419
+ resolve(ABORTED);
420
+ };
421
+ signal.addEventListener('abort', onAbort, { once: true });
422
+ work.then((value) => {
423
+ signal.removeEventListener('abort', onAbort);
424
+ resolve(value);
425
+ }, (error) => {
426
+ signal.removeEventListener('abort', onAbort);
427
+ reject(error instanceof Error ? error : new Error(String(error)));
428
+ });
429
+ });
430
+ }
431
+ /** The refresh, or `unavailable` once `ms` have passed; the refresh itself goes on. */
432
+ function within(work, ms) {
433
+ return new Promise((resolve, reject) => {
434
+ const timer = setTimeout(() => {
435
+ resolve(UNAVAILABLE);
436
+ }, ms);
437
+ work.then((outcome) => {
438
+ clearTimeout(timer);
439
+ resolve(outcome);
440
+ }, (error) => {
441
+ clearTimeout(timer);
442
+ reject(error instanceof Error ? error : new Error(String(error)));
443
+ });
444
+ });
445
+ }
446
+ // RFC 6749 §6: a new refresh token replaces the old; none (pulse-auth sends "") means keep it.
447
+ function updateOf(answer, replaces, sentAt) {
448
+ const expiry = answer.expires_in === undefined ? {} : { expiresAt: sentAt + answer.expires_in * 1000 };
449
+ return answer.refresh_token !== undefined && answer.refresh_token !== ''
450
+ ? { kind: 'rotated', accessToken: answer.access_token, refreshToken: answer.refresh_token, ...expiry, replaces }
451
+ : { kind: 'access-only', accessToken: answer.access_token, ...expiry, replaces };
452
+ }
453
+ function failureOf(error) {
454
+ switch (error.kind) {
455
+ case 'unavailable':
456
+ case 'timeout':
457
+ return UNAVAILABLE;
458
+ // pulse-auth answers a refresh token it doesn't know with 400 invalid_grant, and the reuse of
459
+ // a spent one with 401 invalid_grant (it then revokes the session).
460
+ case 'rejected':
461
+ case 'unauthorized':
462
+ return error.code === 'invalid_grant' ? SIGNED_OUT : { kind: 'refresh_failed', error };
463
+ default:
464
+ return { kind: 'refresh_failed', error };
465
+ }
466
+ }
467
+ /**
468
+ * RFC 7009 §2.2: a 200 says the token is revoked, and its body means nothing (pulse-auth's is
469
+ * empty, which `readJson` can't read). So a success's body is let go and read as `null`.
470
+ */
471
+ function withoutBody(transport) {
472
+ return async (request) => {
473
+ const sent = await transport(request);
474
+ if (sent.kind !== 'response' || !sent.response.ok)
475
+ return sent;
476
+ void sent.response.body?.cancel().catch(() => undefined);
477
+ return { kind: 'response', response: new Response('null', { status: 200 }) };
478
+ };
479
+ }
480
+ //# sourceMappingURL=session.js.map