@bluestep-systems/b6p-core 1.8.1 → 1.9.1

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 (53) hide show
  1. package/README.md +105 -10
  2. package/dist/B6PCore.js +48 -1
  3. package/dist/B6PCore.js.map +1 -1
  4. package/dist/Err.d.ts +56 -3
  5. package/dist/Err.js +65 -1
  6. package/dist/Err.js.map +1 -1
  7. package/dist/auth/BearerAuthProvider.d.ts +43 -13
  8. package/dist/auth/BearerAuthProvider.js +151 -22
  9. package/dist/auth/BearerAuthProvider.js.map +1 -1
  10. package/dist/constants/Gateway.d.ts +84 -1
  11. package/dist/constants/Gateway.js +94 -1
  12. package/dist/constants/Gateway.js.map +1 -1
  13. package/dist/gateway/GatewayClient.d.ts +88 -0
  14. package/dist/gateway/GatewayClient.js +157 -15
  15. package/dist/gateway/GatewayClient.js.map +1 -1
  16. package/dist/gateway/GatewayContext.d.ts +16 -3
  17. package/dist/gateway/GatewayKb.d.ts +2 -2
  18. package/dist/gateway/GatewayKb.js +6 -6
  19. package/dist/gateway/GatewayKb.js.map +1 -1
  20. package/dist/gateway/GatewaySecretRecovery.d.ts +35 -0
  21. package/dist/gateway/GatewaySecretRecovery.js +169 -0
  22. package/dist/gateway/GatewaySecretRecovery.js.map +1 -0
  23. package/dist/gateway/GatewayService.d.ts +8 -1
  24. package/dist/gateway/GatewayService.js +8 -0
  25. package/dist/gateway/GatewayService.js.map +1 -1
  26. package/dist/gateway/GatewaySignIn.d.ts +389 -0
  27. package/dist/gateway/GatewaySignIn.js +877 -0
  28. package/dist/gateway/GatewaySignIn.js.map +1 -0
  29. package/dist/gateway/GatewayToken.d.ts +19 -4
  30. package/dist/gateway/GatewayToken.js +51 -10
  31. package/dist/gateway/GatewayToken.js.map +1 -1
  32. package/dist/gateway/GatewayTokenService.d.ts +2 -2
  33. package/dist/gateway/GatewayTokenService.js +67 -51
  34. package/dist/gateway/GatewayTokenService.js.map +1 -1
  35. package/dist/gitCredential/GitCredentialContext.d.ts +7 -1
  36. package/dist/gitCredential/GitCredentialService.d.ts +8 -0
  37. package/dist/gitCredential/GitCredentialService.js +31 -0
  38. package/dist/gitCredential/GitCredentialService.js.map +1 -1
  39. package/dist/index.d.ts +7 -5
  40. package/dist/index.js +8 -3
  41. package/dist/index.js.map +1 -1
  42. package/dist/persistence/PersistenceKeys.d.ts +6 -1
  43. package/dist/persistence/PersistenceKeys.js +5 -0
  44. package/dist/persistence/PersistenceKeys.js.map +1 -1
  45. package/dist/persistence/SharedFilePersistence.d.ts +5 -0
  46. package/dist/persistence/SharedFilePersistence.js +7 -0
  47. package/dist/persistence/SharedFilePersistence.js.map +1 -1
  48. package/dist/providers.d.ts +73 -3
  49. package/dist/testing/FakeGateway.d.ts +135 -1
  50. package/dist/testing/FakeGateway.js +197 -1
  51. package/dist/testing/FakeGateway.js.map +1 -1
  52. package/dist/types.d.ts +78 -0
  53. package/package.json +2 -2
@@ -0,0 +1,877 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.GatewaySignInService = void 0;
37
+ const os = __importStar(require("node:os"));
38
+ const Gateway_1 = require("../constants/Gateway");
39
+ const Http_1 = require("../constants/Http");
40
+ const Err_1 = require("../Err");
41
+ const GatewayClient_1 = require("./GatewayClient");
42
+ const GatewayToken_1 = require("./GatewayToken");
43
+ const GatewayTokenService_1 = require("./GatewayTokenService");
44
+ const GatewaySecretRecovery_1 = require("./GatewaySecretRecovery");
45
+ const DAY_MS = 24 * 60 * 60 * 1_000;
46
+ /**
47
+ * `b6p auth login`'s core (`core.gateway.signIn`): the gateway's device sign-in, modelled on `gh auth login`, plus
48
+ * sign-out, renewal and an offline status of the ONE stored token.
49
+ *
50
+ * - **Sign-in**: start (`POST /api/v1/device-logins`, no token) → the consumer shows the code and page → poll
51
+ * (`POST /api/v1/device-logins/poll`) at the gateway's interval, slower when it says `slow-down` → the approved
52
+ * answer's token is stored with its record (id, name, account, scopes, expiry, refreshable) → the token it
53
+ * replaced is revoked when a sign-in made it, presenting that token's own `tokens:self`. The gateway fixes the
54
+ * scopes, lifetime and name; b6p asks for nothing. 404 on the start is "this gateway does not offer it"
55
+ * ({@link Err.GatewayDeviceLoginError} `unavailable`).
56
+ * - **The token arrives in the poll's answer, over TLS.** The gateway seals it at rest (X25519 + AES-256-GCM, keyed
57
+ * by the device code it holds only as a hash) and opens it itself on the collecting poll; b6p has no key and
58
+ * nothing to unseal.
59
+ * - **Sign-out** revokes a token a sign-in made (a pasted one only when asked), then forgets it. Offline, it forgets
60
+ * it and says the token stays live.
61
+ * - **Renewal** ({@link renewIfDue}): for a consumer's ordinary commands, never for the MCP header helper (a rotation
62
+ * revokes the old secret at once, which would cut the connection the helper is opening).
63
+ *
64
+ * Never logged and never in a message: the device code, the user code and any token. A token is sent only to the
65
+ * gateway that made it.
66
+ * @lastreviewed null
67
+ */
68
+ class GatewaySignInService {
69
+ client;
70
+ tokens;
71
+ ctx;
72
+ constructor(client, tokens, ctx) {
73
+ this.client = client;
74
+ this.tokens = tokens;
75
+ this.ctx = ctx;
76
+ }
77
+ /**
78
+ * Whether the configured gateway offers device sign-in, from its anonymous sign-in options (`deviceLogin: true`).
79
+ * `false` for a gateway that predates it, has it switched off, or has no sign-in options at all (404).
80
+ *
81
+ * @throws {Err.GatewayError} the gateway could not be asked (network, timeout, a redirect, a 5xx)
82
+ * @lastreviewed null
83
+ */
84
+ async available() {
85
+ const answer = await this.client.anonymous(Http_1.Http.Methods.GET, Gateway_1.Gateway.Paths.AUTH_OPTIONS);
86
+ if (answer.status === 404) {
87
+ return false;
88
+ }
89
+ if (answer.status < 200 || answer.status >= 300) {
90
+ throw refusal(answer, "could not read the gateway's sign-in options");
91
+ }
92
+ return isObject(answer.body) && answer.body.deviceLogin === true;
93
+ }
94
+ /**
95
+ * Sign b6p in through the browser: start a device sign-in, hand the code to `options.onCode`, wait while the
96
+ * person allows it on the gateway's `/device` page, then store the token and revoke the one it replaced (when a
97
+ * sign-in made that one, on this gateway). See {@link GatewaySignInService} for the whole flow.
98
+ *
99
+ * Waiting: polls at the gateway's interval (5 s), plus a little jitter, slower after `slow-down` or a `429`; a
100
+ * gateway that does not answer one poll (offline, 502/503/504) is polled again until the code expires.
101
+ *
102
+ * @throws {Err.GatewayDeviceLoginError} `unavailable` (404: the gateway does not offer it), `denied`, `expired`,
103
+ * `rate-limited` (on the start), `aborted` (`options.signal`)
104
+ * @throws {Err.GatewayUnavailableError} the start went unanswered, or the gateway said `503 unavailable`
105
+ * @throws {Err.GatewayInvalidRequestError} the gateway refused the start or a poll as malformed
106
+ * @throws {Err.GatewayUnexpectedResponseError} an answer the contract does not describe; no token was received
107
+ * @throws {Err.GatewayOffContractTokenError} the approved answer carried a token but was malformed (or the token
108
+ * is not a platform token): the error carries the secret, unstored; it is live until it expires or is revoked
109
+ * @throws {Err.GatewayTokenStoreError} the token was received but could not be stored; the error carries it
110
+ * @throws {Err.GatewayConfigError} the configured gateway URL is unusable
111
+ * @lastreviewed null
112
+ */
113
+ async login(options) {
114
+ if (typeof options?.onCode !== "function") {
115
+ throw new Err_1.Err.GatewayInvalidArgumentError("A sign-in needs an onCode callback to show the code.");
116
+ }
117
+ const sleep = options.sleep ?? sleepFor;
118
+ const { signal } = options;
119
+ // One origin for the whole sign-in: every request goes there, a changed setting is refused, and the record
120
+ // names it.
121
+ // One origin for the whole sign-in: the configured gateway, or the one named in `options.gateway`, pinned as a
122
+ // target (anonymous requests only; the configuration is not touched until the token is stored).
123
+ let configured;
124
+ try {
125
+ configured = await this.client.origin();
126
+ }
127
+ catch (error) {
128
+ if (options.gateway === undefined) {
129
+ throw error;
130
+ }
131
+ configured = null;
132
+ }
133
+ const origin = options.gateway === undefined ? configured : (0, GatewayClient_1.parseGatewayOrigin)(options.gateway);
134
+ const switching = origin !== configured;
135
+ if (switching && this.ctx.gatewaySignIn.setGatewayUrl === undefined) {
136
+ throw new Err_1.Err.GatewayConfigError("This b6p cannot make another gateway the configured one, so it cannot sign in to it; nothing was sent.");
137
+ }
138
+ const pin = switching ? { origin, signal, target: true } : { origin, signal };
139
+ throwIfAborted(signal);
140
+ const body = { client: Gateway_1.Gateway.SignIn.CLIENT, host: hostLabel(options.host ?? os.hostname()) };
141
+ const clientVersion = label(options.clientVersion);
142
+ if (clientVersion !== null) {
143
+ body.clientVersion = clientVersion;
144
+ }
145
+ const platform = label(options.platform ?? process.platform);
146
+ if (platform !== null) {
147
+ body.platform = platform;
148
+ }
149
+ const started = startedFrom(await this.ask(Gateway_1.Gateway.Paths.DEVICE_LOGINS, body, pin), origin);
150
+ // The code's lifetime is measured on a monotonic clock: a wall-clock step neither ends nor stretches it.
151
+ const deadline = monotonic() + started.expiresIn * 1_000;
152
+ await options.onCode({
153
+ userCode: started.userCode,
154
+ verificationUri: started.verificationUri,
155
+ expiresAt: new Date(Date.now() + started.expiresIn * 1_000).toISOString(),
156
+ });
157
+ const what = `${Http_1.Http.Methods.POST} ${Gateway_1.Gateway.Paths.DEVICE_LOGIN_POLL}`;
158
+ let interval = started.interval;
159
+ for (;;) {
160
+ throwIfAborted(signal);
161
+ // Never sooner than the gateway allows; a wait that outlasts the code ends the sign-in here.
162
+ const wait = interval * 1_000 + Math.floor(Math.random() * 250);
163
+ if (wait >= deadline - monotonic()) {
164
+ throw expired();
165
+ }
166
+ await sleep(wait, signal);
167
+ throwIfAborted(signal);
168
+ let answer;
169
+ try {
170
+ answer = await this.ask(Gateway_1.Gateway.Paths.DEVICE_LOGIN_POLL, { deviceCode: started.deviceCode }, pin);
171
+ }
172
+ catch (error) {
173
+ // One unanswered poll is not the end: the code is still good until it expires.
174
+ if (error instanceof Err_1.Err.GatewayUnavailableError) {
175
+ continue;
176
+ }
177
+ throw error;
178
+ }
179
+ const answered = isObject(answer.body) ? answer.body : undefined;
180
+ // A token in any answer is a minted secret: it is stored, or handed back in the error, never dropped.
181
+ if (answered !== undefined && typeof answered.token === "string" && answered.token.length > 0) {
182
+ if (answer.status === 200 && (answered.status === "approved" || answered.status === undefined)) {
183
+ return this.collect(answered, origin, switching ? configured : undefined, what, signal);
184
+ }
185
+ throw (0, GatewaySecretRecovery_1.keepUnstored)(this.ctx, new Err_1.Err.GatewayOffContractTokenError(`${what}: an answer that is not an approval (${answer.status}) carried a token; it was not stored. It stays live until it expires or is revoked on My Account.`, "login", answered.token, false));
186
+ }
187
+ if (answer.status === 200 && answered !== undefined) {
188
+ const next = intervalOf(answered.interval);
189
+ if (answered.status === "pending") {
190
+ interval = Math.max(interval, next ?? interval);
191
+ continue;
192
+ }
193
+ if (answered.status === "slow-down") {
194
+ interval = next !== null && next > interval ? next : interval + 5;
195
+ continue;
196
+ }
197
+ if (answered.status === "approved") {
198
+ throw new Err_1.Err.GatewayUnexpectedResponseError(`${what}: the gateway said the sign-in was approved but sent no token; sign in again.`, 200, null);
199
+ }
200
+ }
201
+ const code = knownCode(answer.code);
202
+ if (answer.status === 403 && code === "login-denied") {
203
+ throw new Err_1.Err.GatewayDeviceLoginError(`${what}: the sign-in was denied in the browser (403 login-denied).`, "denied", 403);
204
+ }
205
+ if (answer.status === 410) {
206
+ throw expired(410);
207
+ }
208
+ if (answer.status === 404) {
209
+ throw new Err_1.Err.GatewayDeviceLoginError(`${what}: the gateway stopped offering device sign-in while it waited (404).`, "unavailable", 404);
210
+ }
211
+ if (answer.status === 429) {
212
+ interval = Math.max(interval + 5, answer.retryAfterSeconds ?? 0);
213
+ continue;
214
+ }
215
+ if (answer.status === 502 || answer.status === 503 || answer.status === 504) {
216
+ continue;
217
+ }
218
+ throw refusal(answer, "the poll's answer is not one the contract describes");
219
+ }
220
+ }
221
+ /**
222
+ * Sign out: revoke the stored token when a device sign-in made it (a pasted one only with `revokePasted`), then
223
+ * forget it. The revoke presents the token itself (its own `tokens:self`), and only to the gateway that made it;
224
+ * whatever the gateway says, or when it cannot be reached, the token is forgotten and the result says whether it
225
+ * was revoked and why not. Runs under the sign-in lock (one login, renewal or sign-out at a time), on one gateway
226
+ * origin throughout.
227
+ *
228
+ * @throws {Err.GatewayConfigError} the configured gateway URL is unusable, or changed during the sign-out (nothing
229
+ * was sent to the new one, and nothing was forgotten)
230
+ * @lastreviewed null
231
+ */
232
+ async logout(options = {}) {
233
+ const origin = await this.client.origin();
234
+ return this.ctx.gatewaySignIn.exclusive(async () => {
235
+ const stored = await this.ctx.gatewaySignIn.read();
236
+ if (stored === undefined) {
237
+ return {
238
+ wasSignedIn: false,
239
+ method: null,
240
+ alias: null,
241
+ account: null,
242
+ revoked: false,
243
+ problem: null,
244
+ forgotten: true,
245
+ };
246
+ }
247
+ let problem;
248
+ if (stored.signIn === null && options.revokePasted !== true) {
249
+ problem = "pasted";
250
+ }
251
+ else if (stored.signIn !== null && stored.signIn.gateway !== origin) {
252
+ problem = "other-gateway";
253
+ }
254
+ else {
255
+ problem = await this.revokeWith(stored.token, stored.signIn?.tokenId ?? null, { origin });
256
+ }
257
+ const forgotten = await this.ctx.gatewaySignIn.forget(stored.token);
258
+ return {
259
+ wasSignedIn: true,
260
+ method: stored.signIn === null ? "pasted" : "login",
261
+ alias: stored.signIn?.alias ?? null,
262
+ account: stored.signIn?.account ?? null,
263
+ revoked: problem === null,
264
+ problem,
265
+ forgotten,
266
+ };
267
+ });
268
+ }
269
+ /**
270
+ * Renew the stored token when a device sign-in made it, it is refreshable, and 30 days or fewer are left: rotate
271
+ * it (`core.gateway.tokens.rotate`) to 90 days from now, and store the replacement with its record. At most one
272
+ * attempt a day on one computer, and one login, renewal or sign-out at a time (the sign-in lock, shared by every
273
+ * b6p process that can share it); the state is read again inside the lock, and the rotation presents exactly the
274
+ * token read there and refuses unsent if the store has changed, so a token another b6p just stored is never
275
+ * rotated in its place.
276
+ *
277
+ * For a consumer's ordinary commands, before their first gateway request. Never call it from an MCP header
278
+ * helper: a rotation revokes the old secret at once.
279
+ *
280
+ * Never throws for the gateway's answer or the lock: a failure is `reason: "failed"` with the `error`, so it never
281
+ * fails the command it runs before. A replacement that was received but not stored is in that error
282
+ * ({@link Err.GatewayTokenStoreError}).
283
+ *
284
+ * @param options.force renew now whatever is left, and whatever the day's attempt (`b6p auth refresh`)
285
+ * @param options.now the time to judge by (ms since the epoch); defaults to now
286
+ * @lastreviewed null
287
+ */
288
+ async renewIfDue(options = {}) {
289
+ const force = options.force === true;
290
+ const now = options.now ?? Date.now();
291
+ let origin;
292
+ try {
293
+ origin = await this.client.origin();
294
+ }
295
+ catch (error) {
296
+ return failed(error, null);
297
+ }
298
+ const first = renewVerdict(await this.ctx.gatewaySignIn.read(), origin, now, force);
299
+ if (first !== null) {
300
+ return first;
301
+ }
302
+ try {
303
+ return await this.ctx.gatewaySignIn.exclusive(async () => {
304
+ // Again, inside the lock: another process may have renewed, signed in or signed out meanwhile.
305
+ const stored = await this.ctx.gatewaySignIn.read();
306
+ const verdict = renewVerdict(stored, origin, now, force);
307
+ if (verdict !== null) {
308
+ return verdict;
309
+ }
310
+ const current = stored;
311
+ const signIn = current.signIn;
312
+ if (!force) {
313
+ const last = Date.parse((await this.ctx.gatewaySignIn.lastRenewAttempt()) ?? "");
314
+ if (!Number.isNaN(last) && now - last >= 0 && now - last < Gateway_1.Gateway.SignIn.RENEW_ATTEMPT_INTERVAL_MS) {
315
+ return { renewed: false, reason: "checked-recently", expiresAt: signIn.expiresAt, error: null };
316
+ }
317
+ }
318
+ await this.ctx.gatewaySignIn.recordRenewAttempt(new Date(now).toISOString());
319
+ try {
320
+ const rotated = await this.tokens.rotate(signIn.tokenId ?? signIn.alias, {
321
+ days: Gateway_1.Gateway.SignIn.RENEW_DAYS,
322
+ expectedToken: current.token,
323
+ origin,
324
+ });
325
+ if (!rotated.rotatedCurrent) {
326
+ // Not reachable while `expectedToken` refuses another target; if it ever is, the secret is kept.
327
+ return failed((0, GatewaySecretRecovery_1.keepUnstored)(this.ctx, new Err_1.Err.GatewayTokenStoreError("A token other than the stored one was rotated; its replacement is here, unstored.", rotated.token)), signIn.expiresAt);
328
+ }
329
+ this.ctx.logger.info((0, GatewayToken_1.redactTokenShapes)(`Renewed the signed-in gateway token "${signIn.alias}".`, current.token));
330
+ return { renewed: true, reason: "renewed", expiresAt: rotated.token.expiresAt, error: null };
331
+ }
332
+ catch (error) {
333
+ return failed(error, signIn.expiresAt);
334
+ }
335
+ });
336
+ }
337
+ catch (error) {
338
+ // The lock could not be had (another b6p holds it too long) or its state could not be read.
339
+ return failed(error, null);
340
+ }
341
+ }
342
+ /**
343
+ * The stored sign-in, described from what b6p stored: offline, instant, never the secret. `b6p auth status`.
344
+ * @lastreviewed null
345
+ */
346
+ async status(options = {}) {
347
+ const now = options.now ?? Date.now();
348
+ let gateway;
349
+ try {
350
+ gateway = await this.client.origin();
351
+ }
352
+ catch {
353
+ gateway = null;
354
+ }
355
+ const stored = await this.ctx.gatewaySignIn.read();
356
+ const signIn = stored?.signIn ?? null;
357
+ const expiresAt = signIn?.expiresAt ?? null;
358
+ const expiresMs = expiresAt === null ? NaN : Date.parse(expiresAt);
359
+ const known = signIn !== null && !Number.isNaN(expiresMs);
360
+ const expired = known ? expiresMs <= now : null;
361
+ return {
362
+ signedIn: stored !== undefined,
363
+ method: stored === undefined ? null : signIn === null ? "pasted" : "login",
364
+ tokenPrefix: stored === undefined ? null : (0, GatewayToken_1.gatewayTokenPrefixOf)(stored.token),
365
+ gateway,
366
+ signedInGateway: signIn?.gateway ?? null,
367
+ onConfiguredGateway: signIn === null ? null : signIn.gateway === gateway,
368
+ alias: signIn?.alias ?? null,
369
+ tokenId: signIn?.tokenId ?? null,
370
+ account: signIn?.account ?? null,
371
+ scopes: signIn === null ? null : [...signIn.scopes],
372
+ expiresAt,
373
+ refreshable: signIn?.refreshable ?? null,
374
+ daysLeft: known ? Math.floor((expiresMs - now) / DAY_MS) : null,
375
+ expired,
376
+ renewDue: known
377
+ ? signIn.refreshable && !expired && expiresMs - now <= Gateway_1.Gateway.SignIn.RENEW_WITHIN_DAYS * DAY_MS
378
+ : null,
379
+ };
380
+ }
381
+ /**
382
+ * One anonymous request of a sign-in: on the pinned origin, stopped by its signal (as `aborted`).
383
+ * @lastreviewed null
384
+ */
385
+ async ask(path, body, pin) {
386
+ try {
387
+ return await this.client.anonymous(Http_1.Http.Methods.POST, path, body, pin);
388
+ }
389
+ catch (error) {
390
+ if (error instanceof Err_1.Err.GatewayAbortedError) {
391
+ throw new Err_1.Err.GatewayDeviceLoginError("The sign-in was stopped while b6p was asking the gateway. If it had just been allowed, its token was never received: it is listed on My Account, where it can be revoked.", "aborted", null);
392
+ }
393
+ throw error;
394
+ }
395
+ }
396
+ /**
397
+ * An approval's token: stored and the replaced token retired; or, when the caller stopped the sign-in while the
398
+ * approval was on its way, stored without retiring anything, and the stop reported plainly.
399
+ * @lastreviewed null
400
+ */
401
+ async collect(body, origin, switchedFrom, what, signal) {
402
+ if (!signal?.aborted) {
403
+ return this.finish(body, origin, switchedFrom, what, true);
404
+ }
405
+ const result = await this.finish(body, origin, switchedFrom, what, false);
406
+ const replaced = result.replaced === null
407
+ ? ""
408
+ : result.replaced.alias === null
409
+ ? " The token it replaced (pasted) was not revoked."
410
+ : ` The token it replaced, "${result.replaced.alias}", was not revoked: it stays live until it expires or is revoked on My Account.`;
411
+ throw new Err_1.Err.GatewayDeviceLoginError((0, GatewayToken_1.redactTokenShapes)(`The sign-in was allowed just as it was stopped. Its token "${result.alias}" was stored, so b6p is signed in.${replaced}`), "aborted", null, null, true);
412
+ }
413
+ /**
414
+ * Store the approved answer's token with its record and, when `retire`, revoke the token it replaced; under the
415
+ * sign-in lock. Every received token is stored, or handed back in the error.
416
+ * @lastreviewed null
417
+ */
418
+ async finish(body, origin, switchedFrom, what, retire) {
419
+ const token = body.token;
420
+ const problem = (0, GatewayToken_1.gatewayTokenProblem)(token);
421
+ // Every piece of metadata is shown, logged or stored beside the token: none may carry a secret.
422
+ const tokenId = typeof body.tokenId === "string" &&
423
+ TOKEN_ID.test(body.tokenId) &&
424
+ !(0, GatewayToken_1.containsTokenShape)(body.tokenId) &&
425
+ !body.tokenId.includes(token)
426
+ ? body.tokenId
427
+ : null;
428
+ const alias = aliasOf(body.alias);
429
+ const account = accountOf(body.account);
430
+ const expiresAt = body.expiresAt;
431
+ if (problem !== null ||
432
+ tokenId === null ||
433
+ alias === null ||
434
+ !isStringArray(body.scopes) ||
435
+ !body.scopes.every((scope) => SCOPE.test(scope) && Gateway_1.Gateway.Scopes.KNOWN.includes(scope)) ||
436
+ !(expiresAt === null || (typeof expiresAt === "string" && !Number.isNaN(Date.parse(expiresAt)))) ||
437
+ typeof body.refreshable !== "boolean" ||
438
+ account === undefined) {
439
+ const why = problem === null ? "the rest of the answer was malformed" : `the token is not usable (${problem})`;
440
+ throw (0, GatewaySecretRecovery_1.keepUnstored)(this.ctx, new Err_1.Err.GatewayOffContractTokenError(`${what}: the sign-in was approved and a token was sent, but ${why}; it was not stored. It stays live until it expires or is revoked on My Account.`, "login", token, false));
441
+ }
442
+ const record = {
443
+ gateway: origin,
444
+ tokenId,
445
+ alias,
446
+ account,
447
+ scopes: [...body.scopes],
448
+ expiresAt,
449
+ refreshable: body.refreshable,
450
+ storedAt: new Date().toISOString(),
451
+ };
452
+ const minted = {
453
+ id: tokenId,
454
+ token,
455
+ alias,
456
+ scopes: [...record.scopes],
457
+ expiresAt,
458
+ refreshable: record.refreshable,
459
+ neverExpires: expiresAt === null,
460
+ };
461
+ let stored = false;
462
+ try {
463
+ return await this.ctx.gatewaySignIn.exclusive(async () => {
464
+ // The store, and for a sign-in to another gateway the switch of the configured one, finish once begun: a
465
+ // signal waits until both are written. The token goes first: until the switch lands, the configured
466
+ // gateway gets nothing (a token is sent only to the gateway that made it), so no request ever carries the
467
+ // old token to the new gateway or the new token to the old one.
468
+ const previous = await (0, GatewaySecretRecovery_1.deferSignals)(async () => {
469
+ const before = await this.ctx.gatewaySignIn.store(token, record);
470
+ stored = true;
471
+ if (switchedFrom !== undefined) {
472
+ const setGatewayUrl = this.ctx.gatewaySignIn.setGatewayUrl;
473
+ try {
474
+ if (setGatewayUrl === undefined) {
475
+ throw new Error("this store cannot set the configured gateway");
476
+ }
477
+ await setGatewayUrl.call(this.ctx.gatewaySignIn, origin);
478
+ }
479
+ catch (error) {
480
+ const why = (0, GatewayToken_1.redactTokenShapes)(error instanceof Error ? error.message : String(error), token);
481
+ throw new Err_1.Err.GatewayConfigError(`Signed in and stored the token "${alias}", but the new gateway could not be made the configured one (${why}). Until it is, b6p sends that token nowhere: set gatewayUrl to the gateway you signed in to.`);
482
+ }
483
+ }
484
+ return before;
485
+ });
486
+ this.ctx.logger.info((0, GatewayToken_1.redactTokenShapes)(`Signed in to the gateway; stored the token "${alias}".`, token));
487
+ let replaced = null;
488
+ if (previous !== undefined && previous.token !== token) {
489
+ replaced = retire
490
+ ? await this.retire(previous, origin)
491
+ : {
492
+ method: previous.signIn === null ? "pasted" : "login",
493
+ alias: previous.signIn?.alias ?? null,
494
+ tokenId: previous.signIn?.tokenId ?? null,
495
+ account: previous.signIn?.account ?? null,
496
+ revoked: false,
497
+ problem: "failed",
498
+ };
499
+ }
500
+ return {
501
+ gateway: origin,
502
+ account,
503
+ alias,
504
+ tokenId,
505
+ scopes: [...record.scopes],
506
+ expiresAt,
507
+ refreshable: record.refreshable,
508
+ replaced,
509
+ gatewayChanged: switchedFrom === undefined ? null : { from: switchedFrom, to: origin },
510
+ };
511
+ });
512
+ }
513
+ catch (error) {
514
+ if (stored) {
515
+ throw error;
516
+ }
517
+ const why = (0, GatewayToken_1.redactTokenShapes)(error instanceof Error ? error.message : String(error), token);
518
+ throw (0, GatewaySecretRecovery_1.keepUnstored)(this.ctx, new Err_1.Err.GatewayTokenStoreError((0, GatewayToken_1.redactTokenShapes)(`Signed in as "${alias}", but the token could not be stored: ${why}`, token), minted));
519
+ }
520
+ }
521
+ /**
522
+ * Revoke the token a new sign-in replaced, when a sign-in on this gateway made it; never a pasted one.
523
+ * @lastreviewed null
524
+ */
525
+ async retire(previous, origin) {
526
+ const signIn = previous.signIn;
527
+ const described = {
528
+ method: signIn === null ? "pasted" : "login",
529
+ alias: signIn?.alias ?? null,
530
+ tokenId: signIn?.tokenId ?? null,
531
+ account: signIn?.account ?? null,
532
+ };
533
+ let problem;
534
+ if (signIn === null) {
535
+ problem = "pasted";
536
+ }
537
+ else if (signIn.gateway !== origin) {
538
+ problem = "other-gateway";
539
+ }
540
+ else {
541
+ try {
542
+ problem = await this.revokeWith(previous.token, signIn.tokenId, { origin });
543
+ }
544
+ catch {
545
+ // The setting changed after the new token was stored: nothing was sent anywhere else.
546
+ problem = "failed";
547
+ }
548
+ }
549
+ return { ...described, revoked: problem === null, problem };
550
+ }
551
+ /**
552
+ * Revoke `token` at the pinned origin, presenting `token` itself: by `tokenId`, or, when that is not known, the
553
+ * list's `current` entry. `null` when revoked, else why not. Never throws for the gateway's answer.
554
+ *
555
+ * @throws {Err.GatewayConfigError} the configured gateway is no longer the pinned origin; nothing was sent
556
+ * @lastreviewed null
557
+ */
558
+ async revokeWith(token, tokenId, pin) {
559
+ try {
560
+ await this.client.sequenceAs(token, async (seq) => {
561
+ let id = tokenId;
562
+ if (id === null) {
563
+ const own = (await (0, GatewayTokenService_1.listVia)(seq.request)).find((entry) => entry.current);
564
+ if (own === undefined) {
565
+ throw new Err_1.Err.GatewayNotFoundError("The token is not in its own list.", "not-found");
566
+ }
567
+ id = own.id;
568
+ }
569
+ await seq.request(Http_1.Http.Methods.DELETE, `${Gateway_1.Gateway.Paths.TOKENS}/${encodeURIComponent(id)}`);
570
+ }, pin);
571
+ return null;
572
+ }
573
+ catch (error) {
574
+ if (error instanceof Err_1.Err.GatewayConfigError) {
575
+ throw error;
576
+ }
577
+ if (error instanceof Err_1.Err.GatewayUnavailableError) {
578
+ return "unreachable";
579
+ }
580
+ if ((error instanceof Err_1.Err.GatewayAuthError && error.reason === "token-invalid") ||
581
+ error instanceof Err_1.Err.GatewayNotFoundError) {
582
+ return "already-gone";
583
+ }
584
+ if (error instanceof Err_1.Err.GatewayScopeError) {
585
+ return "scope-missing";
586
+ }
587
+ return "failed";
588
+ }
589
+ }
590
+ }
591
+ exports.GatewaySignInService = GatewaySignInService;
592
+ /**
593
+ * The longest poll interval b6p reads from the gateway, in seconds; a longer one (or a wait past the code's
594
+ * lifetime) ends the sign-in as expired rather than being shortened.
595
+ * @lastreviewed null
596
+ */
597
+ const MAX_INTERVAL_S = 86_400;
598
+ /**
599
+ * Milliseconds on a monotonic clock, for the code's lifetime and the waits: a wall-clock step changes nothing.
600
+ * @lastreviewed null
601
+ */
602
+ function monotonic() {
603
+ return performance.now();
604
+ }
605
+ /**
606
+ * The error codes the device sign-in routes answer (the route contract). Only these reach a message or an error's
607
+ * `code`; anything else in the body's `error` is not passed on.
608
+ * @lastreviewed null
609
+ */
610
+ const KNOWN_CODES = new Set([
611
+ "invalid-request",
612
+ "rate-limited",
613
+ "unavailable",
614
+ "login-denied",
615
+ "login-expired",
616
+ "not-found",
617
+ "too-large",
618
+ ]);
619
+ function knownCode(code) {
620
+ return code !== null && KNOWN_CODES.has(code) ? code : null;
621
+ }
622
+ /**
623
+ * A token id as the gateway sends it (a UUID; the fake's `tok_<n>`).
624
+ * @lastreviewed null
625
+ */
626
+ const TOKEN_ID = /^[A-Za-z0-9._:-]{1,128}$/;
627
+ /**
628
+ * A scope's wire name.
629
+ * @lastreviewed null
630
+ */
631
+ const SCOPE = /^[a-z][a-z0-9:_-]{0,63}$/;
632
+ /**
633
+ * The token's name as the gateway makes it: `b6p on <host> <yyyy-MM-dd HH:mm>`.
634
+ * @lastreviewed null
635
+ */
636
+ const ALIAS = /^b6p on \S(?:.*\S)? \d{4}-\d{2}-\d{2} \d{2}:\d{2}$/;
637
+ /**
638
+ * The approved answer's alias when it is the contract's shape (at most 64 code points, printable, no token
639
+ * prefix), else `null`: it is logged and shown, so nothing else is taken.
640
+ * @lastreviewed null
641
+ */
642
+ function aliasOf(value) {
643
+ return typeof value === "string" &&
644
+ [...value].length <= 64 &&
645
+ ALIAS.test(value) &&
646
+ !new RegExp(UNPRINTABLE.source).test(value) &&
647
+ !(0, GatewayToken_1.containsTokenShape)(value)
648
+ ? value
649
+ : null;
650
+ }
651
+ /**
652
+ * Server text b6p stores and shows (an account's name and login): printable, at most 256 code points, no token
653
+ * prefix.
654
+ * @lastreviewed null
655
+ */
656
+ function isShownText(value) {
657
+ return (typeof value === "string" &&
658
+ value.length > 0 &&
659
+ [...value].length <= 256 &&
660
+ !new RegExp(UNPRINTABLE.source).test(value) &&
661
+ !(0, GatewayToken_1.containsTokenShape)(value));
662
+ }
663
+ /**
664
+ * The start's answer, checked, or the error it amounts to.
665
+ * @lastreviewed null
666
+ */
667
+ function startedFrom(answer, origin) {
668
+ const { status, what } = answer;
669
+ if (status === 404) {
670
+ throw new Err_1.Err.GatewayDeviceLoginError(`${what}: this gateway does not offer device sign-in (404). It is switched off there, or the gateway predates it.`, "unavailable", 404);
671
+ }
672
+ if (status === 429) {
673
+ const wait = answer.retryAfterSeconds === null ? "" : ` Try again in ${answer.retryAfterSeconds} seconds.`;
674
+ throw new Err_1.Err.GatewayDeviceLoginError(`${what}: too many sign-ins were started from this network (429 rate-limited).${wait}`, "rate-limited", 429, answer.retryAfterSeconds);
675
+ }
676
+ if (status !== 200 && status !== 201) {
677
+ throw refusal(answer, "the gateway did not start the sign-in");
678
+ }
679
+ const body = answer.body;
680
+ if (!isObject(body)) {
681
+ throw unexpectedStart(answer);
682
+ }
683
+ const { deviceCode, userCode, verificationUri } = body;
684
+ const expiresIn = body.expiresIn;
685
+ if (typeof deviceCode !== "string" ||
686
+ !/^[\x21-\x7e]{16,512}$/.test(deviceCode) ||
687
+ typeof userCode !== "string" ||
688
+ !/^[\x20-\x7e]{1,32}$/.test(userCode) ||
689
+ typeof verificationUri !== "string" ||
690
+ !isDevicePage(verificationUri, origin) ||
691
+ typeof expiresIn !== "number" ||
692
+ !Number.isInteger(expiresIn) ||
693
+ expiresIn < 1 ||
694
+ expiresIn > 3_600) {
695
+ throw unexpectedStart(answer);
696
+ }
697
+ return { deviceCode, userCode, verificationUri, expiresIn, interval: intervalOf(body.interval) ?? 5 };
698
+ }
699
+ function unexpectedStart(answer) {
700
+ return new Err_1.Err.GatewayUnexpectedResponseError(`${answer.what}: the gateway's answer is not the started sign-in the contract describes; nothing was started on this side.`, answer.status, knownCode(answer.code));
701
+ }
702
+ /**
703
+ * The typed error for an answer nothing above explains. The server's message is never quoted (a poll's body is
704
+ * the device code's business).
705
+ * @lastreviewed null
706
+ */
707
+ function refusal(answer, happened) {
708
+ const code = knownCode(answer.code);
709
+ const tag = code === null ? `${answer.status}` : `${answer.status} ${code}`;
710
+ const message = `${answer.what}: ${happened} (${tag}).`;
711
+ if (answer.status === 400) {
712
+ return new Err_1.Err.GatewayInvalidRequestError(message, code);
713
+ }
714
+ if (answer.status === 502 || answer.status === 503 || answer.status === 504) {
715
+ return new Err_1.Err.GatewayUnavailableError(message, answer.status, code);
716
+ }
717
+ return new Err_1.Err.GatewayUnexpectedResponseError(message, answer.status, code);
718
+ }
719
+ function expired(status = null) {
720
+ return new Err_1.Err.GatewayDeviceLoginError("The sign-in code expired before it was allowed in the browser.", "expired", status);
721
+ }
722
+ function throwIfAborted(signal) {
723
+ if (signal?.aborted) {
724
+ throw new Err_1.Err.GatewayDeviceLoginError("The sign-in was stopped before it was allowed; its code expires at the gateway.", "aborted", null);
725
+ }
726
+ }
727
+ /**
728
+ * The default wait between polls: a timer, ended early by `signal`. Not unref'd: it is what keeps the process
729
+ * waiting for the browser.
730
+ * @lastreviewed null
731
+ */
732
+ function sleepFor(ms, signal) {
733
+ return new Promise((resolve) => {
734
+ if (signal?.aborted) {
735
+ resolve();
736
+ return;
737
+ }
738
+ const done = () => {
739
+ clearTimeout(timer);
740
+ signal?.removeEventListener("abort", done);
741
+ resolve();
742
+ };
743
+ const timer = setTimeout(done, ms);
744
+ signal?.addEventListener("abort", done, { once: true });
745
+ });
746
+ }
747
+ /**
748
+ * The verdict of a renewal before anything is sent, or `null` when one is due (or forced) and may be tried.
749
+ * @lastreviewed null
750
+ */
751
+ function renewVerdict(stored, origin, now, force) {
752
+ const no = (reason, expiresAt = null) => ({
753
+ renewed: false,
754
+ reason,
755
+ expiresAt,
756
+ error: null,
757
+ });
758
+ if (stored === undefined) {
759
+ return no("not-signed-in");
760
+ }
761
+ const signIn = stored.signIn;
762
+ if (signIn === null) {
763
+ return no("pasted");
764
+ }
765
+ if (signIn.expiresAt === null) {
766
+ return no("never-expires");
767
+ }
768
+ if (!signIn.refreshable) {
769
+ return no("not-refreshable", signIn.expiresAt);
770
+ }
771
+ if (signIn.gateway !== origin) {
772
+ return no("other-gateway", signIn.expiresAt);
773
+ }
774
+ const left = Date.parse(signIn.expiresAt) - now;
775
+ if (left <= 0) {
776
+ return no("expired", signIn.expiresAt);
777
+ }
778
+ if (!force && left > Gateway_1.Gateway.SignIn.RENEW_WITHIN_DAYS * DAY_MS) {
779
+ return no("not-due", signIn.expiresAt);
780
+ }
781
+ return null;
782
+ }
783
+ function failed(error, expiresAt) {
784
+ return {
785
+ renewed: false,
786
+ reason: "failed",
787
+ expiresAt,
788
+ error: error instanceof Error ? error : new Error(String(error)),
789
+ };
790
+ }
791
+ /**
792
+ * Characters never sent in a label: controls (C0, C1, line and paragraph separators) and direction overrides,
793
+ * isolates and marks, which the gateway refuses (they could make a name on the confirm page read as something else).
794
+ * @lastreviewed null
795
+ */
796
+ // Built from a string of escapes: a regular expression literal holding U+2028 is emitted with the raw character,
797
+ // which ends the line and breaks the compiled file.
798
+ const UNPRINTABLE = new RegExp("[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029\\u202a-\\u202e\\u2066-\\u2069\\u200e\\u200f\\u061c\\ufeff]", "g");
799
+ /**
800
+ * The computer's name as the gateway takes it: unprintable characters dropped, trimmed, cut to 40 code points;
801
+ * `computer` when nothing is left.
802
+ * @lastreviewed null
803
+ */
804
+ function hostLabel(raw) {
805
+ const cleaned = [...String(raw).replace(UNPRINTABLE, "").trim()].slice(0, Gateway_1.Gateway.SignIn.MAX_HOST).join("").trim();
806
+ return cleaned.length > 0 ? cleaned : "computer";
807
+ }
808
+ /**
809
+ * An optional label (`clientVersion`, `platform`): trimmed, at most 32 code points and printable, else `null` (left
810
+ * out rather than refused).
811
+ * @lastreviewed null
812
+ */
813
+ function label(raw) {
814
+ if (typeof raw !== "string") {
815
+ return null;
816
+ }
817
+ const value = raw.trim();
818
+ if (value.length === 0 ||
819
+ [...value].length > Gateway_1.Gateway.SignIn.MAX_LABEL ||
820
+ new RegExp(UNPRINTABLE.source).test(value)) {
821
+ return null;
822
+ }
823
+ return value;
824
+ }
825
+ /**
826
+ * A poll interval the gateway sent, in whole seconds from 1 to 60, else `null`.
827
+ * @lastreviewed null
828
+ */
829
+ function intervalOf(value) {
830
+ return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= MAX_INTERVAL_S ? value : null;
831
+ }
832
+ /**
833
+ * The page a code is typed on, as the contract fixes it: exactly `<the pinned gateway's origin>/device` (https, or http
834
+ * only for a loopback gateway, which the origin's own rules allow), with no credentials, query or fragment. Anything
835
+ * else (another host, a path or query carrying the code) is an off-contract start, and the value is never shown.
836
+ * @lastreviewed null
837
+ */
838
+ function isDevicePage(value, origin) {
839
+ let url;
840
+ try {
841
+ url = new URL(value);
842
+ }
843
+ catch {
844
+ return false;
845
+ }
846
+ return (url.origin === origin &&
847
+ (url.protocol === "https:" || url.protocol === "http:") &&
848
+ url.username === "" &&
849
+ url.password === "" &&
850
+ url.pathname === "/device" &&
851
+ url.search === "" &&
852
+ url.hash === "" &&
853
+ !value.includes("?") &&
854
+ !value.includes("#") &&
855
+ value === `${origin}/device`);
856
+ }
857
+ /**
858
+ * The approved answer's `account`: the account, `null` when absent or null (an older gateway replica), or
859
+ * `undefined` when it is there and malformed.
860
+ * @lastreviewed null
861
+ */
862
+ function accountOf(value) {
863
+ if (value === undefined || value === null) {
864
+ return null;
865
+ }
866
+ if (isObject(value) && isShownText(value.name) && isShownText(value.login)) {
867
+ return { name: value.name, login: value.login };
868
+ }
869
+ return undefined;
870
+ }
871
+ function isObject(value) {
872
+ return typeof value === "object" && value !== null && !Array.isArray(value);
873
+ }
874
+ function isStringArray(value) {
875
+ return Array.isArray(value) && value.every((v) => typeof v === "string");
876
+ }
877
+ //# sourceMappingURL=GatewaySignIn.js.map