@datarails-ai/dr-appspace-cli 0.12.89 → 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 +1487 -1286
- 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,1136 +442,1512 @@ function msgOf(err) {
|
|
|
433
442
|
return err instanceof Error ? err.message : String(err);
|
|
434
443
|
}
|
|
435
444
|
|
|
436
|
-
// src/auth/
|
|
437
|
-
import {
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
445
|
+
// src/auth/keyring/fileBackend.ts
|
|
446
|
+
import { rm as rm2 } from "fs/promises";
|
|
447
|
+
|
|
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();
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// src/servers/servers.ts
|
|
458
|
+
var UnknownServerError = class extends Error {
|
|
459
|
+
code = "ERR_UNKNOWN_SERVER";
|
|
460
|
+
constructor(input) {
|
|
461
|
+
super(`unknown server: ${JSON.stringify(input)}`);
|
|
462
|
+
this.name = "UnknownServerError";
|
|
451
463
|
}
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
return;
|
|
464
|
+
};
|
|
465
|
+
var InvalidServerUrlError = class extends Error {
|
|
466
|
+
code = "ERR_INVALID_SERVER_URL";
|
|
467
|
+
constructor(input, reason) {
|
|
468
|
+
super(`invalid server URL ${JSON.stringify(input)}: ${reason}`);
|
|
469
|
+
this.name = "InvalidServerUrlError";
|
|
459
470
|
}
|
|
471
|
+
};
|
|
472
|
+
var ordered = [
|
|
473
|
+
{ key: "US", host: "https://app.datarails.com", subDomain: "us" },
|
|
474
|
+
{ key: "US2", host: "https://us-2.datarails.com", subDomain: "us-2" },
|
|
475
|
+
{ key: "UK", host: "https://ukapp.datarails.com", subDomain: "uk" },
|
|
476
|
+
{ key: "CA", host: "https://caapp.datarails.com", subDomain: "canada" },
|
|
477
|
+
{ key: "EU", host: "https://euapp.datarails.com", subDomain: "eu" },
|
|
478
|
+
{ key: "STUDIO", host: "https://studio.datarails.com", subDomain: "studio" },
|
|
479
|
+
{ key: "DEV", host: "https://dev.datarails.com", subDomain: "dev" },
|
|
480
|
+
{ key: "DEV-1", host: "https://dev-1.datarails.com", subDomain: "dev-1" },
|
|
481
|
+
{ key: "TEST", host: "https://testapp.datarails.com", subDomain: "test" },
|
|
482
|
+
{ key: "TEST-1", host: "https://test-1.datarails.com", subDomain: "test-1" },
|
|
483
|
+
{ key: "TEST-2", host: "https://test-2.datarails.com", subDomain: "test-2" },
|
|
484
|
+
{ key: "TEST-3", host: "https://test-3.datarails.com", subDomain: "test-3" },
|
|
485
|
+
{ key: "TEST-4", host: "https://test-4.datarails.com", subDomain: "test-4" },
|
|
486
|
+
{ key: "TEST-5", host: "https://test-5.datarails.com", subDomain: "test-5" },
|
|
487
|
+
{ key: "TEST-6", host: "https://test-6.datarails.com", subDomain: "test-6" },
|
|
488
|
+
{ key: "TEST-7", host: "https://test-7.datarails.com", subDomain: "test-7" },
|
|
489
|
+
{ key: "DEMO", host: "https://demoapp.datarails.com", subDomain: "demo" }
|
|
490
|
+
];
|
|
491
|
+
var byKey = new Map(ordered.map((s) => [s.key, s]));
|
|
492
|
+
function lookup(input) {
|
|
493
|
+
const key = input.trim().toUpperCase();
|
|
494
|
+
const s = byKey.get(key);
|
|
495
|
+
if (!s) throw new UnknownServerError(input);
|
|
496
|
+
return s;
|
|
497
|
+
}
|
|
498
|
+
function list() {
|
|
499
|
+
return ordered;
|
|
500
|
+
}
|
|
501
|
+
function keys() {
|
|
502
|
+
return ordered.map((s) => s.key);
|
|
503
|
+
}
|
|
504
|
+
function isLikelyUrl(s) {
|
|
505
|
+
return s.includes("://") || /^https?:/i.test(s);
|
|
506
|
+
}
|
|
507
|
+
function isBareDatarailsHost(s) {
|
|
508
|
+
return !s.includes("/") && s.toLowerCase().endsWith(".datarails.com");
|
|
509
|
+
}
|
|
510
|
+
function resolveUrl(raw) {
|
|
511
|
+
let url;
|
|
460
512
|
try {
|
|
461
|
-
|
|
513
|
+
url = new URL(raw);
|
|
462
514
|
} catch {
|
|
515
|
+
throw new InvalidServerUrlError(raw, "could not parse URL; expected https://<host>.datarails.com");
|
|
463
516
|
}
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
517
|
+
if (url.protocol !== "https:") {
|
|
518
|
+
throw new InvalidServerUrlError(raw, "only https is supported for a --server URL");
|
|
519
|
+
}
|
|
520
|
+
const host = url.hostname.toLowerCase();
|
|
521
|
+
if (!host.endsWith(".datarails.com")) {
|
|
522
|
+
throw new InvalidServerUrlError(raw, "--server URL must point at a *.datarails.com host");
|
|
523
|
+
}
|
|
524
|
+
const normalizedHost = `https://${host}`;
|
|
525
|
+
const known = ordered.find((s) => s.host === normalizedHost);
|
|
526
|
+
if (known) return known;
|
|
527
|
+
return { key: host, host: normalizedHost };
|
|
467
528
|
}
|
|
468
|
-
function
|
|
469
|
-
|
|
529
|
+
function resolve2(input) {
|
|
530
|
+
const trimmed = input.trim();
|
|
531
|
+
if (isLikelyUrl(trimmed)) return resolveUrl(trimmed);
|
|
532
|
+
if (isBareDatarailsHost(trimmed)) return resolveUrl(`https://${trimmed}`);
|
|
533
|
+
return lookup(trimmed);
|
|
470
534
|
}
|
|
471
535
|
|
|
472
|
-
// src/auth/
|
|
473
|
-
var
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
this.backend = backend;
|
|
536
|
+
// src/auth/errors.ts
|
|
537
|
+
var NotLoggedInError = class extends Error {
|
|
538
|
+
code = "ERR_NOT_LOGGED_IN";
|
|
539
|
+
constructor(message) {
|
|
540
|
+
super(message ?? "not logged in");
|
|
541
|
+
this.name = "NotLoggedInError";
|
|
479
542
|
}
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
543
|
+
};
|
|
544
|
+
var SessionExpiredError = class extends Error {
|
|
545
|
+
code = "ERR_SESSION_EXPIRED";
|
|
546
|
+
constructor(message) {
|
|
547
|
+
super(message ?? "session expired; re-login required");
|
|
548
|
+
this.name = "SessionExpiredError";
|
|
483
549
|
}
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
550
|
+
};
|
|
551
|
+
var LoginAsError = class _LoginAsError extends Error {
|
|
552
|
+
httpStatus;
|
|
553
|
+
errorCode;
|
|
554
|
+
detail;
|
|
555
|
+
constructor(httpStatus, info = {}) {
|
|
556
|
+
super(_LoginAsError.buildMessage(httpStatus, info));
|
|
557
|
+
this.name = "LoginAsError";
|
|
558
|
+
this.httpStatus = httpStatus;
|
|
559
|
+
this.errorCode = info.code;
|
|
560
|
+
this.detail = info.detail;
|
|
561
|
+
}
|
|
562
|
+
/** Alias so callers/tests can read `.code` symmetrically with the sibling errors. */
|
|
563
|
+
get code() {
|
|
564
|
+
return this.errorCode;
|
|
565
|
+
}
|
|
566
|
+
static buildMessage(status, info) {
|
|
567
|
+
if (info.code !== void 0 && info.code !== "") {
|
|
568
|
+
const tail = info.detail !== void 0 && info.detail !== "" ? `: ${info.detail}` : "";
|
|
569
|
+
return `login-as denied (${info.code})${tail} (HTTP ${status})`;
|
|
492
570
|
}
|
|
493
|
-
|
|
494
|
-
return
|
|
571
|
+
const body = info.body !== void 0 && info.body !== "" ? `: ${info.body}` : "";
|
|
572
|
+
return `login-as failed: HTTP ${status}${body}`;
|
|
495
573
|
}
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
574
|
+
};
|
|
575
|
+
|
|
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
|
+
];
|
|
597
|
+
}
|
|
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 {
|
|
511
641
|
try {
|
|
512
|
-
|
|
642
|
+
notes = await revoke(host, session) ?? [];
|
|
513
643
|
} catch {
|
|
514
|
-
|
|
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 });
|
|
644
|
+
notes = ["Warning: could not revoke the stored refresh token server-side."];
|
|
533
645
|
}
|
|
534
|
-
return out;
|
|
535
646
|
}
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
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";
|
|
548
663
|
}
|
|
549
|
-
|
|
550
|
-
|
|
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);
|
|
679
|
+
}
|
|
680
|
+
function trimTrailingSlash(s) {
|
|
681
|
+
return s.replace(/\/+$/, "");
|
|
682
|
+
}
|
|
683
|
+
function base64UrlDecode(input) {
|
|
684
|
+
const padded = input.replace(/-/g, "+").replace(/_/g, "/");
|
|
685
|
+
const padLen = (4 - padded.length % 4) % 4;
|
|
686
|
+
return Buffer.from(padded + "=".repeat(padLen), "base64");
|
|
687
|
+
}
|
|
688
|
+
function decodeJwtClaims(token) {
|
|
689
|
+
const parts = token.split(".");
|
|
690
|
+
if (parts.length !== 3) {
|
|
691
|
+
throw new Error(`jwt: expected 3 parts, got ${parts.length}`);
|
|
692
|
+
}
|
|
693
|
+
let decoded;
|
|
694
|
+
try {
|
|
695
|
+
decoded = base64UrlDecode(parts[1]).toString("utf8");
|
|
696
|
+
} catch (err) {
|
|
697
|
+
throw new Error(`jwt: decode payload: ${msgOf2(err)}`);
|
|
698
|
+
}
|
|
699
|
+
let parsed2;
|
|
700
|
+
try {
|
|
701
|
+
parsed2 = JSON.parse(decoded);
|
|
702
|
+
} catch (err) {
|
|
703
|
+
throw new Error(`jwt: parse claims: ${msgOf2(err)}`);
|
|
704
|
+
}
|
|
705
|
+
if (parsed2 === null || typeof parsed2 !== "object" || Array.isArray(parsed2)) {
|
|
706
|
+
throw new Error("jwt: parse claims: expected object");
|
|
707
|
+
}
|
|
708
|
+
return parsed2;
|
|
709
|
+
}
|
|
710
|
+
function decodeJwtExpiration(token) {
|
|
711
|
+
const claims = decodeJwtClaims(token);
|
|
712
|
+
const exp = claims.exp;
|
|
713
|
+
if (typeof exp !== "number" || !Number.isFinite(exp) || exp === 0) {
|
|
714
|
+
throw new Error("jwt: no exp claim");
|
|
715
|
+
}
|
|
716
|
+
return new Date(exp * 1e3);
|
|
717
|
+
}
|
|
718
|
+
function parseTokenBody(text4) {
|
|
719
|
+
const raw = JSON.parse(text4);
|
|
720
|
+
if (raw === null || typeof raw !== "object") {
|
|
721
|
+
throw new Error("expected object");
|
|
722
|
+
}
|
|
723
|
+
const obj5 = raw;
|
|
724
|
+
return {
|
|
725
|
+
access: typeof obj5.access === "string" ? obj5.access : "",
|
|
726
|
+
refresh: typeof obj5.refresh === "string" ? obj5.refresh : ""
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
function errorCodeOf(text4) {
|
|
730
|
+
try {
|
|
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 "";
|
|
737
|
+
}
|
|
738
|
+
}
|
|
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;
|
|
747
|
+
}
|
|
748
|
+
};
|
|
749
|
+
async function refreshExternalJwt(host, refreshToken, options) {
|
|
750
|
+
const base = trimTrailingSlash(host);
|
|
751
|
+
const res = await fetch(`${base}/jwt/api/external/token/refresh/`, {
|
|
752
|
+
method: "POST",
|
|
753
|
+
headers: { "Content-Type": "application/json" },
|
|
754
|
+
body: JSON.stringify({ refresh: refreshToken }),
|
|
755
|
+
signal: options?.signal
|
|
756
|
+
});
|
|
757
|
+
const text4 = await res.text();
|
|
758
|
+
if (!res.ok) {
|
|
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");
|
|
768
|
+
}
|
|
769
|
+
if (out.access === "") {
|
|
770
|
+
throw new Error("jwt external refresh: empty access token");
|
|
771
|
+
}
|
|
772
|
+
let expiresAt;
|
|
773
|
+
try {
|
|
774
|
+
expiresAt = decodeJwtExpiration(out.access);
|
|
775
|
+
} catch (err) {
|
|
776
|
+
throw new Error(`jwt external refresh: ${msgOf2(err)}`);
|
|
777
|
+
}
|
|
778
|
+
return { access: out.access, refresh: out.refresh, expiresAt };
|
|
779
|
+
}
|
|
780
|
+
async function revokeRefreshToken(host, refreshToken, options) {
|
|
781
|
+
try {
|
|
782
|
+
const res = await fetch(`${trimTrailingSlash(host)}/jwt/api/token/revoke/`, {
|
|
783
|
+
method: "POST",
|
|
784
|
+
headers: { "Content-Type": "application/json" },
|
|
785
|
+
body: JSON.stringify({ refresh: refreshToken }),
|
|
786
|
+
signal: options?.signal
|
|
787
|
+
});
|
|
788
|
+
return res.ok ? void 0 : `HTTP ${res.status}`;
|
|
789
|
+
} catch (err) {
|
|
790
|
+
return msgOf2(err);
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
async function loginAs(host, operatorAccessToken, userId, options) {
|
|
794
|
+
const base = trimTrailingSlash(host);
|
|
795
|
+
const body = { user_id: userId };
|
|
796
|
+
if (options?.prevRefresh !== void 0 && options.prevRefresh !== "") {
|
|
797
|
+
body.prev_refresh = options.prevRefresh;
|
|
798
|
+
}
|
|
799
|
+
const res = await fetch(`${base}/jwt/api/loginas/`, {
|
|
800
|
+
method: "POST",
|
|
801
|
+
headers: {
|
|
802
|
+
"Content-Type": "application/json",
|
|
803
|
+
Authorization: `Bearer ${operatorAccessToken}`
|
|
804
|
+
},
|
|
805
|
+
body: JSON.stringify(body),
|
|
806
|
+
signal: options?.signal
|
|
807
|
+
});
|
|
808
|
+
const text4 = await res.text();
|
|
809
|
+
if (!res.ok) {
|
|
810
|
+
let code;
|
|
811
|
+
let detail;
|
|
551
812
|
try {
|
|
552
|
-
parsed2 = JSON.parse(
|
|
813
|
+
const parsed2 = JSON.parse(text4);
|
|
814
|
+
if (typeof parsed2["code"] === "string") code = parsed2["code"];
|
|
815
|
+
if (typeof parsed2["detail"] === "string") detail = parsed2["detail"];
|
|
553
816
|
} catch {
|
|
554
|
-
return out;
|
|
555
817
|
}
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
818
|
+
throw new LoginAsError(res.status, {
|
|
819
|
+
code,
|
|
820
|
+
detail,
|
|
821
|
+
body: truncate(text4, TRUNCATE)
|
|
822
|
+
});
|
|
823
|
+
}
|
|
824
|
+
let raw;
|
|
825
|
+
try {
|
|
826
|
+
raw = JSON.parse(text4);
|
|
827
|
+
} catch (err) {
|
|
828
|
+
throw new Error(`jwt loginas parse: ${msgOf2(err)}`);
|
|
829
|
+
}
|
|
830
|
+
if (raw === null || typeof raw !== "object") {
|
|
831
|
+
throw new Error("jwt loginas parse: expected object");
|
|
832
|
+
}
|
|
833
|
+
const obj5 = raw;
|
|
834
|
+
const access2 = typeof obj5["access"] === "string" ? obj5["access"] : "";
|
|
835
|
+
const refresh = typeof obj5["refresh"] === "string" ? obj5["refresh"] : "";
|
|
836
|
+
if (access2 === "") {
|
|
837
|
+
throw new Error("jwt loginas: empty access token");
|
|
838
|
+
}
|
|
839
|
+
let expiresAt;
|
|
840
|
+
try {
|
|
841
|
+
expiresAt = decodeJwtExpiration(access2);
|
|
842
|
+
} catch (err) {
|
|
843
|
+
throw new Error(`jwt loginas: ${msgOf2(err)}`);
|
|
844
|
+
}
|
|
845
|
+
return { access: access2, refresh, expiresAt, user: obj5["user"] };
|
|
846
|
+
}
|
|
847
|
+
async function exchangeApiKey(host, apiKey, options) {
|
|
848
|
+
const key = apiKey.trim();
|
|
849
|
+
if (key === "") {
|
|
850
|
+
throw new Error("api-key exchange: the stored API key is empty");
|
|
851
|
+
}
|
|
852
|
+
if (options?.opaque === true) {
|
|
853
|
+
if (/[\r\n\0]/.test(key) || !/^[\x00-\xff]+$/.test(key)) {
|
|
854
|
+
throw new Error(
|
|
855
|
+
"api-key exchange: the environment variable named by apiKeyEnvVar holds a value that cannot travel in an HTTP header (a line break, NUL, or a character above U+00FF)"
|
|
856
|
+
);
|
|
563
857
|
}
|
|
564
|
-
|
|
858
|
+
} else if (!/^[\x21-\x7e]+$/.test(key)) {
|
|
859
|
+
throw new Error(
|
|
860
|
+
"api-key exchange: only a printable-ASCII API key with no spaces is accepted; the stored one contains whitespace, control characters, or non-ASCII characters"
|
|
861
|
+
);
|
|
565
862
|
}
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
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;
|
|
863
|
+
const base = trimTrailingSlash(host);
|
|
864
|
+
const res = await fetch(`${base}/jwt/api/apikey/token/`, {
|
|
865
|
+
method: "POST",
|
|
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;
|
|
585
872
|
try {
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
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;
|
|
873
|
+
const value = JSON.parse(text4)["error"];
|
|
874
|
+
if (value === "invalid_key" || value === "exchange_unavailable") code = value;
|
|
875
|
+
} catch {
|
|
645
876
|
}
|
|
646
|
-
|
|
877
|
+
throw new Error(
|
|
878
|
+
`api-key exchange: HTTP ${res.status}${code !== void 0 ? ` (${code})` : ""}`
|
|
879
|
+
);
|
|
647
880
|
}
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
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 });
|
|
712
986
|
}
|
|
713
|
-
|
|
714
|
-
|
|
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 = "";
|
|
715
999
|
}
|
|
716
|
-
|
|
717
|
-
|
|
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}`);
|
|
718
1015
|
}
|
|
719
|
-
if (
|
|
720
|
-
|
|
1016
|
+
if (usesApiKey(current)) {
|
|
1017
|
+
const host = opts.host ?? resolve2(serverKey).host;
|
|
1018
|
+
return exchangeKeyedSession(store, serverKey, email, current, host, { ...opts, signal });
|
|
721
1019
|
}
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
1020
|
+
if (isLegacyCookieSession(current)) {
|
|
1021
|
+
throw await retireLegacySession(
|
|
1022
|
+
store,
|
|
1023
|
+
serverKey,
|
|
1024
|
+
email,
|
|
1025
|
+
current,
|
|
1026
|
+
opts.host ?? resolve2(serverKey).host
|
|
1027
|
+
);
|
|
727
1028
|
}
|
|
728
|
-
if (
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
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));
|
|
732
1058
|
}
|
|
733
|
-
|
|
734
|
-
email:
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
});
|
|
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
|
+
);
|
|
738
1063
|
}
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
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 {
|
|
744
1076
|
try {
|
|
745
|
-
|
|
746
|
-
} catch {
|
|
747
|
-
|
|
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
|
+
);
|
|
748
1086
|
}
|
|
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
1087
|
}
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
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) {
|
|
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) {
|
|
768
1093
|
try {
|
|
769
|
-
|
|
770
|
-
map.set(entry.email, entry);
|
|
771
|
-
await this.writeIndex(serverKey, [...map.values()]);
|
|
1094
|
+
latest = await store.getSession(serverKey, email);
|
|
772
1095
|
} catch {
|
|
1096
|
+
latest = null;
|
|
773
1097
|
}
|
|
774
1098
|
}
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
} catch {
|
|
785
|
-
idx = [];
|
|
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;
|
|
786
1108
|
}
|
|
787
|
-
if (
|
|
788
|
-
|
|
789
|
-
} else {
|
|
790
|
-
try {
|
|
791
|
-
await this.writeIndex(serverKey, idx);
|
|
792
|
-
} catch {
|
|
793
|
-
}
|
|
1109
|
+
if (!usesApiKey(latest) && (storedRefresh === startedRefresh || sameRefreshToken(storedRefresh, startedRefresh))) {
|
|
1110
|
+
return void 0;
|
|
794
1111
|
}
|
|
795
|
-
return true;
|
|
796
1112
|
}
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
savedAt: e.savedAt.toISOString(),
|
|
801
|
-
lastUsedAt: e.lastUsedAt.toISOString()
|
|
802
|
-
}));
|
|
803
|
-
await this.backend.set(SERVICE, INDEX_PREFIX + serverKey, JSON.stringify(serialized));
|
|
1113
|
+
await revokeStoredCredentials(host, next);
|
|
1114
|
+
if (latest === void 0) {
|
|
1115
|
+
throw new NotLoggedInError(`not logged in: ${serverKey}:${email}`);
|
|
804
1116
|
}
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
if (typeof value !== "string" || value === "") return void 0;
|
|
808
|
-
const d = new Date(value);
|
|
809
|
-
return Number.isNaN(d.getTime()) ? void 0 : d;
|
|
810
|
-
}
|
|
811
|
-
|
|
812
|
-
// src/servers/servers.ts
|
|
813
|
-
var UnknownServerError = class extends Error {
|
|
814
|
-
code = "ERR_UNKNOWN_SERVER";
|
|
815
|
-
constructor(input) {
|
|
816
|
-
super(`unknown server: ${JSON.stringify(input)}`);
|
|
817
|
-
this.name = "UnknownServerError";
|
|
1117
|
+
if (isLegacyCookieSession(latest)) {
|
|
1118
|
+
throw await retireLegacySession(store, serverKey, email, latest, host);
|
|
818
1119
|
}
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
code = "ERR_INVALID_SERVER_URL";
|
|
822
|
-
constructor(input, reason) {
|
|
823
|
-
super(`invalid server URL ${JSON.stringify(input)}: ${reason}`);
|
|
824
|
-
this.name = "InvalidServerUrlError";
|
|
1120
|
+
if (usesApiKey(latest)) {
|
|
1121
|
+
return exchangeKeyedSession(store, serverKey, email, latest, host, opts);
|
|
825
1122
|
}
|
|
826
|
-
|
|
827
|
-
var ordered = [
|
|
828
|
-
{ key: "US", host: "https://app.datarails.com", subDomain: "us" },
|
|
829
|
-
{ key: "US2", host: "https://us-2.datarails.com", subDomain: "us-2" },
|
|
830
|
-
{ key: "UK", host: "https://ukapp.datarails.com", subDomain: "uk" },
|
|
831
|
-
{ key: "CA", host: "https://caapp.datarails.com", subDomain: "canada" },
|
|
832
|
-
{ key: "EU", host: "https://euapp.datarails.com", subDomain: "eu" },
|
|
833
|
-
{ key: "STUDIO", host: "https://studio.datarails.com", subDomain: "studio" },
|
|
834
|
-
{ key: "DEV", host: "https://dev.datarails.com", subDomain: "dev" },
|
|
835
|
-
{ key: "DEV-1", host: "https://dev-1.datarails.com", subDomain: "dev-1" },
|
|
836
|
-
{ key: "TEST", host: "https://testapp.datarails.com", subDomain: "test" },
|
|
837
|
-
{ key: "TEST-1", host: "https://test-1.datarails.com", subDomain: "test-1" },
|
|
838
|
-
{ key: "TEST-2", host: "https://test-2.datarails.com", subDomain: "test-2" },
|
|
839
|
-
{ key: "TEST-3", host: "https://test-3.datarails.com", subDomain: "test-3" },
|
|
840
|
-
{ key: "TEST-4", host: "https://test-4.datarails.com", subDomain: "test-4" },
|
|
841
|
-
{ key: "TEST-5", host: "https://test-5.datarails.com", subDomain: "test-5" },
|
|
842
|
-
{ key: "TEST-6", host: "https://test-6.datarails.com", subDomain: "test-6" },
|
|
843
|
-
{ key: "TEST-7", host: "https://test-7.datarails.com", subDomain: "test-7" },
|
|
844
|
-
{ key: "DEMO", host: "https://demoapp.datarails.com", subDomain: "demo" }
|
|
845
|
-
];
|
|
846
|
-
var byKey = new Map(ordered.map((s) => [s.key, s]));
|
|
847
|
-
function lookup(input) {
|
|
848
|
-
const key = input.trim().toUpperCase();
|
|
849
|
-
const s = byKey.get(key);
|
|
850
|
-
if (!s) throw new UnknownServerError(input);
|
|
851
|
-
return s;
|
|
852
|
-
}
|
|
853
|
-
function list() {
|
|
854
|
-
return ordered;
|
|
855
|
-
}
|
|
856
|
-
function keys() {
|
|
857
|
-
return ordered.map((s) => s.key);
|
|
1123
|
+
return latest;
|
|
858
1124
|
}
|
|
859
|
-
function
|
|
860
|
-
return
|
|
861
|
-
}
|
|
862
|
-
function isBareDatarailsHost(s) {
|
|
863
|
-
return !s.includes("/") && s.toLowerCase().endsWith(".datarails.com");
|
|
1125
|
+
function sameApiKey(a, b) {
|
|
1126
|
+
return (a.apiKey ?? "") === (b.apiKey ?? "") && (a.apiKeyEnvVar ?? "") === (b.apiKeyEnvVar ?? "");
|
|
864
1127
|
}
|
|
865
|
-
function
|
|
866
|
-
|
|
1128
|
+
function sameRefreshToken(a, b) {
|
|
1129
|
+
if (a === "" || b === "") return false;
|
|
1130
|
+
if (a === b) return true;
|
|
867
1131
|
try {
|
|
868
|
-
|
|
1132
|
+
const ja = decodeJwtClaims(a)["jti"];
|
|
1133
|
+
const jb = decodeJwtClaims(b)["jti"];
|
|
1134
|
+
return typeof ja === "string" && ja !== "" && ja === jb;
|
|
869
1135
|
} catch {
|
|
870
|
-
|
|
871
|
-
}
|
|
872
|
-
if (url.protocol !== "https:") {
|
|
873
|
-
throw new InvalidServerUrlError(raw, "only https is supported for a --server URL");
|
|
874
|
-
}
|
|
875
|
-
const host = url.hostname.toLowerCase();
|
|
876
|
-
if (!host.endsWith(".datarails.com")) {
|
|
877
|
-
throw new InvalidServerUrlError(raw, "--server URL must point at a *.datarails.com host");
|
|
1136
|
+
return false;
|
|
878
1137
|
}
|
|
879
|
-
const normalizedHost = `https://${host}`;
|
|
880
|
-
const known = ordered.find((s) => s.host === normalizedHost);
|
|
881
|
-
if (known) return known;
|
|
882
|
-
return { key: host, host: normalizedHost };
|
|
883
1138
|
}
|
|
884
|
-
function
|
|
885
|
-
|
|
886
|
-
if (isLikelyUrl(trimmed)) return resolveUrl(trimmed);
|
|
887
|
-
if (isBareDatarailsHost(trimmed)) return resolveUrl(`https://${trimmed}`);
|
|
888
|
-
return lookup(trimmed);
|
|
1139
|
+
function reloginMessage(serverKey, email, why) {
|
|
1140
|
+
return `${serverKey}:${email} (${why}). Run dr-appspace login --server ${serverKey} to log in again.`;
|
|
889
1141
|
}
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
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()}`);
|
|
1142
|
+
async function exchangeKeyedSession(store, serverKey, email, session, host, opts) {
|
|
1143
|
+
if (!opts.force && mintedByStoredApiKey(session) && !jwtExpiringSoon(session, opts.buffer)) {
|
|
1144
|
+
return session;
|
|
907
1145
|
}
|
|
908
|
-
|
|
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;
|
|
909
1153
|
try {
|
|
910
|
-
|
|
1154
|
+
tok = await exchangeApiKey(host, material.key, {
|
|
1155
|
+
signal: opts.signal,
|
|
1156
|
+
opaque: material.fromEnv
|
|
1157
|
+
});
|
|
911
1158
|
} catch (err) {
|
|
912
|
-
|
|
913
|
-
|
|
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
|
+
}
|
|
914
1203
|
}
|
|
915
|
-
|
|
916
|
-
|
|
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
|
+
);
|
|
917
1210
|
}
|
|
918
|
-
const
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
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;
|
|
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
|
+
);
|
|
930
1216
|
}
|
|
931
|
-
|
|
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;
|
|
1217
|
+
let operator;
|
|
943
1218
|
try {
|
|
944
|
-
|
|
1219
|
+
operator = await ensureValidJwt(store, serverKey, operatorEmail, {
|
|
1220
|
+
signal: opts.signal,
|
|
1221
|
+
host
|
|
1222
|
+
});
|
|
945
1223
|
} catch (err) {
|
|
946
|
-
|
|
947
|
-
|
|
1224
|
+
throw new SessionExpiredError(
|
|
1225
|
+
`${serverKey}:${email} (operator ${operatorEmail} session expired \u2014 re-run dr-appspace login --server ${serverKey}; ${msgOf2(err)})`
|
|
1226
|
+
);
|
|
948
1227
|
}
|
|
949
|
-
|
|
950
|
-
|
|
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
|
+
);
|
|
951
1233
|
}
|
|
952
|
-
const
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
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
|
|
956
1243
|
};
|
|
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
1244
|
try {
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
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
|
+
}
|
|
968
1259
|
}
|
|
969
|
-
if (raw === null || typeof raw !== "object") return "";
|
|
970
|
-
const errVal = raw.error;
|
|
971
|
-
return typeof errVal === "string" ? errVal : "";
|
|
972
1260
|
}
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
const
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
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");
|
|
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 {
|
|
1004
1287
|
}
|
|
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
1288
|
}
|
|
1012
|
-
|
|
1013
|
-
|
|
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;
|
|
1014
1333
|
}
|
|
1015
|
-
throw new Error(`token HTTP ${res.status}: ${text4.trim()}`);
|
|
1016
1334
|
}
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
code = "ERR_NOT_LOGGED_IN";
|
|
1031
|
-
constructor(message) {
|
|
1032
|
-
super(message ?? "not logged in");
|
|
1033
|
-
this.name = "NotLoggedInError";
|
|
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
|
+
}
|
|
1034
1348
|
}
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
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
|
+
}
|
|
1041
1362
|
}
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
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
|
+
}
|
|
1053
1399
|
}
|
|
1054
|
-
/**
|
|
1055
|
-
|
|
1056
|
-
|
|
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;
|
|
1057
1415
|
}
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
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
|
+
];
|
|
1065
1425
|
}
|
|
1066
1426
|
};
|
|
1067
1427
|
|
|
1068
|
-
// src/auth/
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
function trimTrailingSlash(s) {
|
|
1078
|
-
return s.replace(/\/+$/, "");
|
|
1079
|
-
}
|
|
1080
|
-
function base64UrlDecode(input) {
|
|
1081
|
-
const padded = input.replace(/-/g, "+").replace(/_/g, "/");
|
|
1082
|
-
const padLen = (4 - padded.length % 4) % 4;
|
|
1083
|
-
return Buffer.from(padded + "=".repeat(padLen), "base64");
|
|
1084
|
-
}
|
|
1085
|
-
function decodeJwtClaims(token) {
|
|
1086
|
-
const parts = token.split(".");
|
|
1087
|
-
if (parts.length !== 3) {
|
|
1088
|
-
throw new Error(`jwt: expected 3 parts, got ${parts.length}`);
|
|
1089
|
-
}
|
|
1090
|
-
let decoded;
|
|
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");
|
|
1091
1437
|
try {
|
|
1092
|
-
|
|
1438
|
+
await fs2.stat(filePath);
|
|
1093
1439
|
} catch (err) {
|
|
1094
|
-
|
|
1440
|
+
if (err.code === "ENOENT") return;
|
|
1441
|
+
log(`dr: warning: could not check ${filePath}: ${msgOf3(err)}`);
|
|
1442
|
+
return;
|
|
1095
1443
|
}
|
|
1096
|
-
let parsed2;
|
|
1097
1444
|
try {
|
|
1098
|
-
|
|
1445
|
+
await fs2.unlink(filePath);
|
|
1099
1446
|
} catch (err) {
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
}
|
|
1105
|
-
return parsed2;
|
|
1106
|
-
}
|
|
1107
|
-
function decodeJwtExpiration(token) {
|
|
1108
|
-
const claims = decodeJwtClaims(token);
|
|
1109
|
-
const exp = claims.exp;
|
|
1110
|
-
if (typeof exp !== "number" || !Number.isFinite(exp) || exp === 0) {
|
|
1111
|
-
throw new Error("jwt: no exp claim");
|
|
1447
|
+
log(
|
|
1448
|
+
`dr: warning: could not remove legacy ${filePath}: ${msgOf3(err)}; please delete manually.`
|
|
1449
|
+
);
|
|
1450
|
+
return;
|
|
1112
1451
|
}
|
|
1113
|
-
return new Date(exp * 1e3);
|
|
1114
|
-
}
|
|
1115
|
-
function parseTokenBody(text4, label) {
|
|
1116
|
-
let raw;
|
|
1117
1452
|
try {
|
|
1118
|
-
|
|
1119
|
-
} catch
|
|
1120
|
-
throw new Error(`jwt ${label} parse: ${msgOf3(err)}`);
|
|
1121
|
-
}
|
|
1122
|
-
if (raw === null || typeof raw !== "object") {
|
|
1123
|
-
throw new Error(`jwt ${label} parse: expected object`);
|
|
1453
|
+
await fs2.rmdir(drDir);
|
|
1454
|
+
} catch {
|
|
1124
1455
|
}
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
refresh: typeof obj5.refresh === "string" ? obj5.refresh : ""
|
|
1129
|
-
};
|
|
1456
|
+
log(
|
|
1457
|
+
`dr: removed legacy ${filePath} \u2014 run dr-appspace login --server <key> to re-authenticate.`
|
|
1458
|
+
);
|
|
1130
1459
|
}
|
|
1131
|
-
|
|
1132
|
-
|
|
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;
|
|
1153
|
-
try {
|
|
1154
|
-
expiresAt = decodeJwtExpiration(out.access);
|
|
1155
|
-
} catch (err) {
|
|
1156
|
-
throw new Error(`jwt mint: ${msgOf3(err)}`);
|
|
1157
|
-
}
|
|
1158
|
-
return { access: out.access, refresh: out.refresh, expiresAt };
|
|
1460
|
+
function msgOf3(err) {
|
|
1461
|
+
return err instanceof Error ? err.message : String(err);
|
|
1159
1462
|
}
|
|
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)}`);
|
|
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;
|
|
1174
1471
|
}
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1472
|
+
backend;
|
|
1473
|
+
static default() {
|
|
1474
|
+
return new _KeyringStore(new NapiKeyringBackend());
|
|
1178
1475
|
}
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
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();
|
|
1184
1487
|
}
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
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;
|
|
1198
1527
|
}
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
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;
|
|
1202
1557
|
}
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
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;
|
|
1208
1643
|
}
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
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
|
|
1218
1733
|
});
|
|
1219
|
-
return res.ok ? void 0 : `HTTP ${res.status}`;
|
|
1220
|
-
} catch (err) {
|
|
1221
|
-
return msgOf3(err);
|
|
1222
|
-
}
|
|
1223
|
-
}
|
|
1224
|
-
async function loginAs(host, operatorAccessToken, userId, options) {
|
|
1225
|
-
const base = trimTrailingSlash(host);
|
|
1226
|
-
const body = { user_id: userId };
|
|
1227
|
-
if (options?.prevRefresh !== void 0 && options.prevRefresh !== "") {
|
|
1228
|
-
body.prev_refresh = options.prevRefresh;
|
|
1229
1734
|
}
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
},
|
|
1236
|
-
body: JSON.stringify(body),
|
|
1237
|
-
signal: options?.signal
|
|
1238
|
-
});
|
|
1239
|
-
const text4 = await res.text();
|
|
1240
|
-
if (!res.ok) {
|
|
1241
|
-
let code;
|
|
1242
|
-
let detail;
|
|
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;
|
|
1243
1740
|
try {
|
|
1244
|
-
|
|
1245
|
-
if (typeof parsed2["code"] === "string") code = parsed2["code"];
|
|
1246
|
-
if (typeof parsed2["detail"] === "string") detail = parsed2["detail"];
|
|
1741
|
+
blob = JSON.parse(raw);
|
|
1247
1742
|
} catch {
|
|
1743
|
+
return;
|
|
1248
1744
|
}
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
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
|
|
1253
1758
|
});
|
|
1254
1759
|
}
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
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
|
+
}
|
|
1260
1775
|
}
|
|
1261
|
-
|
|
1262
|
-
|
|
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;
|
|
1263
1782
|
}
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
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;
|
|
1269
1804
|
}
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
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));
|
|
1275
1812
|
}
|
|
1276
|
-
|
|
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;
|
|
1277
1818
|
}
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
}
|
|
1289
|
-
} else if (!/^[\x21-\x7e]+$/.test(key)) {
|
|
1290
|
-
throw new Error(
|
|
1291
|
-
"api-key exchange: only a printable-ASCII API key with no spaces is accepted; the stored one contains whitespace, control characters, or non-ASCII characters"
|
|
1292
|
-
);
|
|
1293
|
-
}
|
|
1294
|
-
const base = trimTrailingSlash(host);
|
|
1295
|
-
const res = await fetch(`${base}/jwt/api/apikey/token/`, {
|
|
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}`, {
|
|
1296
1829
|
method: "POST",
|
|
1297
|
-
headers: {
|
|
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)}`);
|
|
1330
|
-
}
|
|
1331
|
-
return { access: access2, expiresAt };
|
|
1332
|
-
}
|
|
1333
|
-
function apiKeyFingerprint(apiKey) {
|
|
1334
|
-
return createHash("sha256").update(apiKey.trim()).digest("hex").slice(0, 32);
|
|
1335
|
-
}
|
|
1336
|
-
function resolveApiKeyMaterial(session) {
|
|
1337
|
-
if (session.apiKey !== void 0 && session.apiKey !== "") {
|
|
1338
|
-
return { key: session.apiKey, fromEnv: false };
|
|
1339
|
-
}
|
|
1340
|
-
const name = session.apiKeyEnvVar;
|
|
1341
|
-
if (name === void 0 || name === "") {
|
|
1342
|
-
throw new Error("api-key exchange: the session carries no API key");
|
|
1343
|
-
}
|
|
1344
|
-
const value = process.env[name];
|
|
1345
|
-
if (value === void 0 || value === "") {
|
|
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
|
-
);
|
|
1852
|
+
throw new Error(`device/code parse: expected object`);
|
|
1349
1853
|
}
|
|
1350
|
-
|
|
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
|
+
};
|
|
1351
1861
|
}
|
|
1352
|
-
|
|
1353
|
-
if (
|
|
1354
|
-
|
|
1355
|
-
return
|
|
1862
|
+
var defaultSleep = (ms, signal) => new Promise((resolve18, reject) => {
|
|
1863
|
+
if (signal?.aborted) {
|
|
1864
|
+
reject(signal.reason ?? new Error("aborted"));
|
|
1865
|
+
return;
|
|
1356
1866
|
}
|
|
1357
|
-
|
|
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;
|
|
1358
1879
|
try {
|
|
1359
|
-
|
|
1880
|
+
raw = JSON.parse(text4);
|
|
1360
1881
|
} catch {
|
|
1361
|
-
|
|
1362
|
-
}
|
|
1363
|
-
return session.jwtApiKeyFingerprint === apiKeyFingerprint(material.key);
|
|
1364
|
-
}
|
|
1365
|
-
async function ensureValidJwt(store, serverKey, email, options) {
|
|
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
|
-
});
|
|
1380
|
-
}
|
|
1381
|
-
async function ensureJwt(store, serverKey, email, opts) {
|
|
1382
|
-
const session = await store.getSession(serverKey, email);
|
|
1383
|
-
if (session === void 0) {
|
|
1384
|
-
throw new NotLoggedInError(`not logged in: ${serverKey}:${email}`);
|
|
1385
|
-
}
|
|
1386
|
-
if (usesApiKey(session)) {
|
|
1387
|
-
const host2 = opts.host ?? resolve2(serverKey).host;
|
|
1388
|
-
return exchangeKeyedSession(store, serverKey, email, session, host2, opts);
|
|
1389
|
-
}
|
|
1390
|
-
if (!opts.force && session.jwtAccess !== void 0 && session.jwtAccess !== "" && !jwtExpiringSoon(session, opts.buffer)) {
|
|
1391
|
-
return session;
|
|
1392
|
-
}
|
|
1393
|
-
const host = opts.host ?? resolve2(serverKey).host;
|
|
1394
|
-
if (session.impersonatorEmail !== void 0 && session.impersonatorEmail !== "") {
|
|
1395
|
-
return recoverImpersonatedJwt(store, serverKey, email, session, host, opts);
|
|
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;
|
|
1439
|
-
}
|
|
1440
|
-
}
|
|
1441
|
-
if (mintNext !== void 0) {
|
|
1442
|
-
try {
|
|
1443
|
-
await store.saveSession(serverKey, mintNext);
|
|
1444
|
-
} catch (err) {
|
|
1445
|
-
throw new Error(`save credentials: ${msgOf3(err)}`, { cause: err });
|
|
1446
|
-
}
|
|
1447
|
-
return mintNext;
|
|
1448
|
-
}
|
|
1449
|
-
const reasons = [];
|
|
1450
|
-
if (session.jwtRefresh === void 0 || session.jwtRefresh === "") {
|
|
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
|
|
1478
|
-
});
|
|
1479
|
-
} catch (err) {
|
|
1480
|
-
throw new SessionExpiredError(`${serverKey}:${email} (${msgOf3(err)})`);
|
|
1882
|
+
throw new Error("token parse: the response is not JSON");
|
|
1481
1883
|
}
|
|
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 });
|
|
1884
|
+
if (raw === null || typeof raw !== "object") {
|
|
1885
|
+
throw new Error(`token parse: expected object`);
|
|
1495
1886
|
}
|
|
1496
|
-
return
|
|
1887
|
+
return raw;
|
|
1497
1888
|
}
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
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
|
|
1533
|
-
});
|
|
1534
|
-
} catch (err) {
|
|
1535
|
-
throw new SessionExpiredError(
|
|
1536
|
-
`${serverKey}:${email} (operator ${operatorEmail} session expired \u2014 re-run dr-appspace login --server ${serverKey}; ${msgOf3(err)})`
|
|
1537
|
-
);
|
|
1538
|
-
}
|
|
1539
|
-
const operatorAccess = operator.jwtAccess ?? "";
|
|
1540
|
-
if (operatorAccess === "") {
|
|
1541
|
-
throw new SessionExpiredError(
|
|
1542
|
-
`${serverKey}:${email} (operator ${operatorEmail} has no JWT \u2014 re-run dr-appspace login --server ${serverKey})`
|
|
1543
|
-
);
|
|
1889
|
+
function tryParseErrorCode(text4) {
|
|
1890
|
+
let raw;
|
|
1891
|
+
try {
|
|
1892
|
+
raw = JSON.parse(text4);
|
|
1893
|
+
} catch {
|
|
1894
|
+
return "";
|
|
1544
1895
|
}
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
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 : "";
|
|
1899
|
+
}
|
|
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");
|
|
1915
|
+
}
|
|
1916
|
+
if (signal?.aborted) {
|
|
1917
|
+
throw signal.reason instanceof Error ? signal.reason : new Error("aborted");
|
|
1918
|
+
}
|
|
1919
|
+
const body = new URLSearchParams({
|
|
1920
|
+
grant_type: GRANT_TYPE,
|
|
1921
|
+
client_id: CLIENT_ID,
|
|
1922
|
+
device_code: deviceCode
|
|
1923
|
+
});
|
|
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
|
|
1929
|
+
});
|
|
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`
|