@fluid-app/fluid-cli 0.1.809 → 0.1.810

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.
@@ -5,7 +5,7 @@ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
5
5
  import { homedir } from "node:os";
6
6
  import { execFile, spawn } from "node:child_process";
7
7
  import { createServer } from "node:http";
8
- //#region src/config/types.ts
8
+ // src/config/types.ts
9
9
  /** Whether a profile signs in through the identity service. */
10
10
  function isIdentityProfile(profile) {
11
11
  return profile?.auth?.mode === "identity";
@@ -22,8 +22,7 @@ function createDefaultConfig() {
22
22
  enabledPlugins: null
23
23
  };
24
24
  }
25
- //#endregion
26
- //#region src/config/paths.ts
25
+ // src/config/paths.ts
27
26
  /**
28
27
  * XDG-compliant config directory resolution
29
28
  *
@@ -38,7 +37,10 @@ function getConfigDir() {
38
37
  const envOverride = process.env["FLUID_CONFIG_DIR"];
39
38
  if (envOverride) return envOverride;
40
39
  if (process.platform === "darwin") return join(homedir(), ".fluid");
41
- if (process.platform === "win32") return join(process.env["APPDATA"] ?? join(homedir(), "AppData", "Roaming"), "fluid");
40
+ if (process.platform === "win32") {
41
+ const appData = process.env["APPDATA"] ?? join(homedir(), "AppData", "Roaming");
42
+ return join(appData, "fluid");
43
+ }
42
44
  const xdgConfig = process.env["XDG_CONFIG_HOME"];
43
45
  if (xdgConfig) return join(xdgConfig, "fluid");
44
46
  return join(homedir(), ".config", "fluid");
@@ -46,10 +48,10 @@ function getConfigDir() {
46
48
  function getConfigFilePath() {
47
49
  return join(getConfigDir(), "config.json");
48
50
  }
49
- //#endregion
50
- //#region src/config/lock.ts
51
+ // src/config/lock.ts
51
52
  /** The config lock could not be acquired in time. */
52
53
  var ConfigLockTimeoutError = class extends Error {
54
+ lockPath;
53
55
  constructor(lockPath) {
54
56
  super(`The config lock ${lockPath} is held by another fluid process. If no fluid command is running, remove that file and try again.`);
55
57
  this.lockPath = lockPath;
@@ -61,7 +63,20 @@ const configLockTimings = {
61
63
  staleMs: 3e4,
62
64
  breakStaleMs: 5e3
63
65
  };
64
- const lockIo = { write: writeSync };
66
+ function processStartTime(pid) {
67
+ if (process.platform !== "linux") return void 0;
68
+ try {
69
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
70
+ const value = stat.slice(stat.lastIndexOf(")") + 2).split(/\s+/)[19];
71
+ return value && /^\d+$/.test(value) ? value : void 0;
72
+ } catch {
73
+ return;
74
+ }
75
+ }
76
+ const lockIo = {
77
+ write: writeSync,
78
+ processStartTime
79
+ };
65
80
  const RETRY_MS = 25;
66
81
  const heldLocks = /* @__PURE__ */ new Set();
67
82
  function sleep(ms) {
@@ -77,18 +92,25 @@ function ageMs(path) {
77
92
  function isStale(path, staleMs) {
78
93
  return ageMs(path) > staleMs;
79
94
  }
95
+ function holderIdentity(content) {
96
+ return /(?:-s(\d+))?:(\d+)$/.exec(content);
97
+ }
80
98
  function holderAlive(content) {
81
- const pid = Number(/:(\d+)$/.exec(content)?.[1]);
99
+ const holder = holderIdentity(content);
100
+ const pid = Number(holder?.[2]);
82
101
  if (!Number.isInteger(pid) || pid <= 0) return false;
83
102
  try {
84
103
  process.kill(pid, 0);
85
- return true;
86
104
  } catch (error) {
87
- return error.code === "EPERM";
105
+ if (error.code !== "EPERM") return false;
88
106
  }
107
+ const recordedStartTime = holder?.[1];
108
+ if (!recordedStartTime) return true;
109
+ const currentStartTime = lockIo.processStartTime(pid);
110
+ return currentStartTime === void 0 || currentStartTime === recordedStartTime;
89
111
  }
90
112
  function hasHolderPid(content) {
91
- return /:\d+$/.test(content);
113
+ return holderIdentity(content) !== null;
92
114
  }
93
115
  function isLockStale(path) {
94
116
  if (ageMs(path) <= configLockTimings.staleMs) return false;
@@ -121,7 +143,8 @@ function tryCreate(path, content) {
121
143
  }
122
144
  }
123
145
  function newContent() {
124
- return `${randomUUID()}:${process.pid}`;
146
+ const startTime = lockIo.processStartTime(process.pid);
147
+ return `${randomUUID()}${startTime === void 0 ? "" : `-s${startTime}`}:${process.pid}`;
125
148
  }
126
149
  function release(path, content) {
127
150
  try {
@@ -181,8 +204,7 @@ function withConfigLock(fn, timeoutMs = configLockTimings.timeoutMs) {
181
204
  release(lockPath, token);
182
205
  }
183
206
  }
184
- //#endregion
185
- //#region src/config/strict.ts
207
+ // src/config/strict.ts
186
208
  /**
187
209
  * Whether this process runs under a host that supplies the base URL and
188
210
  * credential through the environment alone. The host sets
@@ -192,8 +214,7 @@ function withConfigLock(fn, timeoutMs = configLockTimings.timeoutMs) {
192
214
  function isStrictConfig() {
193
215
  return process.env["FLUID_RUNTIME_STRICT_CONFIG"] === "1";
194
216
  }
195
- //#endregion
196
- //#region src/config/config.ts
217
+ // src/config/config.ts
197
218
  /**
198
219
  * Read/write config.json with atomic writes and safe defaults
199
220
  */
@@ -229,7 +250,8 @@ function writeConfig(config) {
229
250
  recursive: true,
230
251
  mode: 448
231
252
  });
232
- const tmpPath = join(dir, `.fluid-config-${randomBytes(6).toString("hex")}.tmp`);
253
+ const suffix = randomBytes(6).toString("hex");
254
+ const tmpPath = join(dir, `.fluid-config-${suffix}.tmp`);
233
255
  try {
234
256
  writeFileSync(tmpPath, JSON.stringify(withDurableWorkspaceAliases(config), null, 2) + "\n", {
235
257
  encoding: "utf8",
@@ -282,8 +304,7 @@ function updateConfig(updater) {
282
304
  return updated;
283
305
  });
284
306
  }
285
- //#endregion
286
- //#region ../../platform/api-client-core/src/api-error-shape.ts
307
+ // ../../platform/api-client-core/src/api-error-shape.ts
287
308
  /**
288
309
  * Narrows a parsed JSON error payload to the envelope contract. Arrays and
289
310
  * primitives are not envelopes, so they resolve to `null` — their content is
@@ -357,8 +378,7 @@ function pickFieldErrors(record) {
357
378
  function isMessageList(value) {
358
379
  return Array.isArray(value) && value.length > 0 && value.every((message) => typeof message === "string");
359
380
  }
360
- //#endregion
361
- //#region ../../platform/api-client-core/src/fetch-client.ts
381
+ // ../../platform/api-client-core/src/fetch-client.ts
362
382
  /**
363
383
  * API Error class compatible with fluid-admin's ApiError
364
384
  */
@@ -637,8 +657,7 @@ function createFetchClient(config) {
637
657
  })
638
658
  };
639
659
  }
640
- //#endregion
641
- //#region ../../platform/api-client-core/src/hey-api-error-policy.ts
660
+ // ../../platform/api-client-core/src/hey-api-error-policy.ts
642
661
  function getNonEmptyString(value) {
643
662
  if (typeof value !== "string") return;
644
663
  const trimmed = value.trim();
@@ -676,8 +695,7 @@ function createHeyApiErrorInterceptor(options = {}) {
676
695
  return new ApiError(isJson && text ? text.slice(0, 200) : `${method} request failed with status ${response.status}`, response.status, isJson ? error : null, requestId, null);
677
696
  };
678
697
  }
679
- //#endregion
680
- //#region ../../api-clients/hey-api-fetch-runtime/src/generated/core/bodySerializer.gen.ts
698
+ // ../../api-clients/hey-api-fetch-runtime/src/generated/core/bodySerializer.gen.ts
681
699
  const serializeUrlSearchParamsPair = (data, key, value) => {
682
700
  if (typeof value === "string") data.append(key, value);
683
701
  else data.append(key, JSON.stringify(value));
@@ -698,8 +716,7 @@ Object.entries({
698
716
  $path_: "path",
699
717
  $query_: "query"
700
718
  });
701
- //#endregion
702
- //#region ../../api-clients/hey-api-fetch-runtime/src/generated/core/serverSentEvents.gen.ts
719
+ // ../../api-clients/hey-api-fetch-runtime/src/generated/core/serverSentEvents.gen.ts
703
720
  function createSseClient({ onRequest, onSseError, onSseEvent, responseTransformer, responseValidator, sseDefaultRetryDelay, sseMaxRetryAttempts, sseMaxRetryDelay, sseSleepFn, url, ...options }) {
704
721
  let lastEventId;
705
722
  const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
@@ -784,14 +801,14 @@ function createSseClient({ onRequest, onSseError, onSseEvent, responseTransforme
784
801
  } catch (error) {
785
802
  onSseError?.(error);
786
803
  if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) break;
787
- await sleep(Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4));
804
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
805
+ await sleep(backoff);
788
806
  }
789
807
  }
790
808
  };
791
809
  return { stream: createStream() };
792
810
  }
793
- //#endregion
794
- //#region ../../api-clients/hey-api-fetch-runtime/src/generated/core/pathSerializer.gen.ts
811
+ // ../../api-clients/hey-api-fetch-runtime/src/generated/core/pathSerializer.gen.ts
795
812
  const separatorArrayExplode = (style) => {
796
813
  switch (style) {
797
814
  case "label": return ".";
@@ -869,8 +886,7 @@ const serializeObjectParam = ({ allowReserved, explode, name, style, value, valu
869
886
  })).join(separator);
870
887
  return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
871
888
  };
872
- //#endregion
873
- //#region ../../api-clients/hey-api-fetch-runtime/src/generated/core/utils.gen.ts
889
+ // ../../api-clients/hey-api-fetch-runtime/src/generated/core/utils.gen.ts
874
890
  const PATH_PARAM_RE = /\{[^{}]+\}/g;
875
891
  const defaultPathSerializer = ({ path, url: _url }) => {
876
892
  let url = _url;
@@ -943,8 +959,7 @@ function getValidRequestBody(options) {
943
959
  }
944
960
  if (hasBody) return options.body;
945
961
  }
946
- //#endregion
947
- //#region ../../api-clients/hey-api-fetch-runtime/src/generated/core/auth.gen.ts
962
+ // ../../api-clients/hey-api-fetch-runtime/src/generated/core/auth.gen.ts
948
963
  const getAuthToken = async (auth, callback) => {
949
964
  const token = typeof callback === "function" ? await callback(auth) : callback;
950
965
  if (!token) return;
@@ -952,8 +967,7 @@ const getAuthToken = async (auth, callback) => {
952
967
  if (auth.scheme === "basic") return `Basic ${btoa(token)}`;
953
968
  return token;
954
969
  };
955
- //#endregion
956
- //#region ../../api-clients/hey-api-fetch-runtime/src/generated/client/utils.gen.ts
970
+ // ../../api-clients/hey-api-fetch-runtime/src/generated/client/utils.gen.ts
957
971
  const createQuerySerializer = ({ parameters = {}, ...args } = {}) => {
958
972
  const querySerializer = (queryParams) => {
959
973
  const search = [];
@@ -1030,9 +1044,7 @@ async function setAuthParams(options) {
1030
1044
  case "cookie":
1031
1045
  options.headers.append("Cookie", `${name}=${token}`);
1032
1046
  break;
1033
- default:
1034
- options.headers.set(name, token);
1035
- break;
1047
+ default: options.headers.set(name, token);
1036
1048
  }
1037
1049
  }
1038
1050
  }
@@ -1124,8 +1136,7 @@ const createConfig = (override = {}) => ({
1124
1136
  querySerializer: defaultQuerySerializer,
1125
1137
  ...override
1126
1138
  });
1127
- //#endregion
1128
- //#region ../../api-clients/hey-api-fetch-runtime/src/generated/client/client.gen.ts
1139
+ // ../../api-clients/hey-api-fetch-runtime/src/generated/client/client.gen.ts
1129
1140
  const createClient = (config = {}) => {
1130
1141
  let _config = mergeConfigs(createConfig(), config);
1131
1142
  const getConfig = () => ({ ..._config });
@@ -1189,9 +1200,7 @@ const createClient = (config = {}) => {
1189
1200
  case "stream":
1190
1201
  emptyData = response.body;
1191
1202
  break;
1192
- default:
1193
- emptyData = {};
1194
- break;
1203
+ default: emptyData = {};
1195
1204
  }
1196
1205
  return opts.responseStyle === "data" ? emptyData : {
1197
1206
  data: emptyData,
@@ -1294,8 +1303,7 @@ const createClient = (config = {}) => {
1294
1303
  trace: makeMethodFn("TRACE")
1295
1304
  };
1296
1305
  };
1297
- //#endregion
1298
- //#region ../../api-clients/identity/src/hey-api-client.ts
1306
+ // ../../api-clients/identity/src/hey-api-client.ts
1299
1307
  function isAbortError(error) {
1300
1308
  return error instanceof DOMException && error.name === "AbortError" || error instanceof Error && error.name === "AbortError";
1301
1309
  }
@@ -1328,7 +1336,7 @@ function createIdentityHeyApiClient(config) {
1328
1336
  }));
1329
1337
  return client;
1330
1338
  }
1331
- const OAUTH_ERROR_CODES = new Set([
1339
+ const OAUTH_ERROR_CODES = /* @__PURE__ */ new Set([
1332
1340
  "invalid_request",
1333
1341
  "invalid_client",
1334
1342
  "invalid_grant",
@@ -1357,8 +1365,7 @@ function oauthErrorCode(error) {
1357
1365
  const code = error.body?.error;
1358
1366
  return isOAuthErrorCode(code) ? code : null;
1359
1367
  }
1360
- //#endregion
1361
- //#region ../../api-clients/identity/src/hey-api/sdk.gen.ts
1368
+ // ../../api-clients/identity/src/hey-api/sdk.gen.ts
1362
1369
  /**
1363
1370
  * Token endpoint
1364
1371
  *
@@ -1590,8 +1597,7 @@ const revokeToken = (options) => options.client.post({
1590
1597
  ...options.headers
1591
1598
  }
1592
1599
  });
1593
- //#endregion
1594
- //#region ../../platform/auth/src/constants.ts
1600
+ // ../../platform/auth/src/constants.ts
1595
1601
  /**
1596
1602
  * Auth Constants
1597
1603
  *
@@ -1602,11 +1608,19 @@ const revokeToken = (options) => options.client.post({
1602
1608
  * Authentication-related constants with sensible defaults.
1603
1609
  */
1604
1610
  const AUTH_CONSTANTS = {
1611
+ /**
1612
+ * Grace period in milliseconds to account for clock skew
1613
+ * when checking token expiration. Tokens are considered valid
1614
+ * if they expire within this period.
1615
+ */
1605
1616
  TOKEN_GRACE_PERIOD_MS: 3e4,
1617
+ /**
1618
+ * Default cookie max age in seconds (9 days).
1619
+ * This matches the typical JWT token lifetime from the Fluid API.
1620
+ */
1606
1621
  COOKIE_MAX_AGE: 777600
1607
1622
  };
1608
- //#endregion
1609
- //#region ../../platform/auth/src/session/refresher.ts
1623
+ // ../../platform/auth/src/session/refresher.ts
1610
1624
  /**
1611
1625
  * Single-flight refresh (INV-6.6).
1612
1626
  *
@@ -1635,9 +1649,8 @@ function classifyRefreshFailure(error) {
1635
1649
  if (isApiError(error)) return error.status === 0 || error.status >= 500 || error.status === 429 ? "unavailable" : "rejected";
1636
1650
  return "unavailable";
1637
1651
  }
1638
- //#endregion
1639
- //#region ../../platform/auth/src/session/types.ts
1640
- const REFUSAL_REASONS = new Set([
1652
+ // ../../platform/auth/src/session/types.ts
1653
+ const REFUSAL_REASONS = /* @__PURE__ */ new Set([
1641
1654
  "company_not_yet_available",
1642
1655
  "not_on_one_auth",
1643
1656
  "not_mirrored",
@@ -1663,8 +1676,7 @@ var SessionError = class extends Error {
1663
1676
  if (navigationStarted) this.navigationStarted = navigationStarted;
1664
1677
  }
1665
1678
  };
1666
- //#endregion
1667
- //#region ../../platform/auth/src/session/exchange.ts
1679
+ // ../../platform/auth/src/session/exchange.ts
1668
1680
  /**
1669
1681
  * Token exchange (RFC 8693): company switch, role narrowing, and a root
1670
1682
  * admin's company entry (Phase 007 FR-3, FR-4).
@@ -1726,8 +1738,7 @@ function classifyExchangeFailure(error) {
1726
1738
  if (code === "invalid_target" && refusalReason(error) === "company_not_yet_available") return "not_yet_available";
1727
1739
  return "refused";
1728
1740
  }
1729
- //#endregion
1730
- //#region ../../platform/auth/src/session/facts.ts
1741
+ // ../../platform/auth/src/session/facts.ts
1731
1742
  /** Maps `/userinfo` onto the facts an app reads. */
1732
1743
  function toSessionFacts(info, expiresAt, exchanged = false) {
1733
1744
  const actor = info.act?.sub ?? null;
@@ -1745,8 +1756,7 @@ function toSessionFacts(info, expiresAt, exchanged = false) {
1745
1756
  exchanged
1746
1757
  };
1747
1758
  }
1748
- //#endregion
1749
- //#region ../../platform/auth/src/native/exchange.ts
1759
+ // ../../platform/auth/src/native/exchange.ts
1750
1760
  /**
1751
1761
  * Token exchange for native clients (Phase 007 FR-3): moves a native
1752
1762
  * session's access token to another company, or narrows its roles, without a
@@ -1800,8 +1810,7 @@ async function exchangeNativeToken(config, subjectToken, target) {
1800
1810
  throw new SessionError("access_denied", "The identity service rejected the token it exchanged.");
1801
1811
  }
1802
1812
  }
1803
- //#endregion
1804
- //#region ../../platform/auth/src/session/pkce.ts
1813
+ // ../../platform/auth/src/session/pkce.ts
1805
1814
  function base64Url(bytes) {
1806
1815
  let binary = "";
1807
1816
  for (const byte of bytes) binary += String.fromCharCode(byte);
@@ -1825,8 +1834,7 @@ async function createCodeChallenge(verifier, cryptoImpl = crypto) {
1825
1834
  const digest = await cryptoImpl.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
1826
1835
  return base64Url(new Uint8Array(digest));
1827
1836
  }
1828
- //#endregion
1829
- //#region ../../platform/auth/src/native/secure-session.ts
1837
+ // ../../platform/auth/src/native/secure-session.ts
1830
1838
  /**
1831
1839
  * Native secure session: the authorization code flow with PKCE for public
1832
1840
  * clients that are not browsers (the CLI, `apps/mist-desktop`,
@@ -1892,18 +1900,21 @@ function createChainTracker() {
1892
1900
  get doubt() {
1893
1901
  return doubt;
1894
1902
  },
1903
+ /** A company the chain has been confirmed to name, as `/userinfo` said. */
1895
1904
  confirmed(chainOrg) {
1896
1905
  org = chainOrg;
1897
1906
  doubt = false;
1898
1907
  learned = true;
1899
1908
  if (home === void 0 && !moved) home = chainOrg;
1900
1909
  },
1910
+ /** A refresh that named `named` was answered: the chain may have moved. */
1901
1911
  namedMoved(named) {
1902
1912
  if (doubt || !sameOrg(named, org)) {
1903
1913
  doubt = true;
1904
1914
  moved = true;
1905
1915
  }
1906
1916
  },
1917
+ /** The identity service sent a refresh to its home company, `home_org`. */
1907
1918
  homeRetried(homeCompany, renewed) {
1908
1919
  home = homeCompany;
1909
1920
  if (renewed) {
@@ -1911,9 +1922,11 @@ function createChainTracker() {
1911
1922
  moved = false;
1912
1923
  }
1913
1924
  },
1925
+ /** Whether a refresh may name a company: the chain's home is confirmed. */
1914
1926
  known() {
1915
1927
  return !doubt && learned && home !== void 0 && home !== null;
1916
1928
  },
1929
+ /** What a null target means: the company the chain was moved away from. */
1917
1930
  homeTarget() {
1918
1931
  return moved && home !== void 0 && home !== null ? home : null;
1919
1932
  },
@@ -1947,6 +1960,7 @@ function createNativeSession(config) {
1947
1960
  get: () => serial(() => config.storage.get(storageKey)),
1948
1961
  set: (value) => serial(() => config.storage.set(storageKey, value)),
1949
1962
  delete: () => serial(() => config.storage.delete(storageKey)),
1963
+ /** Deletes the credential only if it is still `value`. */
1950
1964
  deleteIf: (value) => serial(async () => {
1951
1965
  if (await config.storage.get(storageKey) === value) await config.storage.delete(storageKey);
1952
1966
  })
@@ -2259,7 +2273,7 @@ function createNativeSession(config) {
2259
2273
  const bound = new Promise((resolve) => {
2260
2274
  timer = setTimeout(resolve, config.signOutWaitMs ?? SIGN_OUT_WAIT_MS);
2261
2275
  });
2262
- await Promise.race([Promise.allSettled([...work]), bound]);
2276
+ await Promise.race([Promise.allSettled(work), bound]);
2263
2277
  clearTimeout(timer);
2264
2278
  }
2265
2279
  async function forget(cap, error, refreshToken) {
@@ -2316,15 +2330,16 @@ function createNativeSession(config) {
2316
2330
  if (!isCurrent(cap)) throw new SessionError("not_signed_in");
2317
2331
  const refresh = async (org) => {
2318
2332
  if (!isCurrent(cap)) throw new SessionError("not_signed_in");
2333
+ const body = {
2334
+ grant_type: "refresh_token",
2335
+ client_id: config.clientId,
2336
+ refresh_token: refreshToken,
2337
+ ...opId ? { op_id: opId } : {},
2338
+ ...org ? { org } : {}
2339
+ };
2319
2340
  return createToken({
2320
2341
  client,
2321
- body: {
2322
- grant_type: "refresh_token",
2323
- client_id: config.clientId,
2324
- refresh_token: refreshToken,
2325
- ...opId ? { op_id: opId } : {},
2326
- ...org ? { org } : {}
2327
- }
2342
+ body
2328
2343
  });
2329
2344
  };
2330
2345
  let token;
@@ -2453,6 +2468,8 @@ function createNativeSession(config) {
2453
2468
  * a sign-in code and an adopt code both take.
2454
2469
  */
2455
2470
  class UnconfirmedAdopt extends Error {
2471
+ cap;
2472
+ error;
2456
2473
  constructor(cap, error) {
2457
2474
  super(error.message);
2458
2475
  this.cap = cap;
@@ -2577,7 +2594,7 @@ function createNativeSession(config) {
2577
2594
  function signOutIfCurrent(cap) {
2578
2595
  if (!isCurrent(cap)) return Promise.resolve(false);
2579
2596
  if (redemptions.size > 0) {
2580
- Promise.allSettled([...redemptions]).then(() => isCurrent(cap) && redemptions.size === 0 ? session.signOut() : void 0).catch(() => void 0);
2597
+ Promise.allSettled(redemptions).then(() => isCurrent(cap) && redemptions.size === 0 ? session.signOut() : void 0).catch(() => void 0);
2581
2598
  return Promise.resolve(false);
2582
2599
  }
2583
2600
  return session.signOut().then(() => true);
@@ -2834,6 +2851,9 @@ function createNativeSession(config) {
2834
2851
  signOutConfirmed() {
2835
2852
  return runSignOut(true);
2836
2853
  },
2854
+ discardIf(value) {
2855
+ return store.deleteIf(value);
2856
+ },
2837
2857
  subscribe(listener) {
2838
2858
  listeners.add(listener);
2839
2859
  return () => {
@@ -2855,8 +2875,7 @@ function createNativeSession(config) {
2855
2875
  session.completeSignIn = (callbackUrl) => tracked(completeSignIn(callbackUrl));
2856
2876
  return session;
2857
2877
  }
2858
- //#endregion
2859
- //#region ../../platform/auth/src/native/storage-adapters.ts
2878
+ // ../../platform/auth/src/native/storage-adapters.ts
2860
2879
  /** Raised when the platform offers no protected store for a credential. */
2861
2880
  var SecureStorageUnavailableError = class extends Error {
2862
2881
  constructor(message) {
@@ -2905,284 +2924,7 @@ function createMemorySecureStorage() {
2905
2924
  }
2906
2925
  };
2907
2926
  }
2908
- //#endregion
2909
- //#region ../../platform/auth/src/native/trade-legacy-token.ts
2910
- /**
2911
- * Trades a legacy Fluid token for a native identity session with no browser
2912
- * hop (RFC 004 S3.4g): Rails mints a PKCE-bound adopt code for the legacy
2913
- * bearer, and the session redeems it at the identity service's `/token`.
2914
- * The legacy token is never altered here; the caller removes it only after
2915
- * an `adopted` result.
2916
- */
2917
- const REQUEST_TIMEOUT_MS = 15e3;
2918
- function record(value) {
2919
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
2920
- }
2921
- function idText(value) {
2922
- if (typeof value === "number" && Number.isFinite(value)) return String(value);
2923
- return typeof value === "string" && value.trim() ? value.trim() : null;
2924
- }
2925
- function meIdentityOf(raw) {
2926
- const root = record(raw);
2927
- if (!root) return null;
2928
- const wrapped = record(root["me"]) ?? record(root["user"]);
2929
- const user = record(wrapped?.["user"]) ?? wrapped ?? root;
2930
- const company = record(wrapped?.["company"]) ?? record(root["company"]);
2931
- const userId = idText(user["id"]);
2932
- const companyId = company ? idText(company["id"]) : null;
2933
- return userId && companyId ? {
2934
- userId,
2935
- companyId
2936
- } : null;
2937
- }
2938
- async function readMe(doFetch, apiBase, token, timeoutMs) {
2939
- let response;
2940
- const abort = new AbortController();
2941
- const timer = setTimeout(() => abort.abort(), timeoutMs);
2942
- try {
2943
- response = await doFetch(`${apiBase}/api/me`, {
2944
- headers: {
2945
- Authorization: `Bearer ${token}`,
2946
- Accept: "application/json"
2947
- },
2948
- signal: abort.signal
2949
- });
2950
- } catch {
2951
- clearTimeout(timer);
2952
- return { kind: "unavailable" };
2953
- }
2954
- if (response.status >= 500 || response.status === 429) {
2955
- clearTimeout(timer);
2956
- return { kind: "unavailable" };
2957
- }
2958
- if (!response.ok) {
2959
- clearTimeout(timer);
2960
- return { kind: "refused" };
2961
- }
2962
- try {
2963
- const me = meIdentityOf(await response.json());
2964
- return me ? {
2965
- kind: "ok",
2966
- me
2967
- } : { kind: "refused" };
2968
- } catch {
2969
- return abort.signal.aborted ? { kind: "unavailable" } : { kind: "refused" };
2970
- } finally {
2971
- clearTimeout(timer);
2972
- }
2973
- }
2974
- async function mintAdoptCode(doFetch, apiBase, legacyToken, challenge, timeoutMs) {
2975
- let response;
2976
- const abort = new AbortController();
2977
- const timer = setTimeout(() => abort.abort(), timeoutMs);
2978
- try {
2979
- response = await doFetch(`${apiBase}/api/identity/adopt_code`, {
2980
- method: "POST",
2981
- headers: {
2982
- Authorization: `Bearer ${legacyToken}`,
2983
- "Content-Type": "application/json",
2984
- Accept: "application/json"
2985
- },
2986
- body: JSON.stringify({
2987
- code_challenge: challenge,
2988
- code_challenge_method: "S256"
2989
- }),
2990
- signal: abort.signal
2991
- });
2992
- } catch {
2993
- clearTimeout(timer);
2994
- return { kind: "unavailable" };
2995
- }
2996
- if (response.status === 404) {
2997
- clearTimeout(timer);
2998
- return { kind: "not_targeted" };
2999
- }
3000
- if (response.status >= 500 || response.status === 429) {
3001
- clearTimeout(timer);
3002
- return { kind: "unavailable" };
3003
- }
3004
- if (!response.ok) {
3005
- clearTimeout(timer);
3006
- return { kind: "refused" };
3007
- }
3008
- try {
3009
- const code = record(await response.json())?.["code"];
3010
- return typeof code === "string" && code ? {
3011
- kind: "ok",
3012
- code
3013
- } : { kind: "refused" };
3014
- } catch {
3015
- return abort.signal.aborted ? { kind: "unavailable" } : { kind: "refused" };
3016
- } finally {
3017
- clearTimeout(timer);
3018
- }
3019
- }
3020
- /**
3021
- * Trades `legacyToken` for an identity session held by `session`.
3022
- *
3023
- * Returns `adopted` once the session is stored and its user and company match
3024
- * the legacy token's, as `/api/me` answers for each. A session that lands on
3025
- * another user or company is signed out again and the trade is `refused`.
3026
- * `not_targeted` means Rails does not offer adoption to this company;
3027
- * `unavailable` means a network or server failure worth retrying later.
3028
- */
3029
- async function tradeLegacyToken(options) {
3030
- const doFetch = options.fetch ?? ((...args) => fetch(...args));
3031
- const finish = (result) => {
3032
- options.log?.(result.outcome === "refused" ? `adopt outcome: refused (${result.reason})` : `adopt outcome: ${result.outcome}`);
3033
- return result;
3034
- };
3035
- if (options.session.facts() !== null) return finish({ outcome: "unavailable" });
3036
- const timeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS;
3037
- const epoch = options.session.epoch();
3038
- const verifier = createCodeVerifier(options.crypto);
3039
- const challenge = await createCodeChallenge(verifier, options.crypto);
3040
- const minted = await mintAdoptCode(doFetch, options.apiBase, options.legacyToken, challenge, timeoutMs);
3041
- if (minted.kind === "not_targeted") return finish({ outcome: "not_targeted" });
3042
- if (minted.kind === "unavailable") return finish({ outcome: "unavailable" });
3043
- if (minted.kind === "refused") return finish({
3044
- outcome: "refused",
3045
- reason: "mint_refused"
3046
- });
3047
- try {
3048
- await options.beforeRedeem?.();
3049
- } catch {
3050
- return finish({ outcome: "unavailable" });
3051
- }
3052
- return landAdoptCode({
3053
- session: options.session,
3054
- doFetch,
3055
- apiBase: options.apiBase,
3056
- legacyToken: options.legacyToken,
3057
- code: minted.code,
3058
- verifier,
3059
- epoch,
3060
- timeoutMs,
3061
- finish,
3062
- expectedCompanyId: null,
3063
- beforeDiscard: options.beforeDiscard
3064
- });
3065
- }
3066
- async function landAdoptCode(options) {
3067
- const { session, doFetch, apiBase, legacyToken, timeoutMs, finish } = options;
3068
- let adoptedSession;
3069
- try {
3070
- adoptedSession = await session.redeemAdopt({
3071
- adoptCode: options.code,
3072
- codeVerifier: options.verifier,
3073
- epoch: options.epoch
3074
- });
3075
- } catch (error) {
3076
- if (error instanceof SessionError && error.code !== "temporarily_unavailable" && error.code !== "not_signed_in") return finish({
3077
- outcome: "refused",
3078
- reason: "grant_refused"
3079
- });
3080
- return finish({ outcome: "unavailable" });
3081
- }
3082
- const discard = async (result) => {
3083
- try {
3084
- options.beforeDiscard?.();
3085
- } catch {}
3086
- await adoptedSession.discard().catch(() => void 0);
3087
- return finish(result);
3088
- };
3089
- const [legacy, adopted] = await Promise.all([readMe(doFetch, apiBase, legacyToken, timeoutMs), session.getAccessToken().then((token) => readMe(doFetch, apiBase, token, timeoutMs)).catch(() => ({ kind: "unavailable" }))]);
3090
- if (!adoptedSession.isCurrent()) return finish({ outcome: "unavailable" });
3091
- if (legacy.kind === "unavailable" || adopted.kind === "unavailable") return discard({ outcome: "unavailable" });
3092
- if (legacy.kind !== "ok" || adopted.kind !== "ok") return discard({
3093
- outcome: "refused",
3094
- reason: "landing_unverifiable"
3095
- });
3096
- const wantedCompany = options.expectedCompanyId ?? legacy.me.companyId;
3097
- if (legacy.me.userId !== adopted.me.userId || wantedCompany !== adopted.me.companyId) return discard({
3098
- outcome: "refused",
3099
- reason: "landing_mismatch"
3100
- });
3101
- return finish({
3102
- outcome: "adopted",
3103
- facts: adoptedSession.facts,
3104
- isCurrent: () => adoptedSession.isCurrent(),
3105
- discard: () => adoptedSession.discard()
3106
- });
3107
- }
3108
- /**
3109
- * Prepares the PKCE challenge a company switch sends as `adopt`, and the
3110
- * redeem that lands the answered code. `redeem` reports `adopted` only when
3111
- * the session names the legacy bearer's user in the target company; any other
3112
- * landing is signed out again and `refused`.
3113
- */
3114
- async function createSwitchAdoptRequest(session, crypto) {
3115
- const epoch = session.epoch();
3116
- const verifier = createCodeVerifier(crypto);
3117
- return {
3118
- codeChallenge: await createCodeChallenge(verifier, crypto),
3119
- codeChallengeMethod: "S256",
3120
- redeem: async (options) => {
3121
- const finish = (result) => {
3122
- options.log?.(result.outcome === "refused" ? `switch adopt outcome: refused (${result.reason})` : `switch adopt outcome: ${result.outcome}`);
3123
- return result;
3124
- };
3125
- if (session.facts() !== null) return finish({ outcome: "unavailable" });
3126
- return landAdoptCode({
3127
- session,
3128
- doFetch: options.fetch ?? ((...args) => fetch(...args)),
3129
- apiBase: options.apiBase,
3130
- legacyToken: options.legacyToken,
3131
- code: options.code,
3132
- verifier,
3133
- epoch,
3134
- timeoutMs: options.requestTimeoutMs ?? REQUEST_TIMEOUT_MS,
3135
- finish,
3136
- expectedCompanyId: String(options.targetCompanyId)
3137
- });
3138
- }
3139
- };
3140
- }
3141
- //#endregion
3142
- //#region ../../platform/auth/src/native/adopt-marker.ts
3143
- /**
3144
- * A pending-adopt marker: written once a legacy trade has minted an adopt
3145
- * code and before it is redeemed, so a crash after the redeem leaves a
3146
- * record that something may need revoking. It names the credential slot,
3147
- * never a token.
3148
- */
3149
- const ADOPT_MARKER_GRACE_MS = 3e4;
3150
- /** The marker as the text a file holds. */
3151
- function serializeAdoptMarker(marker) {
3152
- return JSON.stringify({
3153
- storageKey: marker.storageKey,
3154
- ...marker.identityUrl ? { identityUrl: marker.identityUrl } : {},
3155
- startedAt: marker.startedAt,
3156
- ...marker.attemptCount ? { attemptCount: marker.attemptCount } : {}
3157
- });
3158
- }
3159
- /** The marker `text` holds, or null when it is not one. */
3160
- function parseAdoptMarker(text) {
3161
- try {
3162
- const raw = JSON.parse(text);
3163
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
3164
- const { storageKey, identityUrl, startedAt, attemptCount } = raw;
3165
- if (typeof storageKey !== "string" || !storageKey) return null;
3166
- if (typeof startedAt !== "number" || !Number.isFinite(startedAt)) return null;
3167
- return {
3168
- storageKey,
3169
- startedAt,
3170
- ...typeof attemptCount === "number" && attemptCount > 0 ? { attemptCount } : {},
3171
- ...typeof identityUrl === "string" && identityUrl ? { identityUrl } : {}
3172
- };
3173
- } catch {
3174
- return null;
3175
- }
3176
- }
3177
- /**
3178
- * Whether `marker` is old enough that no live attempt can still own it.
3179
- * The grace must outlast the attempt's deadline plus its cleanup.
3180
- */
3181
- function isStalePendingAdopt(marker, now, graceMs = ADOPT_MARKER_GRACE_MS) {
3182
- return now - marker.startedAt >= graceMs;
3183
- }
3184
- //#endregion
3185
- //#region src/auth/identity/environment.ts
2927
+ // src/auth/identity/environment.ts
3186
2928
  /**
3187
2929
  * Which identity service the CLI signs in with, following the API base the
3188
2930
  * CLI already talks to (`FLUID_API_BASE`, production by default).
@@ -3229,8 +2971,7 @@ function resolveIdentityUrl(apiBase, env = process.env) {
3229
2971
  if (STAGING_API_HOSTS.some((pattern) => pattern.test(hostname))) return STAGING_IDENTITY_URL;
3230
2972
  return null;
3231
2973
  }
3232
- //#endregion
3233
- //#region src/auth/identity/keyring.ts
2974
+ // src/auth/identity/keyring.ts
3234
2975
  /**
3235
2976
  * The operating system credential store for identity sessions: macOS
3236
2977
  * Keychain, Windows Credential Manager, or the Secret Service on Linux,
@@ -3264,6 +3005,10 @@ const refreshTimers$1 = /* @__PURE__ */ new Map();
3264
3005
  function cacheKey(auth) {
3265
3006
  return `${auth.identityUrl} ${auth.storageKey}`;
3266
3007
  }
3008
+ /** Returns the active credential store for client profiles. */
3009
+ function getClientStorage() {
3010
+ return deps$1.storage();
3011
+ }
3267
3012
  /**
3268
3013
  * Drops a profile's held token so the next read asks the identity service
3269
3014
  * again. With `sent`, only when the held token is that one, so a late 401 for
@@ -3367,89 +3112,14 @@ function peekClientToken(profile) {
3367
3112
  if (!existing || deps$1.now() >= existing.expiresAt - EXPIRY_MARGIN_MS$1) return null;
3368
3113
  return existing.token;
3369
3114
  }
3370
- /** A profile with this name exists and the caller asked not to replace it. */
3371
- var ProfileExistsError = class extends Error {
3372
- constructor(profileName) {
3373
- super(`profile "${profileName}" already exists`);
3374
- this.profileName = profileName;
3375
- this.name = "ProfileExistsError";
3376
- }
3377
- };
3378
- /**
3379
- * The secret stored for a profile that could not be written is still in the
3380
- * credential store under `storageKey`, because deleting it failed too.
3381
- */
3382
- var OrphanedClientSecretError = class extends Error {
3383
- constructor(storageKey, options) {
3384
- super("The client profile could not be saved and its secret could not be removed from the credential store.", options);
3385
- this.storageKey = storageKey;
3386
- this.name = "OrphanedClientSecretError";
3387
- }
3388
- };
3389
- /**
3390
- * Stores the client secret in the credential store and writes a `client`
3391
- * profile named `name`, replacing any profile of that name. The profile
3392
- * becomes active only when none was. `problems` names each replaced
3393
- * credential that could not be cleaned up. When the profile cannot be
3394
- * written, the new secret is deleted again and the error is rethrown; if that
3395
- * delete fails too, an OrphanedClientSecretError names the key left behind.
3396
- */
3397
- async function saveClientProfile(name, input, options = {}) {
3398
- const storage = await deps$1.storage();
3399
- const storageKey = `client.${randomUUID()}`;
3400
- await storage.set(storageKey, input.clientSecret);
3401
- const profile = {
3402
- name,
3403
- companyName: input.companyName,
3404
- storedAt: (/* @__PURE__ */ new Date()).toISOString(),
3405
- baseUrl: input.baseUrl,
3406
- auth: {
3407
- mode: "client",
3408
- clientId: input.clientId,
3409
- org: input.org,
3410
- identityUrl: input.identityUrl,
3411
- storageKey
3412
- }
3413
- };
3414
- let before;
3415
- let after;
3416
- try {
3417
- [before, after] = withConfigLock(() => {
3418
- return [readConfig(), updateConfig((config) => {
3419
- if (options.replace === false && config.profiles[name]) throw new ProfileExistsError(name);
3420
- return {
3421
- ...config,
3422
- activeProfile: config.activeProfile ?? name,
3423
- profiles: {
3424
- ...config.profiles,
3425
- [name]: profile
3426
- }
3427
- };
3428
- })];
3429
- });
3430
- } catch (error) {
3431
- try {
3432
- await storage.delete(storageKey);
3433
- } catch {
3434
- throw new OrphanedClientSecretError(storageKey, { cause: error });
3435
- }
3436
- throw error;
3437
- }
3438
- return {
3439
- profile,
3440
- problems: await endUnusedSessions(before, after)
3441
- };
3442
- }
3443
3115
  /** Deletes a client secret from the credential store. */
3444
3116
  async function deleteClientSecret(auth) {
3445
3117
  held.delete(cacheKey(auth));
3446
3118
  await (await deps$1.storage()).delete(auth.storageKey);
3447
3119
  }
3448
- //#endregion
3449
- //#region src/auth/identity/adopt-timeouts.ts
3120
+ // src/auth/identity/adopt-timeouts.ts
3450
3121
  const ADOPT_CLEANUP_TIMEOUT_MS = 8e3;
3451
- //#endregion
3452
- //#region src/auth/identity/browser.ts
3122
+ // src/auth/identity/browser.ts
3453
3123
  /**
3454
3124
  * Opens a URL in the user's default browser. Best effort: the sign-in URL is
3455
3125
  * always printed too, for a terminal with no browser to open.
@@ -3628,8 +3298,7 @@ function createChildKeyringStorage(options = {}) {
3628
3298
  }
3629
3299
  };
3630
3300
  }
3631
- //#endregion
3632
- //#region src/auth/identity/loopback.ts
3301
+ // src/auth/identity/loopback.ts
3633
3302
  /**
3634
3303
  * The loopback redirect for a native sign-in (RFC 8252 sections 7.3 and 8.3):
3635
3304
  * a one-shot HTTP server on 127.0.0.1, on a port the operating system picks,
@@ -3641,7 +3310,7 @@ function createChildKeyringStorage(options = {}) {
3641
3310
  * the wait times out.
3642
3311
  */
3643
3312
  const CALLBACK_PATH = "/callback";
3644
- const DEFAULT_CALLBACK_TIMEOUT_MS = 300 * 1e3;
3313
+ const DEFAULT_CALLBACK_TIMEOUT_MS = 3e5;
3645
3314
  var LoopbackTimeoutError = class extends Error {
3646
3315
  constructor() {
3647
3316
  super("Timed out waiting for the browser to finish signing in.");
@@ -3824,6 +3493,9 @@ async function exchangeInto(auth, held, org, roles) {
3824
3493
  * of this package.
3825
3494
  */
3826
3495
  var RoleNotGrantedError = class extends Error {
3496
+ roles;
3497
+ org;
3498
+ companyName;
3827
3499
  code = "role_not_granted";
3828
3500
  constructor(roles, org, companyName) {
3829
3501
  super(`The identity service did not grant ${roles.join(" and ")} at ${companyName ?? org}.`);
@@ -3948,6 +3620,16 @@ async function signOutIdentity(auth) {
3948
3620
  await held.session.signOut();
3949
3621
  }
3950
3622
  /**
3623
+ * Deletes the refresh token stored for the session without revoking it, for
3624
+ * a profile that shares its server session with another.
3625
+ */
3626
+ async function forgetIdentitySession(auth) {
3627
+ const storage = await deps.storage();
3628
+ sessions.delete(sessionKey(auth));
3629
+ await storage.delete(auth.storageKey);
3630
+ await storage.delete(`${auth.storageKey}.refresh-op`);
3631
+ }
3632
+ /**
3951
3633
  * Finishes a sign-in the identity service could not confirm. Its code may
3952
3634
  * already be redeemed and its session stored, and the code is spent either
3953
3635
  * way, so the stored session is the only way in: it is restored, retrying
@@ -4169,6 +3851,23 @@ async function adoptionStorageAvailable(signal) {
4169
3851
  return false;
4170
3852
  }
4171
3853
  }
3854
+ const REPORTED_FAILURE = Symbol.for("fluid.identityFailureReported");
3855
+ /** Records the identity-session failure message this process already showed the person. */
3856
+ function markIdentityFailureReported(message) {
3857
+ globalThis[REPORTED_FAILURE] = message;
3858
+ }
3859
+ /**
3860
+ * Whether this process already showed the person this exact identity-session
3861
+ * failure message. Held on `globalThis` because a plugin may load its own copy
3862
+ * of this package.
3863
+ */
3864
+ function identityFailureReported(message) {
3865
+ return globalThis[REPORTED_FAILURE] === message;
3866
+ }
3867
+ /** Whether the identity service no longer holds the session: it ended, or none is stored. */
3868
+ function isIdentitySessionEnded(error) {
3869
+ return error instanceof SessionError && (error.code === "not_signed_in" || error.code === "session_expired");
3870
+ }
4172
3871
  /** A sentence for the user about an identity failure. */
4173
3872
  function describeIdentityError(error) {
4174
3873
  if (error instanceof PickerRemovedError) return error.message;
@@ -4185,8 +3884,7 @@ function describeIdentityError(error) {
4185
3884
  if (error instanceof Error && error.name === "SecureStorageUnavailableError") return `Identity sign-in needs the operating system credential store (Keychain, Credential Manager, or Secret Service). ${error.message}`;
4186
3885
  return error instanceof Error ? error.message : String(error);
4187
3886
  }
4188
- //#endregion
4189
- //#region src/auth/identity/profiles.ts
3887
+ // src/auth/identity/profiles.ts
4190
3888
  /**
4191
3889
  * Ending identity sessions when the profiles that use them go away.
4192
3890
  *
@@ -4212,22 +3910,61 @@ function clientsIn(config) {
4212
3910
  return found;
4213
3911
  }
4214
3912
  /**
4215
- * Revokes every identity session `before` used that `after` no longer does,
4216
- * and deletes its refresh token from the credential store, and deletes the
4217
- * secret of every client profile `before` had that `after` no longer does.
4218
- * Resolves with a
4219
- * message for each session that could not be ended cleanly; never rejects.
3913
+ * Ends the identity sessions `before` used that `after` no longer does, and
3914
+ * deletes the secret of every client profile `before` had that `after` no
3915
+ * longer does. Profiles with different storage keys can name the same server
3916
+ * session, so a removed profile's session is revoked only when it is not one
3917
+ * a remaining profile uses. When that cannot be told, the session is kept:
3918
+ * only the removed profile's local credential is deleted, and a message says
3919
+ * so. Resolves with a message for each session that could not be ended
3920
+ * cleanly; never rejects.
4220
3921
  */
4221
3922
  async function endUnusedSessions(before, after) {
4222
3923
  const remaining = sessionsIn(after);
4223
3924
  const problems = [];
4224
- for (const [key, auth] of sessionsIn(before)) {
4225
- if (remaining.has(key)) continue;
3925
+ const removed = [...sessionsIn(before)].filter(([key]) => !remaining.has(key));
3926
+ const attempt = async (end) => {
4226
3927
  try {
4227
- await signOutIdentity(auth);
3928
+ await end();
4228
3929
  } catch (error) {
4229
3930
  problems.push(describeIdentityError(error));
4230
3931
  }
3932
+ };
3933
+ const origins = new Set(removed.map(([, auth]) => auth.identityUrl));
3934
+ for (const origin of origins) {
3935
+ const here = removed.filter(([, auth]) => auth.identityUrl === origin);
3936
+ const stay = [...remaining.values()].filter((auth) => auth.identityUrl === origin);
3937
+ if (stay.length === 0) {
3938
+ for (const [, auth] of here) await attempt(() => signOutIdentity(auth));
3939
+ continue;
3940
+ }
3941
+ const inUse = /* @__PURE__ */ new Set();
3942
+ let unreadable;
3943
+ for (const auth of stay) try {
3944
+ inUse.add((await sessionFacts(auth)).sessionId);
3945
+ } catch (error) {
3946
+ if (!isIdentitySessionEnded(error)) unreadable ??= error;
3947
+ }
3948
+ const revoked = /* @__PURE__ */ new Set();
3949
+ for (const [, auth] of here) {
3950
+ let sessionId;
3951
+ let failure = unreadable;
3952
+ if (failure === void 0) try {
3953
+ sessionId = (await sessionFacts(auth)).sessionId;
3954
+ } catch (error) {
3955
+ if (!isIdentitySessionEnded(error)) failure = error;
3956
+ }
3957
+ if (failure !== void 0) {
3958
+ problems.push(`Could not tell whether another profile still uses a removed sign-in, so its session was kept. ${describeIdentityError(failure)}`);
3959
+ await attempt(() => forgetIdentitySession(auth));
3960
+ } else if (sessionId !== void 0 && (inUse.has(sessionId) || revoked.has(sessionId))) await attempt(() => forgetIdentitySession(auth));
3961
+ else try {
3962
+ await signOutIdentity(auth);
3963
+ if (sessionId !== void 0) revoked.add(sessionId);
3964
+ } catch (error) {
3965
+ problems.push(describeIdentityError(error));
3966
+ }
3967
+ }
4231
3968
  }
4232
3969
  const remainingClients = clientsIn(after);
4233
3970
  for (const [key, auth] of clientsIn(before)) {
@@ -4240,7 +3977,88 @@ async function endUnusedSessions(before, after) {
4240
3977
  }
4241
3978
  return problems;
4242
3979
  }
4243
- //#endregion
4244
- export { createSwitchAdoptRequest as A, withConfigLock as B, primeClientProfile as C, isStalePendingAdopt as D, resolveIdentityUrl as E, readStoredConfig as F, isIdentityProfile as G, getConfigFilePath as H, updateConfig as I, writeConfig as L, ApiError as M, createFetchClient as N, parseAdoptMarker as O, readConfig as P, isStrictConfig as R, peekClientToken as S, IDENTITY_ROOT_COMPANY_ID as T, createDefaultConfig as U, getConfigDir as V, isClientProfile as W, OrphanedClientSecretError as _, describeIdentityError as a, deleteClientSecret as b, peekIdentityToken as c, revokeStoredAdoption as d, sessionFacts as f, ADOPT_CLEANUP_TIMEOUT_MS as g, KeyringRefusedError as h, deleteStoredAdoption as i, tradeLegacyToken as j, serializeAdoptMarker as k, primeIdentityProfile as l, signOutIdentity as m, adoptionStorageAvailable as n, identityToken as o, signInWithBrowser as p, createAdoptionSession as r, isRoleNotGrantedError as s, endUnusedSessions as t, profileAccessToken as u, ProfileExistsError as v, saveClientProfile as w, invalidateClientToken as x, clientAccessToken as y, configLockTimings as z };
3980
+ // src/auth/identity/client.ts
3981
+ /**
3982
+ * Machine-credential profiles: `client_credentials` against the identity
3983
+ * service's `/token` with HTTP Basic client authentication. The secret is read
3984
+ * from the operating system credential store for each token request; the
3985
+ * access token is held only in this process's memory.
3986
+ */
3987
+ /** A profile with this name exists and the caller asked not to replace it. */
3988
+ var ProfileExistsError = class extends Error {
3989
+ profileName;
3990
+ constructor(profileName) {
3991
+ super(`profile "${profileName}" already exists`);
3992
+ this.profileName = profileName;
3993
+ this.name = "ProfileExistsError";
3994
+ }
3995
+ };
3996
+ /**
3997
+ * The secret stored for a profile that could not be written is still in the
3998
+ * credential store under `storageKey`, because deleting it failed too.
3999
+ */
4000
+ var OrphanedClientSecretError = class extends Error {
4001
+ storageKey;
4002
+ constructor(storageKey, options) {
4003
+ super("The client profile could not be saved and its secret could not be removed from the credential store.", options);
4004
+ this.storageKey = storageKey;
4005
+ this.name = "OrphanedClientSecretError";
4006
+ }
4007
+ };
4008
+ /**
4009
+ * Stores the client secret in the credential store and writes a `client`
4010
+ * profile named `name`, replacing any profile of that name. The profile
4011
+ * becomes active only when none was. `problems` names each replaced
4012
+ * credential that could not be cleaned up. When the profile cannot be
4013
+ * written, the new secret is deleted again and the error is rethrown; if that
4014
+ * delete fails too, an OrphanedClientSecretError names the key left behind.
4015
+ */
4016
+ async function saveClientProfile(name, input, options = {}) {
4017
+ const storage = await getClientStorage();
4018
+ const storageKey = `client.${randomUUID()}`;
4019
+ await storage.set(storageKey, input.clientSecret);
4020
+ const profile = {
4021
+ name,
4022
+ companyName: input.companyName,
4023
+ storedAt: (/* @__PURE__ */ new Date()).toISOString(),
4024
+ baseUrl: input.baseUrl,
4025
+ auth: {
4026
+ mode: "client",
4027
+ clientId: input.clientId,
4028
+ org: input.org,
4029
+ identityUrl: input.identityUrl,
4030
+ storageKey
4031
+ }
4032
+ };
4033
+ let before;
4034
+ let after;
4035
+ try {
4036
+ [before, after] = withConfigLock(() => {
4037
+ return [readConfig(), updateConfig((config) => {
4038
+ if (options.replace === false && config.profiles[name]) throw new ProfileExistsError(name);
4039
+ return {
4040
+ ...config,
4041
+ activeProfile: config.activeProfile ?? name,
4042
+ profiles: {
4043
+ ...config.profiles,
4044
+ [name]: profile
4045
+ }
4046
+ };
4047
+ })];
4048
+ });
4049
+ } catch (error) {
4050
+ try {
4051
+ await storage.delete(storageKey);
4052
+ } catch {
4053
+ throw new OrphanedClientSecretError(storageKey, { cause: error });
4054
+ }
4055
+ throw error;
4056
+ }
4057
+ return {
4058
+ profile,
4059
+ problems: await endUnusedSessions(before, after)
4060
+ };
4061
+ }
4062
+ export { IDENTITY_ROOT_COMPANY_ID as A, updateConfig as B, ADOPT_CLEANUP_TIMEOUT_MS as C, peekClientToken as D, invalidateClientToken as E, SessionError as F, getConfigDir as G, isStrictConfig as H, ApiError as I, isClientProfile as J, getConfigFilePath as K, createFetchClient as L, createCodeChallenge as M, createCodeVerifier as N, primeClientProfile as O, exchangeNativeToken as P, readConfig as R, KeyringRefusedError as S, deleteClientSecret as T, configLockTimings as U, writeConfig as V, withConfigLock as W, isIdentityProfile as Y, profileAccessToken as _, RoleNotGrantedError as a, signInWithBrowser as b, deleteStoredAdoption as c, identityToken as d, isIdentitySessionEnded as f, primeIdentityProfile as g, peekIdentityToken as h, endUnusedSessions as i, resolveIdentityUrl as j, IDENTITY_CLIENT_ID as k, describeIdentityError as l, markIdentityFailureReported as m, ProfileExistsError as n, adoptionStorageAvailable as o, isRoleNotGrantedError as p, createDefaultConfig as q, saveClientProfile as r, createAdoptionSession as s, OrphanedClientSecretError as t, identityFailureReported as u, revokeStoredAdoption as v, clientAccessToken as w, signOutIdentity as x, sessionFacts as y, readStoredConfig as z };
4245
4063
 
4246
- //# sourceMappingURL=profiles-BxQg0jB_.mjs.map
4064
+ //# sourceMappingURL=client-B1TfaVpZ.mjs.map