@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,248 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, open, readFile, stat, unlink } from 'node:fs/promises';
3
+ import { dirname, isAbsolute } from 'node:path';
4
+ import { clearInterval, setInterval } from 'node:timers';
5
+ import { setTimeout as pause } from 'node:timers/promises';
6
+ /*
7
+ * The session's `lock` (D444), ready-made for Node processes that share one token store, such as
8
+ * the CLI run by several agents at once (#114): a lock file, created exclusively, held while `work`
9
+ * runs, and removed afterwards.
10
+ *
11
+ * A holder that died must not hold every other process off for ever, and a slow one must never be
12
+ * taken for dead: either way, two refreshes would spend one refresh token. So a holder touches its
13
+ * file every second, and a file nobody touches any more is taken over.
14
+ * - A timeout alone can't tell them apart: a hold lasts as long as its save, which the session
15
+ * waits out and never cuts short.
16
+ * - Nor can the holder's process ID: IDs are reused, and two containers sharing a folder each see
17
+ * the other's processes as gone.
18
+ * - A file is stale once a waiter has seen it unchanged over 10 s of its own tries, or over 3 s
19
+ * when its last touch is also 10 s old by this machine's clock. The second lets a sign-out, whose
20
+ * whole budget is 10 s (D445), take over a crashed holder's leftover (rev143 P1-1). Neither a
21
+ * clock that jumps forward nor a laptop waking from sleep (a sleep counts as one try) makes a
22
+ * live lock stale on its own: its holder would also have to go 2 to 3 s without a touch just
23
+ * then, as the waiter's watch starts at the last one. A holder on a clock 10 s or more behind
24
+ * this one, in a virtual machine sharing the folder say, has only those 2 to 3 s all the time.
25
+ *
26
+ * Waiters that judge a lock stale together take turns through a second file, so none removes a
27
+ * lock another has just taken (honest-typescript §5): of those, only the first finds it unchanged.
28
+ */
29
+ /** How often a waiter tries again. */
30
+ const RETRY_MS = 100;
31
+ /** How often a holder touches its lock file. */
32
+ const TOUCH_MS = 1_000;
33
+ /** A file untouched this long has no live holder. */
34
+ const STALE_MS = 10_000;
35
+ /** How long a waiter watches a file whose last touch is already STALE_MS old by the clock. */
36
+ const OLD_WATCH_MS = 3_000;
37
+ /**
38
+ * A lock across processes, for `createSession`'s `lock` option: for a token store that several
39
+ * Node processes share, such as a CLI run several times at once. Give every process the same
40
+ * absolute path, on a local disk, beside the store.
41
+ *
42
+ * - **It is taken by creating the file exclusively,** and removed once `work` has settled, whether
43
+ * it succeeded or failed. Only then does the lock settle, with `work`'s outcome.
44
+ * - **While another process holds it,** it tries again every 100 ms. When `signal` fires it gives
45
+ * up, rejecting with `signal.reason`, and `work` never runs after that. With a signal that has
46
+ * already fired, it creates nothing.
47
+ * - **A process that dies holding it** leaves a file nobody touches any more: a holder touches it
48
+ * every second. The next process takes it over once the file is 10 s old by this machine's clock
49
+ * and it has seen it unchanged for 3 s, or, whatever the clock says, once it has seen it unchanged
50
+ * for 10 s.
51
+ * - **A holder that can't touch its file for 10 s loses it,** and its `work` goes on beside the next
52
+ * holder's: a thread blocked by a synchronous store, or a process stopped by Ctrl-Z or a
53
+ * debugger. Keep the store asynchronous.
54
+ * - **It isn't reentrant:** `work` that takes the same lock again waits for itself until its
55
+ * signal.
56
+ * - **When the file can't be removed,** `work`'s outcome still stands, and the next process takes
57
+ * the file over as stale.
58
+ *
59
+ * @param path - The lock file. Its folder is made when it isn't there (on POSIX, for this user
60
+ * only, as the file is).
61
+ */
62
+ export function fileLock(path) {
63
+ // A relative path names another file in each working directory, and locks nothing.
64
+ if (!isAbsolute(path))
65
+ throw new TypeError(`fileLock needs an absolute path, the same in every process: ${path}`);
66
+ return async (work, signal) => {
67
+ const held = await take(path, signal);
68
+ try {
69
+ return await work();
70
+ }
71
+ finally {
72
+ await held.release();
73
+ }
74
+ };
75
+ }
76
+ async function take(path, signal) {
77
+ const id = randomUUID();
78
+ const lock = lookout(path);
79
+ const turns = lookout(turnsOf(path));
80
+ for (;;) {
81
+ if (signal.aborted)
82
+ return aborted(signal);
83
+ const handle = await createWith(path, id);
84
+ if (handle !== null) {
85
+ const held = hold(path, id, handle);
86
+ // Taken in the same moment the signal fired: let go at once, unused.
87
+ if (!signal.aborted)
88
+ return held;
89
+ await held.release();
90
+ return aborted(signal);
91
+ }
92
+ const stale = await lock();
93
+ if (stale !== null)
94
+ await takeOver(path, stale, id, turns);
95
+ // An abort ends the pause early; the loop's first line then gives up.
96
+ await pause(RETRY_MS, undefined, { signal }).catch(noop);
97
+ }
98
+ }
99
+ function hold(path, id, handle) {
100
+ let touching = false;
101
+ const touched = () => {
102
+ touching = false;
103
+ };
104
+ const touch = setInterval(() => {
105
+ // One at a time: on a hung disk, touches would pile up behind each other. A touch that fails
106
+ // is tried again a second later; ten seconds of them and the lock looks stale.
107
+ if (touching)
108
+ return;
109
+ touching = true;
110
+ const now = new Date();
111
+ handle.utimes(now, now).then(touched, touched);
112
+ }, TOUCH_MS);
113
+ // A process with nothing left to do but hold the lock exits, and its lock goes stale, rather
114
+ // than holding every other process off for ever.
115
+ touch.unref();
116
+ return {
117
+ release: async () => {
118
+ // Removed while it is still being touched, so no waiter can take it over as stale meanwhile.
119
+ await removeOwn(path, id);
120
+ clearInterval(touch);
121
+ await handle.close().catch(noop);
122
+ },
123
+ };
124
+ }
125
+ /**
126
+ * Removes a stale lock file, unless it changed since it was judged stale, while holding the turns
127
+ * file. A turns file left by a waiter that died is removed in its turn, once it too is stale.
128
+ */
129
+ async function takeOver(path, stale, id, turns) {
130
+ const file = turnsOf(path);
131
+ const handle = await createWith(file, id);
132
+ if (handle === null) {
133
+ const dead = await turns();
134
+ if (dead !== null)
135
+ await removeIf(file, dead);
136
+ return;
137
+ }
138
+ try {
139
+ await removeIf(path, stale);
140
+ }
141
+ finally {
142
+ await removeOwn(file, id);
143
+ await handle.close().catch(noop);
144
+ }
145
+ }
146
+ const turnsOf = (path) => `${path}.stale`;
147
+ /**
148
+ * The file, created exclusively for this user with `id` in it; null while another holds it.
149
+ * Windows removes an open file's name only once its last handle closes, so every removal here
150
+ * comes before its handle's close, and a name still pending removal reads as held (`createNew`).
151
+ */
152
+ async function createWith(file, id) {
153
+ const handle = await createNew(file).catch(async (error) => {
154
+ if (codeOf(error) !== 'ENOENT')
155
+ throw error;
156
+ // The folder isn't there yet: a keychain store has none of its own.
157
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
158
+ return createNew(file);
159
+ });
160
+ if (handle === null)
161
+ return null;
162
+ try {
163
+ await handle.writeFile(id);
164
+ }
165
+ catch (error) {
166
+ // Nothing this attempt made is left behind (honest-typescript §7).
167
+ if (await isStill(file, handle).catch(() => false))
168
+ await unlink(file).catch(noop);
169
+ await handle.close().catch(noop);
170
+ throw error;
171
+ }
172
+ // A write that hung for 10 s can let a waiter take the file over while it is still empty (rev143
173
+ // P3-2): the name is then another's, and this handle holds nothing.
174
+ if (await isStill(file, handle))
175
+ return handle;
176
+ await handle.close().catch(noop);
177
+ return null;
178
+ }
179
+ async function createNew(file) {
180
+ try {
181
+ return await open(file, 'wx', 0o600);
182
+ }
183
+ catch (error) {
184
+ if (codeOf(error) === 'EEXIST' || deletePending(error))
185
+ return null;
186
+ throw error;
187
+ }
188
+ }
189
+ /** Whether `file` names the file `handle` has open. */
190
+ async function isStill(file, handle) {
191
+ const [mine, now] = await Promise.all([handle.stat({ bigint: true }), stat(file, { bigint: true }).catch(() => null)]);
192
+ return now !== null && now.dev === mine.dev && now.ino === mine.ino;
193
+ }
194
+ /**
195
+ * What a waiter sees of a file at each try: its holder and when it was last touched. It comes back
196
+ * as stale once it has been seen unchanged over STALE_MS of tries, or over OLD_WATCH_MS when its
197
+ * last touch is also STALE_MS old by the clock. Time seen is counted in tries, so a slow waiter
198
+ * only takes longer. Any change, or a try that found nothing, starts the count again.
199
+ */
200
+ function lookout(file) {
201
+ let seen = null;
202
+ let tries = 0;
203
+ return async () => {
204
+ const now = await look(file);
205
+ tries = now !== null && now.key === seen ? tries + 1 : 0;
206
+ seen = now?.key ?? null;
207
+ if (now === null)
208
+ return null;
209
+ const watched = tries * RETRY_MS;
210
+ const old = Date.now() - now.touchedAt >= STALE_MS;
211
+ return watched >= STALE_MS || (old && watched >= OLD_WATCH_MS) ? now.key : null;
212
+ };
213
+ }
214
+ async function look(file) {
215
+ try {
216
+ // Read apart: a file replaced between the two only starts the count again.
217
+ const [holder, { mtimeMs }] = await Promise.all([readFile(file, 'utf8'), stat(file)]);
218
+ return { key: `${holder} ${String(mtimeMs)}`, touchedAt: mtimeMs };
219
+ }
220
+ catch (error) {
221
+ if (codeOf(error) === 'ENOENT' || deletePending(error))
222
+ return null;
223
+ throw error;
224
+ }
225
+ }
226
+ /** Removes `file` only if it is still as it was seen. */
227
+ async function removeIf(file, seen) {
228
+ if ((await look(file))?.key !== seen)
229
+ return;
230
+ await unlink(file).catch((error) => {
231
+ if (codeOf(error) !== 'ENOENT')
232
+ throw error;
233
+ });
234
+ }
235
+ /** Removes `file` only while it holds `id`: one taken over meanwhile is its new holder's. */
236
+ async function removeOwn(file, id) {
237
+ if ((await readFile(file, 'utf8').catch(() => null)) === id)
238
+ await unlink(file).catch(noop);
239
+ }
240
+ function aborted(signal) {
241
+ const reason = signal.reason;
242
+ throw reason;
243
+ }
244
+ /** Windows refuses to open a removed file's name while another process still has it open. */
245
+ const deletePending = (error) => process.platform === 'win32' && codeOf(error) === 'EPERM';
246
+ const codeOf = (error) => (error instanceof Error && 'code' in error ? error.code : undefined);
247
+ const noop = () => undefined;
248
+ //# sourceMappingURL=fileLock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fileLock.js","sourceRoot":"","sources":["../../src/node/fileLock.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAmB,MAAM,kBAAkB,CAAA;AACvF,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAA;AAC/C,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE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AAW,EAAE,CAAC,OAAO,CAAC,QAAQ,KAAK,OAAO,IAAI,MAAM,CAAC,KAAK,CAAC,KAAK,OAAO,CAAA;AAE5G,MAAM,MAAM,GAAG,CAAC,KAAc,EAAW,EAAE,CAAC,CAAC,KAAK,YAAY,KAAK,IAAI,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAA;AAEhH,MAAM,IAAI,GAAG,GAAc,EAAE,CAAC,SAAS,CAAA"}
@@ -11,10 +11,15 @@ export type PastedRedirect =
11
11
  readonly ok: false;
12
12
  readonly error: CallbackError | {
13
13
  readonly kind: 'not_a_url';
14
+ }
15
+ /** Not the address the sign-in sends the browser back to (`pending.redirectUri`). */
16
+ | {
17
+ readonly kind: 'wrong_redirect';
14
18
  };
15
19
  };
16
20
  /**
17
- * The redirect the person pasted, checked as the loopback checks one (its state first, then its
18
- * issuer, the server's error, the code) before anything is sent.
21
+ * The redirect the person pasted, checked as the loopback checks one, before anything is sent: its
22
+ * address first (the loopback answers only its own `/callback`), then its state, its issuer, the
23
+ * server's error, the code.
19
24
  */
20
25
  export declare function parsePastedRedirect(text: string, pending: PendingSignIn): PastedRedirect;
@@ -14,15 +14,28 @@ export function isHeadless(env, platform = process.platform) {
14
14
  }
15
15
  const nonEmpty = (value) => value !== undefined && value !== '';
16
16
  /**
17
- * The redirect the person pasted, checked as the loopback checks one (its state first, then its
18
- * issuer, the server's error, the code) before anything is sent.
17
+ * The redirect the person pasted, checked as the loopback checks one, before anything is sent: its
18
+ * address first (the loopback answers only its own `/callback`), then its state, its issuer, the
19
+ * server's error, the code.
19
20
  */
20
21
  export function parsePastedRedirect(text, pending) {
21
22
  const trimmed = text.trim();
22
23
  if (!URL.canParse(trimmed))
23
24
  return { ok: false, error: { kind: 'not_a_url' } };
24
25
  const callbackUrl = new URL(trimmed);
26
+ if (!isRedirectTo(callbackUrl, pending.redirectUri))
27
+ return { ok: false, error: { kind: 'wrong_redirect' } };
25
28
  const read = readCallback(callbackUrl, pending);
26
29
  return read.kind === 'code' ? { ok: true, callbackUrl, code: read.code } : { ok: false, error: read };
27
30
  }
31
+ /**
32
+ * The same scheme, host, port and path; the query is the redirect's own. Not `origin`, which is
33
+ * "null" for every private-use scheme (RFC 8252 §7.1), so any two of them would match.
34
+ */
35
+ function isRedirectTo(url, redirectUri) {
36
+ if (!URL.canParse(redirectUri))
37
+ return false;
38
+ const expected = new URL(redirectUri);
39
+ return url.protocol === expected.protocol && url.host === expected.host && url.pathname === expected.pathname;
40
+ }
28
41
  //# sourceMappingURL=headless.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"headless.js","sourceRoot":"","sources":["../../src/node/headless.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAA0C,MAAM,mBAAmB,CAAA;AAExF;;;;GAIG;AAEH,4FAA4F;AAC5F,MAAM,UAAU,UAAU,CAAC,GAAiD,EAAE,WAAmB,OAAO,CAAC,QAAQ;IAC/G,IAAI,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAAE,OAAO,IAAI,CAAA;IACpC,IAAI,QAAQ,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC,IAAI,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QAAE,OAAO,IAAI,CAAA;IAC5E,OAAO,QAAQ,KAAK,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC,CAAA;AAC/F,CAAC;AAED,MAAM,QAAQ,GAAG,CAAC,KAAyB,EAAW,EAAE,CAAC,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,EAAE,CAAA;AAO5F;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,IAAY,EAAE,OAAsB;IACtE,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,CAAA;IAC3B,IAAI,C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opback.js';
3
3
  export { isHeadless, parsePastedRedirect } from './headless.js';
4
4
  export type { PastedRedirect } from './headless.js';
5
+ export { createSession, SessionError } from './session.js';
6
+ export { fileLock } from './fileLock.js';
7
+ export type { RevokeResult, Session, SessionFailure, SessionOptions, SessionTokens, TokenUpdate } from './session.js';
8
+ export { finishSignIn } from './clientSecret.js';
9
+ export type { ServerSignInOptions } from './clientSecret.js';
@@ -1,5 +1,11 @@
1
1
  // The `@flipstream/sdk/node` entry: sign-in for Node apps, which the main entry never pulls in,
2
- // so a browser bundle has no node:http (#65).
2
+ // so a browser bundle has no node:http (#65), and the session, which holds a refresh token and so
3
+ // belongs on a backend or in a CLI, never in browser code (D452), with a lock for a store several
4
+ // processes share (#114).
3
5
  export { signInWithLoopback } from './loopback.js';
4
6
  export { isHeadless, parsePastedRedirect } from './headless.js';
7
+ export { createSession, SessionError } from './session.js';
8
+ export { fileLock } from './fileLock.js';
9
+ // An app with a server signs in as a confidential client, with its client secret (#123).
10
+ export { finishSignIn } from './clientSecret.js';
5
11
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,8CAA8C;AAC9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAA;AAElD,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,kGAAkG;AAClG,kGAAkG;AAClG,0BAA0B;AAC1B,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAA;AAElD,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAA;AAE/D,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAExC,yFAAyF;AACzF,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA"}
@@ -1,21 +1,34 @@
1
1
  import { type Server } from 'node:http';
2
2
  import { type SignInError, type SignInRequest, type Tokens } from '../auth/signIn.js';
3
3
  import type { AuthCallOptions } from '../auth/transport.js';
4
+ import { type PastedRedirect } from './headless.js';
4
5
  export interface LoopbackSignInOptions extends Omit<SignInRequest, 'redirectUri'>, AuthCallOptions {
5
6
  /**
6
7
  * Shows the person where to sign in: opens their browser, or prints the URL. Called once, when
7
8
  * the port is open. The SDK opens nothing itself and writes nothing to the terminal.
8
9
  */
9
10
  readonly open: (url: string) => void | Promise<void>;
11
+ /**
12
+ * Reads the address the person pastes back when their browser can't reach this machine's port (a
13
+ * remote session), for this same sign-in. Called once, just after `open`; prompting is the app's.
14
+ * Whichever comes first is taken, the port's redirect or the paste, and a paste is checked as
15
+ * `parsePastedRedirect` checks one. `signal` fires once a paste can no longer be taken (the port's
16
+ * redirect came first, or the sign-in ended): stop reading then. A rejection is `paste_failed`.
17
+ */
18
+ readonly readPasted?: (signal: AbortSignal) => Promise<string>;
10
19
  /** The pages the browser shows after the redirect; neutral ones when left out (HTML). */
11
20
  readonly page?: {
12
21
  readonly signedIn: string;
13
22
  readonly failed: string;
14
23
  };
15
- /** How long to wait for the redirect: 5 minutes when left out. */
24
+ /** How long to wait for the redirect, on the port or pasted: 5 minutes when left out. */
16
25
  readonly timeoutMs?: number;
17
26
  }
18
27
  export type LoopbackError = SignInError
28
+ /** The pasted address isn't a URL, or isn't this sign-in's redirect. Nothing was sent. */
29
+ | Extract<PastedRedirect, {
30
+ readonly ok: false;
31
+ }>['error']
19
32
  /** The port couldn't be opened. */
20
33
  | {
21
34
  readonly kind: 'listen_failed';
@@ -25,6 +38,11 @@ export type LoopbackError = SignInError
25
38
  | {
26
39
  readonly kind: 'open_failed';
27
40
  readonly cause: unknown;
41
+ }
42
+ /** `readPasted` rejected before a redirect was taken. */
43
+ | {
44
+ readonly kind: 'paste_failed';
45
+ readonly cause: unknown;
28
46
  };
29
47
  export type LoopbackResult = {
30
48
  readonly ok: true;
@@ -35,10 +53,11 @@ export type LoopbackResult = {
35
53
  };
36
54
  /**
37
55
  * Signs the person in through their browser, with the redirect `http://127.0.0.1:<port>/callback`
38
- * on a port of the system's choosing, bound to 127.0.0.1 only. The redirect is checked as
39
- * `finishSignIn` checks one (its state first), and its code exchanged. The first redirect decides,
40
- * if it comes within `timeoutMs`; the port is closed on every path: signed in, refused,
41
- * `timeout`, `aborted`, or `open_failed`.
56
+ * on a port of the system's choosing, bound to 127.0.0.1 only. The redirect, on the port or pasted
57
+ * (`readPasted`), is checked as `finishSignIn` checks one (its state first), and its code
58
+ * exchanged. The first redirect decides, if it comes within `timeoutMs`, and only its code is ever
59
+ * exchanged; the port is closed on every path: signed in, refused, `timeout`, `aborted`,
60
+ * `open_failed` or `paste_failed`.
42
61
  */
43
62
  export declare function signInWithLoopback(options: LoopbackSignInOptions): Promise<LoopbackResult>;
44
63
  type Listening = {
@@ -1,5 +1,6 @@
1
1
  import { createServer } from 'node:http';
2
2
  import { finishSignIn, startSignIn } from '../auth/signIn.js';
3
+ import { parsePastedRedirect } from './headless.js';
3
4
  const WAIT_MS = 300_000;
4
5
  const PAGE = (heading, text) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${heading}</title></head>` +
5
6
  `<body style="font-family:system-ui,sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem">` +
@@ -7,15 +8,17 @@ const PAGE = (heading, text) => `<!doctype html><html lang="en"><head><meta char
7
8
  // The code is good once, and is then exchanged; still, it leaves the address bar.
8
9
  `<script>try{history.replaceState(null,'',location.pathname)}catch(e){}</script></body></html>`;
9
10
  const PAGES = { signedIn: PAGE('Signed in', 'You can close this tab.'), failed: PAGE('Sign-in failed', 'Return to the app for details.') };
11
+ const asError = (error) => (error instanceof Error ? error : new Error(String(error)));
10
12
  /**
11
13
  * Signs the person in through their browser, with the redirect `http://127.0.0.1:<port>/callback`
12
- * on a port of the system's choosing, bound to 127.0.0.1 only. The redirect is checked as
13
- * `finishSignIn` checks one (its state first), and its code exchanged. The first redirect decides,
14
- * if it comes within `timeoutMs`; the port is closed on every path: signed in, refused,
15
- * `timeout`, `aborted`, or `open_failed`.
14
+ * on a port of the system's choosing, bound to 127.0.0.1 only. The redirect, on the port or pasted
15
+ * (`readPasted`), is checked as `finishSignIn` checks one (its state first), and its code
16
+ * exchanged. The first redirect decides, if it comes within `timeoutMs`, and only its code is ever
17
+ * exchanged; the port is closed on every path: signed in, refused, `timeout`, `aborted`,
18
+ * `open_failed` or `paste_failed`.
16
19
  */
17
20
  export async function signInWithLoopback(options) {
18
- const { signal } = options;
21
+ const { signal, readPasted } = options;
19
22
  // A function, so each look reads the signal as it is now, past the awaits between them.
20
23
  const aborted = () => signal?.aborted === true;
21
24
  if (aborted())
@@ -26,20 +29,53 @@ export async function signInWithLoopback(options) {
26
29
  return { ok: false, error: { kind: 'listen_failed', cause: listening.cause } };
27
30
  const { server, close } = listening;
28
31
  const redirectUri = `http://127.0.0.1:${String(listening.port)}/callback`;
32
+ // The reader's signal: it fires once a paste can no longer be taken.
33
+ const reading = new AbortController();
29
34
  let timer;
30
35
  let onAbort;
31
- const redirect = { taken: false };
32
36
  try {
33
37
  const { url, pending } = await startSignIn({ server: options.server, clientId: options.clientId, scopes: options.scopes, redirectUri });
34
38
  // An abort while the port opened, or the URL was made, fired no event this could still hear.
35
39
  if (aborted())
36
40
  return { ok: false, error: { kind: 'aborted' } };
37
- const settled = new Promise((resolve, reject) => {
41
+ return await new Promise((resolve, reject) => {
42
+ /*
43
+ * One phase, so the sign-in ends once and one code is exchanged (D446). `listening`: no
44
+ * redirect yet; the timeout, a failing opener or reader, or a refused paste ends the wait.
45
+ * `exchanging`: one redirect was taken, and only its exchange or an abort decides now; the
46
+ * port answers anything else with the failure page, and a paste is dropped. `done`: settled.
47
+ */
48
+ let phase = 'listening';
49
+ const settle = (result) => {
50
+ phase = 'done';
51
+ resolve(result);
52
+ };
53
+ const fail = (error) => {
54
+ phase = 'done';
55
+ reject(asError(error));
56
+ };
57
+ const endWait = (error) => {
58
+ if (phase === 'listening')
59
+ settle({ ok: false, error });
60
+ };
61
+ const exchanged = (result) => {
62
+ if (phase === 'exchanging')
63
+ settle(result);
64
+ };
65
+ // Takes the redirect: the one exchange of this sign-in.
66
+ const exchange = (callbackUrl) => {
67
+ phase = 'exchanging';
68
+ // The redirect came in time: the exchange has its own deadline (`finishSignIn`).
69
+ clearTimeout(timer);
70
+ reading.abort();
71
+ return finishSignIn(callbackUrl, pending, { signal, fetch: options.fetch });
72
+ };
38
73
  timer = setTimeout(() => {
39
- resolve({ ok: false, error: { kind: 'timeout' } });
74
+ endWait({ kind: 'timeout' });
40
75
  }, options.timeoutMs ?? WAIT_MS);
41
76
  onAbort = () => {
42
- resolve({ ok: false, error: { kind: 'aborted' } });
77
+ if (phase !== 'done')
78
+ settle({ ok: false, error: { kind: 'aborted' } });
43
79
  };
44
80
  signal?.addEventListener('abort', onAbort, { once: true });
45
81
  server.on('request', (request, response) => {
@@ -47,34 +83,55 @@ export async function signInWithLoopback(options) {
47
83
  // where nothing would catch it.
48
84
  const target = request.url ?? '/';
49
85
  const callbackUrl = URL.canParse(target, redirectUri) ? new URL(target, redirectUri) : null;
50
- if (callbackUrl?.pathname !== '/callback' || redirect.taken) {
86
+ if (callbackUrl?.pathname !== '/callback' || phase !== 'listening') {
51
87
  void send(response, callbackUrl === null ? 400 : 404, pages.failed);
52
88
  return;
53
89
  }
54
- redirect.taken = true;
55
- // The redirect came in time: the exchange has its own deadline (`finishSignIn`).
56
- clearTimeout(timer);
57
- finishSignIn(callbackUrl, pending, { signal, fetch: options.fetch }).then(async (result) => {
90
+ // The page is sent before the sign-in settles, so closing the port can't cut it short.
91
+ exchange(callbackUrl).then(async (result) => {
58
92
  await send(response, result.ok ? 200 : 400, result.ok ? pages.signedIn : pages.failed);
59
- resolve(result);
93
+ exchanged(result);
60
94
  }, async (error) => {
61
95
  await send(response, 500, pages.failed);
62
- reject(error instanceof Error ? error : new Error(String(error)));
96
+ fail(error);
63
97
  });
64
98
  });
99
+ // Neither is awaited: an `open` or a reader that never settles (one waiting on a browser
100
+ // process, or on a person) must not hold back the redirect, the timeout or an abort.
101
+ // `open` is called here, so one that throws at once has ended the wait before the reader
102
+ // would be called: no prompt for a sign-in that already failed.
103
+ let opening = undefined;
104
+ try {
105
+ opening = options.open(url);
106
+ }
107
+ catch (cause) {
108
+ endWait({ kind: 'open_failed', cause });
109
+ }
110
+ Promise.resolve(opening).then(undefined, (cause) => {
111
+ endWait({ kind: 'open_failed', cause });
112
+ });
113
+ if (readPasted !== undefined) {
114
+ Promise.resolve()
115
+ .then(() => (phase === 'listening' ? readPasted(reading.signal) : undefined))
116
+ .then((text) => {
117
+ if (phase !== 'listening')
118
+ return;
119
+ const pasted = parsePastedRedirect(typeof text === 'string' ? text : '', pending);
120
+ if (pasted.ok)
121
+ exchange(pasted.callbackUrl).then(exchanged, fail);
122
+ else
123
+ endWait(pasted.error);
124
+ }, (cause) => {
125
+ endWait({ kind: 'paste_failed', cause });
126
+ });
127
+ }
65
128
  });
66
- // Not awaited on its own: an `open` that never settles (one waiting on a browser process)
67
- // must not hold back the redirect, the timeout or an abort.
68
- // Once a redirect is taken, its exchange decides: an opener failing later loses nothing.
69
- const openFailed = Promise.resolve()
70
- .then(() => options.open(url))
71
- .then(() => new Promise(() => undefined), (cause) => redirect.taken ? new Promise(() => undefined) : Promise.resolve({ ok: false, error: { kind: 'open_failed', cause } }));
72
- return await Promise.race([settled, openFailed]);
73
129
  }
74
130
  finally {
75
131
  clearTimeout(timer);
76
132
  if (onAbort !== undefined)
77
133
  signal?.removeEventListener('abort', onAbort);
134
+ reading.abort();
78
135
  await close();
79
136
  }
80
137
  }
@@ -1 +1 @@
1
- {"version":3,"file":"loopback.js","sourceRoot":"","sources":["../../src/node/loopback.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY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