@fluid-app/fluid-cli 0.1.181 → 0.1.183

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.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { A as signup, C as FLUID_API_ERROR, D as getFluidApiBase, E as fetchUserCompanies, J as visibleOptions, K as filterCatalog, M as validateToken, O as redeemIdentityLink, S as isIdentityProfile, T as confirmMfa, X as walkCommands, Y as visibleSubcommands, _ as signInWithBrowser, a as resolveCredentialSource, c as updateConfig, f as describeIdentityError, g as sessionFacts, j as switchCompany, k as sendMfa, l as writeConfig, m as primeIdentityProfile, n as getAuthToken, p as identityToken, q as rootCommand, s as readConfig, t as getActiveProfile, u as getConfigDir, v as signOutIdentity, y as resolveIdentityUrl } from "../token-C0rW9D-J.mjs";
2
+ import { A as signup, C as FLUID_API_ERROR, D as getFluidApiBase, E as fetchUserCompanies, J as visibleOptions, K as filterCatalog, M as validateToken, O as redeemIdentityLink, S as isIdentityProfile, T as confirmMfa, X as walkCommands, Y as visibleSubcommands, _ as signInWithBrowser, a as resolveCredentialSource, c as updateConfig, f as describeIdentityError, g as sessionFacts, j as switchCompany, k as sendMfa, l as writeConfig, m as primeIdentityProfile, n as getAuthToken, p as identityToken, q as rootCommand, s as readConfig, t as getActiveProfile, u as getConfigDir, v as signOutIdentity, y as resolveIdentityUrl } from "../token-dTSRF0Qx.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { A as signup, B as mapResult, D as getFluidApiBase, E as fetchUserCompanies, F as isError, G as unwrapOr, H as tryCatch, I as isFailure, L as isNodeError, M as validateToken, N as failure, P as getErrorMessage, R as isSuccess, S as isIdentityProfile, T as confirmMfa, U as tryCatchAsync, V as success, W as unwrap, X as walkCommands, Z as describeCommand, a as resolveCredentialSource, b as createFetchClient, c as updateConfig, d as getConfigFilePath, h as profileAccessToken, i as listProfileNames, j as switchCompany, k as sendMfa, l as writeConfig, n as getAuthToken, o as findProjectConfig, r as getAuthTokenAsync, s as readConfig, t as getActiveProfile, u as getConfigDir, w as SIGNUP_ERROR, x as createDefaultConfig, z as mapError } from "./token-C0rW9D-J.mjs";
1
+ import { A as signup, B as mapResult, D as getFluidApiBase, E as fetchUserCompanies, F as isError, G as unwrapOr, H as tryCatch, I as isFailure, L as isNodeError, M as validateToken, N as failure, P as getErrorMessage, R as isSuccess, S as isIdentityProfile, T as confirmMfa, U as tryCatchAsync, V as success, W as unwrap, X as walkCommands, Z as describeCommand, a as resolveCredentialSource, b as createFetchClient, c as updateConfig, d as getConfigFilePath, h as profileAccessToken, i as listProfileNames, j as switchCompany, k as sendMfa, l as writeConfig, n as getAuthToken, o as findProjectConfig, r as getAuthTokenAsync, s as readConfig, t as getActiveProfile, u as getConfigDir, w as SIGNUP_ERROR, x as createDefaultConfig, z as mapError } from "./token-dTSRF0Qx.mjs";
2
2
  import { Command } from "commander";
3
3
  import prompts from "prompts";
4
4
  //#region src/domain/output.ts
@@ -1831,49 +1831,6 @@ const AUTH_CONSTANTS = {
1831
1831
  COOKIE_MAX_AGE: 777600
1832
1832
  };
1833
1833
  //#endregion
1834
- //#region ../../platform/auth/src/session/facts.ts
1835
- /** Maps `/userinfo` onto the facts an app reads. */
1836
- function toSessionFacts(info, expiresAt, exchanged = false) {
1837
- const actor = info.act?.sub ?? null;
1838
- return {
1839
- subject: info.sub,
1840
- companyId: info.org ?? null,
1841
- roles: [...info.roles],
1842
- actor,
1843
- impersonating: actor !== null,
1844
- sessionId: info.sid,
1845
- authTime: info.auth_time,
1846
- authMethods: [...info.amr],
1847
- expiresAt,
1848
- exchanged
1849
- };
1850
- }
1851
- //#endregion
1852
- //#region ../../platform/auth/src/session/pkce.ts
1853
- function base64Url(bytes) {
1854
- let binary = "";
1855
- for (const byte of bytes) binary += String.fromCharCode(byte);
1856
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1857
- }
1858
- function randomString(byteLength, cryptoImpl) {
1859
- const bytes = new Uint8Array(byteLength);
1860
- cryptoImpl.getRandomValues(bytes);
1861
- return base64Url(bytes);
1862
- }
1863
- /** A 43-character verifier from 32 random bytes, the RFC 7636 minimum. */
1864
- function createCodeVerifier(cryptoImpl = crypto) {
1865
- return randomString(32, cryptoImpl);
1866
- }
1867
- /** An unguessable `state` binding the callback to this tab's request. */
1868
- function createState(cryptoImpl = crypto) {
1869
- return randomString(32, cryptoImpl);
1870
- }
1871
- /** `BASE64URL(SHA256(verifier))`, the S256 challenge. */
1872
- async function createCodeChallenge(verifier, cryptoImpl = crypto) {
1873
- const digest = await cryptoImpl.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
1874
- return base64Url(new Uint8Array(digest));
1875
- }
1876
- //#endregion
1877
1834
  //#region ../../platform/auth/src/session/refresher.ts
1878
1835
  /**
1879
1836
  * Single-flight refresh (INV-6.6).
@@ -1910,6 +1867,66 @@ function classifyRefreshFailure(error) {
1910
1867
  return "unavailable";
1911
1868
  }
1912
1869
  //#endregion
1870
+ //#region ../../platform/auth/src/session/exchange.ts
1871
+ /**
1872
+ * Token exchange (RFC 8693): company switch, role narrowing, and a root
1873
+ * admin's company entry (Phase 007 FR-3, FR-4).
1874
+ *
1875
+ * An exchanged token comes with no refresh token and never outlives the token
1876
+ * it was made from, while the session's own refresh chain keeps the company
1877
+ * it was opened with. So the company and roles a tab moved to are remembered
1878
+ * as an exchange target, and the session exchanges into it again after every
1879
+ * refresh. The target is a company id and role names, which are not secrets
1880
+ * and grant nothing on their own; it lives in sessionStorage so a reload of
1881
+ * the same tab stays where it was, and other tabs keep their own.
1882
+ */
1883
+ const TOKEN_EXCHANGE_GRANT = "urn:ietf:params:oauth:grant-type:token-exchange";
1884
+ const ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
1885
+ /**
1886
+ * Exchanges `subjectToken`, the session's own chain token, for one naming
1887
+ * `target`. The request carries no cookie: an exchange is judged on its
1888
+ * subject token alone and sets nothing.
1889
+ */
1890
+ function exchangeToken(client, clientId, subjectToken, target) {
1891
+ return createToken({
1892
+ client,
1893
+ body: {
1894
+ grant_type: TOKEN_EXCHANGE_GRANT,
1895
+ client_id: clientId,
1896
+ subject_token: subjectToken,
1897
+ subject_token_type: ACCESS_TOKEN_TYPE,
1898
+ requested_token_type: ACCESS_TOKEN_TYPE,
1899
+ org: target.org,
1900
+ ...target.roles ? { roles: target.roles.join(" ") } : {}
1901
+ },
1902
+ credentials: "omit"
1903
+ });
1904
+ }
1905
+ function classifyExchangeFailure(error) {
1906
+ if (classifyRefreshFailure(error) === "unavailable") return "unavailable";
1907
+ const code = oauthErrorCode(error);
1908
+ if (code === "invalid_request" || code === "invalid_token") return "unusable";
1909
+ return "refused";
1910
+ }
1911
+ //#endregion
1912
+ //#region ../../platform/auth/src/session/facts.ts
1913
+ /** Maps `/userinfo` onto the facts an app reads. */
1914
+ function toSessionFacts(info, expiresAt, exchanged = false) {
1915
+ const actor = info.act?.sub ?? null;
1916
+ return {
1917
+ subject: info.sub,
1918
+ companyId: info.org ?? null,
1919
+ roles: [...info.roles],
1920
+ actor,
1921
+ impersonating: actor !== null,
1922
+ sessionId: info.sid,
1923
+ authTime: info.auth_time,
1924
+ authMethods: [...info.amr],
1925
+ expiresAt,
1926
+ exchanged
1927
+ };
1928
+ }
1929
+ //#endregion
1913
1930
  //#region ../../platform/auth/src/session/types.ts
1914
1931
  var SessionError = class extends Error {
1915
1932
  code;
@@ -1920,6 +1937,86 @@ var SessionError = class extends Error {
1920
1937
  }
1921
1938
  };
1922
1939
  //#endregion
1940
+ //#region ../../platform/auth/src/native/exchange.ts
1941
+ /**
1942
+ * Token exchange for native clients (Phase 007 FR-3): moves a native
1943
+ * session's access token to another company, or narrows its roles, without a
1944
+ * new sign-in.
1945
+ *
1946
+ * The exchanged token comes with no refresh token and never outlives the
1947
+ * subject token, so the client keeps its own refresh chain in its
1948
+ * {@link NativeSession} and exchanges again after every refresh. The exchange
1949
+ * target, a company id and role names, is not a secret and grants nothing on
1950
+ * its own, so a client may remember it in its plain configuration.
1951
+ */
1952
+ /**
1953
+ * Exchanges `subjectToken`, the session's own access token from
1954
+ * `NativeSession.getAccessToken()`, for one naming `target`.
1955
+ *
1956
+ * Rejects with `access_denied` when the identity service refuses the target,
1957
+ * `session_expired` when it does not accept the subject token (refresh it and
1958
+ * try again), and `temporarily_unavailable` when it could not answer.
1959
+ */
1960
+ async function exchangeNativeToken(config, subjectToken, target) {
1961
+ const now = config.now ?? Date.now;
1962
+ const client = createIdentityHeyApiClient({
1963
+ baseUrl: config.identityUrl,
1964
+ credentials: "omit",
1965
+ fetch: config.fetch
1966
+ });
1967
+ let accessToken;
1968
+ let expiresAt;
1969
+ try {
1970
+ const token = await exchangeToken(client, config.clientId, subjectToken, target);
1971
+ accessToken = token.access_token;
1972
+ expiresAt = now() + token.expires_in * 1e3;
1973
+ } catch (error) {
1974
+ const failure = classifyExchangeFailure(error);
1975
+ if (failure === "unavailable") throw new SessionError("temporarily_unavailable");
1976
+ if (failure === "unusable") throw new SessionError("session_expired", "The identity service did not accept the token to exchange.");
1977
+ throw new SessionError("access_denied", "The identity service refused the exchange.");
1978
+ }
1979
+ try {
1980
+ const info = await getUserinfo({
1981
+ client,
1982
+ auth: accessToken
1983
+ });
1984
+ return {
1985
+ accessToken,
1986
+ expiresAt,
1987
+ facts: toSessionFacts(info, expiresAt, true)
1988
+ };
1989
+ } catch (error) {
1990
+ if (classifyRefreshFailure(error) === "unavailable") throw new SessionError("temporarily_unavailable");
1991
+ throw new SessionError("access_denied", "The identity service rejected the token it exchanged.");
1992
+ }
1993
+ }
1994
+ //#endregion
1995
+ //#region ../../platform/auth/src/session/pkce.ts
1996
+ function base64Url(bytes) {
1997
+ let binary = "";
1998
+ for (const byte of bytes) binary += String.fromCharCode(byte);
1999
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2000
+ }
2001
+ function randomString(byteLength, cryptoImpl) {
2002
+ const bytes = new Uint8Array(byteLength);
2003
+ cryptoImpl.getRandomValues(bytes);
2004
+ return base64Url(bytes);
2005
+ }
2006
+ /** A 43-character verifier from 32 random bytes, the RFC 7636 minimum. */
2007
+ function createCodeVerifier(cryptoImpl = crypto) {
2008
+ return randomString(32, cryptoImpl);
2009
+ }
2010
+ /** An unguessable `state` binding the callback to this tab's request. */
2011
+ function createState(cryptoImpl = crypto) {
2012
+ return randomString(32, cryptoImpl);
2013
+ }
2014
+ /** `BASE64URL(SHA256(verifier))`, the S256 challenge. */
2015
+ async function createCodeChallenge(verifier, cryptoImpl = crypto) {
2016
+ const digest = await cryptoImpl.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
2017
+ return base64Url(new Uint8Array(digest));
2018
+ }
2019
+ //#endregion
1923
2020
  //#region ../../platform/auth/src/native/secure-session.ts
1924
2021
  /**
1925
2022
  * Native secure session: the authorization code flow with PKCE for public
@@ -1935,6 +2032,13 @@ var SessionError = class extends Error {
1935
2032
  * storage without a prompt. Facts come from `/userinfo`, never from decoding
1936
2033
  * a token (INV-6.3).
1937
2034
  *
2035
+ * `switchCompany()` moves the session to another company by token exchange
2036
+ * (Phase 007 FR-3). The refresh chain keeps the company the session signed in
2037
+ * with, so the company moved to is remembered as the session's target and
2038
+ * every refresh exchanges into it again. A token is handed out only for the
2039
+ * target it was made for, so a refresh or exchange that answers after a move
2040
+ * can never hand one company's token to work started for another.
2041
+ *
1938
2042
  * Nothing here touches `window`, the DOM, cookies, or Web Storage, so it runs
1939
2043
  * in Node, Electron's main process, and React Native alike.
1940
2044
  */
@@ -1943,6 +2047,11 @@ var SessionError = class extends Error {
1943
2047
  * before it revokes regardless.
1944
2048
  */
1945
2049
  const SIGN_OUT_WAIT_MS = 5e3;
2050
+ /** Company ids are uuids, which the identity service compares in any case. */
2051
+ function sameOrg(a, b) {
2052
+ if (a === null || a === void 0 || b === null || b === void 0) return (a ?? null) === (b ?? null);
2053
+ return a.toLowerCase() === b.toLowerCase();
2054
+ }
1946
2055
  function sameRedirect(callback, redirectUri) {
1947
2056
  return callback.protocol === redirectUri.protocol && callback.host === redirectUri.host && callback.pathname === redirectUri.pathname;
1948
2057
  }
@@ -1965,6 +2074,9 @@ function createNativeSession(config) {
1965
2074
  };
1966
2075
  const grace = AUTH_CONSTANTS.TOKEN_GRACE_PERIOD_MS;
1967
2076
  let held = null;
2077
+ let chain = null;
2078
+ let chainOrg = null;
2079
+ let target = null;
1968
2080
  let pending = null;
1969
2081
  let snapshot = {
1970
2082
  status: "idle",
@@ -1987,11 +2099,17 @@ function createNativeSession(config) {
1987
2099
  };
1988
2100
  for (const listener of listeners) listener(snapshot);
1989
2101
  }
2102
+ /** The held token, if it is fresh and made for the current target. */
2103
+ function current() {
2104
+ return held && sameOrg(held.target, target) && now() < held.expiresAt - grace ? held : null;
2105
+ }
1990
2106
  /**
1991
2107
  * Keeps a newly issued token pair: the refresh token goes to secure storage
1992
2108
  * before the access token is used, so a crash cannot lose a rotation the
1993
2109
  * server has already made. A response without a refresh token (the reuse
1994
- * grace absorbed a concurrent rotation) keeps the stored one.
2110
+ * grace absorbed a concurrent rotation) keeps the stored one. When the
2111
+ * session holds another company by exchange, the new chain token is
2112
+ * exchanged into it before anything is handed out.
1995
2113
  */
1996
2114
  async function adopt(token, started) {
1997
2115
  if (started !== generation) {
@@ -2006,16 +2124,72 @@ function createNativeSession(config) {
2006
2124
  }
2007
2125
  throw new SessionError("not_signed_in");
2008
2126
  }
2009
- held = {
2127
+ const issued = {
2010
2128
  accessToken: token.access_token,
2011
- expiresAt: now() + token.expires_in * 1e3
2129
+ expiresAt: now() + token.expires_in * 1e3,
2130
+ target: null
2012
2131
  };
2013
- const info = await getUserinfo({ client });
2132
+ chain = issued;
2133
+ if (target === null) held = issued;
2134
+ const info = await getUserinfo({
2135
+ client,
2136
+ auth: issued.accessToken
2137
+ });
2014
2138
  if (started !== generation) {
2015
2139
  held = null;
2140
+ chain = null;
2016
2141
  throw new SessionError("not_signed_in");
2017
2142
  }
2018
- const facts = toSessionFacts(info, held.expiresAt);
2143
+ chainOrg = info.org ?? null;
2144
+ if (target !== null && !sameOrg(target, chainOrg)) return enter(target, started);
2145
+ held = {
2146
+ ...issued,
2147
+ target
2148
+ };
2149
+ const facts = toSessionFacts(info, issued.expiresAt);
2150
+ update({
2151
+ status: "authenticated",
2152
+ facts,
2153
+ error: null
2154
+ });
2155
+ return facts;
2156
+ }
2157
+ /**
2158
+ * Exchanges the chain token for one naming `org` and holds it. A refusal
2159
+ * rejects with `access_denied` and hands nothing out, so work started for
2160
+ * `org` can never be given the chain's own company's token instead.
2161
+ */
2162
+ async function enter(org, started) {
2163
+ const from = chain;
2164
+ if (!from) throw new SessionError("not_signed_in");
2165
+ let exchanged;
2166
+ try {
2167
+ exchanged = await exchangeNativeToken({
2168
+ identityUrl: config.identityUrl,
2169
+ clientId: config.clientId,
2170
+ fetch: config.fetch,
2171
+ now
2172
+ }, from.accessToken, {
2173
+ org,
2174
+ roles: null
2175
+ });
2176
+ } catch (error) {
2177
+ if (started !== generation) throw new SessionError("not_signed_in");
2178
+ const sessionError = error instanceof SessionError && error.code === "access_denied" ? new SessionError("access_denied", `The identity service will not move this session to company ${org}.`) : new SessionError("temporarily_unavailable", error instanceof SessionError && error.code === "session_expired" ? "The identity service did not accept the session's token for an exchange; a refresh may." : "The identity service could not exchange the session's token; retry later.");
2179
+ update({ error: sessionError });
2180
+ throw sessionError;
2181
+ }
2182
+ if (started !== generation) throw new SessionError("not_signed_in");
2183
+ const expiresAt = Math.min(from.expiresAt, exchanged.expiresAt);
2184
+ held = {
2185
+ accessToken: exchanged.accessToken,
2186
+ expiresAt,
2187
+ target: org
2188
+ };
2189
+ const facts = {
2190
+ ...exchanged.facts,
2191
+ expiresAt
2192
+ };
2019
2193
  update({
2020
2194
  status: "authenticated",
2021
2195
  facts,
@@ -2095,6 +2269,8 @@ function createNativeSession(config) {
2095
2269
  }
2096
2270
  async function forget(error) {
2097
2271
  held = null;
2272
+ chain = null;
2273
+ chainOrg = null;
2098
2274
  await store.delete();
2099
2275
  update({
2100
2276
  status: "unauthenticated",
@@ -2152,11 +2328,30 @@ function createNativeSession(config) {
2152
2328
  if (!held) throw new SessionError("not_signed_in");
2153
2329
  return held;
2154
2330
  }
2331
+ /**
2332
+ * A fresh token for the current target: joins or starts a refresh, and
2333
+ * refreshes once more when the one it joined was made for a target the
2334
+ * session has since moved from.
2335
+ */
2336
+ async function freshToken() {
2337
+ for (let attempt = 0; attempt < 2; attempt += 1) {
2338
+ const refreshed = await refresher.refresh();
2339
+ if (sameOrg(refreshed.target, target)) return refreshed;
2340
+ }
2341
+ throw new SessionError("temporarily_unavailable", "The session moved company while a token was being issued; retry.");
2342
+ }
2155
2343
  const session = {
2156
- async restore() {
2157
- if (held && now() < held.expiresAt - grace) return snapshot.facts;
2344
+ async restore(options) {
2345
+ if (options && "org" in options) {
2346
+ const org = options.org ?? null;
2347
+ if (!sameOrg(org, target)) {
2348
+ target = org;
2349
+ held = null;
2350
+ }
2351
+ }
2352
+ if (current()) return snapshot.facts;
2158
2353
  try {
2159
- await refresher.refresh();
2354
+ await freshToken();
2160
2355
  return snapshot.facts;
2161
2356
  } catch (error) {
2162
2357
  if (error instanceof SessionError && (error.code === "not_signed_in" || error.code === "session_expired")) return null;
@@ -2164,18 +2359,21 @@ function createNativeSession(config) {
2164
2359
  }
2165
2360
  },
2166
2361
  async beginSignIn(options) {
2362
+ const redirectUri = options?.redirectUri ?? config.redirectUri;
2363
+ if (!redirectUri) throw new SessionError("redirect_failed", "No redirect URI was configured or given for this sign-in.");
2167
2364
  const cryptoImpl = config.crypto;
2168
2365
  const verifier = createCodeVerifier(cryptoImpl);
2169
2366
  const state = createState(cryptoImpl);
2170
2367
  const challenge = await createCodeChallenge(verifier, cryptoImpl);
2171
2368
  pending = {
2172
2369
  state,
2173
- verifier
2370
+ verifier,
2371
+ redirectUri
2174
2372
  };
2175
2373
  const url = new URL("/authorize", config.identityUrl);
2176
2374
  url.searchParams.set("response_type", "code");
2177
2375
  url.searchParams.set("client_id", config.clientId);
2178
- url.searchParams.set("redirect_uri", config.redirectUri);
2376
+ url.searchParams.set("redirect_uri", redirectUri);
2179
2377
  url.searchParams.set("state", state);
2180
2378
  url.searchParams.set("code_challenge", challenge);
2181
2379
  url.searchParams.set("code_challenge_method", "S256");
@@ -2195,7 +2393,7 @@ function createNativeSession(config) {
2195
2393
  throw new SessionError("state_mismatch", "The redirect was not a URL.");
2196
2394
  }
2197
2395
  const state = callback.searchParams.get("state");
2198
- if (!request || !sameRedirect(callback, new URL(config.redirectUri)) || state === null || state !== request.state) throw new SessionError("state_mismatch", "The redirect did not match a sign-in this client started.");
2396
+ if (!request || !sameRedirect(callback, new URL(request.redirectUri)) || state === null || state !== request.state) throw new SessionError("state_mismatch", "The redirect did not match a sign-in this client started.");
2199
2397
  const error = callback.searchParams.get("error");
2200
2398
  if (error) throw new SessionError(error === "access_denied" || error === "login_required" || error === "account_selection_required" || error === "temporarily_unavailable" ? error : "redemption_failed", `The identity service answered ${error}.`);
2201
2399
  const code = callback.searchParams.get("code");
@@ -2207,7 +2405,7 @@ function createNativeSession(config) {
2207
2405
  body: {
2208
2406
  grant_type: "authorization_code",
2209
2407
  code,
2210
- redirect_uri: config.redirectUri,
2408
+ redirect_uri: request.redirectUri,
2211
2409
  client_id: config.clientId,
2212
2410
  code_verifier: request.verifier
2213
2411
  }
@@ -2216,6 +2414,8 @@ function createNativeSession(config) {
2216
2414
  throw classifyRefreshFailure(redeemError) === "unavailable" ? new SessionError("temporarily_unavailable") : new SessionError("redemption_failed", "The code was not redeemed.");
2217
2415
  }
2218
2416
  if (!token.refresh_token) throw new SessionError("redemption_failed", "The identity service issued no refresh token to a native client.");
2417
+ target = null;
2418
+ held = null;
2219
2419
  try {
2220
2420
  return await adopt(token, started);
2221
2421
  } catch (adoptError) {
@@ -2224,9 +2424,51 @@ function createNativeSession(config) {
2224
2424
  }
2225
2425
  },
2226
2426
  async getAccessToken(options) {
2227
- const current = held && now() < held.expiresAt - grace ? held : null;
2228
- if (current && current.accessToken !== options?.replacing) return current.accessToken;
2229
- return (await refresher.refresh()).accessToken;
2427
+ const fresh = current();
2428
+ if (fresh && fresh.accessToken !== options?.replacing) return fresh.accessToken;
2429
+ return (await freshToken()).accessToken;
2430
+ },
2431
+ async switchCompany(org) {
2432
+ if (signOutsRunning > 0) throw new SessionError("not_signed_in");
2433
+ while (refresher.inFlight()) await refresher.refresh().catch(() => void 0);
2434
+ const started = generation;
2435
+ const previous = target;
2436
+ const previousHeld = held;
2437
+ target = org;
2438
+ if (!sameOrg(previous, org)) held = null;
2439
+ try {
2440
+ const base = chain && now() < chain.expiresAt - grace ? chain : null;
2441
+ if (!base) {
2442
+ await freshToken();
2443
+ if (!snapshot.facts) throw new SessionError("not_signed_in");
2444
+ return snapshot.facts;
2445
+ }
2446
+ if (org === null || sameOrg(org, chainOrg)) {
2447
+ const info = await getUserinfo({
2448
+ client,
2449
+ auth: base.accessToken
2450
+ });
2451
+ if (started !== generation) throw new SessionError("not_signed_in");
2452
+ held = {
2453
+ ...base,
2454
+ target: org
2455
+ };
2456
+ const facts = toSessionFacts(info, base.expiresAt);
2457
+ update({
2458
+ status: "authenticated",
2459
+ facts,
2460
+ error: null
2461
+ });
2462
+ return facts;
2463
+ }
2464
+ return await tracked(enter(org, started));
2465
+ } catch (error) {
2466
+ if (sameOrg(target, org)) {
2467
+ target = previous;
2468
+ held = started === generation ? previousHeld : null;
2469
+ }
2470
+ throw error;
2471
+ }
2230
2472
  },
2231
2473
  facts() {
2232
2474
  return snapshot.facts;
@@ -2238,6 +2480,9 @@ function createNativeSession(config) {
2238
2480
  signOutsRunning += 1;
2239
2481
  pending = null;
2240
2482
  held = null;
2483
+ chain = null;
2484
+ chainOrg = null;
2485
+ target = null;
2241
2486
  let refreshToken;
2242
2487
  try {
2243
2488
  await settleWork();
@@ -2307,103 +2552,6 @@ function createKeyringSecureStorage(options) {
2307
2552
  };
2308
2553
  }
2309
2554
  //#endregion
2310
- //#region ../../platform/auth/src/session/exchange.ts
2311
- /**
2312
- * Token exchange (RFC 8693): company switch, role narrowing, and a root
2313
- * admin's company entry (Phase 007 FR-3, FR-4).
2314
- *
2315
- * An exchanged token comes with no refresh token and never outlives the token
2316
- * it was made from, while the session's own refresh chain keeps the company
2317
- * it was opened with. So the company and roles a tab moved to are remembered
2318
- * as an exchange target, and the session exchanges into it again after every
2319
- * refresh. The target is a company id and role names, which are not secrets
2320
- * and grant nothing on their own; it lives in sessionStorage so a reload of
2321
- * the same tab stays where it was, and other tabs keep their own.
2322
- */
2323
- const TOKEN_EXCHANGE_GRANT = "urn:ietf:params:oauth:grant-type:token-exchange";
2324
- const ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
2325
- /**
2326
- * Exchanges `subjectToken`, the session's own chain token, for one naming
2327
- * `target`. The request carries no cookie: an exchange is judged on its
2328
- * subject token alone and sets nothing.
2329
- */
2330
- function exchangeToken(client, clientId, subjectToken, target) {
2331
- return createToken({
2332
- client,
2333
- body: {
2334
- grant_type: TOKEN_EXCHANGE_GRANT,
2335
- client_id: clientId,
2336
- subject_token: subjectToken,
2337
- subject_token_type: ACCESS_TOKEN_TYPE,
2338
- requested_token_type: ACCESS_TOKEN_TYPE,
2339
- org: target.org,
2340
- ...target.roles ? { roles: target.roles.join(" ") } : {}
2341
- },
2342
- credentials: "omit"
2343
- });
2344
- }
2345
- function classifyExchangeFailure(error) {
2346
- if (classifyRefreshFailure(error) === "unavailable") return "unavailable";
2347
- const code = oauthErrorCode(error);
2348
- if (code === "invalid_request" || code === "invalid_token") return "unusable";
2349
- return "refused";
2350
- }
2351
- //#endregion
2352
- //#region ../../platform/auth/src/native/exchange.ts
2353
- /**
2354
- * Token exchange for native clients (Phase 007 FR-3): moves a native
2355
- * session's access token to another company, or narrows its roles, without a
2356
- * new sign-in.
2357
- *
2358
- * The exchanged token comes with no refresh token and never outlives the
2359
- * subject token, so the client keeps its own refresh chain in its
2360
- * {@link NativeSession} and exchanges again after every refresh. The exchange
2361
- * target, a company id and role names, is not a secret and grants nothing on
2362
- * its own, so a client may remember it in its plain configuration.
2363
- */
2364
- /**
2365
- * Exchanges `subjectToken`, the session's own access token from
2366
- * `NativeSession.getAccessToken()`, for one naming `target`.
2367
- *
2368
- * Rejects with `access_denied` when the identity service refuses the target,
2369
- * `session_expired` when it does not accept the subject token (refresh it and
2370
- * try again), and `temporarily_unavailable` when it could not answer.
2371
- */
2372
- async function exchangeNativeToken(config, subjectToken, target) {
2373
- const now = config.now ?? Date.now;
2374
- const client = createIdentityHeyApiClient({
2375
- baseUrl: config.identityUrl,
2376
- credentials: "omit",
2377
- fetch: config.fetch
2378
- });
2379
- let accessToken;
2380
- let expiresAt;
2381
- try {
2382
- const token = await exchangeToken(client, config.clientId, subjectToken, target);
2383
- accessToken = token.access_token;
2384
- expiresAt = now() + token.expires_in * 1e3;
2385
- } catch (error) {
2386
- const failure = classifyExchangeFailure(error);
2387
- if (failure === "unavailable") throw new SessionError("temporarily_unavailable");
2388
- if (failure === "unusable") throw new SessionError("session_expired", "The identity service did not accept the token to exchange.");
2389
- throw new SessionError("access_denied", "The identity service refused the exchange.");
2390
- }
2391
- try {
2392
- const info = await getUserinfo({
2393
- client,
2394
- auth: accessToken
2395
- });
2396
- return {
2397
- accessToken,
2398
- expiresAt,
2399
- facts: toSessionFacts(info, expiresAt, true)
2400
- };
2401
- } catch (error) {
2402
- if (classifyRefreshFailure(error) === "unavailable") throw new SessionError("temporarily_unavailable");
2403
- throw new SessionError("access_denied", "The identity service rejected the token it exchanged.");
2404
- }
2405
- }
2406
- //#endregion
2407
2555
  //#region src/auth/identity/browser.ts
2408
2556
  /**
2409
2557
  * Opens a URL in the user's default browser. Best effort: the sign-in URL is
@@ -3110,4 +3258,4 @@ function listProfileNames() {
3110
3258
  //#endregion
3111
3259
  export { signup as A, mapResult as B, FLUID_API_ERROR as C, getFluidApiBase as D, fetchUserCompanies as E, isError as F, unwrapOr as G, tryCatch as H, isFailure as I, visibleOptions as J, filterCatalog as K, isNodeError as L, validateToken as M, failure as N, redeemIdentityLink as O, getErrorMessage$1 as P, isSuccess as R, isIdentityProfile as S, confirmMfa as T, tryCatchAsync as U, success as V, unwrap as W, walkCommands as X, visibleSubcommands as Y, describeCommand as Z, signInWithBrowser as _, resolveCredentialSource as a, createFetchClient as b, updateConfig as c, getConfigFilePath as d, describeIdentityError as f, sessionFacts as g, profileAccessToken as h, listProfileNames as i, switchCompany as j, sendMfa as k, writeConfig as l, primeIdentityProfile as m, getAuthToken as n, findProjectConfig as o, identityToken as p, rootCommand as q, getAuthTokenAsync as r, readConfig as s, getActiveProfile as t, getConfigDir as u, signOutIdentity as v, SIGNUP_ERROR as w, createDefaultConfig as x, resolveIdentityUrl as y, mapError as z };
3112
3260
 
3113
- //# sourceMappingURL=token-C0rW9D-J.mjs.map
3261
+ //# sourceMappingURL=token-dTSRF0Qx.mjs.map