@datarails-ai/dr-appspace-cli 0.12.80 → 0.12.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +24 -0
  2. package/dist/cli.js +303 -9
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -28,6 +28,30 @@ dr-appspace app-space whoami -s DEV
28
28
  or other users can access (anything but `0600` or `0400`) or that another
29
29
  user owns, and says to `chmod 600` it (DR-57810), so a file it reads
30
30
  directly must be owner-only.
31
+ - **`login-as <email>`** — act as a customer org's user (typically
32
+ `support@<org>`) without a browser, the operator recorded on the token
33
+ (`impersonator_id`, audited by the monolith). Log in as yourself first, then
34
+ pass `--account` to the commands that should run as that user:
35
+
36
+ ```
37
+ dr-appspace login -s DEMO
38
+ dr-appspace login-as support@customer.com -s DEMO
39
+ dr-appspace app-space push ./my-app -s DEMO --account support@customer.com
40
+ dr-appspace whoami -s DEMO --account support@customer.com # "Impersonated by: you@datarails.com"
41
+ ```
42
+
43
+ With two identities stored for the server, every command on it needs
44
+ `--account` — `--account you@datarails.com` for your own login too.
45
+ `dr-appspace logout -s DEMO --account support@customer.com` removes the
46
+ impersonated one.
47
+
48
+ It needs the same permission as Login As in the main app
49
+ (`support-manager:write`). `--user-id <n>` skips the email lookup; `--as
50
+ <operator-email>` picks the operator when you have several logins on the
51
+ server. Do not use `dr-appspace login` from a Login As browser tab instead:
52
+ that credential records no operator. `dr app-space …` reads this same
53
+ keychain, so `--account` works there too; `dr login-as` (dr-cli's own store)
54
+ does not.
31
55
  - **`app-space` commands** (ported from `dr-dev-cli app-space`, re-based onto
32
56
  this auth): `whoami`, `list`, `get`, `logs`, `try`, `push`, `publish`,
33
57
  `unpublish` — plus `scaffold`, `preview`, `test`, `contract`, `compile`,
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.80",
16
+ version: "0.12.81",
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-11T08:31:34.925Z";
60
+ var BUILD_TIME = "2026-11-11T15:51:20.638Z";
61
61
  function formatBuildTime(iso) {
62
62
  if (iso === "") return "";
63
63
  const d = new Date(iso);
@@ -1208,6 +1208,19 @@ async function refreshExternalJwt(host, refreshToken, options) {
1208
1208
  }
1209
1209
  return { access: out.access, refresh: out.refresh, expiresAt };
1210
1210
  }
1211
+ async function revokeRefreshToken(host, refreshToken, options) {
1212
+ try {
1213
+ const res = await fetch(`${trimTrailingSlash(host)}/jwt/api/token/revoke/`, {
1214
+ method: "POST",
1215
+ headers: { "Content-Type": "application/json" },
1216
+ body: JSON.stringify({ refresh: refreshToken }),
1217
+ signal: options?.signal
1218
+ });
1219
+ return res.ok ? void 0 : `HTTP ${res.status}`;
1220
+ } catch (err) {
1221
+ return msgOf3(err);
1222
+ }
1223
+ }
1211
1224
  async function loginAs(host, operatorAccessToken, userId, options) {
1212
1225
  const base = trimTrailingSlash(host);
1213
1226
  const body = { user_id: userId };
@@ -1506,6 +1519,12 @@ async function recoverImpersonatedJwt(store, serverKey, email, session, host, op
1506
1519
  `${serverKey}:${email} (impersonation refresh dead and no user id stored to re-mint; re-run dr-appspace login-as)`
1507
1520
  );
1508
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
+ }
1509
1528
  let operator;
1510
1529
  try {
1511
1530
  operator = await ensureValidJwt(store, serverKey, operatorEmail, {
@@ -1534,6 +1553,15 @@ async function recoverImpersonatedJwt(store, serverKey, email, session, host, op
1534
1553
  jwtExpiresAt: result.expiresAt
1535
1554
  };
1536
1555
  await store.saveSession(serverKey, next);
1556
+ if (session.jwtRefresh !== void 0 && session.jwtRefresh !== "") {
1557
+ const failure = await revokeRefreshToken(host, session.jwtRefresh, { signal: opts.signal });
1558
+ if (failure !== void 0) {
1559
+ process.stderr.write(
1560
+ `Warning: could not revoke the previous login-as token for ${serverKey}:${email} (${failure}); it stays valid until it expires.
1561
+ `
1562
+ );
1563
+ }
1564
+ }
1537
1565
  return next;
1538
1566
  }
1539
1567
 
@@ -2444,6 +2472,18 @@ function provisionedExternallyError(path3, action) {
2444
2472
  `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.`
2445
2473
  );
2446
2474
  }
2475
+ async function refuseImpersonationWithCredentialFile() {
2476
+ const action = "log in as another user";
2477
+ const path3 = credentialsFilePath();
2478
+ const creds = await readCredentialsFile(path3);
2479
+ if (creds === void 0) return;
2480
+ if (creds.sessionId === void 0 || creds.sessionId === "") {
2481
+ throw provisionedExternallyError(path3, action);
2482
+ }
2483
+ throw new Error(
2484
+ `cannot ${action}: ${path3} is in use as a single-identity credential store, which cannot hold a second identity. Remove that file to store sessions in the OS keychain instead.`
2485
+ );
2486
+ }
2447
2487
  function fileStoreServerKey(creds, serverFlag) {
2448
2488
  if (serverFlag === void 0 || serverFlag.trim() === "") return creds.server;
2449
2489
  const requested = resolveServer(serverFlag);
@@ -2585,6 +2625,246 @@ async function runLogin(cfg) {
2585
2625
  }
2586
2626
  }
2587
2627
 
2628
+ // src/commands/loginAs.ts
2629
+ import { z as z2 } from "zod";
2630
+ var SEARCH_PAGE_SIZE = 50;
2631
+ var canLoginAsPage = z2.object({
2632
+ next: z2.string().nullable(),
2633
+ results: z2.array(
2634
+ z2.object({
2635
+ id: z2.number().int().positive(),
2636
+ email: z2.string(),
2637
+ profile: z2.object({ organization_name: z2.string().optional() }).nullish()
2638
+ })
2639
+ )
2640
+ });
2641
+ async function resolveOperator(store, serverKey, operatorFlag) {
2642
+ const metas = await store.listSessions(serverKey);
2643
+ if (metas.length === 0) {
2644
+ throw new NotLoggedInError(
2645
+ `not logged in to ${serverKey}; run dr-appspace login --server ${serverKey}`
2646
+ );
2647
+ }
2648
+ const operators = [];
2649
+ const autoSelectable = [];
2650
+ for (const m of metas) {
2651
+ const s = await store.getSession(serverKey, m.email);
2652
+ if (s !== void 0 && (s.impersonatorEmail === void 0 || s.impersonatorEmail === "")) {
2653
+ operators.push(m.email);
2654
+ if (!usesApiKey(s)) autoSelectable.push(m.email);
2655
+ }
2656
+ }
2657
+ if (operatorFlag !== void 0 && operatorFlag !== "") {
2658
+ if (operators.includes(operatorFlag)) return operatorFlag;
2659
+ const list3 = operators.length > 0 ? operators.join(", ") : "(none \u2014 run dr-appspace login)";
2660
+ throw new Error(`${operatorFlag} is not an operator login on ${serverKey}. Operators: ${list3}`);
2661
+ }
2662
+ const candidates = autoSelectable.length > 0 ? autoSelectable : operators;
2663
+ if (candidates.length === 1) return candidates[0];
2664
+ if (candidates.length === 0) {
2665
+ throw new NotLoggedInError(
2666
+ `no operator (browser) login on ${serverKey}; run dr-appspace login --server ${serverKey}`
2667
+ );
2668
+ }
2669
+ const lines = candidates.map((e) => ` - ${e}`).join("\n");
2670
+ throw new Error(
2671
+ `multiple operator logins on ${serverKey}. Specify --as <operator-email>:
2672
+ ${lines}`
2673
+ );
2674
+ }
2675
+ async function resolveTargetUserId(client, targetEmail, signal) {
2676
+ const wanted = targetEmail.toLowerCase();
2677
+ const seen = [];
2678
+ for (let page = 1; ; page += 1) {
2679
+ const qs = new URLSearchParams({
2680
+ search: targetEmail,
2681
+ page: String(page),
2682
+ page_size: String(SEARCH_PAGE_SIZE)
2683
+ });
2684
+ const raw = await client.getJSON(`/api/it/users/can_login_as?${qs}`, { signal });
2685
+ if (raw === null) break;
2686
+ const parsed2 = canLoginAsPage.safeParse(raw);
2687
+ if (!parsed2.success) {
2688
+ throw new Error(`unexpected /api/it/users/can_login_as response: ${parsed2.error.message}`);
2689
+ }
2690
+ const resp = parsed2.data;
2691
+ for (const u of resp.results) {
2692
+ if (u.email.toLowerCase() === wanted) {
2693
+ return { id: u.id, email: u.email, orgName: u.profile?.organization_name ?? "" };
2694
+ }
2695
+ seen.push(u.email);
2696
+ }
2697
+ if (resp.next === null) break;
2698
+ }
2699
+ const near = seen.length > 0 ? ` Did you mean one of: ${seen.slice(0, 10).join(", ")}?` : "";
2700
+ throw new Error(
2701
+ `no user you can log in as matches "${targetEmail}".${near} Use --user-id <n> to impersonate by id.`
2702
+ );
2703
+ }
2704
+ function isImpersonated(s) {
2705
+ return s.impersonatorEmail !== void 0 && s.impersonatorEmail !== "";
2706
+ }
2707
+ async function storedCaseVariants(store, serverKey, email) {
2708
+ const wanted = email.toLowerCase();
2709
+ const out = [];
2710
+ for (const m of await store.listSessions(serverKey)) {
2711
+ if (m.email.toLowerCase() !== wanted) continue;
2712
+ const session = await store.getSession(serverKey, m.email);
2713
+ if (session !== void 0) out.push({ email: m.email, session });
2714
+ }
2715
+ return out;
2716
+ }
2717
+ function refuseOverwritingDirectLogin(serverKey, stored) {
2718
+ const direct = stored.find((s) => !isImpersonated(s.session));
2719
+ if (direct === void 0) return;
2720
+ throw new Error(
2721
+ `${direct.email} is one of your own logins on ${serverKey}; login-as will not replace it. Run dr-appspace logout --server ${serverKey} --account ${direct.email} first.`
2722
+ );
2723
+ }
2724
+ function friendlyLoginAsError(err, targetEmail) {
2725
+ if (err.code === "insufficient_scope" && err.httpStatus === 403) {
2726
+ return new Error(
2727
+ "Your login does not carry the support-manager:write scope that login-as needs."
2728
+ );
2729
+ }
2730
+ switch (err.code) {
2731
+ case "not_permitted":
2732
+ return new Error(`You are not permitted to impersonate ${targetEmail}.`);
2733
+ case "target_inactive":
2734
+ return new Error(`${targetEmail} is inactive and cannot be impersonated.`);
2735
+ case "impersonation_unavailable":
2736
+ return new Error("Impersonation service is temporarily unavailable; try again shortly.");
2737
+ default:
2738
+ return err;
2739
+ }
2740
+ }
2741
+ async function runLoginAs(cfg) {
2742
+ await refuseImpersonationWithCredentialFile();
2743
+ const host = cfg.host ?? resolve2(cfg.serverKey).host;
2744
+ const operatorEmail = await resolveOperator(cfg.store, cfg.serverKey, cfg.operatorFlag);
2745
+ const operatorSession = await cfg.store.getSession(cfg.serverKey, operatorEmail);
2746
+ if (operatorSession !== void 0 && usesApiKey(operatorSession)) {
2747
+ throw new Error(
2748
+ `cannot log in as another user: ${cfg.serverKey}:${operatorEmail} authenticates with an API key, and an API-key token cannot mint further credentials. Run dr-appspace login --server ${cfg.serverKey} as an operator first.`
2749
+ );
2750
+ }
2751
+ const operator = await ensureValidJwt(cfg.store, cfg.serverKey, operatorEmail, {
2752
+ buffer: JWT_REFRESH_BUFFER_MS,
2753
+ host,
2754
+ signal: cfg.signal
2755
+ });
2756
+ const operatorAccess = operator.jwtAccess ?? "";
2757
+ if (operatorAccess === "") {
2758
+ throw new NotLoggedInError(
2759
+ `operator ${operatorEmail} has no JWT on ${cfg.serverKey}; run dr-appspace login --server ${cfg.serverKey}`
2760
+ );
2761
+ }
2762
+ let userId;
2763
+ let targetEmail = cfg.targetEmail;
2764
+ let orgName = "";
2765
+ if (cfg.userIdOverride !== void 0) {
2766
+ userId = cfg.userIdOverride;
2767
+ } else {
2768
+ const client = await AuthorizedClient.create(cfg.store, cfg.serverKey, operatorEmail, {
2769
+ host
2770
+ });
2771
+ const target = await resolveTargetUserId(client, cfg.targetEmail, cfg.signal);
2772
+ userId = target.id;
2773
+ targetEmail = target.email;
2774
+ orgName = target.orgName;
2775
+ }
2776
+ const existing = await storedCaseVariants(cfg.store, cfg.serverKey, targetEmail);
2777
+ refuseOverwritingDirectLogin(cfg.serverKey, existing);
2778
+ const prevRefresh = existing.find((s) => isImpersonated(s.session))?.session.jwtRefresh;
2779
+ let result;
2780
+ try {
2781
+ result = await loginAs(host, operatorAccess, userId, {
2782
+ prevRefresh,
2783
+ signal: cfg.signal
2784
+ });
2785
+ } catch (err) {
2786
+ if (err instanceof LoginAsError) throw friendlyLoginAsError(err, cfg.targetEmail);
2787
+ throw err;
2788
+ }
2789
+ let storageEmail = cfg.targetEmail;
2790
+ try {
2791
+ const claim = decodeJwtClaims(result.access)["email"];
2792
+ if (typeof claim === "string" && claim !== "") storageEmail = claim;
2793
+ } catch {
2794
+ }
2795
+ const replaced = storageEmail.toLowerCase() === targetEmail.toLowerCase() ? existing : await storedCaseVariants(cfg.store, cfg.serverKey, storageEmail);
2796
+ try {
2797
+ refuseOverwritingDirectLogin(cfg.serverKey, replaced);
2798
+ } catch (err) {
2799
+ await revokeRefreshToken(host, result.refresh, { signal: cfg.signal });
2800
+ throw err;
2801
+ }
2802
+ const session = {
2803
+ email: storageEmail,
2804
+ sessionId: "",
2805
+ csrfToken: "",
2806
+ jwtAccess: result.access,
2807
+ jwtRefresh: result.refresh,
2808
+ jwtExpiresAt: result.expiresAt,
2809
+ savedAt: /* @__PURE__ */ new Date(),
2810
+ impersonatorEmail: operatorEmail,
2811
+ impersonatedUserId: userId,
2812
+ ...orgName !== "" && { impersonatedOrgName: orgName }
2813
+ };
2814
+ await cfg.store.saveSession(cfg.serverKey, session);
2815
+ for (const old of replaced) {
2816
+ if (old.email !== storageEmail) await cfg.store.removeSession(cfg.serverKey, old.email);
2817
+ const oldRefresh = old.session.jwtRefresh;
2818
+ if (oldRefresh === void 0 || oldRefresh === "" || oldRefresh === result.refresh) continue;
2819
+ const failure = await revokeRefreshToken(host, oldRefresh, { signal: cfg.signal });
2820
+ if (failure !== void 0) {
2821
+ cfg.out.write(
2822
+ `Warning: could not revoke the previous login-as token on ${cfg.serverKey} (${failure}); it stays valid until it expires.
2823
+ `
2824
+ );
2825
+ }
2826
+ }
2827
+ const remainingMs = result.expiresAt.getTime() - Date.now();
2828
+ cfg.out.write(
2829
+ `Logged into ${cfg.serverKey} as ${storageEmail} (impersonated by ${operatorEmail}). JWT expires in ${formatGoDuration(roundToMinuteMs(remainingMs))}.
2830
+ Use --account ${storageEmail} on later commands.
2831
+ `
2832
+ );
2833
+ }
2834
+ function registerLoginAsCommand(root) {
2835
+ const cmd = root.command("login-as").description(
2836
+ "Act as another user (e.g. support@<org>) with a JWT recording you as the operator. Requires your own dr-appspace login on the same server first."
2837
+ ).argument("<email>", "email of the user to act as").option("--as <operator-email>", "operator login to authorize with (auto-picked if sole)").option("--user-id <n>", "act as this user id directly (skips the directory lookup)").action(async (email, opts) => {
2838
+ await refuseImpersonationWithCredentialFile();
2839
+ const serverKey = resolveServer(opts.server);
2840
+ let userIdOverride;
2841
+ if (opts.userId !== void 0) {
2842
+ const n = Number(opts.userId);
2843
+ if (!Number.isInteger(n) || n <= 0 || String(n) !== opts.userId) {
2844
+ throw new Error(`--user-id must be a positive integer, got "${opts.userId}"`);
2845
+ }
2846
+ userIdOverride = n;
2847
+ }
2848
+ const store = await KeyringStore.defaultWithCleanup();
2849
+ const controller = new AbortController();
2850
+ const timer = setTimeout(() => controller.abort(), DEFAULT_CALL_TIMEOUT_MS);
2851
+ try {
2852
+ await runLoginAs({
2853
+ store,
2854
+ serverKey,
2855
+ targetEmail: email,
2856
+ operatorFlag: opts.as,
2857
+ userIdOverride,
2858
+ signal: controller.signal,
2859
+ out: process.stderr
2860
+ });
2861
+ } finally {
2862
+ clearTimeout(timer);
2863
+ }
2864
+ });
2865
+ addServerFlag(cmd);
2866
+ }
2867
+
2588
2868
  // src/commands/_accountFlag.ts
2589
2869
  function addAccountFlag(cmd) {
2590
2870
  return cmd.option(
@@ -2649,10 +2929,7 @@ async function runLogout(cfg) {
2649
2929
  for (const meta of sessions) {
2650
2930
  const session2 = await cfg.store.getSession(key, meta.email);
2651
2931
  if (session2 === void 0) continue;
2652
- try {
2653
- await revoker(host2, session2);
2654
- } catch {
2655
- }
2932
+ await revokeAndWarn(revoker, host2, session2, cfg.out);
2656
2933
  await cfg.store.removeSession(key, meta.email);
2657
2934
  cfg.out.write(`Logged out of ${key} as ${meta.email}.
2658
2935
  `);
@@ -2678,12 +2955,18 @@ async function runLogout(cfg) {
2678
2955
  return;
2679
2956
  }
2680
2957
  const host = resolve2(cfg.serverKey).host;
2958
+ await revokeAndWarn(revoker, host, session, cfg.out);
2959
+ await cfg.store.removeSession(cfg.serverKey, email);
2960
+ cfg.out.write(`Logged out of ${cfg.serverKey} as ${email}.
2961
+ `);
2962
+ }
2963
+ async function revokeAndWarn(revoker, host, session, out) {
2964
+ let warning = void 0;
2681
2965
  try {
2682
- await revoker(host, session);
2966
+ warning = await revoker(host, session);
2683
2967
  } catch {
2684
2968
  }
2685
- await cfg.store.removeSession(cfg.serverKey, email);
2686
- cfg.out.write(`Logged out of ${cfg.serverKey} as ${email}.
2969
+ if (typeof warning === "string" && warning !== "") out.write(`${warning}
2687
2970
  `);
2688
2971
  }
2689
2972
  async function bestEffortLogout(host, session) {
@@ -2692,6 +2975,16 @@ async function bestEffortLogout(host, session) {
2692
2975
  const controller = new AbortController();
2693
2976
  const timeout = setTimeout(() => controller.abort(), 5e3);
2694
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
+ }
2695
2988
  await fetch(`${base}/oauth/revoke/`, {
2696
2989
  method: "POST",
2697
2990
  headers: {
@@ -43540,6 +43833,7 @@ function buildRootCommand() {
43540
43833
  root.exitOverride();
43541
43834
  root.enablePositionalOptions();
43542
43835
  registerLoginCommand(root);
43836
+ registerLoginAsCommand(root);
43543
43837
  registerLogoutCommand(root);
43544
43838
  registerWhoamiCommand(root);
43545
43839
  registerAppSpaceCommand(root);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@datarails-ai/dr-appspace-cli",
3
- "version": "0.12.80",
3
+ "version": "0.12.81",
4
4
  "description": "Datarails App Space CLI — build, try, push and publish App Space apps",
5
5
  "type": "module",
6
6
  "engines": {