aegiscode 7.0.10 → 7.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/aegiscode.js +29 -0
- package/package.json +1 -1
- package/src/app.js +335 -24
- package/src/autonomous.js +19 -2
- package/src/chatflow.js +77 -4
- package/src/commands.js +175 -5
- package/src/config.js +21 -0
- package/src/connect.js +351 -0
- package/src/deps.js +97 -1
- package/src/engine.js +98 -8
- package/src/fingerprint.js +46 -16
- package/src/limits.js +1 -1
- package/src/overlays.js +54 -0
- package/src/provenance.lock.json +3 -3
- package/src/screens.js +14 -1
- package/vendor/client/credentials.js +9 -2
- package/vendor/client/google-signin.js +127 -0
- package/vendor/client/record-vault.js +431 -113
- package/vendor/client/update.js +266 -0
- package/vendor/desktop/lib/local/claude-pro.js +134 -11
- package/vendor/desktop/lib/local/engine.js +47 -25
- package/vendor/desktop/lib/settings.js +65 -24
package/src/fingerprint.js
CHANGED
|
@@ -140,8 +140,19 @@ Key:
|
|
|
140
140
|
Vault:
|
|
141
141
|
publish copies the SEALED BYTES to the vault, byte-identical, and
|
|
142
142
|
writes the link (<record>.anchor.json) beside the local
|
|
143
|
-
copy.
|
|
144
|
-
|
|
143
|
+
copy.
|
|
144
|
+
|
|
145
|
+
DEFAULT BACKEND: aegiscloud — the account this machine
|
|
146
|
+
already registered for (the same device key every other
|
|
147
|
+
cloud feature uses, so publishing needs no second
|
|
148
|
+
sign-in). Nothing to configure; if there is no key yet,
|
|
149
|
+
'aegiscode login' gives you one.
|
|
150
|
+
|
|
151
|
+
--backend rclone puts the copy somewhere YOU own instead:
|
|
152
|
+
--remote <name> --root <folder> (AEGIS_VAULT_REMOTE /
|
|
153
|
+
AEGIS_VAULT_ROOT), e.g. --remote gdrive --root
|
|
154
|
+
AEGIS-AGPL. That needs an rclone remote already
|
|
155
|
+
configured; the account vault does not.
|
|
145
156
|
anchor re-downloads the published copy and checks three separate
|
|
146
157
|
things: present, unchanged (sha256), still attested.
|
|
147
158
|
vault --audit inspects every object already in the vault for key
|
|
@@ -370,7 +381,7 @@ function newestRecord(dataDir) {
|
|
|
370
381
|
return files.length ? files[0].f : null;
|
|
371
382
|
}
|
|
372
383
|
|
|
373
|
-
function publish(argv, io) {
|
|
384
|
+
async function publish(argv, io) {
|
|
374
385
|
const { authorship, vault } = load();
|
|
375
386
|
const env = io.env || process.env;
|
|
376
387
|
const positional = argv.find((a) => !a.startsWith('-'));
|
|
@@ -385,7 +396,7 @@ function publish(argv, io) {
|
|
|
385
396
|
}
|
|
386
397
|
if (!fs.existsSync(file)) throw new Error(`fingerprint: no record at ${file}`);
|
|
387
398
|
|
|
388
|
-
const r = vault.publish({
|
|
399
|
+
const r = await vault.publish({
|
|
389
400
|
file,
|
|
390
401
|
argv,
|
|
391
402
|
env,
|
|
@@ -401,6 +412,7 @@ function publish(argv, io) {
|
|
|
401
412
|
io.stdout.write(
|
|
402
413
|
[
|
|
403
414
|
`dry run nothing uploaded`,
|
|
415
|
+
`backend ${r.backend}`,
|
|
404
416
|
`record ${file}`,
|
|
405
417
|
`would go ${r.remotePath}`,
|
|
406
418
|
...r.commands.map((c) => ` ${c}`),
|
|
@@ -410,10 +422,10 @@ function publish(argv, io) {
|
|
|
410
422
|
}
|
|
411
423
|
io.stdout.write(
|
|
412
424
|
[
|
|
413
|
-
`published ${r.remotePath}`,
|
|
425
|
+
`published ${r.remotePath} (${r.backend})`,
|
|
414
426
|
`identity φ_${r.anchor.keyFingerprint}-${r.anchor.behaviour || 'unobserved'}`,
|
|
415
427
|
`digest sha256 ${r.sha256.slice(0, 16)}… (${r.bytes} bytes, byte-identical to ${file})`,
|
|
416
|
-
`link ${r.url || '(no
|
|
428
|
+
`link ${r.url || '(no share link — the copy is at the path above)'}`,
|
|
417
429
|
`anchored ${r.localAnchor}${r.indexLines === null ? '' : ` · ledger lines ${r.indexLines}`}`,
|
|
418
430
|
'',
|
|
419
431
|
'The key was NOT published. Only the sealed record travels; verify the copy',
|
|
@@ -423,12 +435,12 @@ function publish(argv, io) {
|
|
|
423
435
|
return 0;
|
|
424
436
|
}
|
|
425
437
|
|
|
426
|
-
function anchorCmd(argv, io) {
|
|
438
|
+
async function anchorCmd(argv, io) {
|
|
427
439
|
const { vault } = load();
|
|
428
440
|
const file = argv.find((a) => !a.startsWith('-'));
|
|
429
441
|
if (!file) throw new Error('fingerprint: anchor needs a record file (the one you published)');
|
|
430
442
|
|
|
431
|
-
const r = vault.checkAnchor({ file: path.resolve(file), argv, env: io.env || process.env });
|
|
443
|
+
const r = await vault.checkAnchor({ file: path.resolve(file), argv, env: io.env || process.env });
|
|
432
444
|
if (io.json) {
|
|
433
445
|
io.stdout.write(JSON.stringify(r, null, 2) + '\n');
|
|
434
446
|
return r.ok ? 0 : 1;
|
|
@@ -452,13 +464,13 @@ function anchorCmd(argv, io) {
|
|
|
452
464
|
return r.ok ? 0 : 1;
|
|
453
465
|
}
|
|
454
466
|
|
|
455
|
-
function vaultCmd(argv, io) {
|
|
467
|
+
async function vaultCmd(argv, io) {
|
|
456
468
|
const { authorship, vault } = load();
|
|
457
469
|
const env = io.env || process.env;
|
|
458
470
|
const audit = has(argv, '--audit');
|
|
459
471
|
|
|
460
472
|
if (audit) {
|
|
461
|
-
const r = vault.audit({ argv, env, secret: secretOrNull(authorship, argv, env) });
|
|
473
|
+
const r = await vault.audit({ argv, env, secret: secretOrNull(authorship, argv, env) });
|
|
462
474
|
if (io.json) {
|
|
463
475
|
io.stdout.write(JSON.stringify(r, null, 2) + '\n');
|
|
464
476
|
return r.ok ? 0 : 1;
|
|
@@ -469,7 +481,7 @@ function vaultCmd(argv, io) {
|
|
|
469
481
|
}
|
|
470
482
|
io.stdout.write(
|
|
471
483
|
[
|
|
472
|
-
`vault ${r.
|
|
484
|
+
`vault ${r.where} (backend ${r.backend})`,
|
|
473
485
|
`inspected ${r.checked} of ${r.files} object(s)`,
|
|
474
486
|
r.uninspected.length ? `skipped ${r.uninspected.length} (see --json)` : '',
|
|
475
487
|
'',
|
|
@@ -490,12 +502,12 @@ function vaultCmd(argv, io) {
|
|
|
490
502
|
return r.ok ? 0 : 1;
|
|
491
503
|
}
|
|
492
504
|
|
|
493
|
-
const r = vault.list({ argv, env });
|
|
505
|
+
const r = await vault.list({ argv, env });
|
|
494
506
|
if (io.json) {
|
|
495
507
|
io.stdout.write(JSON.stringify(r, null, 2) + '\n');
|
|
496
508
|
return 0;
|
|
497
509
|
}
|
|
498
|
-
const lines = [`vault ${r.
|
|
510
|
+
const lines = [`vault ${r.where} (${r.records.length} record(s), backend ${r.backend})`];
|
|
499
511
|
for (const rec of r.records) {
|
|
500
512
|
lines.push(
|
|
501
513
|
` ${rec.name}`,
|
|
@@ -545,12 +557,18 @@ function runFingerprint(sub, argv = [], io = {}) {
|
|
|
545
557
|
return verify(argv, out);
|
|
546
558
|
case 'backup':
|
|
547
559
|
return backup(argv, out);
|
|
560
|
+
// The three vault subcommands are async because the default vault is
|
|
561
|
+
// the account (an HTTP vault) as well as rclone. They keep the same
|
|
562
|
+
// contract though — an exit code, and a throw becomes exit 2 — so a
|
|
563
|
+
// caller only has to `await` the result; the sync subcommands above
|
|
564
|
+
// still return a plain number, which is what `runFingerprint` always did
|
|
565
|
+
// and what its tests assert.
|
|
548
566
|
case 'publish':
|
|
549
|
-
return publish(argv, out);
|
|
567
|
+
return asExitCode(publish(argv, out), out);
|
|
550
568
|
case 'anchor':
|
|
551
|
-
return anchorCmd(argv, out);
|
|
569
|
+
return asExitCode(anchorCmd(argv, out), out);
|
|
552
570
|
case 'vault':
|
|
553
|
-
return vaultCmd(argv, out);
|
|
571
|
+
return asExitCode(vaultCmd(argv, out), out);
|
|
554
572
|
default:
|
|
555
573
|
out.stderr.write(`aegiscode: unknown fingerprint subcommand "${sub}"\n\n${HELP}\n`);
|
|
556
574
|
return 2;
|
|
@@ -561,4 +579,16 @@ function runFingerprint(sub, argv = [], io = {}) {
|
|
|
561
579
|
}
|
|
562
580
|
}
|
|
563
581
|
|
|
582
|
+
/**
|
|
583
|
+
* A vault subcommand's promise, as the same exit-code contract the sync
|
|
584
|
+
* subcommands have: a rejection is a usage-shaped line on stderr and exit 2,
|
|
585
|
+
* never a stack trace over a user's record (see this file's header on 1 vs 2).
|
|
586
|
+
*/
|
|
587
|
+
function asExitCode(promise, io) {
|
|
588
|
+
return promise.catch((e) => {
|
|
589
|
+
io.stderr.write(`aegiscode: ${(e && e.message) || e}\n`);
|
|
590
|
+
return 2;
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
|
|
564
594
|
module.exports = { runFingerprint, HELP, slug, defaultRecordPath, flag, everyFlag };
|
package/src/limits.js
CHANGED
|
@@ -101,7 +101,7 @@ const UNITS = Object.freeze([
|
|
|
101
101
|
* The masked digest of the sealed set. Rewritten ONLY by
|
|
102
102
|
* `node tools/provenance.mjs seal --write`, never by hand.
|
|
103
103
|
*/
|
|
104
|
-
const SEALED = '
|
|
104
|
+
const SEALED = '5109d6727943ad3404b26820f686c7a4e056b5a334e1f5905322e403c06fb68a';
|
|
105
105
|
|
|
106
106
|
/** Subcommands that a build failing this check does not get to run. */
|
|
107
107
|
const PRIVILEGED = Object.freeze(['gate', 'provenance', 'mcp']);
|
package/src/overlays.js
CHANGED
|
@@ -396,12 +396,66 @@ function ago(ts) {
|
|
|
396
396
|
return `${Math.round(ms / 86_400_000)}d ago`;
|
|
397
397
|
}
|
|
398
398
|
|
|
399
|
+
// ── BYOK provider picker overlay (/byok-set, /byok-key with no argument) ────
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* The picker `/byok-set <provider>` draws when no provider was typed.
|
|
403
|
+
*
|
|
404
|
+
* The provider id was the one thing this flow asked the user to RECALL: `/byok`
|
|
405
|
+
* listed ~20 ids, and storing a key meant reading one off that list and typing
|
|
406
|
+
* it back — retyped wrong, it either matched nothing ("unknown provider") or,
|
|
407
|
+
* worse, matched an alias of another vendor. The rows are the catalog's own,
|
|
408
|
+
* so the id Enter sends is the id the relay will be asked for.
|
|
409
|
+
*
|
|
410
|
+
* @param {Array} providers catalog rows ({id, label?, configured?, masked?})
|
|
411
|
+
* @param {number} sel selected index
|
|
412
|
+
* @param {number} width
|
|
413
|
+
* @param {string|null} [current] the provider already set on this machine, if
|
|
414
|
+
* any (marked, not selected — "set" is shown per row anyway)
|
|
415
|
+
* @param {string} [hint] the footer line; differs between `/byok-set` (the
|
|
416
|
+
* account-side store) and `/byok-key` (this machine's store)
|
|
417
|
+
*/
|
|
418
|
+
function renderProviderPicker(providers, sel = 0, width = 80, current = null, hint = null) {
|
|
419
|
+
const list = Array.isArray(providers) ? providers : [];
|
|
420
|
+
const lines = [];
|
|
421
|
+
lines.push(blank(width));
|
|
422
|
+
lines.push([span('', ' '), span(C.white + BOLD, 'Select provider'), span(BOLD_OFF, '')]);
|
|
423
|
+
lines.push([span('', ' '), span(C.gray, 'Which vendor the key you are about to paste belongs to.')]);
|
|
424
|
+
lines.push(blank(width));
|
|
425
|
+
for (let i = 0; i < list.length; i++) {
|
|
426
|
+
const p = list[i] || {};
|
|
427
|
+
const id = String(p.id || '');
|
|
428
|
+
if (!id) continue;
|
|
429
|
+
const active = i === sel;
|
|
430
|
+
const cur = current != null && id === current;
|
|
431
|
+
const left = active ? span(C.lavender, GLYPH.cursor) : span('', ' ');
|
|
432
|
+
const nameSpan = active ? span(C.lavender, id) : span(C.white, id);
|
|
433
|
+
const mark = cur ? span(C.green, ' ' + GLYPH.check) : span('', '');
|
|
434
|
+
const name = String(p.label || '');
|
|
435
|
+
const pad = ' '.repeat(Math.max(1, 16 - [...id].length));
|
|
436
|
+
const state = p.configured
|
|
437
|
+
? span(C.green, `set${p.masked ? ` (${p.masked})` : ''}`)
|
|
438
|
+
: span(C.gray, 'not set');
|
|
439
|
+
lines.push([
|
|
440
|
+
span('', ' '), left, span('', ' '), nameSpan, mark,
|
|
441
|
+
span(C.gray, pad + (name ? `${name} · ` : '')), state,
|
|
442
|
+
]);
|
|
443
|
+
}
|
|
444
|
+
lines.push(blank(width));
|
|
445
|
+
lines.push([
|
|
446
|
+
span('', ' '),
|
|
447
|
+
span(C.gray, hint || `↑↓ or tab move ${GLYPH.bullet} enter picks ${GLYPH.bullet} esc cancels`),
|
|
448
|
+
]);
|
|
449
|
+
return fit(lines, width);
|
|
450
|
+
}
|
|
451
|
+
|
|
399
452
|
module.exports = {
|
|
400
453
|
boldMatched,
|
|
401
454
|
renderPalette,
|
|
402
455
|
renderModelPicker,
|
|
403
456
|
renderEffortPicker,
|
|
404
457
|
renderClassPicker,
|
|
458
|
+
renderProviderPicker,
|
|
405
459
|
renderResumeList,
|
|
406
460
|
EFFORT_LEVELS,
|
|
407
461
|
EFFORT_VALUES,
|
package/src/provenance.lock.json
CHANGED
|
@@ -24,13 +24,13 @@
|
|
|
24
24
|
"license": "AGPL-3.0-or-later",
|
|
25
25
|
"source": "https://github.com/aegisinfo/aegiscode-plugin",
|
|
26
26
|
"units": {
|
|
27
|
-
"p1": "
|
|
27
|
+
"p1": "b992aa725ee2c371e3ae857d6dedd4aa398b8decff00326d2ad11ed996299eb0",
|
|
28
28
|
"p2": "d63d147de5455eea111d000b748d7eef9572a11a08d31f2471d5ff146701342c",
|
|
29
29
|
"p3": "ff962ac8dbf42cecb2477e2f77bf5ec61f88aa1751b0d4e506bf030fbc5fc6c6",
|
|
30
30
|
"p4": "2e8385c3a653a2af324050b4b92aeb9d142fc6765c91a13ccc928c5d4a2dbedb",
|
|
31
31
|
"p5": "408d67f78f31f6d637a26d2852e0c809a260544e613afdc64b731401c0ba3801",
|
|
32
|
-
"p6": "
|
|
33
|
-
"p7": "
|
|
32
|
+
"p6": "22bcd0b5dc1afad8d870652fbf1fd25bd0a547be9d8700161449cafa35bab6eb",
|
|
33
|
+
"p7": "89ee0c5ab9640c470c03cddcfa9e3722182dca62eb2df8e3f0a53342e59207f3",
|
|
34
34
|
"p8": "3cc054d06715e065fe635b37b7d1bb98bf7989d64453a572ddbb77cec5b830e7"
|
|
35
35
|
}
|
|
36
36
|
}
|
package/src/screens.js
CHANGED
|
@@ -44,7 +44,7 @@ const { TAGLINE, TAGLINE_SHORT, welcomeArtParts } = require('./art.js');
|
|
|
44
44
|
const { renderDiffPreview } = require('./markdown.js');
|
|
45
45
|
const render = require('./render.js');
|
|
46
46
|
const { updateConfig, configExists, loadConfig } = require('./config.js');
|
|
47
|
-
const { updateNotice, updateLine } = require('./update.js');
|
|
47
|
+
const { updateNotice, updateLine, serverNotice, serverUpdateLine } = require('./update.js');
|
|
48
48
|
const credentials = require('./credentials.js');
|
|
49
49
|
const { signupUrl, signupDisplayUrl } = require('./signup.js');
|
|
50
50
|
const { createSettingsStore, isReservedNamespace } = require('./deps.js');
|
|
@@ -392,6 +392,19 @@ function welcomeLines(ctx, cols, rows, firstRun = true) {
|
|
|
392
392
|
save: (v) => { try { updateConfig({ updateCheck: v }); } catch { /* not fatal */ } },
|
|
393
393
|
});
|
|
394
394
|
updateMsg = updateLine({ current: VERSION, ...notice });
|
|
395
|
+
|
|
396
|
+
// The server's own verdict, which outranks the registry's: "a newer
|
|
397
|
+
// release exists" is a suggestion, "this build is no longer served" is
|
|
398
|
+
// the app about to stop working. aegis1 refuses clients below
|
|
399
|
+
// MIN_CLIENT_VERSION with a 426, so without this line a user learns it
|
|
400
|
+
// by being cut off mid-task instead of by reading their welcome box.
|
|
401
|
+
// Same cache-read-only rule: the refresh lands for the next launch.
|
|
402
|
+
const srv = serverNotice({
|
|
403
|
+
current: VERSION,
|
|
404
|
+
cache: cfg.updateCheckServer,
|
|
405
|
+
save: (v) => { try { updateConfig({ updateCheckServer: v }); } catch { /* not fatal */ } },
|
|
406
|
+
});
|
|
407
|
+
updateMsg = serverUpdateLine(srv) || updateMsg;
|
|
395
408
|
} catch {
|
|
396
409
|
// An update notice is never worth failing a launch over.
|
|
397
410
|
}
|
|
@@ -382,8 +382,15 @@ function clientOptions(o = {}) {
|
|
|
382
382
|
const { key } = resolveApiKey(o);
|
|
383
383
|
const { token } = resolveMemoryToken(o);
|
|
384
384
|
const opts = {};
|
|
385
|
-
|
|
386
|
-
|
|
385
|
+
// Set explicitly, even when empty: `createClient` only re-checks its own
|
|
386
|
+
// (real, ambient) process.env when `apiKey`/`memoryToken` are `undefined`.
|
|
387
|
+
// Omitting an empty result here was indistinguishable from "not resolved
|
|
388
|
+
// yet" and let that fallback see the real environment's key even when an
|
|
389
|
+
// injected `o.env`/`o.dir` (tests, a hosted agent, a `--base` against a
|
|
390
|
+
// staging account — the reason this function takes them at all) had
|
|
391
|
+
// already and correctly resolved to "no key".
|
|
392
|
+
opts.apiKey = key;
|
|
393
|
+
opts.memoryToken = token;
|
|
387
394
|
// The host names itself so upgrade prompts raised inside the shared client
|
|
388
395
|
// are attributed to the right product. Unset means desktop, which matches
|
|
389
396
|
// createClient's own default.
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
|
|
3
|
+
// AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
|
|
4
|
+
// Conveying a modified copy, or running one as a network service, owes the
|
|
5
|
+
// corresponding source under this licence (§5/§13) — see LICENSING.md.
|
|
6
|
+
'use strict';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Sign this machine in with the user's actual Google identity, instead of the
|
|
10
|
+
* anonymous per-machine key `auto-provision.js`/`connect.js` mint by default.
|
|
11
|
+
*
|
|
12
|
+
* aegis1 already runs the full web side of this (`app.py`: `/auth/google`,
|
|
13
|
+
* `/auth/callback/google`) including a desktop round-trip it was built for:
|
|
14
|
+
* pass `?callback=http://127.0.0.1:{port}` and, once the browser finishes the
|
|
15
|
+
* Google consent screen, aegis1 redirects the browser back to that local
|
|
16
|
+
* address with `token`, `username` and (when available) `memory_token` as
|
|
17
|
+
* query params. Nothing here talks to Google or to aegis1 directly — this
|
|
18
|
+
* module only runs the localhost half of that round-trip: open a one-shot
|
|
19
|
+
* HTTP server, hand the caller the URL to open, and resolve once the browser
|
|
20
|
+
* comes back to it.
|
|
21
|
+
*
|
|
22
|
+
* `token` IS the ordinary AEGIS API key for the account aegis1 resolved
|
|
23
|
+
* (looked up or created by `google_id`/email) — there is no second credential
|
|
24
|
+
* format to support. The caller saves it exactly as `register-device`'s key,
|
|
25
|
+
* through `credentials.saveApiKey`.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
const http = require('node:http');
|
|
29
|
+
const { URL } = require('node:url');
|
|
30
|
+
|
|
31
|
+
/** Escapes text placed into the one-shot HTML page — the values riding in the
|
|
32
|
+
* query string came back through the user's browser, so treat them as
|
|
33
|
+
* untrusted even though this server only ever talks to localhost. */
|
|
34
|
+
function escapeHtml(s) {
|
|
35
|
+
return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({
|
|
36
|
+
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
|
|
37
|
+
}[c]));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function page({ ok, error, username }) {
|
|
41
|
+
const title = ok ? 'Signed in' : 'Sign-in failed';
|
|
42
|
+
const body = ok
|
|
43
|
+
? `Signed in${username ? ` as <b>${escapeHtml(username)}</b>` : ''}. You can close this tab and return to the terminal.`
|
|
44
|
+
: `Sign-in failed: ${escapeHtml(error || 'no token was returned')}. You can close this tab and try again.`;
|
|
45
|
+
return `<!doctype html><html><head><meta charset="utf-8"><title>${title} — AEGIS</title></head>` +
|
|
46
|
+
`<body style="font:16px sans-serif;max-width:32rem;margin:4rem auto;text-align:center;">` +
|
|
47
|
+
`<h2>${title}</h2><p>${body}</p></body></html>`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** `${apiBase}/auth/google?callback=${callbackUrl}` — the one URL this flow opens. */
|
|
51
|
+
function buildAuthUrl(apiBase, callbackUrl) {
|
|
52
|
+
const url = new URL('/auth/google', apiBase);
|
|
53
|
+
url.searchParams.set('callback', callbackUrl);
|
|
54
|
+
return url.toString();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Starts the local callback server and returns the URL to open, plus a
|
|
59
|
+
* `wait()` that resolves once the browser lands on it.
|
|
60
|
+
*
|
|
61
|
+
* Only a request that carries `token` or `error` ends the wait — anything
|
|
62
|
+
* else (a browser pre-connect, `/favicon.ico`) gets a plain 404 and the
|
|
63
|
+
* server keeps listening for the real one.
|
|
64
|
+
*
|
|
65
|
+
* @returns {Promise<{url: string, wait: () => Promise<{apiKey:string, username:?string, memoryToken:?string}>}>}
|
|
66
|
+
*/
|
|
67
|
+
async function startGoogleSignIn({ apiBase, host = '127.0.0.1', timeoutMs = 5 * 60 * 1000 } = {}) {
|
|
68
|
+
if (!apiBase) throw new Error('startGoogleSignIn requires apiBase');
|
|
69
|
+
|
|
70
|
+
let settled = false;
|
|
71
|
+
let resolveResult;
|
|
72
|
+
let rejectResult;
|
|
73
|
+
const result = new Promise((resolve, reject) => {
|
|
74
|
+
resolveResult = resolve;
|
|
75
|
+
rejectResult = reject;
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
const server = http.createServer((req, res) => {
|
|
79
|
+
let parsed;
|
|
80
|
+
try {
|
|
81
|
+
parsed = new URL(req.url, `http://${host}`);
|
|
82
|
+
} catch {
|
|
83
|
+
res.writeHead(400).end();
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const token = parsed.searchParams.get('token');
|
|
87
|
+
const username = parsed.searchParams.get('username');
|
|
88
|
+
const memoryToken = parsed.searchParams.get('memory_token');
|
|
89
|
+
const error = parsed.searchParams.get('error');
|
|
90
|
+
|
|
91
|
+
if (!token && !error) {
|
|
92
|
+
res.writeHead(404).end();
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
96
|
+
res.end(page({ ok: Boolean(token), error, username }));
|
|
97
|
+
|
|
98
|
+
if (settled) return;
|
|
99
|
+
settled = true;
|
|
100
|
+
clearTimeout(timer);
|
|
101
|
+
server.close();
|
|
102
|
+
if (token) resolveResult({ apiKey: token, username: username || null, memoryToken: memoryToken || null });
|
|
103
|
+
else rejectResult(new Error(error || 'no token was returned'));
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
await new Promise((resolve, reject) => {
|
|
107
|
+
server.once('error', reject);
|
|
108
|
+
server.listen(0, host, resolve);
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
const { port } = server.address();
|
|
112
|
+
const callbackUrl = `http://${host}:${port}`;
|
|
113
|
+
const url = buildAuthUrl(apiBase, callbackUrl);
|
|
114
|
+
|
|
115
|
+
const timer = setTimeout(() => {
|
|
116
|
+
if (settled) return;
|
|
117
|
+
settled = true;
|
|
118
|
+
server.close();
|
|
119
|
+
rejectResult(new Error(`timed out after ${Math.round(timeoutMs / 1000)}s waiting for the browser sign-in`));
|
|
120
|
+
}, timeoutMs);
|
|
121
|
+
// A pending timer must not keep the process alive just for this wait.
|
|
122
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
123
|
+
|
|
124
|
+
return { url, wait: () => result };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
module.exports = { startGoogleSignIn, buildAuthUrl };
|