@datarails-ai/dr-appspace-cli 0.12.88 → 0.12.90
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/README.md +12 -4
- package/dist/cli.js +1406 -1115
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -13,7 +13,7 @@ import { fileURLToPath as fileURLToPath6 } from "url";
|
|
|
13
13
|
// package.json
|
|
14
14
|
var package_default = {
|
|
15
15
|
name: "@datarails-ai/dr-appspace-cli",
|
|
16
|
-
version: "0.12.
|
|
16
|
+
version: "0.12.90",
|
|
17
17
|
description: "Datarails App Space CLI \u2014 build, try, push and publish App Space apps",
|
|
18
18
|
type: "module",
|
|
19
19
|
engines: {
|
|
@@ -57,7 +57,7 @@ var package_default = {
|
|
|
57
57
|
};
|
|
58
58
|
|
|
59
59
|
// src/buildInfo.ts
|
|
60
|
-
var BUILD_TIME = "2026-11-
|
|
60
|
+
var BUILD_TIME = "2026-11-16T15:39:46.390Z";
|
|
61
61
|
function formatBuildTime(iso) {
|
|
62
62
|
if (iso === "") return "";
|
|
63
63
|
const d = new Date(iso);
|
|
@@ -123,6 +123,10 @@ var credentialsFileSchema = z.object({
|
|
|
123
123
|
// Validated, not just typed: `KeyringStore` turns this straight into a Date
|
|
124
124
|
// and later calls `toISOString()` on it, which throws on an Invalid Date.
|
|
125
125
|
// `datetime()` is a regex, so it passes 2026-13-40 — hence the parse check.
|
|
126
|
+
// Written by a v2 `dr-appspace login` or `dr login`: a person approved this
|
|
127
|
+
// pair in the browser, so a later login may replace it and logout may
|
|
128
|
+
// remove it. A provisioned pair has no such mark.
|
|
129
|
+
interactiveLogin: z.boolean().optional(),
|
|
126
130
|
savedAt: z.iso.datetime({ offset: true }).refine((s) => !Number.isNaN(Date.parse(s)), { message: "not a valid date" }).optional()
|
|
127
131
|
}).loose().refine((c) => c.sessionId === void 0 === (c.csrfToken === void 0), {
|
|
128
132
|
message: "sessionId and csrfToken must be provided together",
|
|
@@ -196,6 +200,11 @@ function refuseUnlessPrivate(path3, st, platform = process.platform) {
|
|
|
196
200
|
}
|
|
197
201
|
async function writeCredentialsFile(path3, creds) {
|
|
198
202
|
await ensureCredentialsDir(dirname(path3));
|
|
203
|
+
if (creds.sessionId !== void 0 || creds.csrfToken !== void 0) {
|
|
204
|
+
throw new Error(
|
|
205
|
+
`refusing to write a session cookie into ${path3}: the CLI authenticates with JWTs only`
|
|
206
|
+
);
|
|
207
|
+
}
|
|
199
208
|
let next;
|
|
200
209
|
try {
|
|
201
210
|
next = credentialsFileSchema.parse({
|
|
@@ -433,380 +442,16 @@ function msgOf(err) {
|
|
|
433
442
|
return err instanceof Error ? err.message : String(err);
|
|
434
443
|
}
|
|
435
444
|
|
|
436
|
-
// src/auth/
|
|
437
|
-
import {
|
|
438
|
-
import * as path2 from "path";
|
|
439
|
-
import * as os2 from "os";
|
|
440
|
-
async function cleanupV1IfPresent(opts = {}) {
|
|
441
|
-
const home = opts.home ?? os2.homedir();
|
|
442
|
-
const log = opts.logger ?? ((m) => process.stderr.write(m + "\n"));
|
|
443
|
-
const drDir = path2.join(home, ".dr");
|
|
444
|
-
const filePath = path2.join(drDir, "credentials.json");
|
|
445
|
-
try {
|
|
446
|
-
await fs2.stat(filePath);
|
|
447
|
-
} catch (err) {
|
|
448
|
-
if (err.code === "ENOENT") return;
|
|
449
|
-
log(`dr: warning: could not check ${filePath}: ${msgOf2(err)}`);
|
|
450
|
-
return;
|
|
451
|
-
}
|
|
452
|
-
try {
|
|
453
|
-
await fs2.unlink(filePath);
|
|
454
|
-
} catch (err) {
|
|
455
|
-
log(
|
|
456
|
-
`dr: warning: could not remove legacy ${filePath}: ${msgOf2(err)}; please delete manually.`
|
|
457
|
-
);
|
|
458
|
-
return;
|
|
459
|
-
}
|
|
460
|
-
try {
|
|
461
|
-
await fs2.rmdir(drDir);
|
|
462
|
-
} catch {
|
|
463
|
-
}
|
|
464
|
-
log(
|
|
465
|
-
`dr: removed legacy ${filePath} \u2014 run dr-appspace login --server <key> to re-authenticate.`
|
|
466
|
-
);
|
|
467
|
-
}
|
|
468
|
-
function msgOf2(err) {
|
|
469
|
-
return err instanceof Error ? err.message : String(err);
|
|
470
|
-
}
|
|
445
|
+
// src/auth/keyring/fileBackend.ts
|
|
446
|
+
import { rm as rm2 } from "fs/promises";
|
|
471
447
|
|
|
472
|
-
// src/auth/
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
}
|
|
480
|
-
backend;
|
|
481
|
-
static default() {
|
|
482
|
-
return new _KeyringStore(new NapiKeyringBackend());
|
|
483
|
-
}
|
|
484
|
-
/**
|
|
485
|
-
* Like `default()`, but runs the one-shot legacy-file cleanup on first
|
|
486
|
-
* call within the process. Subsequent calls re-use the cached promise and
|
|
487
|
-
* are non-blocking once cleanup has resolved.
|
|
488
|
-
*/
|
|
489
|
-
static async defaultWithCleanup() {
|
|
490
|
-
if (cleanupOnce === void 0) {
|
|
491
|
-
cleanupOnce = cleanupV1IfPresent();
|
|
492
|
-
}
|
|
493
|
-
await cleanupOnce;
|
|
494
|
-
return _KeyringStore.default();
|
|
495
|
-
}
|
|
496
|
-
/**
|
|
497
|
-
* The account list is derived by enumerating the per-account keychain
|
|
498
|
-
* entries (`<server>:<email>`), not from a monolithic index blob. The index
|
|
499
|
-
* used to be the source of truth but grew unbounded and hit the Windows
|
|
500
|
-
* 2560-byte per-credential cap at ~11 accounts (see design doc
|
|
501
|
-
* 2026-07-02-keychain-index-enumerate). Enumeration scales indefinitely and
|
|
502
|
-
* self-heals accounts a failed index write left orphaned.
|
|
503
|
-
*
|
|
504
|
-
* The legacy `__index__:<server>` entry is retained only to back-fill
|
|
505
|
-
* `lastUsedAt` for accounts saved before the fix, and as a fallback when the
|
|
506
|
-
* backend cannot enumerate (some platforms).
|
|
507
|
-
*/
|
|
508
|
-
async listSessions(serverKey) {
|
|
509
|
-
const legacy = await this.readLegacyIndex(serverKey);
|
|
510
|
-
let entries;
|
|
511
|
-
try {
|
|
512
|
-
entries = await this.backend.list(SERVICE);
|
|
513
|
-
} catch {
|
|
514
|
-
return [...legacy.values()];
|
|
515
|
-
}
|
|
516
|
-
const prefix = `${serverKey}:`;
|
|
517
|
-
const out = [];
|
|
518
|
-
for (const { account, value } of entries) {
|
|
519
|
-
if (!account.startsWith(prefix)) continue;
|
|
520
|
-
const rest = account.slice(prefix.length);
|
|
521
|
-
if (rest === "" || rest.endsWith(":access") || rest.endsWith(":refresh")) continue;
|
|
522
|
-
const email = rest;
|
|
523
|
-
let blob;
|
|
524
|
-
try {
|
|
525
|
-
blob = JSON.parse(value);
|
|
526
|
-
} catch {
|
|
527
|
-
continue;
|
|
528
|
-
}
|
|
529
|
-
const savedAt = parseDate(blob.savedAt);
|
|
530
|
-
if (savedAt === void 0) continue;
|
|
531
|
-
const lastUsedAt = parseDate(blob.lastUsedAt) ?? legacy.get(email)?.lastUsedAt ?? savedAt;
|
|
532
|
-
out.push({ email, savedAt, lastUsedAt });
|
|
533
|
-
}
|
|
534
|
-
return out;
|
|
535
|
-
}
|
|
536
|
-
/**
|
|
537
|
-
* Reads the legacy `__index__:<server>` blob into an email→metadata map.
|
|
538
|
-
* Best-effort: a missing, malformed, or non-array index yields an empty map
|
|
539
|
-
* rather than throwing — the index is no longer authoritative.
|
|
540
|
-
*/
|
|
541
|
-
async readLegacyIndex(serverKey) {
|
|
542
|
-
const out = /* @__PURE__ */ new Map();
|
|
543
|
-
let raw;
|
|
544
|
-
try {
|
|
545
|
-
raw = await this.backend.get(SERVICE, INDEX_PREFIX + serverKey);
|
|
546
|
-
} catch {
|
|
547
|
-
return out;
|
|
548
|
-
}
|
|
549
|
-
if (raw === void 0) return out;
|
|
550
|
-
let parsed2;
|
|
551
|
-
try {
|
|
552
|
-
parsed2 = JSON.parse(raw);
|
|
553
|
-
} catch {
|
|
554
|
-
return out;
|
|
555
|
-
}
|
|
556
|
-
if (!Array.isArray(parsed2)) return out;
|
|
557
|
-
for (const item of parsed2) {
|
|
558
|
-
const savedAt = parseDate(item?.savedAt);
|
|
559
|
-
const lastUsedAt = parseDate(item?.lastUsedAt);
|
|
560
|
-
if (typeof item?.email === "string" && savedAt !== void 0 && lastUsedAt !== void 0) {
|
|
561
|
-
out.set(item.email, { email: item.email, savedAt, lastUsedAt });
|
|
562
|
-
}
|
|
563
|
-
}
|
|
564
|
-
return out;
|
|
565
|
-
}
|
|
566
|
-
/**
|
|
567
|
-
* Returns the session for `(serverKey, email)`. Returns undefined if no
|
|
568
|
-
* entry exists.
|
|
569
|
-
*
|
|
570
|
-
* `email` is the lookup key — the stored blob does not carry it. The
|
|
571
|
-
* returned `Session.email` is populated from the argument, not from the
|
|
572
|
-
* keychain. This avoids denormalising the identity across the key and
|
|
573
|
-
* the value.
|
|
574
|
-
*
|
|
575
|
-
* Storage layout (see `saveSession`): the JWT bodies live in sibling
|
|
576
|
-
* entries (`:access`, `:refresh`) so each individual blob fits under the
|
|
577
|
-
* Windows Credential Manager 2560-byte (UTF-16) per-credential limit.
|
|
578
|
-
* This method reassembles the full Session by reading all three.
|
|
579
|
-
*/
|
|
580
|
-
async getSession(serverKey, email) {
|
|
581
|
-
const sessionAccount = `${serverKey}:${email}`;
|
|
582
|
-
const raw = await this.backend.get(SERVICE, sessionAccount);
|
|
583
|
-
if (raw === void 0) return void 0;
|
|
584
|
-
let parsed2;
|
|
585
|
-
try {
|
|
586
|
-
parsed2 = JSON.parse(raw);
|
|
587
|
-
} catch (err) {
|
|
588
|
-
throw new KeychainError(`decode session for ${serverKey}:${email}`, {
|
|
589
|
-
cause: err
|
|
590
|
-
});
|
|
591
|
-
}
|
|
592
|
-
const sessionId = typeof parsed2.sessionId === "string" ? parsed2.sessionId : "";
|
|
593
|
-
const csrfToken = typeof parsed2.csrfToken === "string" ? parsed2.csrfToken : "";
|
|
594
|
-
const savedAtStr = typeof parsed2.savedAt === "string" ? parsed2.savedAt : "";
|
|
595
|
-
const impersonatorEmail = typeof parsed2.impersonatorEmail === "string" ? parsed2.impersonatorEmail : "";
|
|
596
|
-
const impersonated = impersonatorEmail !== "";
|
|
597
|
-
const cookielessFlag = parsed2.cookieless === true;
|
|
598
|
-
const apiKey = typeof parsed2.apiKey === "string" && parsed2.apiKey !== "" ? parsed2.apiKey : "";
|
|
599
|
-
const apiKeyEnvVar = typeof parsed2.apiKeyEnvVar === "string" && parsed2.apiKeyEnvVar !== "" ? parsed2.apiKeyEnvVar : "";
|
|
600
|
-
const keyed = apiKey !== "" || apiKeyEnvVar !== "";
|
|
601
|
-
const cookieless = impersonated || cookielessFlag || keyed;
|
|
602
|
-
if (savedAtStr === "" || !cookieless && (sessionId === "" || csrfToken === "")) {
|
|
603
|
-
throw new KeychainError(`session for ${serverKey}:${email} is malformed`);
|
|
604
|
-
}
|
|
605
|
-
const session = {
|
|
606
|
-
email,
|
|
607
|
-
sessionId,
|
|
608
|
-
csrfToken,
|
|
609
|
-
savedAt: new Date(savedAtStr)
|
|
610
|
-
};
|
|
611
|
-
if (impersonated) {
|
|
612
|
-
session.impersonatorEmail = impersonatorEmail;
|
|
613
|
-
if (typeof parsed2.impersonatedUserId === "number") {
|
|
614
|
-
session.impersonatedUserId = parsed2.impersonatedUserId;
|
|
615
|
-
}
|
|
616
|
-
if (typeof parsed2.impersonatedOrgName === "string" && parsed2.impersonatedOrgName !== "") {
|
|
617
|
-
session.impersonatedOrgName = parsed2.impersonatedOrgName;
|
|
618
|
-
}
|
|
619
|
-
}
|
|
620
|
-
if (cookielessFlag) {
|
|
621
|
-
session.cookieless = true;
|
|
622
|
-
}
|
|
623
|
-
if (apiKey !== "") {
|
|
624
|
-
session.apiKey = apiKey;
|
|
625
|
-
}
|
|
626
|
-
if (apiKeyEnvVar !== "") {
|
|
627
|
-
session.apiKeyEnvVar = apiKeyEnvVar;
|
|
628
|
-
}
|
|
629
|
-
if (typeof parsed2.apiKeyExpiresAt === "string" && parsed2.apiKeyExpiresAt !== "") {
|
|
630
|
-
session.apiKeyExpiresAt = new Date(parsed2.apiKeyExpiresAt);
|
|
631
|
-
}
|
|
632
|
-
if (typeof parsed2.jwtApiKeyFingerprint === "string" && parsed2.jwtApiKeyFingerprint !== "") {
|
|
633
|
-
session.jwtApiKeyFingerprint = parsed2.jwtApiKeyFingerprint;
|
|
634
|
-
}
|
|
635
|
-
if (typeof parsed2.jwtExpiresAt === "string" && parsed2.jwtExpiresAt !== "") {
|
|
636
|
-
session.jwtExpiresAt = new Date(parsed2.jwtExpiresAt);
|
|
637
|
-
}
|
|
638
|
-
const jwtAccess = await this.backend.get(SERVICE, `${sessionAccount}:access`);
|
|
639
|
-
if (jwtAccess !== void 0 && jwtAccess !== "") {
|
|
640
|
-
session.jwtAccess = jwtAccess;
|
|
641
|
-
}
|
|
642
|
-
const jwtRefresh = await this.backend.get(SERVICE, `${sessionAccount}:refresh`);
|
|
643
|
-
if (jwtRefresh !== void 0 && jwtRefresh !== "") {
|
|
644
|
-
session.jwtRefresh = jwtRefresh;
|
|
645
|
-
}
|
|
646
|
-
return session;
|
|
647
|
-
}
|
|
648
|
-
/**
|
|
649
|
-
* Writes the per-account entries for `(serverKey, session.email)` and
|
|
650
|
-
* refreshes the legacy index best-effort. Overwrites any existing entry for
|
|
651
|
-
* the same identity.
|
|
652
|
-
*
|
|
653
|
-
* `session.email` is used to derive the keychain account name but is NOT
|
|
654
|
-
* stored inside the session blob — the (server, email) pair is already
|
|
655
|
-
* encoded in the keychain account key. `getSession` re-seeds the returned
|
|
656
|
-
* `Session.email` from its argument.
|
|
657
|
-
*
|
|
658
|
-
* Storage layout: three sibling keychain entries per identity, because
|
|
659
|
-
* Windows Credential Manager caps each blob at 2560 bytes UTF-16
|
|
660
|
-
* (~1280 ASCII chars) and a real session with two JWTs is 3-4 KB total.
|
|
661
|
-
* - `<server>:<email>` → metadata (ids, csrf, savedAt, lastUsedAt, exp)
|
|
662
|
-
* - `<server>:<email>:access` → access JWT body
|
|
663
|
-
* - `<server>:<email>:refresh` → refresh JWT body
|
|
664
|
-
* Each piece fits comfortably under the limit; the metadata blob is
|
|
665
|
-
* ~200 bytes, and Datarails JWTs are typically 800-1500 chars each.
|
|
666
|
-
* If a JWT ever exceeds ~1280 chars on its own, the underlying backend
|
|
667
|
-
* surfaces a clear "longer than the platform limit" error.
|
|
668
|
-
*/
|
|
669
|
-
async saveSession(serverKey, session) {
|
|
670
|
-
if (session.email === "") {
|
|
671
|
-
throw new Error("saveSession: email must not be empty");
|
|
672
|
-
}
|
|
673
|
-
const impersonated = session.impersonatorEmail !== void 0 && session.impersonatorEmail !== "";
|
|
674
|
-
const cookieless = session.cookieless === true;
|
|
675
|
-
if (isCookielessSession(session)) {
|
|
676
|
-
if (!usesApiKey(session) && (session.jwtAccess === void 0 || session.jwtAccess === "")) {
|
|
677
|
-
throw new Error("saveSession: cookie-less session must have a jwtAccess token");
|
|
678
|
-
}
|
|
679
|
-
} else {
|
|
680
|
-
if (session.sessionId === "") {
|
|
681
|
-
throw new Error("saveSession: sessionId must not be empty");
|
|
682
|
-
}
|
|
683
|
-
if (session.csrfToken === "") {
|
|
684
|
-
throw new Error("saveSession: csrfToken must not be empty");
|
|
685
|
-
}
|
|
686
|
-
}
|
|
687
|
-
const sessionAccount = `${serverKey}:${session.email}`;
|
|
688
|
-
const now = /* @__PURE__ */ new Date();
|
|
689
|
-
const metaBlob = {
|
|
690
|
-
sessionId: session.sessionId,
|
|
691
|
-
csrfToken: session.csrfToken,
|
|
692
|
-
savedAt: session.savedAt.toISOString(),
|
|
693
|
-
lastUsedAt: now.toISOString()
|
|
694
|
-
};
|
|
695
|
-
if (session.jwtExpiresAt !== void 0) {
|
|
696
|
-
metaBlob.jwtExpiresAt = session.jwtExpiresAt.toISOString();
|
|
697
|
-
}
|
|
698
|
-
if (impersonated) {
|
|
699
|
-
metaBlob.impersonatorEmail = session.impersonatorEmail;
|
|
700
|
-
if (session.impersonatedUserId !== void 0) {
|
|
701
|
-
metaBlob.impersonatedUserId = session.impersonatedUserId;
|
|
702
|
-
}
|
|
703
|
-
if (session.impersonatedOrgName !== void 0 && session.impersonatedOrgName !== "") {
|
|
704
|
-
metaBlob.impersonatedOrgName = session.impersonatedOrgName;
|
|
705
|
-
}
|
|
706
|
-
}
|
|
707
|
-
if (cookieless) {
|
|
708
|
-
metaBlob.cookieless = true;
|
|
709
|
-
}
|
|
710
|
-
if (session.apiKey !== void 0 && session.apiKey !== "") {
|
|
711
|
-
metaBlob.apiKey = session.apiKey;
|
|
712
|
-
}
|
|
713
|
-
if (session.apiKeyEnvVar !== void 0 && session.apiKeyEnvVar !== "") {
|
|
714
|
-
metaBlob.apiKeyEnvVar = session.apiKeyEnvVar;
|
|
715
|
-
}
|
|
716
|
-
if (session.apiKeyExpiresAt !== void 0) {
|
|
717
|
-
metaBlob.apiKeyExpiresAt = session.apiKeyExpiresAt.toISOString();
|
|
718
|
-
}
|
|
719
|
-
if (session.jwtApiKeyFingerprint !== void 0 && session.jwtApiKeyFingerprint !== "") {
|
|
720
|
-
metaBlob.jwtApiKeyFingerprint = session.jwtApiKeyFingerprint;
|
|
721
|
-
}
|
|
722
|
-
await this.backend.set(SERVICE, sessionAccount, JSON.stringify(metaBlob));
|
|
723
|
-
if (session.jwtAccess !== void 0 && session.jwtAccess !== "") {
|
|
724
|
-
await this.backend.set(SERVICE, `${sessionAccount}:access`, session.jwtAccess);
|
|
725
|
-
} else {
|
|
726
|
-
await this.backend.delete(SERVICE, `${sessionAccount}:access`);
|
|
727
|
-
}
|
|
728
|
-
if (session.jwtRefresh !== void 0 && session.jwtRefresh !== "") {
|
|
729
|
-
await this.backend.set(SERVICE, `${sessionAccount}:refresh`, session.jwtRefresh);
|
|
730
|
-
} else {
|
|
731
|
-
await this.backend.delete(SERVICE, `${sessionAccount}:refresh`);
|
|
732
|
-
}
|
|
733
|
-
await this.tryUpsertLegacyIndex(serverKey, {
|
|
734
|
-
email: session.email,
|
|
735
|
-
savedAt: session.savedAt,
|
|
736
|
-
lastUsedAt: now
|
|
737
|
-
});
|
|
738
|
-
}
|
|
739
|
-
async touch(serverKey, email) {
|
|
740
|
-
const sessionAccount = `${serverKey}:${email}`;
|
|
741
|
-
const raw = await this.backend.get(SERVICE, sessionAccount);
|
|
742
|
-
if (raw === void 0) return;
|
|
743
|
-
let blob;
|
|
744
|
-
try {
|
|
745
|
-
blob = JSON.parse(raw);
|
|
746
|
-
} catch {
|
|
747
|
-
return;
|
|
748
|
-
}
|
|
749
|
-
const now = /* @__PURE__ */ new Date();
|
|
750
|
-
blob.lastUsedAt = now.toISOString();
|
|
751
|
-
await this.backend.set(SERVICE, sessionAccount, JSON.stringify(blob));
|
|
752
|
-
const savedAt = parseDate(blob.savedAt) ?? now;
|
|
753
|
-
await this.tryUpsertLegacyIndex(serverKey, {
|
|
754
|
-
email,
|
|
755
|
-
savedAt,
|
|
756
|
-
lastUsedAt: now
|
|
757
|
-
});
|
|
758
|
-
}
|
|
759
|
-
/**
|
|
760
|
-
* Upserts one account into the legacy `__index__:<server>` entry via a
|
|
761
|
-
* read-modify-write on the index itself (not enumeration). This keeps the
|
|
762
|
-
* index correct even where the backend cannot enumerate — the platform on
|
|
763
|
-
* which the index is the actual fallback. Best-effort: any failure (notably
|
|
764
|
-
* the Windows blob-size cap) is swallowed, since enumeration is the source
|
|
765
|
-
* of truth wherever it works.
|
|
766
|
-
*/
|
|
767
|
-
async tryUpsertLegacyIndex(serverKey, entry) {
|
|
768
|
-
try {
|
|
769
|
-
const map = await this.readLegacyIndex(serverKey);
|
|
770
|
-
map.set(entry.email, entry);
|
|
771
|
-
await this.writeIndex(serverKey, [...map.values()]);
|
|
772
|
-
} catch {
|
|
773
|
-
}
|
|
774
|
-
}
|
|
775
|
-
async removeSession(serverKey, email) {
|
|
776
|
-
const sessionAccount = `${serverKey}:${email}`;
|
|
777
|
-
const removed = await this.backend.delete(SERVICE, sessionAccount);
|
|
778
|
-
await this.backend.delete(SERVICE, `${sessionAccount}:access`);
|
|
779
|
-
await this.backend.delete(SERVICE, `${sessionAccount}:refresh`);
|
|
780
|
-
if (!removed) return false;
|
|
781
|
-
let idx;
|
|
782
|
-
try {
|
|
783
|
-
idx = (await this.listSessions(serverKey)).filter((e) => e.email !== email);
|
|
784
|
-
} catch {
|
|
785
|
-
idx = [];
|
|
786
|
-
}
|
|
787
|
-
if (idx.length === 0) {
|
|
788
|
-
await this.backend.delete(SERVICE, INDEX_PREFIX + serverKey);
|
|
789
|
-
} else {
|
|
790
|
-
try {
|
|
791
|
-
await this.writeIndex(serverKey, idx);
|
|
792
|
-
} catch {
|
|
793
|
-
}
|
|
794
|
-
}
|
|
795
|
-
return true;
|
|
796
|
-
}
|
|
797
|
-
async writeIndex(serverKey, idx) {
|
|
798
|
-
const serialized = idx.map((e) => ({
|
|
799
|
-
email: e.email,
|
|
800
|
-
savedAt: e.savedAt.toISOString(),
|
|
801
|
-
lastUsedAt: e.lastUsedAt.toISOString()
|
|
802
|
-
}));
|
|
803
|
-
await this.backend.set(SERVICE, INDEX_PREFIX + serverKey, JSON.stringify(serialized));
|
|
804
|
-
}
|
|
805
|
-
};
|
|
806
|
-
function parseDate(value) {
|
|
807
|
-
if (typeof value !== "string" || value === "") return void 0;
|
|
808
|
-
const d = new Date(value);
|
|
809
|
-
return Number.isNaN(d.getTime()) ? void 0 : d;
|
|
448
|
+
// src/auth/jwt.ts
|
|
449
|
+
import { createHash } from "crypto";
|
|
450
|
+
|
|
451
|
+
// src/auth/types.ts
|
|
452
|
+
function jwtExpiringSoon(e, bufferMs) {
|
|
453
|
+
if (!e.jwtExpiresAt) return true;
|
|
454
|
+
return Date.now() + bufferMs > e.jwtExpiresAt.getTime();
|
|
810
455
|
}
|
|
811
456
|
|
|
812
457
|
// src/servers/servers.ts
|
|
@@ -888,143 +533,6 @@ function resolve2(input) {
|
|
|
888
533
|
return lookup(trimmed);
|
|
889
534
|
}
|
|
890
535
|
|
|
891
|
-
// src/auth/deviceFlow.ts
|
|
892
|
-
var CLIENT_ID = "dr-cs-cli";
|
|
893
|
-
var SCOPE = "DR-ADDIN";
|
|
894
|
-
var GRANT_TYPE = "urn:ietf:params:oauth:grant-type:";
|
|
895
|
-
async function requestDeviceCode(host, options) {
|
|
896
|
-
const base = host.replace(/\/+$/, "");
|
|
897
|
-
const body = new URLSearchParams({ client_id: CLIENT_ID, scope: SCOPE });
|
|
898
|
-
const res = await fetch(`${base}/oauth/device/code/`, {
|
|
899
|
-
method: "POST",
|
|
900
|
-
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
901
|
-
body: body.toString(),
|
|
902
|
-
signal: options?.signal
|
|
903
|
-
});
|
|
904
|
-
const text4 = await res.text();
|
|
905
|
-
if (!res.ok) {
|
|
906
|
-
throw new Error(`device/code failed: ${res.status} ${text4.trim()}`);
|
|
907
|
-
}
|
|
908
|
-
let raw;
|
|
909
|
-
try {
|
|
910
|
-
raw = JSON.parse(text4);
|
|
911
|
-
} catch (err) {
|
|
912
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
913
|
-
throw new Error(`device/code parse: ${msg}`);
|
|
914
|
-
}
|
|
915
|
-
if (raw === null || typeof raw !== "object") {
|
|
916
|
-
throw new Error(`device/code parse: expected object`);
|
|
917
|
-
}
|
|
918
|
-
const obj5 = raw;
|
|
919
|
-
return {
|
|
920
|
-
deviceCode: typeof obj5.device_code === "string" ? obj5.device_code : "",
|
|
921
|
-
userCode: typeof obj5.user_code === "string" ? obj5.user_code : "",
|
|
922
|
-
verificationUriComplete: typeof obj5.verification_uri_complete === "string" ? obj5.verification_uri_complete : "",
|
|
923
|
-
interval: typeof obj5.interval === "number" ? obj5.interval : 0
|
|
924
|
-
};
|
|
925
|
-
}
|
|
926
|
-
var defaultSleep = (ms, signal) => new Promise((resolve18, reject) => {
|
|
927
|
-
if (signal?.aborted) {
|
|
928
|
-
reject(signal.reason ?? new Error("aborted"));
|
|
929
|
-
return;
|
|
930
|
-
}
|
|
931
|
-
const t = setTimeout(resolve18, ms);
|
|
932
|
-
signal?.addEventListener(
|
|
933
|
-
"abort",
|
|
934
|
-
() => {
|
|
935
|
-
clearTimeout(t);
|
|
936
|
-
reject(signal.reason ?? new Error("aborted"));
|
|
937
|
-
},
|
|
938
|
-
{ once: true }
|
|
939
|
-
);
|
|
940
|
-
});
|
|
941
|
-
function parseTokenResponse(text4) {
|
|
942
|
-
let raw;
|
|
943
|
-
try {
|
|
944
|
-
raw = JSON.parse(text4);
|
|
945
|
-
} catch (err) {
|
|
946
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
947
|
-
throw new Error(`token parse: ${msg}`);
|
|
948
|
-
}
|
|
949
|
-
if (raw === null || typeof raw !== "object") {
|
|
950
|
-
throw new Error(`token parse: expected object`);
|
|
951
|
-
}
|
|
952
|
-
const obj5 = raw;
|
|
953
|
-
const tok = {
|
|
954
|
-
sessionId: typeof obj5.session_id === "string" ? obj5.session_id : "",
|
|
955
|
-
csrfToken: typeof obj5.csrf_token === "string" ? obj5.csrf_token : ""
|
|
956
|
-
};
|
|
957
|
-
if (typeof obj5.access_token === "string") {
|
|
958
|
-
tok.accessToken = obj5.access_token;
|
|
959
|
-
}
|
|
960
|
-
return tok;
|
|
961
|
-
}
|
|
962
|
-
function tryParseErrorCode(text4) {
|
|
963
|
-
let raw;
|
|
964
|
-
try {
|
|
965
|
-
raw = JSON.parse(text4);
|
|
966
|
-
} catch {
|
|
967
|
-
return "";
|
|
968
|
-
}
|
|
969
|
-
if (raw === null || typeof raw !== "object") return "";
|
|
970
|
-
const errVal = raw.error;
|
|
971
|
-
return typeof errVal === "string" ? errVal : "";
|
|
972
|
-
}
|
|
973
|
-
async function pollForToken(host, deviceCode, options = {}) {
|
|
974
|
-
const interval = options.interval ?? 2e3;
|
|
975
|
-
const maxWait = options.maxWait ?? 6e5;
|
|
976
|
-
const now = options.now ?? Date.now;
|
|
977
|
-
const sleep3 = options.sleep ?? defaultSleep;
|
|
978
|
-
const signal = options.signal;
|
|
979
|
-
const base = host.replace(/\/+$/, "");
|
|
980
|
-
const deadline = now() + maxWait;
|
|
981
|
-
for (; ; ) {
|
|
982
|
-
if (now() > deadline) {
|
|
983
|
-
throw new Error("device code timed out");
|
|
984
|
-
}
|
|
985
|
-
if (signal?.aborted) {
|
|
986
|
-
throw signal.reason instanceof Error ? signal.reason : new Error("aborted");
|
|
987
|
-
}
|
|
988
|
-
const body = new URLSearchParams({
|
|
989
|
-
grant_type: GRANT_TYPE,
|
|
990
|
-
client_id: CLIENT_ID,
|
|
991
|
-
device_code: deviceCode
|
|
992
|
-
});
|
|
993
|
-
const res = await fetch(`${base}/oauth/token/`, {
|
|
994
|
-
method: "POST",
|
|
995
|
-
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
996
|
-
body: body.toString(),
|
|
997
|
-
signal
|
|
998
|
-
});
|
|
999
|
-
const text4 = await res.text();
|
|
1000
|
-
if (res.ok) {
|
|
1001
|
-
const tok = parseTokenResponse(text4);
|
|
1002
|
-
if (!tok.sessionId || !tok.csrfToken) {
|
|
1003
|
-
throw new Error("token response missing session_id or csrf_token");
|
|
1004
|
-
}
|
|
1005
|
-
return tok;
|
|
1006
|
-
}
|
|
1007
|
-
const errCode = tryParseErrorCode(text4);
|
|
1008
|
-
if (errCode === "authorization_pending" || errCode === "slow_down") {
|
|
1009
|
-
await sleep3(interval, signal);
|
|
1010
|
-
continue;
|
|
1011
|
-
}
|
|
1012
|
-
if (errCode) {
|
|
1013
|
-
throw new Error(`token error: ${errCode}`);
|
|
1014
|
-
}
|
|
1015
|
-
throw new Error(`token HTTP ${res.status}: ${text4.trim()}`);
|
|
1016
|
-
}
|
|
1017
|
-
}
|
|
1018
|
-
|
|
1019
|
-
// src/auth/jwt.ts
|
|
1020
|
-
import { createHash } from "crypto";
|
|
1021
|
-
|
|
1022
|
-
// src/auth/types.ts
|
|
1023
|
-
function jwtExpiringSoon(e, bufferMs) {
|
|
1024
|
-
if (!e.jwtExpiresAt) return true;
|
|
1025
|
-
return Date.now() + bufferMs > e.jwtExpiresAt.getTime();
|
|
1026
|
-
}
|
|
1027
|
-
|
|
1028
536
|
// src/auth/errors.ts
|
|
1029
537
|
var NotLoggedInError = class extends Error {
|
|
1030
538
|
code = "ERR_NOT_LOGGED_IN";
|
|
@@ -1065,14 +573,109 @@ var LoginAsError = class _LoginAsError extends Error {
|
|
|
1065
573
|
}
|
|
1066
574
|
};
|
|
1067
575
|
|
|
1068
|
-
// src/auth/
|
|
1069
|
-
var
|
|
1070
|
-
function
|
|
1071
|
-
if (
|
|
1072
|
-
|
|
576
|
+
// src/auth/revoke.ts
|
|
577
|
+
var REVOKE_TIMEOUT_MS = 5e3;
|
|
578
|
+
async function revokeStoredCredentials(host, session) {
|
|
579
|
+
if (host === "") return [];
|
|
580
|
+
const base = host.replace(/\/+$/, "");
|
|
581
|
+
if (usesApiKey(session)) {
|
|
582
|
+
return [
|
|
583
|
+
"Note: the API key is still valid server-side until it is revoked where it was issued; only the local copy was removed."
|
|
584
|
+
];
|
|
585
|
+
}
|
|
586
|
+
const refresh = session.jwtRefresh ?? "";
|
|
587
|
+
if (refresh === "") {
|
|
588
|
+
return [
|
|
589
|
+
`Warning: no refresh token is stored for this identity, so nothing was revoked on ${base}; only the local copy was removed.`
|
|
590
|
+
];
|
|
591
|
+
}
|
|
592
|
+
const failure = await revokeRefresh(base, refresh);
|
|
593
|
+
if (failure === void 0) return [];
|
|
594
|
+
return [
|
|
595
|
+
`Warning: could not revoke the refresh token on ${base} (${failure}); it stays valid server-side until it expires.`
|
|
596
|
+
];
|
|
1073
597
|
}
|
|
1074
|
-
function
|
|
1075
|
-
|
|
598
|
+
async function revokeRefresh(base, refresh) {
|
|
599
|
+
const controller = new AbortController();
|
|
600
|
+
const timeout = setTimeout(() => controller.abort(), REVOKE_TIMEOUT_MS);
|
|
601
|
+
try {
|
|
602
|
+
const res = await fetch(`${base}/jwt/api/token/revoke/`, {
|
|
603
|
+
method: "POST",
|
|
604
|
+
headers: { "Content-Type": "application/json" },
|
|
605
|
+
body: JSON.stringify({ refresh }),
|
|
606
|
+
signal: controller.signal
|
|
607
|
+
});
|
|
608
|
+
await discardBody(res);
|
|
609
|
+
return res.status === 204 ? void 0 : `HTTP ${res.status}`;
|
|
610
|
+
} catch {
|
|
611
|
+
return controller.signal.aborted ? "timed out" : "network error";
|
|
612
|
+
} finally {
|
|
613
|
+
clearTimeout(timeout);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
async function discardBody(res) {
|
|
617
|
+
try {
|
|
618
|
+
await res.text();
|
|
619
|
+
} catch {
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
// src/auth/legacySession.ts
|
|
624
|
+
var LegacySessionRetiredError = class extends SessionExpiredError {
|
|
625
|
+
constructor(message) {
|
|
626
|
+
super(message);
|
|
627
|
+
this.name = "LegacySessionRetiredError";
|
|
628
|
+
}
|
|
629
|
+
};
|
|
630
|
+
function isLegacyCookieSession(session) {
|
|
631
|
+
return !isCookielessSession(session) && session.sessionId !== "";
|
|
632
|
+
}
|
|
633
|
+
async function retireLegacySession(store, serverKey, email, session, host, options) {
|
|
634
|
+
const revoke = options?.revoker ?? revokeStoredCredentials;
|
|
635
|
+
let notes = [];
|
|
636
|
+
if (host === "") {
|
|
637
|
+
notes = [
|
|
638
|
+
"Warning: the server for this identity is not known, so its refresh token was not revoked; it stays valid server-side until it expires."
|
|
639
|
+
];
|
|
640
|
+
} else {
|
|
641
|
+
try {
|
|
642
|
+
notes = await revoke(host, session) ?? [];
|
|
643
|
+
} catch {
|
|
644
|
+
notes = ["Warning: could not revoke the stored refresh token server-side."];
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
const local = await removeIfUnchanged(store, serverKey, email, session);
|
|
648
|
+
const revokedPart = notes.length === 0 ? "revoked its refresh token" : "could not fully revoke it (below)";
|
|
649
|
+
const localPart = local === "removed" ? "removed the local copy" : local === "kept" ? "kept the credential file for the new login to replace" : local === "replaced" ? "kept the newer login saved meanwhile" : "could not remove the local copy";
|
|
650
|
+
const lines = [
|
|
651
|
+
`${serverKey}:${email} was saved by an older dr-appspace login that used a browser session. dr-appspace now signs in with tokens only, so it ${revokedPart} and ${localPart}. Run dr-appspace login --server ${serverKey} to log in again.`,
|
|
652
|
+
...notes
|
|
653
|
+
];
|
|
654
|
+
return new LegacySessionRetiredError(lines.join("\n"));
|
|
655
|
+
}
|
|
656
|
+
async function removeIfUnchanged(store, serverKey, email, session) {
|
|
657
|
+
if (store.isCredentialFile) return "kept";
|
|
658
|
+
try {
|
|
659
|
+
const current = await store.getSession(serverKey, email);
|
|
660
|
+
if (current === void 0) return "removed";
|
|
661
|
+
if (!isLegacyCookieSession(current) || current.sessionId !== session.sessionId || current.jwtRefresh !== session.jwtRefresh) {
|
|
662
|
+
return "replaced";
|
|
663
|
+
}
|
|
664
|
+
await store.removeSession(serverKey, email);
|
|
665
|
+
return "removed";
|
|
666
|
+
} catch {
|
|
667
|
+
return "failed";
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// src/auth/jwt.ts
|
|
672
|
+
var TRUNCATE = 200;
|
|
673
|
+
function truncate(s, n) {
|
|
674
|
+
if (s.length <= n) return s;
|
|
675
|
+
return s.slice(0, n) + "\u2026";
|
|
676
|
+
}
|
|
677
|
+
function msgOf2(err) {
|
|
678
|
+
return err instanceof Error ? err.message : String(err);
|
|
1076
679
|
}
|
|
1077
680
|
function trimTrailingSlash(s) {
|
|
1078
681
|
return s.replace(/\/+$/, "");
|
|
@@ -1091,13 +694,13 @@ function decodeJwtClaims(token) {
|
|
|
1091
694
|
try {
|
|
1092
695
|
decoded = base64UrlDecode(parts[1]).toString("utf8");
|
|
1093
696
|
} catch (err) {
|
|
1094
|
-
throw new Error(`jwt: decode payload: ${
|
|
697
|
+
throw new Error(`jwt: decode payload: ${msgOf2(err)}`);
|
|
1095
698
|
}
|
|
1096
699
|
let parsed2;
|
|
1097
700
|
try {
|
|
1098
701
|
parsed2 = JSON.parse(decoded);
|
|
1099
702
|
} catch (err) {
|
|
1100
|
-
throw new Error(`jwt: parse claims: ${
|
|
703
|
+
throw new Error(`jwt: parse claims: ${msgOf2(err)}`);
|
|
1101
704
|
}
|
|
1102
705
|
if (parsed2 === null || typeof parsed2 !== "object" || Array.isArray(parsed2)) {
|
|
1103
706
|
throw new Error("jwt: parse claims: expected object");
|
|
@@ -1112,15 +715,10 @@ function decodeJwtExpiration(token) {
|
|
|
1112
715
|
}
|
|
1113
716
|
return new Date(exp * 1e3);
|
|
1114
717
|
}
|
|
1115
|
-
function parseTokenBody(text4
|
|
1116
|
-
|
|
1117
|
-
try {
|
|
1118
|
-
raw = JSON.parse(text4);
|
|
1119
|
-
} catch (err) {
|
|
1120
|
-
throw new Error(`jwt ${label} parse: ${msgOf3(err)}`);
|
|
1121
|
-
}
|
|
718
|
+
function parseTokenBody(text4) {
|
|
719
|
+
const raw = JSON.parse(text4);
|
|
1122
720
|
if (raw === null || typeof raw !== "object") {
|
|
1123
|
-
throw new Error(
|
|
721
|
+
throw new Error("expected object");
|
|
1124
722
|
}
|
|
1125
723
|
const obj5 = raw;
|
|
1126
724
|
return {
|
|
@@ -1128,62 +726,26 @@ function parseTokenBody(text4, label) {
|
|
|
1128
726
|
refresh: typeof obj5.refresh === "string" ? obj5.refresh : ""
|
|
1129
727
|
};
|
|
1130
728
|
}
|
|
1131
|
-
|
|
1132
|
-
const base = trimTrailingSlash(host);
|
|
1133
|
-
const res = await fetch(`${base}/jwt/api/token/`, {
|
|
1134
|
-
method: "POST",
|
|
1135
|
-
headers: {
|
|
1136
|
-
"Content-Type": "application/json",
|
|
1137
|
-
Cookie: `sessionid=${sessionId}; csrftoken=${csrfToken}`,
|
|
1138
|
-
"X-CSRFToken": csrfToken,
|
|
1139
|
-
Referer: `${base}/`
|
|
1140
|
-
},
|
|
1141
|
-
body: "{}",
|
|
1142
|
-
signal: options?.signal
|
|
1143
|
-
});
|
|
1144
|
-
const text4 = await res.text();
|
|
1145
|
-
if (!res.ok) {
|
|
1146
|
-
throw new Error(`jwt mint: HTTP ${res.status}: ${truncate(text4, TRUNCATE)}`);
|
|
1147
|
-
}
|
|
1148
|
-
const out = parseTokenBody(text4, "mint");
|
|
1149
|
-
if (out.access === "") {
|
|
1150
|
-
throw new Error("jwt mint: empty access token");
|
|
1151
|
-
}
|
|
1152
|
-
let expiresAt;
|
|
729
|
+
function errorCodeOf(text4) {
|
|
1153
730
|
try {
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
731
|
+
const parsed2 = JSON.parse(text4);
|
|
732
|
+
if (parsed2 === null || typeof parsed2 !== "object") return "";
|
|
733
|
+
const code = parsed2["code"];
|
|
734
|
+
return typeof code === "string" && /^[a-z_]{1,64}$/.test(code) ? code : "";
|
|
735
|
+
} catch {
|
|
736
|
+
return "";
|
|
1157
737
|
}
|
|
1158
|
-
return { access: out.access, refresh: out.refresh, expiresAt };
|
|
1159
738
|
}
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
body: JSON.stringify({ refresh: refreshToken }),
|
|
1169
|
-
signal: options?.signal
|
|
1170
|
-
});
|
|
1171
|
-
const text4 = await res.text();
|
|
1172
|
-
if (!res.ok) {
|
|
1173
|
-
throw new Error(`jwt refresh: HTTP ${res.status}: ${truncate(text4, TRUNCATE)}`);
|
|
1174
|
-
}
|
|
1175
|
-
const out = parseTokenBody(text4, "refresh");
|
|
1176
|
-
if (out.access === "") {
|
|
1177
|
-
throw new Error("jwt refresh: empty access token");
|
|
1178
|
-
}
|
|
1179
|
-
let expiresAt;
|
|
1180
|
-
try {
|
|
1181
|
-
expiresAt = decodeJwtExpiration(out.access);
|
|
1182
|
-
} catch (err) {
|
|
1183
|
-
throw new Error(`jwt refresh: ${msgOf3(err)}`);
|
|
739
|
+
var TOKEN_FAMILY_REVOKED_CODE = "token_family_revoked";
|
|
740
|
+
var RefreshRejectedError = class extends Error {
|
|
741
|
+
/** The body's `code`: `token_not_valid`, `user_inactive`, `token_family_revoked`, or ''. */
|
|
742
|
+
code;
|
|
743
|
+
constructor(message, code) {
|
|
744
|
+
super(message);
|
|
745
|
+
this.name = "RefreshRejectedError";
|
|
746
|
+
this.code = code;
|
|
1184
747
|
}
|
|
1185
|
-
|
|
1186
|
-
}
|
|
748
|
+
};
|
|
1187
749
|
async function refreshExternalJwt(host, refreshToken, options) {
|
|
1188
750
|
const base = trimTrailingSlash(host);
|
|
1189
751
|
const res = await fetch(`${base}/jwt/api/external/token/refresh/`, {
|
|
@@ -1194,9 +756,16 @@ async function refreshExternalJwt(host, refreshToken, options) {
|
|
|
1194
756
|
});
|
|
1195
757
|
const text4 = await res.text();
|
|
1196
758
|
if (!res.ok) {
|
|
1197
|
-
|
|
759
|
+
const code = errorCodeOf(text4);
|
|
760
|
+
const message = `jwt external refresh: HTTP ${res.status}${code !== "" ? ` (${code})` : ""}`;
|
|
761
|
+
throw res.status === 401 ? new RefreshRejectedError(message, code) : new Error(message);
|
|
762
|
+
}
|
|
763
|
+
let out;
|
|
764
|
+
try {
|
|
765
|
+
out = parseTokenBody(text4);
|
|
766
|
+
} catch {
|
|
767
|
+
throw new Error("jwt external refresh: the response is not a JSON object");
|
|
1198
768
|
}
|
|
1199
|
-
const out = parseTokenBody(text4, "refresh");
|
|
1200
769
|
if (out.access === "") {
|
|
1201
770
|
throw new Error("jwt external refresh: empty access token");
|
|
1202
771
|
}
|
|
@@ -1204,7 +773,7 @@ async function refreshExternalJwt(host, refreshToken, options) {
|
|
|
1204
773
|
try {
|
|
1205
774
|
expiresAt = decodeJwtExpiration(out.access);
|
|
1206
775
|
} catch (err) {
|
|
1207
|
-
throw new Error(`jwt external refresh: ${
|
|
776
|
+
throw new Error(`jwt external refresh: ${msgOf2(err)}`);
|
|
1208
777
|
}
|
|
1209
778
|
return { access: out.access, refresh: out.refresh, expiresAt };
|
|
1210
779
|
}
|
|
@@ -1218,7 +787,7 @@ async function revokeRefreshToken(host, refreshToken, options) {
|
|
|
1218
787
|
});
|
|
1219
788
|
return res.ok ? void 0 : `HTTP ${res.status}`;
|
|
1220
789
|
} catch (err) {
|
|
1221
|
-
return
|
|
790
|
+
return msgOf2(err);
|
|
1222
791
|
}
|
|
1223
792
|
}
|
|
1224
793
|
async function loginAs(host, operatorAccessToken, userId, options) {
|
|
@@ -1256,7 +825,7 @@ async function loginAs(host, operatorAccessToken, userId, options) {
|
|
|
1256
825
|
try {
|
|
1257
826
|
raw = JSON.parse(text4);
|
|
1258
827
|
} catch (err) {
|
|
1259
|
-
throw new Error(`jwt loginas parse: ${
|
|
828
|
+
throw new Error(`jwt loginas parse: ${msgOf2(err)}`);
|
|
1260
829
|
}
|
|
1261
830
|
if (raw === null || typeof raw !== "object") {
|
|
1262
831
|
throw new Error("jwt loginas parse: expected object");
|
|
@@ -1271,7 +840,7 @@ async function loginAs(host, operatorAccessToken, userId, options) {
|
|
|
1271
840
|
try {
|
|
1272
841
|
expiresAt = decodeJwtExpiration(access2);
|
|
1273
842
|
} catch (err) {
|
|
1274
|
-
throw new Error(`jwt loginas: ${
|
|
843
|
+
throw new Error(`jwt loginas: ${msgOf2(err)}`);
|
|
1275
844
|
}
|
|
1276
845
|
return { access: access2, refresh, expiresAt, user: obj5["user"] };
|
|
1277
846
|
}
|
|
@@ -1294,275 +863,1091 @@ async function exchangeApiKey(host, apiKey, options) {
|
|
|
1294
863
|
const base = trimTrailingSlash(host);
|
|
1295
864
|
const res = await fetch(`${base}/jwt/api/apikey/token/`, {
|
|
1296
865
|
method: "POST",
|
|
1297
|
-
headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
|
|
866
|
+
headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
|
|
867
|
+
signal: options?.signal
|
|
868
|
+
});
|
|
869
|
+
const text4 = await res.text();
|
|
870
|
+
if (!res.ok) {
|
|
871
|
+
let code;
|
|
872
|
+
try {
|
|
873
|
+
const value = JSON.parse(text4)["error"];
|
|
874
|
+
if (value === "invalid_key" || value === "exchange_unavailable") code = value;
|
|
875
|
+
} catch {
|
|
876
|
+
}
|
|
877
|
+
throw new Error(
|
|
878
|
+
`api-key exchange: HTTP ${res.status}${code !== void 0 ? ` (${code})` : ""}`
|
|
879
|
+
);
|
|
880
|
+
}
|
|
881
|
+
let raw;
|
|
882
|
+
try {
|
|
883
|
+
raw = JSON.parse(text4);
|
|
884
|
+
} catch {
|
|
885
|
+
throw new Error("api-key exchange parse: the response is not JSON");
|
|
886
|
+
}
|
|
887
|
+
if (raw === null || typeof raw !== "object") {
|
|
888
|
+
throw new Error("api-key exchange parse: expected object");
|
|
889
|
+
}
|
|
890
|
+
const access2 = raw["access_token"];
|
|
891
|
+
if (typeof access2 !== "string" || access2 === "") {
|
|
892
|
+
throw new Error("api-key exchange: empty access token");
|
|
893
|
+
}
|
|
894
|
+
let expiresAt;
|
|
895
|
+
try {
|
|
896
|
+
expiresAt = decodeJwtExpiration(access2);
|
|
897
|
+
} catch (err) {
|
|
898
|
+
throw new Error(`api-key exchange: ${msgOf2(err)}`);
|
|
899
|
+
}
|
|
900
|
+
return { access: access2, expiresAt };
|
|
901
|
+
}
|
|
902
|
+
function apiKeyFingerprint(apiKey) {
|
|
903
|
+
return createHash("sha256").update(apiKey.trim()).digest("hex").slice(0, 32);
|
|
904
|
+
}
|
|
905
|
+
function resolveApiKeyMaterial(session) {
|
|
906
|
+
if (session.apiKey !== void 0 && session.apiKey !== "") {
|
|
907
|
+
return { key: session.apiKey, fromEnv: false };
|
|
908
|
+
}
|
|
909
|
+
const name = session.apiKeyEnvVar;
|
|
910
|
+
if (name === void 0 || name === "") {
|
|
911
|
+
throw new Error("api-key exchange: the session carries no API key");
|
|
912
|
+
}
|
|
913
|
+
const value = process.env[name];
|
|
914
|
+
if (value === void 0 || value === "") {
|
|
915
|
+
throw new Error(
|
|
916
|
+
`api-key exchange: the credential file names environment variable ${name} as the API-key carrier, but it is unset or empty in this environment`
|
|
917
|
+
);
|
|
918
|
+
}
|
|
919
|
+
return { key: value, fromEnv: true };
|
|
920
|
+
}
|
|
921
|
+
function mintedByStoredApiKey(session) {
|
|
922
|
+
if (session.jwtAccess === void 0 || session.jwtAccess === "") return false;
|
|
923
|
+
if (session.jwtApiKeyFingerprint === void 0 || session.jwtApiKeyFingerprint === "") {
|
|
924
|
+
return false;
|
|
925
|
+
}
|
|
926
|
+
let material;
|
|
927
|
+
try {
|
|
928
|
+
material = resolveApiKeyMaterial(session);
|
|
929
|
+
} catch {
|
|
930
|
+
return false;
|
|
931
|
+
}
|
|
932
|
+
return session.jwtApiKeyFingerprint === apiKeyFingerprint(material.key);
|
|
933
|
+
}
|
|
934
|
+
async function ensureValidJwt(store, serverKey, email, options) {
|
|
935
|
+
return ensureJwt(store, serverKey, email, {
|
|
936
|
+
buffer: options?.buffer ?? 0,
|
|
937
|
+
force: false,
|
|
938
|
+
signal: options?.signal,
|
|
939
|
+
host: options?.host
|
|
940
|
+
});
|
|
941
|
+
}
|
|
942
|
+
async function forceRefreshJwt(store, serverKey, email, options) {
|
|
943
|
+
return ensureJwt(store, serverKey, email, {
|
|
944
|
+
buffer: 0,
|
|
945
|
+
force: true,
|
|
946
|
+
signal: options?.signal,
|
|
947
|
+
host: options?.host,
|
|
948
|
+
refused: options?.refused
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
var REFRESH_RUN_DEADLINE_MS = 3e4;
|
|
952
|
+
var inFlightRefreshes = /* @__PURE__ */ new Map();
|
|
953
|
+
function joinRefresh(run, signal) {
|
|
954
|
+
if (signal === void 0) return run;
|
|
955
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
956
|
+
return new Promise((resolvePromise, reject) => {
|
|
957
|
+
const onAbort = () => reject(signal.reason);
|
|
958
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
959
|
+
run.then(resolvePromise, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
async function ensureJwt(store, serverKey, email, opts) {
|
|
963
|
+
const session = await store.getSession(serverKey, email);
|
|
964
|
+
if (session === void 0) {
|
|
965
|
+
throw new NotLoggedInError(`not logged in: ${serverKey}:${email}`);
|
|
966
|
+
}
|
|
967
|
+
if (usesApiKey(session)) {
|
|
968
|
+
const host = opts.host ?? resolve2(serverKey).host;
|
|
969
|
+
return exchangeKeyedSession(store, serverKey, email, session, host, opts);
|
|
970
|
+
}
|
|
971
|
+
if (isLegacyCookieSession(session)) {
|
|
972
|
+
throw await retireLegacySession(
|
|
973
|
+
store,
|
|
974
|
+
serverKey,
|
|
975
|
+
email,
|
|
976
|
+
session,
|
|
977
|
+
opts.host ?? resolve2(serverKey).host
|
|
978
|
+
);
|
|
979
|
+
}
|
|
980
|
+
const slot = JSON.stringify([serverKey, email, slotHost(serverKey, opts.host)]);
|
|
981
|
+
const pending = inFlightRefreshes.get(slot);
|
|
982
|
+
if (pending !== void 0) {
|
|
983
|
+
const joined = await joinRefresh(pending, opts.signal);
|
|
984
|
+
if (opts.force && opts.rejoined !== true && opts.refused !== void 0 && joined.jwtAccess === opts.refused) {
|
|
985
|
+
return ensureJwt(store, serverKey, email, { ...opts, rejoined: true });
|
|
986
|
+
}
|
|
987
|
+
return joined;
|
|
988
|
+
}
|
|
989
|
+
if (answersWithoutRefresh(session, opts)) return session;
|
|
990
|
+
return startDetachedRefresh(slot, store, serverKey, email, opts);
|
|
991
|
+
}
|
|
992
|
+
function slotHost(serverKey, host) {
|
|
993
|
+
let h = host;
|
|
994
|
+
if (h === void 0) {
|
|
995
|
+
try {
|
|
996
|
+
h = resolve2(serverKey).host;
|
|
997
|
+
} catch {
|
|
998
|
+
h = "";
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
return h.replace(/\/+$/, "");
|
|
1002
|
+
}
|
|
1003
|
+
function answersWithoutRefresh(session, opts) {
|
|
1004
|
+
if (session.jwtAccess === void 0 || session.jwtAccess === "") return false;
|
|
1005
|
+
if (!opts.force) return !jwtExpiringSoon(session, opts.buffer);
|
|
1006
|
+
return opts.refused !== void 0 && session.jwtAccess !== opts.refused && !jwtExpiringSoon(session, 0);
|
|
1007
|
+
}
|
|
1008
|
+
function startDetachedRefresh(slot, store, serverKey, email, opts) {
|
|
1009
|
+
if (opts.signal?.aborted === true) return Promise.reject(opts.signal.reason);
|
|
1010
|
+
const signal = AbortSignal.timeout(REFRESH_RUN_DEADLINE_MS);
|
|
1011
|
+
const run = (async () => {
|
|
1012
|
+
const current = await store.getSession(serverKey, email);
|
|
1013
|
+
if (current === void 0) {
|
|
1014
|
+
throw new NotLoggedInError(`not logged in: ${serverKey}:${email}`);
|
|
1015
|
+
}
|
|
1016
|
+
if (usesApiKey(current)) {
|
|
1017
|
+
const host = opts.host ?? resolve2(serverKey).host;
|
|
1018
|
+
return exchangeKeyedSession(store, serverKey, email, current, host, { ...opts, signal });
|
|
1019
|
+
}
|
|
1020
|
+
if (isLegacyCookieSession(current)) {
|
|
1021
|
+
throw await retireLegacySession(
|
|
1022
|
+
store,
|
|
1023
|
+
serverKey,
|
|
1024
|
+
email,
|
|
1025
|
+
current,
|
|
1026
|
+
opts.host ?? resolve2(serverKey).host
|
|
1027
|
+
);
|
|
1028
|
+
}
|
|
1029
|
+
if (answersWithoutRefresh(current, opts)) return current;
|
|
1030
|
+
return recoverNonKeyedJwt(store, serverKey, email, current, { ...opts, signal });
|
|
1031
|
+
})();
|
|
1032
|
+
const evict = () => {
|
|
1033
|
+
if (inFlightRefreshes.get(slot) === run) inFlightRefreshes.delete(slot);
|
|
1034
|
+
};
|
|
1035
|
+
void run.then(evict, evict);
|
|
1036
|
+
inFlightRefreshes.set(slot, run);
|
|
1037
|
+
return joinRefresh(run, opts.signal);
|
|
1038
|
+
}
|
|
1039
|
+
async function recoverNonKeyedJwt(store, serverKey, email, session, opts) {
|
|
1040
|
+
const host = opts.host ?? resolve2(serverKey).host;
|
|
1041
|
+
if (session.impersonatorEmail !== void 0 && session.impersonatorEmail !== "") {
|
|
1042
|
+
return recoverImpersonatedJwt(store, serverKey, email, session, host, opts);
|
|
1043
|
+
}
|
|
1044
|
+
const refreshToken = session.jwtRefresh ?? "";
|
|
1045
|
+
if (refreshToken === "") {
|
|
1046
|
+
throw new SessionExpiredError(reloginMessage(serverKey, email, "no refresh token stored"));
|
|
1047
|
+
}
|
|
1048
|
+
if (host === "") {
|
|
1049
|
+
throw new SessionExpiredError(reloginMessage(serverKey, email, "no host to refresh against"));
|
|
1050
|
+
}
|
|
1051
|
+
let tok;
|
|
1052
|
+
try {
|
|
1053
|
+
tok = await refreshExternalJwt(host, refreshToken, { signal: opts.signal });
|
|
1054
|
+
} catch (err) {
|
|
1055
|
+
if (err instanceof RefreshRejectedError) {
|
|
1056
|
+
const why = err.code === TOKEN_FAMILY_REVOKED_CODE ? "the server revoked this login because its refresh token was used twice. If you did not run dr-appspace on another machine with this login, the token may have been copied" : `the server rejected the refresh token: ${err.message}`;
|
|
1057
|
+
throw new SessionExpiredError(reloginMessage(serverKey, email, why));
|
|
1058
|
+
}
|
|
1059
|
+
throw new Error(
|
|
1060
|
+
`${serverKey}:${email}: could not refresh the access token (${msgOf2(err)}); try again shortly, and if it keeps failing, run dr-appspace login --server ${serverKey}`,
|
|
1061
|
+
{ cause: err }
|
|
1062
|
+
);
|
|
1063
|
+
}
|
|
1064
|
+
const next = {
|
|
1065
|
+
...session,
|
|
1066
|
+
jwtAccess: tok.access,
|
|
1067
|
+
// Only rotate the refresh token when the server gave us a new one.
|
|
1068
|
+
jwtRefresh: tok.refresh !== "" ? tok.refresh : refreshToken,
|
|
1069
|
+
jwtExpiresAt: tok.expiresAt
|
|
1070
|
+
};
|
|
1071
|
+
const answer = await storeMovedOn(store, serverKey, email, session, next, host, opts);
|
|
1072
|
+
if (answer !== void 0) return answer;
|
|
1073
|
+
try {
|
|
1074
|
+
await store.saveSession(serverKey, next);
|
|
1075
|
+
} catch {
|
|
1076
|
+
try {
|
|
1077
|
+
await store.saveSession(serverKey, next);
|
|
1078
|
+
} catch (err) {
|
|
1079
|
+
throw new SessionExpiredError(
|
|
1080
|
+
reloginMessage(
|
|
1081
|
+
serverKey,
|
|
1082
|
+
email,
|
|
1083
|
+
`the refreshed tokens could not be saved (${msgOf2(err)}), and the old refresh token may be spent`
|
|
1084
|
+
)
|
|
1085
|
+
);
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
return next;
|
|
1089
|
+
}
|
|
1090
|
+
async function storeMovedOn(store, serverKey, email, startedFrom, next, host, opts) {
|
|
1091
|
+
let latest = null;
|
|
1092
|
+
for (let attempt = 0; attempt < 2 && latest === null; attempt += 1) {
|
|
1093
|
+
try {
|
|
1094
|
+
latest = await store.getSession(serverKey, email);
|
|
1095
|
+
} catch {
|
|
1096
|
+
latest = null;
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
if (latest === null) return void 0;
|
|
1100
|
+
if (latest !== void 0 && usesApiKey(startedFrom)) {
|
|
1101
|
+
if (usesApiKey(latest) && sameApiKey(latest, startedFrom)) return void 0;
|
|
1102
|
+
} else if (latest !== void 0) {
|
|
1103
|
+
const startedRefresh = startedFrom.jwtRefresh ?? "";
|
|
1104
|
+
const nextRefresh = next.jwtRefresh ?? "";
|
|
1105
|
+
const storedRefresh = latest.jwtRefresh ?? "";
|
|
1106
|
+
if (nextRefresh !== startedRefresh && sameRefreshToken(storedRefresh, nextRefresh)) {
|
|
1107
|
+
return latest;
|
|
1108
|
+
}
|
|
1109
|
+
if (!usesApiKey(latest) && (storedRefresh === startedRefresh || sameRefreshToken(storedRefresh, startedRefresh))) {
|
|
1110
|
+
return void 0;
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
await revokeStoredCredentials(host, next);
|
|
1114
|
+
if (latest === void 0) {
|
|
1115
|
+
throw new NotLoggedInError(`not logged in: ${serverKey}:${email}`);
|
|
1116
|
+
}
|
|
1117
|
+
if (isLegacyCookieSession(latest)) {
|
|
1118
|
+
throw await retireLegacySession(store, serverKey, email, latest, host);
|
|
1119
|
+
}
|
|
1120
|
+
if (usesApiKey(latest)) {
|
|
1121
|
+
return exchangeKeyedSession(store, serverKey, email, latest, host, opts);
|
|
1122
|
+
}
|
|
1123
|
+
return latest;
|
|
1124
|
+
}
|
|
1125
|
+
function sameApiKey(a, b) {
|
|
1126
|
+
return (a.apiKey ?? "") === (b.apiKey ?? "") && (a.apiKeyEnvVar ?? "") === (b.apiKeyEnvVar ?? "");
|
|
1127
|
+
}
|
|
1128
|
+
function sameRefreshToken(a, b) {
|
|
1129
|
+
if (a === "" || b === "") return false;
|
|
1130
|
+
if (a === b) return true;
|
|
1131
|
+
try {
|
|
1132
|
+
const ja = decodeJwtClaims(a)["jti"];
|
|
1133
|
+
const jb = decodeJwtClaims(b)["jti"];
|
|
1134
|
+
return typeof ja === "string" && ja !== "" && ja === jb;
|
|
1135
|
+
} catch {
|
|
1136
|
+
return false;
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
function reloginMessage(serverKey, email, why) {
|
|
1140
|
+
return `${serverKey}:${email} (${why}). Run dr-appspace login --server ${serverKey} to log in again.`;
|
|
1141
|
+
}
|
|
1142
|
+
async function exchangeKeyedSession(store, serverKey, email, session, host, opts) {
|
|
1143
|
+
if (!opts.force && mintedByStoredApiKey(session) && !jwtExpiringSoon(session, opts.buffer)) {
|
|
1144
|
+
return session;
|
|
1145
|
+
}
|
|
1146
|
+
if (host === "") {
|
|
1147
|
+
throw new SessionExpiredError(
|
|
1148
|
+
`${serverKey}:${email} (no host to exchange the API key against)`
|
|
1149
|
+
);
|
|
1150
|
+
}
|
|
1151
|
+
const material = resolveApiKeyMaterial(session);
|
|
1152
|
+
let tok;
|
|
1153
|
+
try {
|
|
1154
|
+
tok = await exchangeApiKey(host, material.key, {
|
|
1155
|
+
signal: opts.signal,
|
|
1156
|
+
opaque: material.fromEnv
|
|
1157
|
+
});
|
|
1158
|
+
} catch (err) {
|
|
1159
|
+
throw new SessionExpiredError(`${serverKey}:${email} (${msgOf2(err)})`);
|
|
1160
|
+
}
|
|
1161
|
+
const next = {
|
|
1162
|
+
...session,
|
|
1163
|
+
jwtAccess: tok.access,
|
|
1164
|
+
jwtExpiresAt: tok.expiresAt,
|
|
1165
|
+
jwtApiKeyFingerprint: apiKeyFingerprint(material.key),
|
|
1166
|
+
// An API-key identity has no refresh token; clear any stale one so the
|
|
1167
|
+
// refresh ladder is never tempted by it on a later non-keyed read.
|
|
1168
|
+
jwtRefresh: void 0
|
|
1169
|
+
};
|
|
1170
|
+
const answer = await storeMovedOn(store, serverKey, email, session, next, host, opts);
|
|
1171
|
+
if (answer !== void 0) return answer;
|
|
1172
|
+
try {
|
|
1173
|
+
await store.saveSession(serverKey, next);
|
|
1174
|
+
} catch (err) {
|
|
1175
|
+
throw new Error(`save credentials: ${msgOf2(err)}`, { cause: err });
|
|
1176
|
+
}
|
|
1177
|
+
return next;
|
|
1178
|
+
}
|
|
1179
|
+
async function recoverImpersonatedJwt(store, serverKey, email, session, host, opts) {
|
|
1180
|
+
if (session.jwtRefresh !== void 0 && session.jwtRefresh !== "" && host !== "") {
|
|
1181
|
+
let next2;
|
|
1182
|
+
try {
|
|
1183
|
+
const tok = await refreshExternalJwt(host, session.jwtRefresh, {
|
|
1184
|
+
signal: opts.signal
|
|
1185
|
+
});
|
|
1186
|
+
next2 = {
|
|
1187
|
+
...session,
|
|
1188
|
+
jwtAccess: tok.access,
|
|
1189
|
+
jwtRefresh: tok.refresh !== "" ? tok.refresh : session.jwtRefresh,
|
|
1190
|
+
jwtExpiresAt: tok.expiresAt
|
|
1191
|
+
};
|
|
1192
|
+
} catch {
|
|
1193
|
+
}
|
|
1194
|
+
if (next2 !== void 0) {
|
|
1195
|
+
const answer = await storeMovedOn(store, serverKey, email, session, next2, host, opts);
|
|
1196
|
+
if (answer !== void 0) return answer;
|
|
1197
|
+
try {
|
|
1198
|
+
await store.saveSession(serverKey, next2);
|
|
1199
|
+
return next2;
|
|
1200
|
+
} catch {
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
const operatorEmail = session.impersonatorEmail;
|
|
1205
|
+
const userId = session.impersonatedUserId;
|
|
1206
|
+
if (userId === void 0) {
|
|
1207
|
+
throw new SessionExpiredError(
|
|
1208
|
+
`${serverKey}:${email} (impersonation refresh dead and no user id stored to re-mint; re-run dr-appspace login-as)`
|
|
1209
|
+
);
|
|
1210
|
+
}
|
|
1211
|
+
const operatorStored = await store.getSession(serverKey, operatorEmail);
|
|
1212
|
+
if (operatorStored !== void 0 && (operatorStored.impersonatorEmail !== void 0 && operatorStored.impersonatorEmail !== "" || usesApiKey(operatorStored))) {
|
|
1213
|
+
throw new SessionExpiredError(
|
|
1214
|
+
`${serverKey}:${email} (operator ${operatorEmail} is no longer a direct login \u2014 re-run dr-appspace login --server ${serverKey} as ${operatorEmail}, then dr-appspace login-as)`
|
|
1215
|
+
);
|
|
1216
|
+
}
|
|
1217
|
+
let operator;
|
|
1218
|
+
try {
|
|
1219
|
+
operator = await ensureValidJwt(store, serverKey, operatorEmail, {
|
|
1220
|
+
signal: opts.signal,
|
|
1221
|
+
host
|
|
1222
|
+
});
|
|
1223
|
+
} catch (err) {
|
|
1224
|
+
throw new SessionExpiredError(
|
|
1225
|
+
`${serverKey}:${email} (operator ${operatorEmail} session expired \u2014 re-run dr-appspace login --server ${serverKey}; ${msgOf2(err)})`
|
|
1226
|
+
);
|
|
1227
|
+
}
|
|
1228
|
+
const operatorAccess = operator.jwtAccess ?? "";
|
|
1229
|
+
if (operatorAccess === "") {
|
|
1230
|
+
throw new SessionExpiredError(
|
|
1231
|
+
`${serverKey}:${email} (operator ${operatorEmail} has no JWT \u2014 re-run dr-appspace login --server ${serverKey})`
|
|
1232
|
+
);
|
|
1233
|
+
}
|
|
1234
|
+
const result = await loginAs(host, operatorAccess, userId, {
|
|
1235
|
+
prevRefresh: session.jwtRefresh,
|
|
1236
|
+
signal: opts.signal
|
|
1237
|
+
});
|
|
1238
|
+
const next = {
|
|
1239
|
+
...session,
|
|
1240
|
+
jwtAccess: result.access,
|
|
1241
|
+
jwtRefresh: result.refresh,
|
|
1242
|
+
jwtExpiresAt: result.expiresAt
|
|
1243
|
+
};
|
|
1244
|
+
try {
|
|
1245
|
+
const answer = await storeMovedOn(store, serverKey, email, session, next, host, opts);
|
|
1246
|
+
if (answer !== void 0) return answer;
|
|
1247
|
+
await store.saveSession(serverKey, next);
|
|
1248
|
+
return next;
|
|
1249
|
+
} finally {
|
|
1250
|
+
if (session.jwtRefresh !== void 0 && session.jwtRefresh !== "") {
|
|
1251
|
+
const failure = await revokeRefreshToken(host, session.jwtRefresh, { signal: opts.signal });
|
|
1252
|
+
if (failure !== void 0) {
|
|
1253
|
+
process.stderr.write(
|
|
1254
|
+
`Warning: could not revoke the previous login-as token for ${serverKey}:${email} (${failure}); it stays valid until it expires.
|
|
1255
|
+
`
|
|
1256
|
+
);
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
// src/auth/keyring/fileBackend.ts
|
|
1263
|
+
var INDEX_PREFIX = "__index__:";
|
|
1264
|
+
var FileKeyringBackend = class _FileKeyringBackend {
|
|
1265
|
+
constructor(path3) {
|
|
1266
|
+
this.path = path3;
|
|
1267
|
+
}
|
|
1268
|
+
path;
|
|
1269
|
+
load() {
|
|
1270
|
+
return readCredentialsFile(this.path);
|
|
1271
|
+
}
|
|
1272
|
+
/**
|
|
1273
|
+
* The metadata blob `KeyringStore.getSession` expects, rebuilt from the file.
|
|
1274
|
+
*
|
|
1275
|
+
* `cookieless` is derived, not stored: a file without a session cookie is
|
|
1276
|
+
* JWT-only. A file that still holds an older login's cookie loads with it,
|
|
1277
|
+
* so that the caller retires it (`legacySession.ts`); it is never sent.
|
|
1278
|
+
*/
|
|
1279
|
+
static metaBlob(creds) {
|
|
1280
|
+
const savedAt = creds.savedAt ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
1281
|
+
const sessionId = creds.sessionId ?? "";
|
|
1282
|
+
let jwtExpiresAt;
|
|
1283
|
+
if (creds.access !== void 0 && creds.access !== "") {
|
|
1284
|
+
try {
|
|
1285
|
+
jwtExpiresAt = decodeJwtExpiration(creds.access).toISOString();
|
|
1286
|
+
} catch {
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
return JSON.stringify({
|
|
1290
|
+
sessionId,
|
|
1291
|
+
csrfToken: creds.csrfToken ?? "",
|
|
1292
|
+
savedAt,
|
|
1293
|
+
lastUsedAt: savedAt,
|
|
1294
|
+
...sessionId === "" && { cookieless: true },
|
|
1295
|
+
...jwtExpiresAt !== void 0 && { jwtExpiresAt },
|
|
1296
|
+
// Carry the API-key carrier through so `KeyringStore.getSession` sees a
|
|
1297
|
+
// keyed identity and routes it to the exchange, plus the fingerprint of the
|
|
1298
|
+
// key that minted the stored `access` so a reload can tell the cached JWT
|
|
1299
|
+
// is still the current key's. Without it a file store would re-exchange on
|
|
1300
|
+
// EVERY request — `ensureFreshAuth` reloads the session each time, and
|
|
1301
|
+
// `mintedByStoredApiKey` can never match a fingerprint that was never
|
|
1302
|
+
// written. `set('meta')` persists it back below.
|
|
1303
|
+
...creds.apiKey !== void 0 && creds.apiKey !== "" && { apiKey: creds.apiKey },
|
|
1304
|
+
...creds.apiKeyEnvVar !== void 0 && creds.apiKeyEnvVar !== "" && { apiKeyEnvVar: creds.apiKeyEnvVar },
|
|
1305
|
+
...creds.accessApiKeyFingerprint !== void 0 && creds.accessApiKeyFingerprint !== "" && {
|
|
1306
|
+
jwtApiKeyFingerprint: creds.accessApiKeyFingerprint
|
|
1307
|
+
},
|
|
1308
|
+
// A v2 `dr-appspace login` (or `dr login`) marks the file it wrote, so a
|
|
1309
|
+
// later login or logout can tell it from a provisioned pair.
|
|
1310
|
+
...creds.interactiveLogin === true && { interactiveLogin: true }
|
|
1311
|
+
});
|
|
1312
|
+
}
|
|
1313
|
+
static slotOf(creds, account) {
|
|
1314
|
+
const base = `${creds.server}:${creds.email}`;
|
|
1315
|
+
if (account === base) return "meta";
|
|
1316
|
+
if (account === `${base}:access`) return "access";
|
|
1317
|
+
if (account === `${base}:refresh`) return "refresh";
|
|
1318
|
+
return void 0;
|
|
1319
|
+
}
|
|
1320
|
+
/** `creds` less the session cookie fields. */
|
|
1321
|
+
static withoutCookie(creds) {
|
|
1322
|
+
const next = { ...creds };
|
|
1323
|
+
delete next.sessionId;
|
|
1324
|
+
delete next.csrfToken;
|
|
1325
|
+
return next;
|
|
1326
|
+
}
|
|
1327
|
+
/** The interactive-login mark out of a metadata blob. */
|
|
1328
|
+
static interactiveOf(blob) {
|
|
1329
|
+
try {
|
|
1330
|
+
return JSON.parse(blob).interactiveLogin === true;
|
|
1331
|
+
} catch {
|
|
1332
|
+
return false;
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
/**
|
|
1336
|
+
* The key fingerprint out of a metadata blob (`KeyringStore` emits it as
|
|
1337
|
+
* `jwtApiKeyFingerprint`), empty when absent. Unlike the cookie it is NOT
|
|
1338
|
+
* derived, so it has to be persisted back to the file or every request
|
|
1339
|
+
* re-exchanges.
|
|
1340
|
+
*/
|
|
1341
|
+
static fingerprintOf(blob) {
|
|
1342
|
+
try {
|
|
1343
|
+
const parsed2 = JSON.parse(blob);
|
|
1344
|
+
return typeof parsed2.jwtApiKeyFingerprint === "string" ? parsed2.jwtApiKeyFingerprint : "";
|
|
1345
|
+
} catch {
|
|
1346
|
+
return "";
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
async get(_service, account) {
|
|
1350
|
+
const creds = await this.load();
|
|
1351
|
+
if (creds === void 0) return void 0;
|
|
1352
|
+
switch (_FileKeyringBackend.slotOf(creds, account)) {
|
|
1353
|
+
case "meta":
|
|
1354
|
+
return _FileKeyringBackend.metaBlob(creds);
|
|
1355
|
+
case "access":
|
|
1356
|
+
return creds.access;
|
|
1357
|
+
case "refresh":
|
|
1358
|
+
return creds.refresh;
|
|
1359
|
+
default:
|
|
1360
|
+
return void 0;
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
async set(_service, account, value) {
|
|
1364
|
+
if (account.startsWith(INDEX_PREFIX)) return;
|
|
1365
|
+
const creds = await this.load();
|
|
1366
|
+
if (creds === void 0) {
|
|
1367
|
+
throw new Error(
|
|
1368
|
+
`credential file ${this.path} disappeared while storing ${account}: nothing was persisted. Re-run the command, or \`dr-appspace login\` if the file is gone for good.`
|
|
1369
|
+
);
|
|
1370
|
+
}
|
|
1371
|
+
switch (_FileKeyringBackend.slotOf(creds, account)) {
|
|
1372
|
+
case "meta": {
|
|
1373
|
+
const interactive = _FileKeyringBackend.interactiveOf(value);
|
|
1374
|
+
const fingerprint = _FileKeyringBackend.fingerprintOf(value);
|
|
1375
|
+
if (creds.sessionId === void 0 && creds.csrfToken === void 0 && interactive === (creds.interactiveLogin === true) && fingerprint === (creds.accessApiKeyFingerprint ?? "")) {
|
|
1376
|
+
return;
|
|
1377
|
+
}
|
|
1378
|
+
const next = _FileKeyringBackend.withoutCookie(creds);
|
|
1379
|
+
if (interactive) next.interactiveLogin = true;
|
|
1380
|
+
else delete next.interactiveLogin;
|
|
1381
|
+
if (fingerprint !== "") next.accessApiKeyFingerprint = fingerprint;
|
|
1382
|
+
else delete next.accessApiKeyFingerprint;
|
|
1383
|
+
await writeCredentialsFile(this.path, next);
|
|
1384
|
+
return;
|
|
1385
|
+
}
|
|
1386
|
+
// A token write also drops an older login's cookie: no write puts one
|
|
1387
|
+
// back on disk (DR-60129).
|
|
1388
|
+
case "access":
|
|
1389
|
+
await writeCredentialsFile(this.path, { ..._FileKeyringBackend.withoutCookie(creds), access: value });
|
|
1390
|
+
return;
|
|
1391
|
+
case "refresh":
|
|
1392
|
+
await writeCredentialsFile(this.path, { ..._FileKeyringBackend.withoutCookie(creds), refresh: value });
|
|
1393
|
+
return;
|
|
1394
|
+
default:
|
|
1395
|
+
throw new Error(
|
|
1396
|
+
`credential file ${this.path} holds ${creds.server}:${creds.email} and cannot also store ${account}: it is a single-identity store. Remove that file to use the OS keychain instead.`
|
|
1397
|
+
);
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
/**
|
|
1401
|
+
* Removing the identity means removing the file — there is only one, and
|
|
1402
|
+
* clearing a single slot would leave a half-identity nothing can repair.
|
|
1403
|
+
*
|
|
1404
|
+
* Keyed off the metadata slot because `KeyringStore.removeSession` deletes
|
|
1405
|
+
* that first; the sibling deletes that follow then find nothing, which is
|
|
1406
|
+
* the correct answer. Without this `dr-appspace logout` would report success and
|
|
1407
|
+
* leave live credentials on disk.
|
|
1408
|
+
*/
|
|
1409
|
+
async delete(_service, account) {
|
|
1410
|
+
const creds = await this.load();
|
|
1411
|
+
if (creds === void 0) return false;
|
|
1412
|
+
if (_FileKeyringBackend.slotOf(creds, account) !== "meta") return false;
|
|
1413
|
+
await rm2(this.path, { force: true });
|
|
1414
|
+
return true;
|
|
1415
|
+
}
|
|
1416
|
+
async list() {
|
|
1417
|
+
const creds = await this.load();
|
|
1418
|
+
if (creds === void 0) return [];
|
|
1419
|
+
return [
|
|
1420
|
+
{
|
|
1421
|
+
account: `${creds.server}:${creds.email}`,
|
|
1422
|
+
value: _FileKeyringBackend.metaBlob(creds)
|
|
1423
|
+
}
|
|
1424
|
+
];
|
|
1425
|
+
}
|
|
1426
|
+
};
|
|
1427
|
+
|
|
1428
|
+
// src/auth/cleanupV1.ts
|
|
1429
|
+
import { promises as fs2 } from "fs";
|
|
1430
|
+
import * as path2 from "path";
|
|
1431
|
+
import * as os2 from "os";
|
|
1432
|
+
async function cleanupV1IfPresent(opts = {}) {
|
|
1433
|
+
const home = opts.home ?? os2.homedir();
|
|
1434
|
+
const log = opts.logger ?? ((m) => process.stderr.write(m + "\n"));
|
|
1435
|
+
const drDir = path2.join(home, ".dr");
|
|
1436
|
+
const filePath = path2.join(drDir, "credentials.json");
|
|
1437
|
+
try {
|
|
1438
|
+
await fs2.stat(filePath);
|
|
1439
|
+
} catch (err) {
|
|
1440
|
+
if (err.code === "ENOENT") return;
|
|
1441
|
+
log(`dr: warning: could not check ${filePath}: ${msgOf3(err)}`);
|
|
1442
|
+
return;
|
|
1443
|
+
}
|
|
1444
|
+
try {
|
|
1445
|
+
await fs2.unlink(filePath);
|
|
1446
|
+
} catch (err) {
|
|
1447
|
+
log(
|
|
1448
|
+
`dr: warning: could not remove legacy ${filePath}: ${msgOf3(err)}; please delete manually.`
|
|
1449
|
+
);
|
|
1450
|
+
return;
|
|
1451
|
+
}
|
|
1452
|
+
try {
|
|
1453
|
+
await fs2.rmdir(drDir);
|
|
1454
|
+
} catch {
|
|
1455
|
+
}
|
|
1456
|
+
log(
|
|
1457
|
+
`dr: removed legacy ${filePath} \u2014 run dr-appspace login --server <key> to re-authenticate.`
|
|
1458
|
+
);
|
|
1459
|
+
}
|
|
1460
|
+
function msgOf3(err) {
|
|
1461
|
+
return err instanceof Error ? err.message : String(err);
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
// src/auth/keyring/store.ts
|
|
1465
|
+
var SERVICE = "dr-appspace-cli";
|
|
1466
|
+
var INDEX_PREFIX2 = "__index__:";
|
|
1467
|
+
var cleanupOnce;
|
|
1468
|
+
var KeyringStore = class _KeyringStore {
|
|
1469
|
+
constructor(backend) {
|
|
1470
|
+
this.backend = backend;
|
|
1471
|
+
}
|
|
1472
|
+
backend;
|
|
1473
|
+
static default() {
|
|
1474
|
+
return new _KeyringStore(new NapiKeyringBackend());
|
|
1475
|
+
}
|
|
1476
|
+
/**
|
|
1477
|
+
* Like `default()`, but runs the one-shot legacy-file cleanup on first
|
|
1478
|
+
* call within the process. Subsequent calls re-use the cached promise and
|
|
1479
|
+
* are non-blocking once cleanup has resolved.
|
|
1480
|
+
*/
|
|
1481
|
+
static async defaultWithCleanup() {
|
|
1482
|
+
if (cleanupOnce === void 0) {
|
|
1483
|
+
cleanupOnce = cleanupV1IfPresent();
|
|
1484
|
+
}
|
|
1485
|
+
await cleanupOnce;
|
|
1486
|
+
return _KeyringStore.default();
|
|
1487
|
+
}
|
|
1488
|
+
/**
|
|
1489
|
+
* The account list is derived by enumerating the per-account keychain
|
|
1490
|
+
* entries (`<server>:<email>`), not from a monolithic index blob. The index
|
|
1491
|
+
* used to be the source of truth but grew unbounded and hit the Windows
|
|
1492
|
+
* 2560-byte per-credential cap at ~11 accounts (see design doc
|
|
1493
|
+
* 2026-07-02-keychain-index-enumerate). Enumeration scales indefinitely and
|
|
1494
|
+
* self-heals accounts a failed index write left orphaned.
|
|
1495
|
+
*
|
|
1496
|
+
* The legacy `__index__:<server>` entry is retained only to back-fill
|
|
1497
|
+
* `lastUsedAt` for accounts saved before the fix, and as a fallback when the
|
|
1498
|
+
* backend cannot enumerate (some platforms).
|
|
1499
|
+
*/
|
|
1500
|
+
async listSessions(serverKey) {
|
|
1501
|
+
const legacy = await this.readLegacyIndex(serverKey);
|
|
1502
|
+
let entries;
|
|
1503
|
+
try {
|
|
1504
|
+
entries = await this.backend.list(SERVICE);
|
|
1505
|
+
} catch {
|
|
1506
|
+
return [...legacy.values()];
|
|
1507
|
+
}
|
|
1508
|
+
const prefix = `${serverKey}:`;
|
|
1509
|
+
const out = [];
|
|
1510
|
+
for (const { account, value } of entries) {
|
|
1511
|
+
if (!account.startsWith(prefix)) continue;
|
|
1512
|
+
const rest = account.slice(prefix.length);
|
|
1513
|
+
if (rest === "" || rest.endsWith(":access") || rest.endsWith(":refresh")) continue;
|
|
1514
|
+
const email = rest;
|
|
1515
|
+
let blob;
|
|
1516
|
+
try {
|
|
1517
|
+
blob = JSON.parse(value);
|
|
1518
|
+
} catch {
|
|
1519
|
+
continue;
|
|
1520
|
+
}
|
|
1521
|
+
const savedAt = parseDate(blob.savedAt);
|
|
1522
|
+
if (savedAt === void 0) continue;
|
|
1523
|
+
const lastUsedAt = parseDate(blob.lastUsedAt) ?? legacy.get(email)?.lastUsedAt ?? savedAt;
|
|
1524
|
+
out.push({ email, savedAt, lastUsedAt });
|
|
1525
|
+
}
|
|
1526
|
+
return out;
|
|
1527
|
+
}
|
|
1528
|
+
/**
|
|
1529
|
+
* Reads the legacy `__index__:<server>` blob into an email→metadata map.
|
|
1530
|
+
* Best-effort: a missing, malformed, or non-array index yields an empty map
|
|
1531
|
+
* rather than throwing — the index is no longer authoritative.
|
|
1532
|
+
*/
|
|
1533
|
+
async readLegacyIndex(serverKey) {
|
|
1534
|
+
const out = /* @__PURE__ */ new Map();
|
|
1535
|
+
let raw;
|
|
1536
|
+
try {
|
|
1537
|
+
raw = await this.backend.get(SERVICE, INDEX_PREFIX2 + serverKey);
|
|
1538
|
+
} catch {
|
|
1539
|
+
return out;
|
|
1540
|
+
}
|
|
1541
|
+
if (raw === void 0) return out;
|
|
1542
|
+
let parsed2;
|
|
1543
|
+
try {
|
|
1544
|
+
parsed2 = JSON.parse(raw);
|
|
1545
|
+
} catch {
|
|
1546
|
+
return out;
|
|
1547
|
+
}
|
|
1548
|
+
if (!Array.isArray(parsed2)) return out;
|
|
1549
|
+
for (const item of parsed2) {
|
|
1550
|
+
const savedAt = parseDate(item?.savedAt);
|
|
1551
|
+
const lastUsedAt = parseDate(item?.lastUsedAt);
|
|
1552
|
+
if (typeof item?.email === "string" && savedAt !== void 0 && lastUsedAt !== void 0) {
|
|
1553
|
+
out.set(item.email, { email: item.email, savedAt, lastUsedAt });
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
return out;
|
|
1557
|
+
}
|
|
1558
|
+
/**
|
|
1559
|
+
* Returns the session for `(serverKey, email)`. Returns undefined if no
|
|
1560
|
+
* entry exists.
|
|
1561
|
+
*
|
|
1562
|
+
* `email` is the lookup key — the stored blob does not carry it. The
|
|
1563
|
+
* returned `Session.email` is populated from the argument, not from the
|
|
1564
|
+
* keychain. This avoids denormalising the identity across the key and
|
|
1565
|
+
* the value.
|
|
1566
|
+
*
|
|
1567
|
+
* Storage layout (see `saveSession`): the JWT bodies live in sibling
|
|
1568
|
+
* entries (`:access`, `:refresh`) so each individual blob fits under the
|
|
1569
|
+
* Windows Credential Manager 2560-byte (UTF-16) per-credential limit.
|
|
1570
|
+
* This method reassembles the full Session by reading all three.
|
|
1571
|
+
*/
|
|
1572
|
+
async getSession(serverKey, email) {
|
|
1573
|
+
const sessionAccount = `${serverKey}:${email}`;
|
|
1574
|
+
const raw = await this.backend.get(SERVICE, sessionAccount);
|
|
1575
|
+
if (raw === void 0) return void 0;
|
|
1576
|
+
let parsed2;
|
|
1577
|
+
try {
|
|
1578
|
+
parsed2 = JSON.parse(raw);
|
|
1579
|
+
} catch (err) {
|
|
1580
|
+
throw new KeychainError(`decode session for ${serverKey}:${email}`, {
|
|
1581
|
+
cause: err
|
|
1582
|
+
});
|
|
1583
|
+
}
|
|
1584
|
+
const sessionId = typeof parsed2.sessionId === "string" ? parsed2.sessionId : "";
|
|
1585
|
+
const csrfToken = typeof parsed2.csrfToken === "string" ? parsed2.csrfToken : "";
|
|
1586
|
+
const savedAtStr = typeof parsed2.savedAt === "string" ? parsed2.savedAt : "";
|
|
1587
|
+
const impersonatorEmail = typeof parsed2.impersonatorEmail === "string" ? parsed2.impersonatorEmail : "";
|
|
1588
|
+
const impersonated = impersonatorEmail !== "";
|
|
1589
|
+
const cookielessFlag = parsed2.cookieless === true;
|
|
1590
|
+
const apiKey = typeof parsed2.apiKey === "string" && parsed2.apiKey !== "" ? parsed2.apiKey : "";
|
|
1591
|
+
const apiKeyEnvVar = typeof parsed2.apiKeyEnvVar === "string" && parsed2.apiKeyEnvVar !== "" ? parsed2.apiKeyEnvVar : "";
|
|
1592
|
+
const keyed = apiKey !== "" || apiKeyEnvVar !== "";
|
|
1593
|
+
const cookieless = impersonated || cookielessFlag || keyed;
|
|
1594
|
+
const halfCookie = sessionId === "" !== (csrfToken === "");
|
|
1595
|
+
if (savedAtStr === "" || halfCookie || !cookieless && sessionId === "") {
|
|
1596
|
+
throw new KeychainError(`session for ${serverKey}:${email} is malformed`);
|
|
1597
|
+
}
|
|
1598
|
+
const session = {
|
|
1599
|
+
email,
|
|
1600
|
+
sessionId: cookieless ? "" : sessionId,
|
|
1601
|
+
csrfToken: cookieless ? "" : csrfToken,
|
|
1602
|
+
savedAt: new Date(savedAtStr)
|
|
1603
|
+
};
|
|
1604
|
+
if (impersonated) {
|
|
1605
|
+
session.impersonatorEmail = impersonatorEmail;
|
|
1606
|
+
if (typeof parsed2.impersonatedUserId === "number") {
|
|
1607
|
+
session.impersonatedUserId = parsed2.impersonatedUserId;
|
|
1608
|
+
}
|
|
1609
|
+
if (typeof parsed2.impersonatedOrgName === "string" && parsed2.impersonatedOrgName !== "") {
|
|
1610
|
+
session.impersonatedOrgName = parsed2.impersonatedOrgName;
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
if (cookielessFlag) {
|
|
1614
|
+
session.cookieless = true;
|
|
1615
|
+
}
|
|
1616
|
+
if (parsed2.interactiveLogin === true) {
|
|
1617
|
+
session.interactiveLogin = true;
|
|
1618
|
+
}
|
|
1619
|
+
if (apiKey !== "") {
|
|
1620
|
+
session.apiKey = apiKey;
|
|
1621
|
+
}
|
|
1622
|
+
if (apiKeyEnvVar !== "") {
|
|
1623
|
+
session.apiKeyEnvVar = apiKeyEnvVar;
|
|
1624
|
+
}
|
|
1625
|
+
if (typeof parsed2.apiKeyExpiresAt === "string" && parsed2.apiKeyExpiresAt !== "") {
|
|
1626
|
+
session.apiKeyExpiresAt = new Date(parsed2.apiKeyExpiresAt);
|
|
1627
|
+
}
|
|
1628
|
+
if (typeof parsed2.jwtApiKeyFingerprint === "string" && parsed2.jwtApiKeyFingerprint !== "") {
|
|
1629
|
+
session.jwtApiKeyFingerprint = parsed2.jwtApiKeyFingerprint;
|
|
1630
|
+
}
|
|
1631
|
+
if (typeof parsed2.jwtExpiresAt === "string" && parsed2.jwtExpiresAt !== "") {
|
|
1632
|
+
session.jwtExpiresAt = new Date(parsed2.jwtExpiresAt);
|
|
1633
|
+
}
|
|
1634
|
+
const jwtAccess = await this.backend.get(SERVICE, `${sessionAccount}:access`);
|
|
1635
|
+
if (jwtAccess !== void 0 && jwtAccess !== "") {
|
|
1636
|
+
session.jwtAccess = jwtAccess;
|
|
1637
|
+
}
|
|
1638
|
+
const jwtRefresh = await this.backend.get(SERVICE, `${sessionAccount}:refresh`);
|
|
1639
|
+
if (jwtRefresh !== void 0 && jwtRefresh !== "") {
|
|
1640
|
+
session.jwtRefresh = jwtRefresh;
|
|
1641
|
+
}
|
|
1642
|
+
return session;
|
|
1643
|
+
}
|
|
1644
|
+
/**
|
|
1645
|
+
* Writes the per-account entries for `(serverKey, session.email)` and
|
|
1646
|
+
* refreshes the legacy index best-effort. Overwrites any existing entry for
|
|
1647
|
+
* the same identity.
|
|
1648
|
+
*
|
|
1649
|
+
* `session.email` is used to derive the keychain account name but is NOT
|
|
1650
|
+
* stored inside the session blob — the (server, email) pair is already
|
|
1651
|
+
* encoded in the keychain account key. `getSession` re-seeds the returned
|
|
1652
|
+
* `Session.email` from its argument.
|
|
1653
|
+
*
|
|
1654
|
+
* Storage layout: three sibling keychain entries per identity, because
|
|
1655
|
+
* Windows Credential Manager caps each blob at 2560 bytes UTF-16
|
|
1656
|
+
* (~1280 ASCII chars) and a real session with two JWTs is 3-4 KB total.
|
|
1657
|
+
* - `<server>:<email>` → metadata (savedAt, lastUsedAt, exp, markers)
|
|
1658
|
+
* - `<server>:<email>:access` → access JWT body
|
|
1659
|
+
* - `<server>:<email>:refresh` → refresh JWT body
|
|
1660
|
+
* Each piece fits comfortably under the limit; the metadata blob is
|
|
1661
|
+
* ~200 bytes, and Datarails JWTs are typically 800-1500 chars each.
|
|
1662
|
+
* If a JWT ever exceeds ~1280 chars on its own, the underlying backend
|
|
1663
|
+
* surfaces a clear "longer than the platform limit" error.
|
|
1664
|
+
*/
|
|
1665
|
+
async saveSession(serverKey, session) {
|
|
1666
|
+
if (session.email === "") {
|
|
1667
|
+
throw new Error("saveSession: email must not be empty");
|
|
1668
|
+
}
|
|
1669
|
+
const impersonated = session.impersonatorEmail !== void 0 && session.impersonatorEmail !== "";
|
|
1670
|
+
const cookieless = session.cookieless === true;
|
|
1671
|
+
if (session.sessionId !== "" || session.csrfToken !== "") {
|
|
1672
|
+
throw new Error("saveSession: a session cookie is never stored (JWT-only)");
|
|
1673
|
+
}
|
|
1674
|
+
if (!isCookielessSession(session)) {
|
|
1675
|
+
throw new Error(
|
|
1676
|
+
"saveSession: the session must be JWT-only (cookieless, impersonated or keyed)"
|
|
1677
|
+
);
|
|
1678
|
+
}
|
|
1679
|
+
if (!usesApiKey(session) && (session.jwtAccess === void 0 || session.jwtAccess === "")) {
|
|
1680
|
+
throw new Error("saveSession: cookie-less session must have a jwtAccess token");
|
|
1681
|
+
}
|
|
1682
|
+
const sessionAccount = `${serverKey}:${session.email}`;
|
|
1683
|
+
const now = /* @__PURE__ */ new Date();
|
|
1684
|
+
const metaBlob = {
|
|
1685
|
+
savedAt: session.savedAt.toISOString(),
|
|
1686
|
+
lastUsedAt: now.toISOString()
|
|
1687
|
+
};
|
|
1688
|
+
if (session.jwtExpiresAt !== void 0) {
|
|
1689
|
+
metaBlob.jwtExpiresAt = session.jwtExpiresAt.toISOString();
|
|
1690
|
+
}
|
|
1691
|
+
if (impersonated) {
|
|
1692
|
+
metaBlob.impersonatorEmail = session.impersonatorEmail;
|
|
1693
|
+
if (session.impersonatedUserId !== void 0) {
|
|
1694
|
+
metaBlob.impersonatedUserId = session.impersonatedUserId;
|
|
1695
|
+
}
|
|
1696
|
+
if (session.impersonatedOrgName !== void 0 && session.impersonatedOrgName !== "") {
|
|
1697
|
+
metaBlob.impersonatedOrgName = session.impersonatedOrgName;
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
if (cookieless) {
|
|
1701
|
+
metaBlob.cookieless = true;
|
|
1702
|
+
}
|
|
1703
|
+
if (session.interactiveLogin === true) {
|
|
1704
|
+
metaBlob.interactiveLogin = true;
|
|
1705
|
+
}
|
|
1706
|
+
if (session.apiKey !== void 0 && session.apiKey !== "") {
|
|
1707
|
+
metaBlob.apiKey = session.apiKey;
|
|
1708
|
+
}
|
|
1709
|
+
if (session.apiKeyEnvVar !== void 0 && session.apiKeyEnvVar !== "") {
|
|
1710
|
+
metaBlob.apiKeyEnvVar = session.apiKeyEnvVar;
|
|
1711
|
+
}
|
|
1712
|
+
if (session.apiKeyExpiresAt !== void 0) {
|
|
1713
|
+
metaBlob.apiKeyExpiresAt = session.apiKeyExpiresAt.toISOString();
|
|
1714
|
+
}
|
|
1715
|
+
if (session.jwtApiKeyFingerprint !== void 0 && session.jwtApiKeyFingerprint !== "") {
|
|
1716
|
+
metaBlob.jwtApiKeyFingerprint = session.jwtApiKeyFingerprint;
|
|
1717
|
+
}
|
|
1718
|
+
if (session.jwtRefresh !== void 0 && session.jwtRefresh !== "") {
|
|
1719
|
+
await this.backend.set(SERVICE, `${sessionAccount}:refresh`, session.jwtRefresh);
|
|
1720
|
+
} else {
|
|
1721
|
+
await this.backend.delete(SERVICE, `${sessionAccount}:refresh`);
|
|
1722
|
+
}
|
|
1723
|
+
if (session.jwtAccess !== void 0 && session.jwtAccess !== "") {
|
|
1724
|
+
await this.backend.set(SERVICE, `${sessionAccount}:access`, session.jwtAccess);
|
|
1725
|
+
} else {
|
|
1726
|
+
await this.backend.delete(SERVICE, `${sessionAccount}:access`);
|
|
1727
|
+
}
|
|
1728
|
+
await this.backend.set(SERVICE, sessionAccount, JSON.stringify(metaBlob));
|
|
1729
|
+
await this.tryUpsertLegacyIndex(serverKey, {
|
|
1730
|
+
email: session.email,
|
|
1731
|
+
savedAt: session.savedAt,
|
|
1732
|
+
lastUsedAt: now
|
|
1733
|
+
});
|
|
1734
|
+
}
|
|
1735
|
+
async touch(serverKey, email) {
|
|
1736
|
+
const sessionAccount = `${serverKey}:${email}`;
|
|
1737
|
+
const raw = await this.backend.get(SERVICE, sessionAccount);
|
|
1738
|
+
if (raw === void 0) return;
|
|
1739
|
+
let blob;
|
|
1740
|
+
try {
|
|
1741
|
+
blob = JSON.parse(raw);
|
|
1742
|
+
} catch {
|
|
1743
|
+
return;
|
|
1744
|
+
}
|
|
1745
|
+
const now = /* @__PURE__ */ new Date();
|
|
1746
|
+
blob.lastUsedAt = now.toISOString();
|
|
1747
|
+
const cookieless = blob.cookieless === true || typeof blob.impersonatorEmail === "string" && blob.impersonatorEmail !== "" || typeof blob.apiKey === "string" && blob.apiKey !== "" || typeof blob.apiKeyEnvVar === "string" && blob.apiKeyEnvVar !== "";
|
|
1748
|
+
if (cookieless) {
|
|
1749
|
+
delete blob.sessionId;
|
|
1750
|
+
delete blob.csrfToken;
|
|
1751
|
+
}
|
|
1752
|
+
await this.backend.set(SERVICE, sessionAccount, JSON.stringify(blob));
|
|
1753
|
+
const savedAt = parseDate(blob.savedAt) ?? now;
|
|
1754
|
+
await this.tryUpsertLegacyIndex(serverKey, {
|
|
1755
|
+
email,
|
|
1756
|
+
savedAt,
|
|
1757
|
+
lastUsedAt: now
|
|
1758
|
+
});
|
|
1759
|
+
}
|
|
1760
|
+
/**
|
|
1761
|
+
* Upserts one account into the legacy `__index__:<server>` entry via a
|
|
1762
|
+
* read-modify-write on the index itself (not enumeration). This keeps the
|
|
1763
|
+
* index correct even where the backend cannot enumerate — the platform on
|
|
1764
|
+
* which the index is the actual fallback. Best-effort: any failure (notably
|
|
1765
|
+
* the Windows blob-size cap) is swallowed, since enumeration is the source
|
|
1766
|
+
* of truth wherever it works.
|
|
1767
|
+
*/
|
|
1768
|
+
async tryUpsertLegacyIndex(serverKey, entry) {
|
|
1769
|
+
try {
|
|
1770
|
+
const map = await this.readLegacyIndex(serverKey);
|
|
1771
|
+
map.set(entry.email, entry);
|
|
1772
|
+
await this.writeIndex(serverKey, [...map.values()]);
|
|
1773
|
+
} catch {
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
/**
|
|
1777
|
+
* True when this store is a credential file (`DR_CREDENTIALS_FILE`): one
|
|
1778
|
+
* identity, and removing it deletes the file.
|
|
1779
|
+
*/
|
|
1780
|
+
get isCredentialFile() {
|
|
1781
|
+
return this.backend instanceof FileKeyringBackend;
|
|
1782
|
+
}
|
|
1783
|
+
async removeSession(serverKey, email) {
|
|
1784
|
+
const sessionAccount = `${serverKey}:${email}`;
|
|
1785
|
+
const removed = await this.backend.delete(SERVICE, sessionAccount);
|
|
1786
|
+
await this.backend.delete(SERVICE, `${sessionAccount}:access`);
|
|
1787
|
+
await this.backend.delete(SERVICE, `${sessionAccount}:refresh`);
|
|
1788
|
+
if (!removed) return false;
|
|
1789
|
+
let idx;
|
|
1790
|
+
try {
|
|
1791
|
+
idx = (await this.listSessions(serverKey)).filter((e) => e.email !== email);
|
|
1792
|
+
} catch {
|
|
1793
|
+
idx = [];
|
|
1794
|
+
}
|
|
1795
|
+
if (idx.length === 0) {
|
|
1796
|
+
await this.backend.delete(SERVICE, INDEX_PREFIX2 + serverKey);
|
|
1797
|
+
} else {
|
|
1798
|
+
try {
|
|
1799
|
+
await this.writeIndex(serverKey, idx);
|
|
1800
|
+
} catch {
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
return true;
|
|
1804
|
+
}
|
|
1805
|
+
async writeIndex(serverKey, idx) {
|
|
1806
|
+
const serialized = idx.map((e) => ({
|
|
1807
|
+
email: e.email,
|
|
1808
|
+
savedAt: e.savedAt.toISOString(),
|
|
1809
|
+
lastUsedAt: e.lastUsedAt.toISOString()
|
|
1810
|
+
}));
|
|
1811
|
+
await this.backend.set(SERVICE, INDEX_PREFIX2 + serverKey, JSON.stringify(serialized));
|
|
1812
|
+
}
|
|
1813
|
+
};
|
|
1814
|
+
function parseDate(value) {
|
|
1815
|
+
if (typeof value !== "string" || value === "") return void 0;
|
|
1816
|
+
const d = new Date(value);
|
|
1817
|
+
return Number.isNaN(d.getTime()) ? void 0 : d;
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
// src/auth/deviceFlow.ts
|
|
1821
|
+
var CLIENT_ID = "dr-cs-cli";
|
|
1822
|
+
var V2_SCOPE = "DR-CLI";
|
|
1823
|
+
var PATHS = { code: "/oauth/v2/device/code/", token: "/oauth/v2/token/" };
|
|
1824
|
+
var GRANT_TYPE = "urn:ietf:params:oauth:grant-type:";
|
|
1825
|
+
async function requestDeviceCode(host, options) {
|
|
1826
|
+
const base = host.replace(/\/+$/, "");
|
|
1827
|
+
const body = new URLSearchParams({ client_id: CLIENT_ID, scope: V2_SCOPE });
|
|
1828
|
+
const res = await fetch(`${base}${PATHS.code}`, {
|
|
1829
|
+
method: "POST",
|
|
1830
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
1831
|
+
body: body.toString(),
|
|
1298
1832
|
signal: options?.signal
|
|
1299
1833
|
});
|
|
1300
1834
|
const text4 = await res.text();
|
|
1301
1835
|
if (!res.ok) {
|
|
1302
|
-
let
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1836
|
+
let hint = "";
|
|
1837
|
+
if (res.status === 429) {
|
|
1838
|
+
hint = " (too many logins from this address: wait a minute and run `dr-appspace login` again)";
|
|
1839
|
+
} else if (res.status === 404) {
|
|
1840
|
+
hint = " (this server does not serve the v2 device flow, which dr-appspace requires)";
|
|
1307
1841
|
}
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
);
|
|
1842
|
+
const code = tryParseErrorCode(text4);
|
|
1843
|
+
throw new Error(`device/code failed: ${res.status}${code !== "" ? ` (${code})` : ""}${hint}`);
|
|
1311
1844
|
}
|
|
1312
1845
|
let raw;
|
|
1313
1846
|
try {
|
|
1314
1847
|
raw = JSON.parse(text4);
|
|
1315
1848
|
} catch {
|
|
1316
|
-
throw new Error("
|
|
1849
|
+
throw new Error("device/code parse: the response is not JSON");
|
|
1317
1850
|
}
|
|
1318
1851
|
if (raw === null || typeof raw !== "object") {
|
|
1319
|
-
throw new Error(
|
|
1320
|
-
}
|
|
1321
|
-
const access2 = raw["access_token"];
|
|
1322
|
-
if (typeof access2 !== "string" || access2 === "") {
|
|
1323
|
-
throw new Error("api-key exchange: empty access token");
|
|
1324
|
-
}
|
|
1325
|
-
let expiresAt;
|
|
1326
|
-
try {
|
|
1327
|
-
expiresAt = decodeJwtExpiration(access2);
|
|
1328
|
-
} catch (err) {
|
|
1329
|
-
throw new Error(`api-key exchange: ${msgOf3(err)}`);
|
|
1852
|
+
throw new Error(`device/code parse: expected object`);
|
|
1330
1853
|
}
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1854
|
+
const obj5 = raw;
|
|
1855
|
+
return {
|
|
1856
|
+
deviceCode: typeof obj5.device_code === "string" ? obj5.device_code : "",
|
|
1857
|
+
userCode: typeof obj5.user_code === "string" ? obj5.user_code : "",
|
|
1858
|
+
verificationUriComplete: typeof obj5.verification_uri_complete === "string" ? obj5.verification_uri_complete : "",
|
|
1859
|
+
interval: typeof obj5.interval === "number" ? obj5.interval : 0
|
|
1860
|
+
};
|
|
1335
1861
|
}
|
|
1336
|
-
|
|
1337
|
-
if (
|
|
1338
|
-
|
|
1862
|
+
var defaultSleep = (ms, signal) => new Promise((resolve18, reject) => {
|
|
1863
|
+
if (signal?.aborted) {
|
|
1864
|
+
reject(signal.reason ?? new Error("aborted"));
|
|
1865
|
+
return;
|
|
1339
1866
|
}
|
|
1340
|
-
const
|
|
1341
|
-
|
|
1342
|
-
|
|
1867
|
+
const t = setTimeout(resolve18, ms);
|
|
1868
|
+
signal?.addEventListener(
|
|
1869
|
+
"abort",
|
|
1870
|
+
() => {
|
|
1871
|
+
clearTimeout(t);
|
|
1872
|
+
reject(signal.reason ?? new Error("aborted"));
|
|
1873
|
+
},
|
|
1874
|
+
{ once: true }
|
|
1875
|
+
);
|
|
1876
|
+
});
|
|
1877
|
+
function parseObject(text4) {
|
|
1878
|
+
let raw;
|
|
1879
|
+
try {
|
|
1880
|
+
raw = JSON.parse(text4);
|
|
1881
|
+
} catch {
|
|
1882
|
+
throw new Error("token parse: the response is not JSON");
|
|
1343
1883
|
}
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
throw new Error(
|
|
1347
|
-
`api-key exchange: the credential file names environment variable ${name} as the API-key carrier, but it is unset or empty in this environment`
|
|
1348
|
-
);
|
|
1884
|
+
if (raw === null || typeof raw !== "object") {
|
|
1885
|
+
throw new Error(`token parse: expected object`);
|
|
1349
1886
|
}
|
|
1350
|
-
return
|
|
1887
|
+
return raw;
|
|
1351
1888
|
}
|
|
1352
|
-
function
|
|
1353
|
-
|
|
1354
|
-
if (session.jwtApiKeyFingerprint === void 0 || session.jwtApiKeyFingerprint === "") {
|
|
1355
|
-
return false;
|
|
1356
|
-
}
|
|
1357
|
-
let material;
|
|
1889
|
+
function tryParseErrorCode(text4) {
|
|
1890
|
+
let raw;
|
|
1358
1891
|
try {
|
|
1359
|
-
|
|
1892
|
+
raw = JSON.parse(text4);
|
|
1360
1893
|
} catch {
|
|
1361
|
-
return
|
|
1894
|
+
return "";
|
|
1362
1895
|
}
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
return ensureJwt(store, serverKey, email, {
|
|
1367
|
-
buffer: options?.buffer ?? 0,
|
|
1368
|
-
force: false,
|
|
1369
|
-
signal: options?.signal,
|
|
1370
|
-
host: options?.host
|
|
1371
|
-
});
|
|
1372
|
-
}
|
|
1373
|
-
async function forceRefreshJwt(store, serverKey, email, options) {
|
|
1374
|
-
return ensureJwt(store, serverKey, email, {
|
|
1375
|
-
buffer: 0,
|
|
1376
|
-
force: true,
|
|
1377
|
-
signal: options?.signal,
|
|
1378
|
-
host: options?.host
|
|
1379
|
-
});
|
|
1896
|
+
if (raw === null || typeof raw !== "object") return "";
|
|
1897
|
+
const errVal = raw.error;
|
|
1898
|
+
return typeof errVal === "string" && /^[a-z_]{1,64}$/.test(errVal) ? errVal : "";
|
|
1380
1899
|
}
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
}
|
|
1397
|
-
let refreshErr = null;
|
|
1398
|
-
let mintErr = null;
|
|
1399
|
-
let refreshNext;
|
|
1400
|
-
if (session.jwtRefresh !== void 0 && session.jwtRefresh !== "" && host !== "") {
|
|
1401
|
-
try {
|
|
1402
|
-
const refresh = session.cookieless === true ? refreshExternalJwt : refreshJwt;
|
|
1403
|
-
const tok = await refresh(host, session.jwtRefresh, {
|
|
1404
|
-
signal: opts.signal
|
|
1405
|
-
});
|
|
1406
|
-
refreshNext = {
|
|
1407
|
-
...session,
|
|
1408
|
-
jwtAccess: tok.access,
|
|
1409
|
-
// Only rotate the refresh token when the server gave us a new one.
|
|
1410
|
-
jwtRefresh: tok.refresh !== "" ? tok.refresh : session.jwtRefresh,
|
|
1411
|
-
jwtExpiresAt: tok.expiresAt
|
|
1412
|
-
};
|
|
1413
|
-
} catch (err) {
|
|
1414
|
-
refreshErr = err;
|
|
1415
|
-
}
|
|
1416
|
-
}
|
|
1417
|
-
if (refreshNext !== void 0) {
|
|
1418
|
-
try {
|
|
1419
|
-
await store.saveSession(serverKey, refreshNext);
|
|
1420
|
-
} catch (err) {
|
|
1421
|
-
throw new Error(`save credentials: ${msgOf3(err)}`, { cause: err });
|
|
1422
|
-
}
|
|
1423
|
-
return refreshNext;
|
|
1424
|
-
}
|
|
1425
|
-
let mintNext;
|
|
1426
|
-
if (session.sessionId !== "" && host !== "") {
|
|
1427
|
-
try {
|
|
1428
|
-
const tok = await mintJwt(host, session.sessionId, session.csrfToken, {
|
|
1429
|
-
signal: opts.signal
|
|
1430
|
-
});
|
|
1431
|
-
mintNext = {
|
|
1432
|
-
...session,
|
|
1433
|
-
jwtAccess: tok.access,
|
|
1434
|
-
jwtRefresh: tok.refresh,
|
|
1435
|
-
jwtExpiresAt: tok.expiresAt
|
|
1436
|
-
};
|
|
1437
|
-
} catch (err) {
|
|
1438
|
-
mintErr = err;
|
|
1900
|
+
var V2_TERMINAL_HINTS = {
|
|
1901
|
+
access_denied: " (the login was refused, expired, or already used: run `dr-appspace login` again)",
|
|
1902
|
+
token_issuance_failed: " (the server could not issue the token: run `dr-appspace login` again to start a new login)"
|
|
1903
|
+
};
|
|
1904
|
+
async function pollForV2Token(host, deviceCode, options = {}) {
|
|
1905
|
+
const interval = options.interval ?? 2e3;
|
|
1906
|
+
const maxWait = options.maxWait ?? 6e5;
|
|
1907
|
+
const now = options.now ?? Date.now;
|
|
1908
|
+
const sleep3 = options.sleep ?? defaultSleep;
|
|
1909
|
+
const signal = options.signal;
|
|
1910
|
+
const base = host.replace(/\/+$/, "");
|
|
1911
|
+
const deadline = now() + maxWait;
|
|
1912
|
+
for (; ; ) {
|
|
1913
|
+
if (now() > deadline) {
|
|
1914
|
+
throw new Error("device code timed out");
|
|
1439
1915
|
}
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
try {
|
|
1443
|
-
await store.saveSession(serverKey, mintNext);
|
|
1444
|
-
} catch (err) {
|
|
1445
|
-
throw new Error(`save credentials: ${msgOf3(err)}`, { cause: err });
|
|
1916
|
+
if (signal?.aborted) {
|
|
1917
|
+
throw signal.reason instanceof Error ? signal.reason : new Error("aborted");
|
|
1446
1918
|
}
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
reasons.push("no refresh token stored");
|
|
1452
|
-
} else if (refreshErr !== null) {
|
|
1453
|
-
reasons.push(`refresh failed: ${msgOf3(refreshErr)}`);
|
|
1454
|
-
}
|
|
1455
|
-
if (session.sessionId === "") {
|
|
1456
|
-
reasons.push("no session cookie stored");
|
|
1457
|
-
} else if (mintErr !== null) {
|
|
1458
|
-
reasons.push(`mint-via-session failed: ${msgOf3(mintErr)}`);
|
|
1459
|
-
}
|
|
1460
|
-
const detail = reasons.length > 0 ? reasons.join("; ") : "no recovery path available";
|
|
1461
|
-
throw new SessionExpiredError(`${serverKey}:${email} (${detail})`);
|
|
1462
|
-
}
|
|
1463
|
-
async function exchangeKeyedSession(store, serverKey, email, session, host, opts) {
|
|
1464
|
-
if (!opts.force && mintedByStoredApiKey(session) && !jwtExpiringSoon(session, opts.buffer)) {
|
|
1465
|
-
return session;
|
|
1466
|
-
}
|
|
1467
|
-
if (host === "") {
|
|
1468
|
-
throw new SessionExpiredError(
|
|
1469
|
-
`${serverKey}:${email} (no host to exchange the API key against)`
|
|
1470
|
-
);
|
|
1471
|
-
}
|
|
1472
|
-
const material = resolveApiKeyMaterial(session);
|
|
1473
|
-
let tok;
|
|
1474
|
-
try {
|
|
1475
|
-
tok = await exchangeApiKey(host, material.key, {
|
|
1476
|
-
signal: opts.signal,
|
|
1477
|
-
opaque: material.fromEnv
|
|
1919
|
+
const body = new URLSearchParams({
|
|
1920
|
+
grant_type: GRANT_TYPE,
|
|
1921
|
+
client_id: CLIENT_ID,
|
|
1922
|
+
device_code: deviceCode
|
|
1478
1923
|
});
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
jwtAccess: tok.access,
|
|
1485
|
-
jwtExpiresAt: tok.expiresAt,
|
|
1486
|
-
jwtApiKeyFingerprint: apiKeyFingerprint(material.key),
|
|
1487
|
-
// An API-key identity has no refresh token; clear any stale one so the
|
|
1488
|
-
// refresh ladder is never tempted by it on a later non-keyed read.
|
|
1489
|
-
jwtRefresh: void 0
|
|
1490
|
-
};
|
|
1491
|
-
try {
|
|
1492
|
-
await store.saveSession(serverKey, next);
|
|
1493
|
-
} catch (err) {
|
|
1494
|
-
throw new Error(`save credentials: ${msgOf3(err)}`, { cause: err });
|
|
1495
|
-
}
|
|
1496
|
-
return next;
|
|
1497
|
-
}
|
|
1498
|
-
async function recoverImpersonatedJwt(store, serverKey, email, session, host, opts) {
|
|
1499
|
-
if (session.jwtRefresh !== void 0 && session.jwtRefresh !== "" && host !== "") {
|
|
1500
|
-
try {
|
|
1501
|
-
const tok = await refreshExternalJwt(host, session.jwtRefresh, {
|
|
1502
|
-
signal: opts.signal
|
|
1503
|
-
});
|
|
1504
|
-
const next2 = {
|
|
1505
|
-
...session,
|
|
1506
|
-
jwtAccess: tok.access,
|
|
1507
|
-
jwtRefresh: tok.refresh !== "" ? tok.refresh : session.jwtRefresh,
|
|
1508
|
-
jwtExpiresAt: tok.expiresAt
|
|
1509
|
-
};
|
|
1510
|
-
await store.saveSession(serverKey, next2);
|
|
1511
|
-
return next2;
|
|
1512
|
-
} catch {
|
|
1513
|
-
}
|
|
1514
|
-
}
|
|
1515
|
-
const operatorEmail = session.impersonatorEmail;
|
|
1516
|
-
const userId = session.impersonatedUserId;
|
|
1517
|
-
if (userId === void 0) {
|
|
1518
|
-
throw new SessionExpiredError(
|
|
1519
|
-
`${serverKey}:${email} (impersonation refresh dead and no user id stored to re-mint; re-run dr-appspace login-as)`
|
|
1520
|
-
);
|
|
1521
|
-
}
|
|
1522
|
-
const operatorStored = await store.getSession(serverKey, operatorEmail);
|
|
1523
|
-
if (operatorStored !== void 0 && (operatorStored.impersonatorEmail !== void 0 && operatorStored.impersonatorEmail !== "" || usesApiKey(operatorStored))) {
|
|
1524
|
-
throw new SessionExpiredError(
|
|
1525
|
-
`${serverKey}:${email} (operator ${operatorEmail} is no longer a direct login \u2014 re-run dr-appspace login --server ${serverKey} as ${operatorEmail}, then dr-appspace login-as)`
|
|
1526
|
-
);
|
|
1527
|
-
}
|
|
1528
|
-
let operator;
|
|
1529
|
-
try {
|
|
1530
|
-
operator = await ensureValidJwt(store, serverKey, operatorEmail, {
|
|
1531
|
-
signal: opts.signal,
|
|
1532
|
-
host
|
|
1924
|
+
const res = await fetch(`${base}${PATHS.token}`, {
|
|
1925
|
+
method: "POST",
|
|
1926
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
1927
|
+
body: body.toString(),
|
|
1928
|
+
signal
|
|
1533
1929
|
});
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
});
|
|
1549
|
-
const next = {
|
|
1550
|
-
...session,
|
|
1551
|
-
jwtAccess: result.access,
|
|
1552
|
-
jwtRefresh: result.refresh,
|
|
1553
|
-
jwtExpiresAt: result.expiresAt
|
|
1554
|
-
};
|
|
1555
|
-
await store.saveSession(serverKey, next);
|
|
1556
|
-
if (session.jwtRefresh !== void 0 && session.jwtRefresh !== "") {
|
|
1557
|
-
const failure = await revokeRefreshToken(host, session.jwtRefresh, { signal: opts.signal });
|
|
1558
|
-
if (failure !== void 0) {
|
|
1559
|
-
process.stderr.write(
|
|
1560
|
-
`Warning: could not revoke the previous login-as token for ${serverKey}:${email} (${failure}); it stays valid until it expires.
|
|
1561
|
-
`
|
|
1562
|
-
);
|
|
1930
|
+
const text4 = await res.text();
|
|
1931
|
+
if (res.ok) {
|
|
1932
|
+
const obj5 = parseObject(text4);
|
|
1933
|
+
const access2 = typeof obj5.access === "string" ? obj5.access : "";
|
|
1934
|
+
const refresh = typeof obj5.refresh === "string" ? obj5.refresh : "";
|
|
1935
|
+
if (access2 === "" || refresh === "") {
|
|
1936
|
+
throw new Error("token response missing access or refresh");
|
|
1937
|
+
}
|
|
1938
|
+
return { access: access2, refresh };
|
|
1939
|
+
}
|
|
1940
|
+
const errCode = tryParseErrorCode(text4);
|
|
1941
|
+
if (errCode === "authorization_pending" || errCode === "slow_down") {
|
|
1942
|
+
await sleep3(interval, signal);
|
|
1943
|
+
continue;
|
|
1563
1944
|
}
|
|
1945
|
+
if (errCode) {
|
|
1946
|
+
const hint = Object.hasOwn(V2_TERMINAL_HINTS, errCode) ? V2_TERMINAL_HINTS[errCode] : "";
|
|
1947
|
+
throw new Error(`token error: ${errCode}${hint}`);
|
|
1948
|
+
}
|
|
1949
|
+
throw new Error(`token HTTP ${res.status}`);
|
|
1564
1950
|
}
|
|
1565
|
-
return next;
|
|
1566
1951
|
}
|
|
1567
1952
|
|
|
1568
1953
|
// src/auth/browser.ts
|
|
@@ -1683,7 +2068,10 @@ var AuthorizedClient = class _AuthorizedClient {
|
|
|
1683
2068
|
/**
|
|
1684
2069
|
* Loads the session for `(serverKey, email)` from `store` and returns a
|
|
1685
2070
|
* client ready to call /api/... paths. Throws {@link NotLoggedInError} if
|
|
1686
|
-
* no entry exists, or if the stored session is missing required fields.
|
|
2071
|
+
* no entry exists, or if the stored session is missing required fields. A
|
|
2072
|
+
* session cookie an older `dr-appspace login` saved is retired here, before
|
|
2073
|
+
* any request goes out: its refresh token is revoked, the local copy is
|
|
2074
|
+
* removed, and a `LegacySessionRetiredError` says to log in again.
|
|
1687
2075
|
*
|
|
1688
2076
|
* The base host is resolved via `resolve(serverKey).host`, which handles
|
|
1689
2077
|
* both registry entries and hostname-style keys. Tests may pass `options.host`
|
|
@@ -1701,15 +2089,14 @@ var AuthorizedClient = class _AuthorizedClient {
|
|
|
1701
2089
|
cookieless ? `not logged in: ${serverKey}:${email} (cookie-less session has no JWT)` : `not logged in: ${serverKey}:${email} (impersonated session has no JWT; re-run dr-appspace login-as)`
|
|
1702
2090
|
);
|
|
1703
2091
|
}
|
|
1704
|
-
} else if (session.sessionId === "") {
|
|
1705
|
-
throw new NotLoggedInError(
|
|
1706
|
-
`not logged in: ${serverKey}:${email} (missing session; re-run dr-appspace login)`
|
|
1707
|
-
);
|
|
1708
2092
|
}
|
|
1709
2093
|
const rawHost = options?.host ?? resolve2(serverKey).host;
|
|
1710
2094
|
const host = rawHost.replace(/\/+$/, "");
|
|
1711
2095
|
const rawAuthHost = options?.authHost ?? rawHost;
|
|
1712
2096
|
const authHost = rawAuthHost.replace(/\/+$/, "");
|
|
2097
|
+
if (isLegacyCookieSession(session)) {
|
|
2098
|
+
throw await retireLegacySession(store, serverKey, email, session, authHost);
|
|
2099
|
+
}
|
|
1713
2100
|
return new _AuthorizedClient(host, store, serverKey, email, session, authHost);
|
|
1714
2101
|
}
|
|
1715
2102
|
/** Base host URL without trailing slash. */
|
|
@@ -1774,29 +2161,21 @@ var AuthorizedClient = class _AuthorizedClient {
|
|
|
1774
2161
|
return raw;
|
|
1775
2162
|
}
|
|
1776
2163
|
/**
|
|
1777
|
-
* Attaches
|
|
1778
|
-
*
|
|
2164
|
+
* Attaches Origin/Referer, Accept, the Bearer JWT, and (for write requests)
|
|
2165
|
+
* a default Content-Type to `headers`. No session cookie and no CSRF token:
|
|
2166
|
+
* the JWT is the only credential (DR-60129).
|
|
1779
2167
|
*
|
|
1780
|
-
* -
|
|
1781
|
-
* when the JWT is rejected but the session cookie is still trusted).
|
|
1782
|
-
* - Authorization is also suppressed when `jwtAccess` is empty.
|
|
2168
|
+
* - Authorization is suppressed when `jwtAccess` is empty.
|
|
1783
2169
|
* - Content-Type is only set when `hasBody=true` AND no Content-Type is
|
|
1784
2170
|
* already present (so multipart callers can set their own boundary).
|
|
1785
2171
|
*
|
|
1786
2172
|
* @internal
|
|
1787
2173
|
*/
|
|
1788
|
-
applyAuthHeaders(headers, hasBody
|
|
1789
|
-
if (!this.isCookieless()) {
|
|
1790
|
-
headers.set(
|
|
1791
|
-
"Cookie",
|
|
1792
|
-
`sessionid=${this._session.sessionId}; csrftoken=${this._session.csrfToken}`
|
|
1793
|
-
);
|
|
1794
|
-
headers.set("X-CSRFToken", this._session.csrfToken);
|
|
1795
|
-
}
|
|
2174
|
+
applyAuthHeaders(headers, hasBody) {
|
|
1796
2175
|
headers.set("Origin", this._host);
|
|
1797
2176
|
headers.set("Referer", `${this._host}/`);
|
|
1798
2177
|
headers.set("Accept", "application/json");
|
|
1799
|
-
if (
|
|
2178
|
+
if (this._session.jwtAccess !== void 0 && this._session.jwtAccess !== "") {
|
|
1800
2179
|
headers.set("Authorization", `Bearer ${this._session.jwtAccess}`);
|
|
1801
2180
|
}
|
|
1802
2181
|
if (hasBody && !headers.has("Content-Type")) {
|
|
@@ -1809,19 +2188,16 @@ var AuthorizedClient = class _AuthorizedClient {
|
|
|
1809
2188
|
* `http(s)://` URLs pass through unchanged. Mirrors `client.go:79-94` `Do`.
|
|
1810
2189
|
*/
|
|
1811
2190
|
async do(method, path3, body, options) {
|
|
1812
|
-
|
|
1813
|
-
let res = await this.doWithAuth(method, path3, body, options, true);
|
|
1814
|
-
if (this.isAuthRejected(res) && sentBearer && !this.isCookieless()) {
|
|
1815
|
-
res = await this.doWithAuth(method, path3, body, options, false);
|
|
1816
|
-
}
|
|
2191
|
+
let res = await this.doWithAuth(method, path3, body, options);
|
|
1817
2192
|
if (this.isAuthRejected(res)) {
|
|
1818
2193
|
try {
|
|
1819
2194
|
const fresh = await forceRefreshJwt(this._store, this._serverKey, this._email, {
|
|
1820
2195
|
signal: options?.signal,
|
|
1821
|
-
host: this._authHost
|
|
2196
|
+
host: this._authHost,
|
|
2197
|
+
refused: this._session.jwtAccess
|
|
1822
2198
|
});
|
|
1823
2199
|
this._session = fresh;
|
|
1824
|
-
res = await this.doWithAuth(method, path3, body, options
|
|
2200
|
+
res = await this.doWithAuth(method, path3, body, options);
|
|
1825
2201
|
} catch (err) {
|
|
1826
2202
|
_AuthorizedClient.logRefreshFailure("post-401 force-refresh", err);
|
|
1827
2203
|
}
|
|
@@ -1847,28 +2223,18 @@ var AuthorizedClient = class _AuthorizedClient {
|
|
|
1847
2223
|
`);
|
|
1848
2224
|
}
|
|
1849
2225
|
/**
|
|
1850
|
-
* Shared dispatch behind {@link AuthorizedClient.do} and
|
|
1851
|
-
*
|
|
1852
|
-
*
|
|
1853
|
-
* variants selected by `includeBearer`.
|
|
1854
|
-
*
|
|
1855
|
-
* The pre-flight {@link AuthorizedClient.ensureFreshAuth | ensureFreshAuth}
|
|
1856
|
-
* is gated on `includeBearer === true`. Go's `doSessionOnly`
|
|
1857
|
-
* (`client.go:122-133`) deliberately skips the pre-flight on the
|
|
1858
|
-
* session-only path — refreshing a JWT we're about to omit is wasteful
|
|
1859
|
-
* and, in the Bearer-rejected branch, the JWT may already be the cause of
|
|
1860
|
-
* the 401, so refreshing here would mask the real recovery.
|
|
2226
|
+
* Shared dispatch behind {@link AuthorizedClient.do} and
|
|
2227
|
+
* {@link AuthorizedClient.requestJson}: refresh the JWT when it is near
|
|
2228
|
+
* expiry, then send the request with the Bearer as its only credential.
|
|
1861
2229
|
*
|
|
1862
2230
|
* @internal
|
|
1863
2231
|
*/
|
|
1864
|
-
async doWithAuth(method, path3, body, options
|
|
1865
|
-
|
|
1866
|
-
await this.ensureFreshAuth(JWT_REFRESH_BUFFER_MS, options?.signal);
|
|
1867
|
-
}
|
|
2232
|
+
async doWithAuth(method, path3, body, options) {
|
|
2233
|
+
await this.ensureFreshAuth(JWT_REFRESH_BUFFER_MS, options?.signal);
|
|
1868
2234
|
const url = this.resolveUrl(path3);
|
|
1869
2235
|
const headers = new Headers();
|
|
1870
2236
|
const hasBody = body !== void 0 && body !== null;
|
|
1871
|
-
this.applyAuthHeaders(headers, hasBody
|
|
2237
|
+
this.applyAuthHeaders(headers, hasBody);
|
|
1872
2238
|
if (options?.headers !== void 0) {
|
|
1873
2239
|
for (const [k, v] of Object.entries(options.headers)) {
|
|
1874
2240
|
if (RESERVED_AUTH_HEADERS.has(k.toLowerCase())) {
|
|
@@ -1968,7 +2334,7 @@ var AuthorizedClient = class _AuthorizedClient {
|
|
|
1968
2334
|
await this.ensureFreshAuth(JWT_REFRESH_BUFFER_MS, options?.signal);
|
|
1969
2335
|
const url = this.resolveUrl(path3);
|
|
1970
2336
|
const headers = new Headers();
|
|
1971
|
-
this.applyAuthHeaders(headers, true
|
|
2337
|
+
this.applyAuthHeaders(headers, true);
|
|
1972
2338
|
headers.delete("Content-Type");
|
|
1973
2339
|
const res = await fetch(url, {
|
|
1974
2340
|
method: "POST",
|
|
@@ -2018,7 +2384,7 @@ var AuthorizedClient = class _AuthorizedClient {
|
|
|
2018
2384
|
await this.ensureFreshAuth(JWT_REFRESH_BUFFER_MS, options?.signal);
|
|
2019
2385
|
const url = this.resolveUrl(path3);
|
|
2020
2386
|
const headers = new Headers();
|
|
2021
|
-
this.applyAuthHeaders(headers, true
|
|
2387
|
+
this.applyAuthHeaders(headers, true);
|
|
2022
2388
|
headers.delete("Content-Type");
|
|
2023
2389
|
const res = await fetch(url, {
|
|
2024
2390
|
method: "POST",
|
|
@@ -2076,7 +2442,7 @@ var AuthorizedClient = class _AuthorizedClient {
|
|
|
2076
2442
|
await this.ensureFreshAuth(JWT_REFRESH_BUFFER_MS, options?.signal);
|
|
2077
2443
|
const url = this.resolveUrl(path3);
|
|
2078
2444
|
const headers = new Headers();
|
|
2079
|
-
this.applyAuthHeaders(headers, true
|
|
2445
|
+
this.applyAuthHeaders(headers, true);
|
|
2080
2446
|
headers.delete("Content-Type");
|
|
2081
2447
|
const res = await fetch(url, {
|
|
2082
2448
|
method: "POST",
|
|
@@ -2104,15 +2470,12 @@ var AuthorizedClient = class _AuthorizedClient {
|
|
|
2104
2470
|
*
|
|
2105
2471
|
* Implements the 401/403 recovery ladder (mirrors `client.go:243-298`):
|
|
2106
2472
|
*
|
|
2107
|
-
* 1. First attempt sends Bearer
|
|
2108
|
-
* 2. If that responds 401/403
|
|
2109
|
-
*
|
|
2110
|
-
*
|
|
2111
|
-
*
|
|
2112
|
-
*
|
|
2113
|
-
* in-place on success.
|
|
2114
|
-
* 4. Final messaging: when refresh+retry (or earlier session-only)
|
|
2115
|
-
* produced 401/403, throw a plain {@link Error} with the
|
|
2473
|
+
* 1. First attempt sends the Bearer.
|
|
2474
|
+
* 2. If that responds 401/403, force-refresh the JWT via `forceRefreshJwt`
|
|
2475
|
+
* and retry once with the fresh Bearer. The store is updated in-place
|
|
2476
|
+
* on success. There is no cookie-only retry: the CLI sends no session
|
|
2477
|
+
* cookie (DR-60129).
|
|
2478
|
+
* 3. Final messaging: when refresh+retry produced 401/403, throw a plain {@link Error} with the
|
|
2116
2479
|
* "authenticated, but endpoint rejected" diagnostic — NOT a
|
|
2117
2480
|
* {@link SessionExpiredError}, since the auth path is fresh and the
|
|
2118
2481
|
* server is rejecting on permissions/tenant/body grounds. When
|
|
@@ -2130,34 +2493,28 @@ var AuthorizedClient = class _AuthorizedClient {
|
|
|
2130
2493
|
*/
|
|
2131
2494
|
async requestJson(method, path3, payload, options) {
|
|
2132
2495
|
const body = payload === void 0 ? void 0 : JSON.stringify(payload);
|
|
2133
|
-
|
|
2134
|
-
let res = await this.doWithAuth(method, path3, body, options, true);
|
|
2135
|
-
let triedSessionOnly = false;
|
|
2496
|
+
let res = await this.doWithAuth(method, path3, body, options);
|
|
2136
2497
|
let refreshed = false;
|
|
2137
2498
|
let refreshErr;
|
|
2138
|
-
if (this.isAuthRejected(res) && sentBearer && !this.isCookieless()) {
|
|
2139
|
-
triedSessionOnly = true;
|
|
2140
|
-
res = await this.doWithAuth(method, path3, body, options, false);
|
|
2141
|
-
}
|
|
2142
2499
|
if (this.isAuthRejected(res)) {
|
|
2143
2500
|
try {
|
|
2144
2501
|
const fresh = await forceRefreshJwt(this._store, this._serverKey, this._email, {
|
|
2145
2502
|
signal: options?.signal,
|
|
2146
|
-
host: this._authHost
|
|
2503
|
+
host: this._authHost,
|
|
2504
|
+
refused: this._session.jwtAccess
|
|
2147
2505
|
});
|
|
2148
2506
|
this._session = fresh;
|
|
2149
2507
|
refreshed = true;
|
|
2150
|
-
res = await this.doWithAuth(method, path3, body, options
|
|
2508
|
+
res = await this.doWithAuth(method, path3, body, options);
|
|
2151
2509
|
} catch (err) {
|
|
2152
2510
|
refreshErr = err;
|
|
2153
2511
|
}
|
|
2154
2512
|
}
|
|
2155
2513
|
if (this.isAuthRejected(res)) {
|
|
2156
2514
|
const text5 = await res.text();
|
|
2157
|
-
if (refreshed
|
|
2158
|
-
const attempted = refreshed ? "session-only retry and JWT refresh" : "session-only retry";
|
|
2515
|
+
if (refreshed) {
|
|
2159
2516
|
throw new Error(
|
|
2160
|
-
`${method} ${path3}: HTTP ${res.status} after
|
|
2517
|
+
`${method} ${path3}: HTTP ${res.status} after JWT refresh (authenticated, but endpoint rejected \u2014 check permissions, tenant/org context, or body): ${truncate2(text5, 200)}`
|
|
2161
2518
|
);
|
|
2162
2519
|
}
|
|
2163
2520
|
if (refreshErr !== void 0) {
|
|
@@ -2194,8 +2551,8 @@ var AuthorizedClient = class _AuthorizedClient {
|
|
|
2194
2551
|
* truly-dead session bottoms out via the ladder with the right error.
|
|
2195
2552
|
*
|
|
2196
2553
|
* Skip when both `jwtAccess` and `jwtRefresh` are empty: there is nothing
|
|
2197
|
-
* to refresh from. Either one alone is enough to attempt —
|
|
2198
|
-
*
|
|
2554
|
+
* to refresh from. Either one alone is enough to attempt — ensureValidJwt
|
|
2555
|
+
* picks the right path based on what's set.
|
|
2199
2556
|
*/
|
|
2200
2557
|
async ensureFreshAuth(bufferMs, signal) {
|
|
2201
2558
|
const access2 = this._session.jwtAccess ?? "";
|
|
@@ -2214,18 +2571,6 @@ var AuthorizedClient = class _AuthorizedClient {
|
|
|
2214
2571
|
_AuthorizedClient.logRefreshFailure("pre-flight", err);
|
|
2215
2572
|
}
|
|
2216
2573
|
}
|
|
2217
|
-
/** True iff the current session has a non-empty Bearer JWT. */
|
|
2218
|
-
hasBearer() {
|
|
2219
|
-
return this._session.jwtAccess !== void 0 && this._session.jwtAccess !== "";
|
|
2220
|
-
}
|
|
2221
|
-
/**
|
|
2222
|
-
* True iff the Bearer JWT is this identity's sole credential — an
|
|
2223
|
-
* impersonated ("login-as") session or an externally provisioned one. Such requests
|
|
2224
|
-
* send no cookie, so the session-only rung of the 401 ladder cannot help.
|
|
2225
|
-
*/
|
|
2226
|
-
isCookieless() {
|
|
2227
|
-
return isCookielessSession(this._session);
|
|
2228
|
-
}
|
|
2229
2574
|
/** True iff `res` is the auth-rejection signal (401 or 403). */
|
|
2230
2575
|
isAuthRejected(res) {
|
|
2231
2576
|
return res.status === 401 || res.status === 403;
|
|
@@ -2241,166 +2586,6 @@ function truncate2(s, n) {
|
|
|
2241
2586
|
return s.slice(0, n) + "\u2026";
|
|
2242
2587
|
}
|
|
2243
2588
|
|
|
2244
|
-
// src/auth/keyring/fileBackend.ts
|
|
2245
|
-
import { rm as rm2 } from "fs/promises";
|
|
2246
|
-
var INDEX_PREFIX2 = "__index__:";
|
|
2247
|
-
var FileKeyringBackend = class _FileKeyringBackend {
|
|
2248
|
-
constructor(path3) {
|
|
2249
|
-
this.path = path3;
|
|
2250
|
-
}
|
|
2251
|
-
path;
|
|
2252
|
-
load() {
|
|
2253
|
-
return readCredentialsFile(this.path);
|
|
2254
|
-
}
|
|
2255
|
-
/**
|
|
2256
|
-
* The metadata blob `KeyringStore.getSession` expects, rebuilt from the file.
|
|
2257
|
-
*
|
|
2258
|
-
* `cookieless` is derived, not stored: credentials provisioned as a bare
|
|
2259
|
-
* token pair have no session cookie, and that is precisely what tells the
|
|
2260
|
-
* refresh ladder to skip the cookie-mint fallback.
|
|
2261
|
-
*/
|
|
2262
|
-
static metaBlob(creds) {
|
|
2263
|
-
const savedAt = creds.savedAt ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
2264
|
-
const sessionId = creds.sessionId ?? "";
|
|
2265
|
-
let jwtExpiresAt;
|
|
2266
|
-
if (creds.access !== void 0 && creds.access !== "") {
|
|
2267
|
-
try {
|
|
2268
|
-
jwtExpiresAt = decodeJwtExpiration(creds.access).toISOString();
|
|
2269
|
-
} catch {
|
|
2270
|
-
}
|
|
2271
|
-
}
|
|
2272
|
-
return JSON.stringify({
|
|
2273
|
-
sessionId,
|
|
2274
|
-
csrfToken: creds.csrfToken ?? "",
|
|
2275
|
-
savedAt,
|
|
2276
|
-
lastUsedAt: savedAt,
|
|
2277
|
-
...sessionId === "" && { cookieless: true },
|
|
2278
|
-
...jwtExpiresAt !== void 0 && { jwtExpiresAt },
|
|
2279
|
-
// Carry the API-key carrier through so `KeyringStore.getSession` sees a
|
|
2280
|
-
// keyed identity and routes it to the exchange, plus the fingerprint of the
|
|
2281
|
-
// key that minted the stored `access` so a reload can tell the cached JWT
|
|
2282
|
-
// is still the current key's. Without it a file store would re-exchange on
|
|
2283
|
-
// EVERY request — `ensureFreshAuth` reloads the session each time, and
|
|
2284
|
-
// `mintedByStoredApiKey` can never match a fingerprint that was never
|
|
2285
|
-
// written. `set('meta')` persists it back below.
|
|
2286
|
-
...creds.apiKey !== void 0 && creds.apiKey !== "" && { apiKey: creds.apiKey },
|
|
2287
|
-
...creds.apiKeyEnvVar !== void 0 && creds.apiKeyEnvVar !== "" && { apiKeyEnvVar: creds.apiKeyEnvVar },
|
|
2288
|
-
...creds.accessApiKeyFingerprint !== void 0 && creds.accessApiKeyFingerprint !== "" && {
|
|
2289
|
-
jwtApiKeyFingerprint: creds.accessApiKeyFingerprint
|
|
2290
|
-
}
|
|
2291
|
-
});
|
|
2292
|
-
}
|
|
2293
|
-
static slotOf(creds, account) {
|
|
2294
|
-
const base = `${creds.server}:${creds.email}`;
|
|
2295
|
-
if (account === base) return "meta";
|
|
2296
|
-
if (account === `${base}:access`) return "access";
|
|
2297
|
-
if (account === `${base}:refresh`) return "refresh";
|
|
2298
|
-
return void 0;
|
|
2299
|
-
}
|
|
2300
|
-
/** Cookie fields out of a metadata blob, dropped when empty. */
|
|
2301
|
-
static cookieOf(blob) {
|
|
2302
|
-
let parsed2;
|
|
2303
|
-
try {
|
|
2304
|
-
parsed2 = JSON.parse(blob);
|
|
2305
|
-
} catch {
|
|
2306
|
-
return {};
|
|
2307
|
-
}
|
|
2308
|
-
const sessionId = typeof parsed2.sessionId === "string" ? parsed2.sessionId : "";
|
|
2309
|
-
const csrfToken = typeof parsed2.csrfToken === "string" ? parsed2.csrfToken : "";
|
|
2310
|
-
return {
|
|
2311
|
-
...sessionId !== "" && { sessionId },
|
|
2312
|
-
...csrfToken !== "" && { csrfToken }
|
|
2313
|
-
};
|
|
2314
|
-
}
|
|
2315
|
-
/**
|
|
2316
|
-
* The key fingerprint out of a metadata blob (`KeyringStore` emits it as
|
|
2317
|
-
* `jwtApiKeyFingerprint`), empty when absent. Unlike the cookie it is NOT
|
|
2318
|
-
* derived, so it has to be persisted back to the file or every request
|
|
2319
|
-
* re-exchanges.
|
|
2320
|
-
*/
|
|
2321
|
-
static fingerprintOf(blob) {
|
|
2322
|
-
try {
|
|
2323
|
-
const parsed2 = JSON.parse(blob);
|
|
2324
|
-
return typeof parsed2.jwtApiKeyFingerprint === "string" ? parsed2.jwtApiKeyFingerprint : "";
|
|
2325
|
-
} catch {
|
|
2326
|
-
return "";
|
|
2327
|
-
}
|
|
2328
|
-
}
|
|
2329
|
-
async get(_service, account) {
|
|
2330
|
-
const creds = await this.load();
|
|
2331
|
-
if (creds === void 0) return void 0;
|
|
2332
|
-
switch (_FileKeyringBackend.slotOf(creds, account)) {
|
|
2333
|
-
case "meta":
|
|
2334
|
-
return _FileKeyringBackend.metaBlob(creds);
|
|
2335
|
-
case "access":
|
|
2336
|
-
return creds.access;
|
|
2337
|
-
case "refresh":
|
|
2338
|
-
return creds.refresh;
|
|
2339
|
-
default:
|
|
2340
|
-
return void 0;
|
|
2341
|
-
}
|
|
2342
|
-
}
|
|
2343
|
-
async set(_service, account, value) {
|
|
2344
|
-
if (account.startsWith(INDEX_PREFIX2)) return;
|
|
2345
|
-
const creds = await this.load();
|
|
2346
|
-
if (creds === void 0) {
|
|
2347
|
-
throw new Error(
|
|
2348
|
-
`credential file ${this.path} disappeared while storing ${account}: nothing was persisted. Re-run the command, or \`dr-appspace login\` if the file is gone for good.`
|
|
2349
|
-
);
|
|
2350
|
-
}
|
|
2351
|
-
switch (_FileKeyringBackend.slotOf(creds, account)) {
|
|
2352
|
-
case "meta": {
|
|
2353
|
-
const cookie = _FileKeyringBackend.cookieOf(value);
|
|
2354
|
-
const fingerprint = _FileKeyringBackend.fingerprintOf(value);
|
|
2355
|
-
if (cookie.sessionId === creds.sessionId && cookie.csrfToken === creds.csrfToken && fingerprint === (creds.accessApiKeyFingerprint ?? "")) {
|
|
2356
|
-
return;
|
|
2357
|
-
}
|
|
2358
|
-
const next = { ...creds, ...cookie };
|
|
2359
|
-
if (fingerprint !== "") next.accessApiKeyFingerprint = fingerprint;
|
|
2360
|
-
else delete next.accessApiKeyFingerprint;
|
|
2361
|
-
await writeCredentialsFile(this.path, next);
|
|
2362
|
-
return;
|
|
2363
|
-
}
|
|
2364
|
-
case "access":
|
|
2365
|
-
await writeCredentialsFile(this.path, { ...creds, access: value });
|
|
2366
|
-
return;
|
|
2367
|
-
case "refresh":
|
|
2368
|
-
await writeCredentialsFile(this.path, { ...creds, refresh: value });
|
|
2369
|
-
return;
|
|
2370
|
-
default:
|
|
2371
|
-
throw new Error(
|
|
2372
|
-
`credential file ${this.path} holds ${creds.server}:${creds.email} and cannot also store ${account}: it is a single-identity store. Remove that file to use the OS keychain instead.`
|
|
2373
|
-
);
|
|
2374
|
-
}
|
|
2375
|
-
}
|
|
2376
|
-
/**
|
|
2377
|
-
* Removing the identity means removing the file — there is only one, and
|
|
2378
|
-
* clearing a single slot would leave a half-identity nothing can repair.
|
|
2379
|
-
*
|
|
2380
|
-
* Keyed off the metadata slot because `KeyringStore.removeSession` deletes
|
|
2381
|
-
* that first; the sibling deletes that follow then find nothing, which is
|
|
2382
|
-
* the correct answer. Without this `dr-appspace logout` would report success and
|
|
2383
|
-
* leave live credentials on disk.
|
|
2384
|
-
*/
|
|
2385
|
-
async delete(_service, account) {
|
|
2386
|
-
const creds = await this.load();
|
|
2387
|
-
if (creds === void 0) return false;
|
|
2388
|
-
if (_FileKeyringBackend.slotOf(creds, account) !== "meta") return false;
|
|
2389
|
-
await rm2(this.path, { force: true });
|
|
2390
|
-
return true;
|
|
2391
|
-
}
|
|
2392
|
-
async list() {
|
|
2393
|
-
const creds = await this.load();
|
|
2394
|
-
if (creds === void 0) return [];
|
|
2395
|
-
return [
|
|
2396
|
-
{
|
|
2397
|
-
account: `${creds.server}:${creds.email}`,
|
|
2398
|
-
value: _FileKeyringBackend.metaBlob(creds)
|
|
2399
|
-
}
|
|
2400
|
-
];
|
|
2401
|
-
}
|
|
2402
|
-
};
|
|
2403
|
-
|
|
2404
2589
|
// src/auth/keyring/resolveAccount.ts
|
|
2405
2590
|
async function resolveAccount(store, serverKey, accountFlag) {
|
|
2406
2591
|
const sessions = await store.listSessions(serverKey);
|
|
@@ -2464,9 +2649,12 @@ async function refuseIfProvisionedExternally(action) {
|
|
|
2464
2649
|
const path3 = credentialsFilePath();
|
|
2465
2650
|
const creds = await readCredentialsFile(path3);
|
|
2466
2651
|
if (creds === void 0) return;
|
|
2467
|
-
if (creds
|
|
2652
|
+
if (isInteractiveFileLogin(creds)) return;
|
|
2468
2653
|
throw provisionedExternallyError(path3, action);
|
|
2469
2654
|
}
|
|
2655
|
+
function isInteractiveFileLogin(creds) {
|
|
2656
|
+
return creds.interactiveLogin === true || creds.sessionId !== void 0 && creds.sessionId !== "";
|
|
2657
|
+
}
|
|
2470
2658
|
function provisionedExternallyError(path3, action) {
|
|
2471
2659
|
return new Error(
|
|
2472
2660
|
`cannot ${action}: the credentials in ${path3} were provisioned externally and carry no interactive session. Whatever provisioned them is responsible for renewing them; remove that file to log in interactively instead.`
|
|
@@ -2477,7 +2665,7 @@ async function refuseImpersonationWithCredentialFile() {
|
|
|
2477
2665
|
const path3 = credentialsFilePath();
|
|
2478
2666
|
const creds = await readCredentialsFile(path3);
|
|
2479
2667
|
if (creds === void 0) return;
|
|
2480
|
-
if (creds
|
|
2668
|
+
if (!isInteractiveFileLogin(creds)) {
|
|
2481
2669
|
throw provisionedExternallyError(path3, action);
|
|
2482
2670
|
}
|
|
2483
2671
|
throw new Error(
|
|
@@ -2591,30 +2779,45 @@ async function runLogin(cfg) {
|
|
|
2591
2779
|
}
|
|
2592
2780
|
}
|
|
2593
2781
|
const intervalMs = dc.interval > 0 ? dc.interval * 1e3 : 2e3;
|
|
2594
|
-
const
|
|
2782
|
+
const pair = await pollForV2Token(host, dc.deviceCode, {
|
|
2595
2783
|
interval: intervalMs,
|
|
2596
2784
|
maxWait: timeoutMs,
|
|
2597
2785
|
signal: controller.signal
|
|
2598
2786
|
});
|
|
2599
|
-
const jwtTokens =
|
|
2600
|
-
signal: controller.signal
|
|
2601
|
-
});
|
|
2787
|
+
const jwtTokens = { ...pair, expiresAt: decodeJwtExpiration(pair.access) };
|
|
2602
2788
|
const claims = decodeJwtClaims(jwtTokens.access);
|
|
2603
2789
|
const emailClaim = claims["email"];
|
|
2604
2790
|
if (typeof emailClaim !== "string" || emailClaim === "") {
|
|
2605
2791
|
throw new Error(`login: JWT for ${cfg.serverKey} has no "email" claim; cannot key session`);
|
|
2606
2792
|
}
|
|
2607
2793
|
const email = emailClaim;
|
|
2794
|
+
const replaced = await replacedCookieSession(cfg, email);
|
|
2795
|
+
const revoking = replaced !== void 0 ? revokeStoredCredentials(host, replaced) : Promise.resolve([]);
|
|
2796
|
+
if (replaced !== void 0 && !cfg.store.isCredentialFile) {
|
|
2797
|
+
try {
|
|
2798
|
+
await cfg.store.removeSession(cfg.serverKey, email);
|
|
2799
|
+
} catch {
|
|
2800
|
+
}
|
|
2801
|
+
}
|
|
2608
2802
|
const session = {
|
|
2609
2803
|
email,
|
|
2610
|
-
sessionId:
|
|
2611
|
-
csrfToken:
|
|
2804
|
+
sessionId: "",
|
|
2805
|
+
csrfToken: "",
|
|
2612
2806
|
jwtAccess: jwtTokens.access,
|
|
2613
2807
|
jwtRefresh: jwtTokens.refresh,
|
|
2614
2808
|
jwtExpiresAt: jwtTokens.expiresAt,
|
|
2615
|
-
savedAt: /* @__PURE__ */ new Date()
|
|
2809
|
+
savedAt: /* @__PURE__ */ new Date(),
|
|
2810
|
+
// `cookieless`: the JWT pair is the only credential. `interactiveLogin`
|
|
2811
|
+
// says a person approved it, which a provisioned pair cannot say.
|
|
2812
|
+
cookieless: true,
|
|
2813
|
+
interactiveLogin: true
|
|
2616
2814
|
};
|
|
2617
|
-
|
|
2815
|
+
try {
|
|
2816
|
+
await cfg.store.saveSession(cfg.serverKey, session);
|
|
2817
|
+
} finally {
|
|
2818
|
+
for (const line2 of await revoking) cfg.out.write(`${line2}
|
|
2819
|
+
`);
|
|
2820
|
+
}
|
|
2618
2821
|
const remainingMs = jwtTokens.expiresAt.getTime() - Date.now();
|
|
2619
2822
|
cfg.out.write(
|
|
2620
2823
|
`Logged into ${cfg.serverKey} as ${email}. JWT expires in ${formatGoDuration(roundToMinuteMs(remainingMs))}.
|
|
@@ -2624,6 +2827,15 @@ async function runLogin(cfg) {
|
|
|
2624
2827
|
clearTimeout(overallTimer);
|
|
2625
2828
|
}
|
|
2626
2829
|
}
|
|
2830
|
+
async function replacedCookieSession(cfg, email) {
|
|
2831
|
+
let previous;
|
|
2832
|
+
try {
|
|
2833
|
+
previous = await cfg.store.getSession(cfg.serverKey, email);
|
|
2834
|
+
} catch {
|
|
2835
|
+
return void 0;
|
|
2836
|
+
}
|
|
2837
|
+
return previous !== void 0 && isLegacyCookieSession(previous) ? previous : void 0;
|
|
2838
|
+
}
|
|
2627
2839
|
|
|
2628
2840
|
// src/commands/loginAs.ts
|
|
2629
2841
|
import { z as z2 } from "zod";
|
|
@@ -2920,7 +3132,7 @@ function registerLogoutCommand(root) {
|
|
|
2920
3132
|
}
|
|
2921
3133
|
async function runLogout(cfg) {
|
|
2922
3134
|
await refuseIfProvisionedExternally("log out");
|
|
2923
|
-
const revoker = cfg.revoker ??
|
|
3135
|
+
const revoker = cfg.revoker ?? revokeStoredCredentials;
|
|
2924
3136
|
if (cfg.all) {
|
|
2925
3137
|
for (const key of keys()) {
|
|
2926
3138
|
const sessions = await cfg.store.listSessions(key);
|
|
@@ -2961,41 +3173,15 @@ async function runLogout(cfg) {
|
|
|
2961
3173
|
`);
|
|
2962
3174
|
}
|
|
2963
3175
|
async function revokeAndWarn(revoker, host, session, out) {
|
|
2964
|
-
let
|
|
3176
|
+
let notes = void 0;
|
|
2965
3177
|
try {
|
|
2966
|
-
|
|
3178
|
+
notes = await revoker(host, session);
|
|
2967
3179
|
} catch {
|
|
2968
3180
|
}
|
|
2969
|
-
|
|
3181
|
+
const lines = typeof notes === "string" ? [notes] : notes ?? [];
|
|
3182
|
+
for (const line2 of lines) {
|
|
3183
|
+
if (line2 !== "") out.write(`${line2}
|
|
2970
3184
|
`);
|
|
2971
|
-
}
|
|
2972
|
-
async function bestEffortLogout(host, session) {
|
|
2973
|
-
if (host === "") return;
|
|
2974
|
-
const base = host.replace(/\/+$/, "");
|
|
2975
|
-
const controller = new AbortController();
|
|
2976
|
-
const timeout = setTimeout(() => controller.abort(), 5e3);
|
|
2977
|
-
try {
|
|
2978
|
-
if (session.impersonatorEmail !== void 0 && session.impersonatorEmail !== "") {
|
|
2979
|
-
if (session.jwtRefresh === void 0 || session.jwtRefresh === "") return;
|
|
2980
|
-
const failure = await revokeRefreshToken(base, session.jwtRefresh, {
|
|
2981
|
-
signal: controller.signal
|
|
2982
|
-
});
|
|
2983
|
-
if (failure !== void 0) {
|
|
2984
|
-
return `Warning: could not revoke the login-as token on ${base} (${failure}); it stays valid until it expires. Only the local copy was removed.`;
|
|
2985
|
-
}
|
|
2986
|
-
return;
|
|
2987
|
-
}
|
|
2988
|
-
await fetch(`${base}/oauth/revoke/`, {
|
|
2989
|
-
method: "POST",
|
|
2990
|
-
headers: {
|
|
2991
|
-
Cookie: `sessionid=${session.sessionId}; csrftoken=${session.csrfToken}`,
|
|
2992
|
-
"X-CSRFToken": session.csrfToken
|
|
2993
|
-
},
|
|
2994
|
-
signal: controller.signal
|
|
2995
|
-
});
|
|
2996
|
-
} catch {
|
|
2997
|
-
} finally {
|
|
2998
|
-
clearTimeout(timeout);
|
|
2999
3185
|
}
|
|
3000
3186
|
}
|
|
3001
3187
|
|
|
@@ -3026,7 +3212,7 @@ function firstStringOrNumber(claims, ...keys2) {
|
|
|
3026
3212
|
// src/commands/whoami.ts
|
|
3027
3213
|
function registerWhoamiCommand(root) {
|
|
3028
3214
|
const cmd = root.command("whoami").description(
|
|
3029
|
-
"whoami decodes the locally-stored JWT for a server and prints the identity claims (user_id, username, email, expiration).
|
|
3215
|
+
"whoami decodes the locally-stored JWT for a server and prints the identity claims (user_id, username, email, expiration). Offline, except that a session cookie saved by an older dr-appspace login is revoked and removed."
|
|
3030
3216
|
).summary("Show the identity encoded in the stored JWT for a server").option("--json", "Output the full claims map as JSON", false).option("--verbose", "Print every claim in a table, sorted alphabetically", false).action(
|
|
3031
3217
|
async (opts) => {
|
|
3032
3218
|
const fileStore = await resolveFileStore(opts.server);
|
|
@@ -3058,6 +3244,21 @@ async function runWhoami(cfg) {
|
|
|
3058
3244
|
`not logged in: ${cfg.serverKey}:${email} (keychain entry missing); re-run dr-appspace login --server ${cfg.serverKey}`
|
|
3059
3245
|
);
|
|
3060
3246
|
}
|
|
3247
|
+
if (isLegacyCookieSession(session)) {
|
|
3248
|
+
let host2 = "";
|
|
3249
|
+
try {
|
|
3250
|
+
host2 = resolve2(cfg.serverKey).host;
|
|
3251
|
+
} catch {
|
|
3252
|
+
}
|
|
3253
|
+
throw await retireLegacySession(
|
|
3254
|
+
cfg.store,
|
|
3255
|
+
cfg.serverKey,
|
|
3256
|
+
email,
|
|
3257
|
+
session,
|
|
3258
|
+
host2,
|
|
3259
|
+
cfg.revoker !== void 0 ? { revoker: cfg.revoker } : void 0
|
|
3260
|
+
);
|
|
3261
|
+
}
|
|
3061
3262
|
if (session.jwtAccess === void 0 || session.jwtAccess === "") {
|
|
3062
3263
|
throw new Error(
|
|
3063
3264
|
`no JWT stored for ${cfg.serverKey}:${email}; run dr-appspace login --server ${cfg.serverKey} to refresh`
|
|
@@ -3181,10 +3382,8 @@ function formatUtc(unix) {
|
|
|
3181
3382
|
return `${d.getUTCFullYear()}-${pad2(d.getUTCMonth() + 1)}-${pad2(d.getUTCDate())} ${pad2(d.getUTCHours())}:${pad2(d.getUTCMinutes())}:${pad2(d.getUTCSeconds())} UTC`;
|
|
3182
3383
|
}
|
|
3183
3384
|
|
|
3184
|
-
// src/commands/appspace/
|
|
3185
|
-
import {
|
|
3186
|
-
import { chmod as chmod2, readFile as readFile12, writeFile as writeFile8 } from "fs/promises";
|
|
3187
|
-
import { join as join17 } from "path";
|
|
3385
|
+
// src/commands/appspace/approveHosts.ts
|
|
3386
|
+
import { createInterface } from "readline/promises";
|
|
3188
3387
|
|
|
3189
3388
|
// src/commands/appspace/_client.ts
|
|
3190
3389
|
function withServerOptions(cmd) {
|
|
@@ -3512,6 +3711,97 @@ ${l}`).join("");
|
|
|
3512
3711
|
${detail}`}`;
|
|
3513
3712
|
}
|
|
3514
3713
|
|
|
3714
|
+
// src/commands/appspace/approveHosts.ts
|
|
3715
|
+
function parseHosts(value) {
|
|
3716
|
+
return value.split(",").map((h) => h.trim()).filter((h) => h !== "");
|
|
3717
|
+
}
|
|
3718
|
+
function describeEntries(res) {
|
|
3719
|
+
if (res.entries.length === 0) return "The app declares no outside hosts.\n";
|
|
3720
|
+
const lines = res.entries.map((e) => {
|
|
3721
|
+
const prefix = e.prefix === "" ? "" : ` with prefix ${JSON.stringify(e.prefix)}`;
|
|
3722
|
+
const key = e.secret === null ? "" : `, sends secret ${e.secret} in ${e.header}${prefix}`;
|
|
3723
|
+
const state = e.approved ? "approved" : "WAITS FOR APPROVAL";
|
|
3724
|
+
return `${e.name}: ${e.methods.join("/")} https://${e.host}${key} \u2014 ${state}`;
|
|
3725
|
+
});
|
|
3726
|
+
return lines.join("\n") + "\n";
|
|
3727
|
+
}
|
|
3728
|
+
async function askYes(question, output) {
|
|
3729
|
+
const rl = createInterface({ input: process.stdin, output });
|
|
3730
|
+
try {
|
|
3731
|
+
const answer = await rl.question(question);
|
|
3732
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
3733
|
+
} finally {
|
|
3734
|
+
rl.close();
|
|
3735
|
+
}
|
|
3736
|
+
}
|
|
3737
|
+
function approvalsPath(appId) {
|
|
3738
|
+
return `/apps/${encodeURIComponent(appId)}/http-approvals`;
|
|
3739
|
+
}
|
|
3740
|
+
function registerApproveHostsCommand(parent) {
|
|
3741
|
+
withJsonOption(
|
|
3742
|
+
withServerOptions(
|
|
3743
|
+
parent.command("approve-hosts <app-id>").description(
|
|
3744
|
+
"List an app's outside hosts, or approve them with --hosts (the app's Owner only, never an agent)."
|
|
3745
|
+
).option("--hosts <hosts>", "comma-separated host names to approve").option("--yes", "approve the entries shown without asking")
|
|
3746
|
+
)
|
|
3747
|
+
).action(async (appId, opts) => {
|
|
3748
|
+
const hosts = opts.hosts === void 0 ? void 0 : parseHosts(opts.hosts);
|
|
3749
|
+
if (hosts !== void 0 && hosts.length === 0) {
|
|
3750
|
+
throw new Error("--hosts needs at least one host name");
|
|
3751
|
+
}
|
|
3752
|
+
const client = await connect(opts);
|
|
3753
|
+
try {
|
|
3754
|
+
let res = await client.request(approvalsPath(appId));
|
|
3755
|
+
if (hosts !== void 0) {
|
|
3756
|
+
const wanted = new Set(hosts);
|
|
3757
|
+
const waiting = res.entries.filter((e) => wanted.has(e.host) && !e.approved);
|
|
3758
|
+
if (waiting.length > 0) {
|
|
3759
|
+
const say = opts.json === true ? process.stderr : process.stdout;
|
|
3760
|
+
say.write(`About to approve for ${appId}:
|
|
3761
|
+
`);
|
|
3762
|
+
say.write(describeEntries({ entries: waiting, pending_hosts: [] }));
|
|
3763
|
+
if (opts.yes !== true) {
|
|
3764
|
+
if (process.stdin.isTTY !== true) {
|
|
3765
|
+
throw new Error("pass --yes to approve without a terminal to confirm on");
|
|
3766
|
+
}
|
|
3767
|
+
if (!await askYes("Approve these? [y/N] ", say)) {
|
|
3768
|
+
throw new Error("not approved");
|
|
3769
|
+
}
|
|
3770
|
+
}
|
|
3771
|
+
}
|
|
3772
|
+
res = await client.request(approvalsPath(appId), {
|
|
3773
|
+
method: "POST",
|
|
3774
|
+
body: { hosts, fingerprints: waiting.map((e) => e.fingerprint) }
|
|
3775
|
+
});
|
|
3776
|
+
}
|
|
3777
|
+
if (opts.json === true) {
|
|
3778
|
+
printJson(res);
|
|
3779
|
+
return;
|
|
3780
|
+
}
|
|
3781
|
+
if (hosts !== void 0) {
|
|
3782
|
+
const done = res.approved ?? [];
|
|
3783
|
+
process.stdout.write(
|
|
3784
|
+
done.length === 0 ? `Nothing new to approve for ${appId}.
|
|
3785
|
+
` : `Approved ${done.join(", ")} for ${appId}.
|
|
3786
|
+
`
|
|
3787
|
+
);
|
|
3788
|
+
}
|
|
3789
|
+
process.stdout.write(describeEntries(res));
|
|
3790
|
+
if (res.approve_with !== void 0) {
|
|
3791
|
+
process.stdout.write(`To approve: ${res.approve_with}
|
|
3792
|
+
`);
|
|
3793
|
+
}
|
|
3794
|
+
} finally {
|
|
3795
|
+
client.cleanup();
|
|
3796
|
+
}
|
|
3797
|
+
});
|
|
3798
|
+
}
|
|
3799
|
+
|
|
3800
|
+
// src/commands/appspace/compare.ts
|
|
3801
|
+
import { createHash as createHash4, randomBytes as randomBytes2 } from "crypto";
|
|
3802
|
+
import { chmod as chmod2, readFile as readFile12, writeFile as writeFile8 } from "fs/promises";
|
|
3803
|
+
import { join as join17 } from "path";
|
|
3804
|
+
|
|
3515
3805
|
// src/commands/appspace/_folder.ts
|
|
3516
3806
|
import { readFile, readdir, stat, writeFile as writeFile2 } from "fs/promises";
|
|
3517
3807
|
import { join as join4 } from "path";
|
|
@@ -45639,6 +45929,7 @@ function registerAppSpaceCommand(root) {
|
|
|
45639
45929
|
registerCompareCommand(cmd);
|
|
45640
45930
|
registerPublishCommands(cmd);
|
|
45641
45931
|
registerSecretsCommand(cmd);
|
|
45932
|
+
registerApproveHostsCommand(cmd);
|
|
45642
45933
|
}
|
|
45643
45934
|
|
|
45644
45935
|
// src/commands/update.ts
|