@ekanos/cli 0.12.0 → 0.14.0

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 (175) hide show
  1. package/README.md +25 -8
  2. package/dist/agents-api.d.ts +11 -2
  3. package/dist/agents-api.js +39 -3
  4. package/dist/agents-api.js.map +1 -1
  5. package/dist/apps-api.d.ts +3 -2
  6. package/dist/apps-api.js +3 -7
  7. package/dist/apps-api.js.map +1 -1
  8. package/dist/auth/ekanos-api.d.ts +16 -2
  9. package/dist/auth/ekanos-api.js +101 -15
  10. package/dist/auth/ekanos-api.js.map +1 -1
  11. package/dist/auth/host-trust.d.ts +46 -0
  12. package/dist/auth/host-trust.js +79 -0
  13. package/dist/auth/host-trust.js.map +1 -0
  14. package/dist/auth/session.d.ts +10 -1
  15. package/dist/auth/session.js +28 -28
  16. package/dist/auth/session.js.map +1 -1
  17. package/dist/commands/agents-edit.d.ts +6 -2
  18. package/dist/commands/agents-edit.js +57 -26
  19. package/dist/commands/agents-edit.js.map +1 -1
  20. package/dist/commands/agents.d.ts +13 -2
  21. package/dist/commands/agents.js +148 -36
  22. package/dist/commands/agents.js.map +1 -1
  23. package/dist/commands/apps.d.ts +15 -4
  24. package/dist/commands/apps.js +133 -51
  25. package/dist/commands/apps.js.map +1 -1
  26. package/dist/commands/catalog.js +7 -6
  27. package/dist/commands/catalog.js.map +1 -1
  28. package/dist/commands/knowledge.d.ts +56 -0
  29. package/dist/commands/knowledge.js +456 -0
  30. package/dist/commands/knowledge.js.map +1 -0
  31. package/dist/commands/login.d.ts +4 -0
  32. package/dist/commands/login.js +30 -2
  33. package/dist/commands/login.js.map +1 -1
  34. package/dist/commands/logout.d.ts +9 -1
  35. package/dist/commands/logout.js +56 -7
  36. package/dist/commands/logout.js.map +1 -1
  37. package/dist/commands/publish.js +3 -3
  38. package/dist/commands/publish.js.map +1 -1
  39. package/dist/commands/reviewers.d.ts +2 -0
  40. package/dist/commands/reviewers.js +7 -3
  41. package/dist/commands/reviewers.js.map +1 -1
  42. package/dist/commands/routes.d.ts +2 -0
  43. package/dist/commands/routes.js +42 -9
  44. package/dist/commands/routes.js.map +1 -1
  45. package/dist/commands/runs.d.ts +13 -2
  46. package/dist/commands/runs.js +96 -15
  47. package/dist/commands/runs.js.map +1 -1
  48. package/dist/commands/scope-notice.d.ts +21 -0
  49. package/dist/commands/scope-notice.js +35 -0
  50. package/dist/commands/scope-notice.js.map +1 -0
  51. package/dist/commands/skills.d.ts +7 -1
  52. package/dist/commands/skills.js +80 -24
  53. package/dist/commands/skills.js.map +1 -1
  54. package/dist/commands/sources.d.ts +4 -0
  55. package/dist/commands/sources.js +233 -5
  56. package/dist/commands/sources.js.map +1 -1
  57. package/dist/commands/status.js +5 -4
  58. package/dist/commands/status.js.map +1 -1
  59. package/dist/commands/team-agent-readiness.d.ts +59 -0
  60. package/dist/commands/team-agent-readiness.js +341 -0
  61. package/dist/commands/team-agent-readiness.js.map +1 -0
  62. package/dist/commands/team-agents-agents.d.ts +24 -3
  63. package/dist/commands/team-agents-agents.js +336 -35
  64. package/dist/commands/team-agents-agents.js.map +1 -1
  65. package/dist/commands/team-agents-mcp.js +32 -3
  66. package/dist/commands/team-agents-mcp.js.map +1 -1
  67. package/dist/commands/team-agents-triggers.js +230 -54
  68. package/dist/commands/team-agents-triggers.js.map +1 -1
  69. package/dist/commands/team-agents.d.ts +3 -1
  70. package/dist/commands/team-agents.js +27 -7
  71. package/dist/commands/team-agents.js.map +1 -1
  72. package/dist/commands/teams-channel-install.d.ts +24 -0
  73. package/dist/commands/teams-channel-install.js +94 -0
  74. package/dist/commands/teams-channel-install.js.map +1 -0
  75. package/dist/commands/teams-connect.d.ts +66 -0
  76. package/dist/commands/teams-connect.js +397 -0
  77. package/dist/commands/teams-connect.js.map +1 -0
  78. package/dist/commands/teams-events.d.ts +12 -0
  79. package/dist/commands/teams-events.js +138 -0
  80. package/dist/commands/teams-events.js.map +1 -0
  81. package/dist/commands/teams-onboard.d.ts +16 -5
  82. package/dist/commands/teams-onboard.js +61 -36
  83. package/dist/commands/teams-onboard.js.map +1 -1
  84. package/dist/commands/teams-overview.d.ts +11 -0
  85. package/dist/commands/teams-overview.js +160 -0
  86. package/dist/commands/teams-overview.js.map +1 -0
  87. package/dist/commands/teams-scope.d.ts +10 -0
  88. package/dist/commands/teams-scope.js +109 -0
  89. package/dist/commands/teams-scope.js.map +1 -0
  90. package/dist/commands/teams.d.ts +64 -7
  91. package/dist/commands/teams.js +254 -60
  92. package/dist/commands/teams.js.map +1 -1
  93. package/dist/commands/upgrade.js +12 -2
  94. package/dist/commands/upgrade.js.map +1 -1
  95. package/dist/commands/use.js +2 -2
  96. package/dist/commands/use.js.map +1 -1
  97. package/dist/commands/whoami.js +1 -1
  98. package/dist/commands/whoami.js.map +1 -1
  99. package/dist/connections-api.js +1 -1
  100. package/dist/connections-api.js.map +1 -1
  101. package/dist/delegate.js +11 -4
  102. package/dist/delegate.js.map +1 -1
  103. package/dist/harness-scaffold.js +12 -0
  104. package/dist/harness-scaffold.js.map +1 -1
  105. package/dist/index.d.ts +6 -0
  106. package/dist/index.js +724 -152
  107. package/dist/index.js.map +1 -1
  108. package/dist/knowledge-api.d.ts +175 -0
  109. package/dist/knowledge-api.js +169 -0
  110. package/dist/knowledge-api.js.map +1 -0
  111. package/dist/open-url.d.ts +16 -0
  112. package/dist/open-url.js +73 -0
  113. package/dist/open-url.js.map +1 -0
  114. package/dist/parse-argv.d.ts +2 -0
  115. package/dist/parse-argv.js.map +1 -1
  116. package/dist/publish-api.d.ts +2 -1
  117. package/dist/publish-api.js +4 -3
  118. package/dist/publish-api.js.map +1 -1
  119. package/dist/pull-write.d.ts +27 -0
  120. package/dist/pull-write.js +60 -0
  121. package/dist/pull-write.js.map +1 -0
  122. package/dist/routes-api.d.ts +3 -0
  123. package/dist/routes-api.js +9 -4
  124. package/dist/routes-api.js.map +1 -1
  125. package/dist/runs-api.d.ts +7 -1
  126. package/dist/runs-api.js +21 -6
  127. package/dist/runs-api.js.map +1 -1
  128. package/dist/safe-fs.d.ts +2 -0
  129. package/dist/safe-fs.js +12 -6
  130. package/dist/safe-fs.js.map +1 -1
  131. package/dist/secret-file.d.ts +17 -0
  132. package/dist/secret-file.js +69 -0
  133. package/dist/secret-file.js.map +1 -0
  134. package/dist/skills-api.d.ts +10 -2
  135. package/dist/skills-api.js +37 -2
  136. package/dist/skills-api.js.map +1 -1
  137. package/dist/source-products-api.d.ts +63 -0
  138. package/dist/source-products-api.js +123 -0
  139. package/dist/source-products-api.js.map +1 -0
  140. package/dist/source-target.js +2 -1
  141. package/dist/source-target.js.map +1 -1
  142. package/dist/sources-api.d.ts +2 -1
  143. package/dist/sources-api.js +3 -2
  144. package/dist/sources-api.js.map +1 -1
  145. package/dist/team-connect-api.d.ts +286 -0
  146. package/dist/team-connect-api.js +107 -0
  147. package/dist/team-connect-api.js.map +1 -0
  148. package/dist/teams-api.d.ts +42 -1
  149. package/dist/teams-api.js +98 -20
  150. package/dist/teams-api.js.map +1 -1
  151. package/dist/toolchain-api.d.ts +9 -0
  152. package/dist/toolchain-api.js +17 -2
  153. package/dist/toolchain-api.js.map +1 -1
  154. package/dist/toolchain-resolve.d.ts +3 -0
  155. package/dist/toolchain-resolve.js +15 -1
  156. package/dist/toolchain-resolve.js.map +1 -1
  157. package/dist/toolchain.d.ts +6 -0
  158. package/dist/toolchain.js +19 -0
  159. package/dist/toolchain.js.map +1 -1
  160. package/dist/update-notice.js +2 -1
  161. package/dist/update-notice.js.map +1 -1
  162. package/package.json +2 -2
  163. package/templates/AGENTS.md.tmpl +6 -1
  164. package/templates/claude-skill.md.tmpl +5 -0
  165. package/templates/package.json.tmpl +4 -4
  166. package/templates/skills/build-agent/SKILL.md +115 -16
  167. package/templates/skills/build-agent/references/agent-json.md +26 -8
  168. package/templates/skills/build-agent/references/app-setup.md +2 -1
  169. package/templates/skills/build-agent/references/rollout.md +27 -4
  170. package/templates/skills/build-agent/references/set-up-an-integration.md +74 -15
  171. package/templates/skills/build-agent/references/skills.md +20 -1
  172. package/templates/skills/build-agent/references/triggers.md +84 -20
  173. package/templates/skills/build-integration/references/widget-design.md +3 -3
  174. package/templates/skills/ekanos-platform/SKILL.md +70 -17
  175. package/templates/skills/polish-widgets/references/patterns.md +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"ekanos-api.js","sourceRoot":"","sources":["../../src/auth/ekanos-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAE/E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8EG;AAEH,MAAM,kBAAkB,GAAG,KAAM,CAAC;AAuBlC,mDAAmD;AACnD,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,IAAY;IACnD,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,GAAG,IAAI,sBAAsB,EAAE;QAC5D,MAAM,EAAE,KAAK;QACb,OAAO,EAAE,EAAE,MAAM,EAAE,kBAAkB,EAAE;KACxC,CAAC,CAAC;IAEH,oBAAoB,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;IAErC,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACjB,MAAM,gBAAgB,CAAC,IAAI,EAAE,sBAAsB,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IACxE,CAAC;IAED,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,QAAQ,EAAE,GAAG,IAAI,sBAAsB,CAAC,CAAC;IAErE,MAAM,MAAM,GAAG;QACb,WAAW,EAAE,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC;QACnC,QAAQ,EAAE,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC;QAC7B,KAAK,EAAE,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC;QACtB,2BAA2B,EAAE,GAAG,CAAC,IAAI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,EAC/C,CAAC;QACD,MAAM,iBAAiB,CACrB,sEAAsE;YACpE,WAAW,GAAG,CAAC,IAAI,IAAI,EACzB,6DAA6D;YAC3D,sDAAsD,CACzD,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,UAAU,CAAC,MAAc;IAChC,OAAO,MAAM,IAAI,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC;AACvC,CAAC;AAED,SAAS,GAAG,CAAC,KAAc;IACzB,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AACtE,CAAC","sourcesContent":["import { authRequiredError, networkError, preconditionError } from '../errors';\n\n/**\n * The CLI's client for the four Ekanos auth routes.\n *\n * ---------------------------------------------------------------------------\n * WIRE CONTRACT — the seam between this package and the Ekanos web app.\n *\n * The server side is the host's `/api/auth/cli-<verb>` routes, and it ships on\n * a DIFFERENT BRANCH from this file. This block is the single place the shapes\n * are written down on the client side; if you change one side, change the\n * other and update this block. Nothing here imports host code — the two\n * halves are coupled only by HTTP, and the tests stub `fetch`, never the route.\n *\n * GET /api/auth/cli-config [no auth]\n * → 200 { auth0_domain, client_id, scope,\n * device_authorization_endpoint, token_endpoint } all strings\n * → 503 { error, code: \"CLI_NOT_CONFIGURED\" } deployment not provisioned\n *\n * POST /api/auth/cli-session [no auth]\n * ← { auth0_access_token: string }\n * → 200 { access_token, expires_at, user: { id, email } }\n * → 400 { error, code: \"INVALID_REQUEST\" } malformed / wrong shape\n * → 401 { error, code: \"SESSION_EXPIRED\" } Auth0 said no, OR no\n * Ekanos account for it\n * → 503 { error, code: \"CLI_NOT_CONFIGURED\" } deployment not provisioned\n * → 500 { error, code: \"INTERNAL_ERROR\" }\n *\n * POST /api/auth/cli-refresh [no auth]\n * ← { auth0_refresh_token: string }\n * → 200 { access_token, expires_at, user: { id, email },\n * auth0_refresh_token } ← ROTATED; the presented one is dead\n * → 400 { error, code: \"INVALID_REQUEST\" }\n * → 401 { error, code: \"SESSION_EXPIRED\" } expired or revoked\n * → 404 { error, code: \"ACCOUNT_NOT_FOUND\",\n * auth0_refresh_token } no Ekanos account\n * → 502 { error, code: \"TOKEN_EXCHANGE_FAILED\" } Auth0 returned no\n * rotated token\n * → 503 { error, code: \"CLI_NOT_CONFIGURED\" } deployment not provisioned\n * → 503 { error, code: \"REFRESH_INCOMPLETE\",\n * auth0_refresh_token } rotated, but /userinfo\n * did not answer; RETRYABLE\n * → 500 { error, code: \"INTERNAL_ERROR\",\n * auth0_refresh_token? } present iff rotation\n * completed before the throw\n *\n * !! cli-refresh MAY RETURN `auth0_refresh_token` ON ERROR RESPONSES, and a\n * client MUST persist it before surfacing the error. Once the server's\n * exchange with Auth0 succeeds the presented token is dead and the value\n * in that body is the ONLY copy in existence; discarding it on a failure\n * path destroys the session permanently. Note 503 has TWO codes here —\n * branch on `code`, not on the status alone.\n *\n * All three routes above read the Fusion CLI Auth0 application config, so all\n * three can answer 503 CLI_NOT_CONFIGURED. cli-whoami cannot — it reads no\n * Auth0 config, only the caller's bearer token.\n *\n * GET /api/auth/cli-whoami [Authorization: Bearer <access_token>]\n * → 200 { user: { id, email, name } }\n * → 401 { error, code: \"AUTH_REQUIRED\" } token absent or invalid\n * → 403 { error, code: \"MFA_REQUIRED\" }\n * → 404 { error, code: \"ACCOUNT_NOT_FOUND\" }\n * → 3xx treated as 401, see below\n *\n * `access_token` is an Ekanos HS256 JWT. Every authenticated Ekanos route\n * accepts it as `Authorization: Bearer` — see `resolveRequestSupabaseJwt` in\n * `@kit/supabase`, which both `requireUser` and the RLS server client consume.\n * ---------------------------------------------------------------------------\n *\n * Two rules hold everywhere in this file:\n *\n * - `redirect: 'manual'`. Ekanos answers an unauthenticated page request with\n * a 307 to `/auth/sign-in`; Node's fetch follows redirects by default, so\n * without this a stale token would come back as a 200 full of HTML and be\n * read as success. A 3xx here is treated as \"not authenticated\", full stop.\n *\n * - No token is ever interpolated into an error message. The server's error\n * bodies are `{ error, code }` documents that do not echo credentials, and\n * the request bodies that DO carry credentials are never included in a\n * thrown message.\n */\n\nconst REQUEST_TIMEOUT_MS = 15_000;\n\nexport interface CliAuthConfig {\n auth0Domain: string;\n clientId: string;\n scope: string;\n deviceAuthorizationEndpoint: string;\n tokenEndpoint: string;\n}\n\nexport interface EkanosSession {\n accessToken: string;\n expiresAt: string;\n userId: string;\n email: string | null;\n}\n\nexport interface EkanosIdentity {\n id: string;\n email: string | null;\n name: string | null;\n}\n\n/** Fetch the device-flow parameters for a host. */\nexport async function fetchCliAuthConfig(host: string): Promise<CliAuthConfig> {\n const response = await request(`${host}/api/auth/cli-config`, {\n method: 'GET',\n headers: { accept: 'application/json' },\n });\n\n throwIfNotConfigured(response, host);\n\n if (!response.ok) {\n throw unexpectedStatus(host, '/api/auth/cli-config', response.status);\n }\n\n const body = await readJson(response, `${host}/api/auth/cli-config`);\n\n const config = {\n auth0Domain: str(body.auth0_domain),\n clientId: str(body.client_id),\n scope: str(body.scope),\n deviceAuthorizationEndpoint: str(body.device_authorization_endpoint),\n tokenEndpoint: str(body.token_endpoint),\n };\n\n if (Object.values(config).some((value) => value === null)) {\n throw preconditionError(\n `${host} returned an incomplete CLI login configuration.`,\n `Confirm the deployment is running an Ekanos build that includes the ` +\n `/api/auth/cli-config route.`,\n );\n }\n\n // The endpoints come from the server, so they are attacker-controlled if the\n // host is. Pin them to the Auth0 domain the same response declares, so a\n // compromised or misconfigured Ekanos cannot redirect the device flow — and\n // the resulting credentials — to an arbitrary origin.\n assertOnDomain(config.deviceAuthorizationEndpoint!, config.auth0Domain!);\n assertOnDomain(config.tokenEndpoint!, config.auth0Domain!);\n\n return config as CliAuthConfig;\n}\n\n/** Exchange a verified Auth0 access token for an Ekanos JWT. */\nexport async function createEkanosSession(\n host: string,\n auth0AccessToken: string,\n): Promise<EkanosSession> {\n const response = await request(`${host}/api/auth/cli-session`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({ auth0_access_token: auth0AccessToken }),\n });\n\n throwIfNotConfigured(response, host);\n\n if (response.status === 401) {\n throw authRequiredError(\n `${host} rejected the Auth0 identity.`,\n `Run \"ekanos login\" again. If it keeps failing, confirm your account ` +\n `exists on ${host} — the browser login can succeed for an identity ` +\n `that has no Ekanos account.`,\n );\n }\n\n if (!response.ok) {\n throw unexpectedStatus(host, '/api/auth/cli-session', response.status);\n }\n\n return toSession(\n await readJson(response, `${host}/api/auth/cli-session`),\n host,\n );\n}\n\nexport interface RefreshedSession extends EkanosSession {\n /** The ROTATED refresh token. The presented one is already invalid. */\n auth0RefreshToken: string;\n}\n\nexport interface RefreshOptions {\n /**\n * Called the INSTANT a rotated refresh token is seen in the response — on\n * success and on failure alike, before anything is thrown.\n *\n * Persist-on-learn, not persist-on-success. Once the server's exchange with\n * Auth0 succeeds the presented token is dead and the replacement in that\n * body is the only copy in existence, so a client that only saves it on the\n * happy path destroys the partner's credential the first time /userinfo\n * blips. The callback runs before any throw so no error path can skip it.\n */\n onRotatedToken?: (rotated: string) => void;\n}\n\n/** Re-mint an Ekanos JWT from the stored Auth0 refresh token. */\nexport async function refreshEkanosSession(\n host: string,\n auth0RefreshToken: string,\n options: RefreshOptions = {},\n): Promise<RefreshedSession> {\n const response = await request(`${host}/api/auth/cli-refresh`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({ auth0_refresh_token: auth0RefreshToken }),\n });\n\n // Read the body FIRST, whatever the status: the rotated token can arrive on\n // a 503, a 404 or a 500 just as readily as on a 200, and it must be captured\n // before any branch below throws.\n const body = await readOptionalJson(response);\n const rotated = str(body.auth0_refresh_token);\n\n if (rotated) {\n options.onRotatedToken?.(rotated);\n }\n\n throwIfNotConfigured(response, host, body);\n\n if (response.status === 401) {\n throw authRequiredError(\n `The stored session for ${host} is no longer valid.`,\n `Run \"ekanos login\" to sign in again. This is expected after the ` +\n `refresh token expires, after it is revoked in Auth0, or if two ` +\n `machines used the same credentials file.`,\n );\n }\n\n if (response.status === 503 && body.code === 'REFRESH_INCOMPLETE') {\n // NOT an auth failure. The credential was renewed — and, thanks to the\n // callback above, already saved. Auth0's /userinfo is simply not answering.\n throw networkError(\n `${host} renewed the session but could not verify the identity with Auth0.`,\n `Retry in a moment — your credentials are still valid and have been ` +\n `updated. You do NOT need to run \"ekanos login\" again.`,\n );\n }\n\n if (response.status === 404) {\n throw authRequiredError(\n `${host} has no Ekanos account for the signed-in identity.`,\n `Sign in to ${host} in a browser once to have the account created, ` +\n `then retry.`,\n );\n }\n\n if (!response.ok) {\n throw unexpectedStatus(host, '/api/auth/cli-refresh', response.status);\n }\n\n if (!rotated) {\n throw networkError(\n `${host} refreshed the session without returning a rotated refresh token.`,\n `Run \"ekanos login\" to start a fresh session, and report this — the ` +\n `deployment's Auth0 CLI application may not have rotation enabled.`,\n );\n }\n\n return { ...toSession(body, host), auth0RefreshToken: rotated };\n}\n\n/**\n * Prove the Ekanos JWT authenticates. Returns null on 401 so the caller can\n * decide whether to refresh and retry — an expired access token is an ordinary\n * event, not an error.\n */\nexport async function fetchIdentity(\n host: string,\n accessToken: string,\n): Promise<EkanosIdentity | null> {\n const response = await request(`${host}/api/auth/cli-whoami`, {\n method: 'GET',\n headers: {\n accept: 'application/json',\n authorization: `Bearer ${accessToken}`,\n },\n });\n\n // 401, or the 307 that an auth-gated Ekanos route answers with. Both mean\n // \"this token did not authenticate\".\n if (response.status === 401 || isRedirect(response.status)) {\n return null;\n }\n\n if (response.status === 403) {\n throw authRequiredError(\n `${host} requires multi-factor authentication for this account.`,\n `Complete MFA in the browser, then run \"ekanos login\" again.`,\n );\n }\n\n if (response.status === 404) {\n throw authRequiredError(\n `${host} has no account for the signed-in identity.`,\n `Sign in to ${host} in a browser once to have the account created, ` +\n `then run \"ekanos login\" again.`,\n );\n }\n\n if (!response.ok) {\n throw unexpectedStatus(host, '/api/auth/cli-whoami', response.status);\n }\n\n const body = await readJson(response, `${host}/api/auth/cli-whoami`);\n const user = (body.user ?? {}) as Record<string, unknown>;\n const id = str(user.id);\n\n if (!id) {\n throw networkError(\n `${host} returned an identity without a user id.`,\n `Confirm the deployment is running an Ekanos build that includes the ` +\n `/api/auth/cli-whoami route.`,\n );\n }\n\n return { id, email: str(user.email), name: str(user.name) };\n}\n\nfunction toSession(body: Record<string, unknown>, host: string): EkanosSession {\n const user = (body.user ?? {}) as Record<string, unknown>;\n\n const accessToken = str(body.access_token);\n const expiresAt = str(body.expires_at);\n const userId = str(user.id);\n\n if (!accessToken || !expiresAt || !userId) {\n throw networkError(\n `${host} returned an incomplete session.`,\n `Confirm the deployment is running an Ekanos build that includes the ` +\n `CLI auth routes, then retry.`,\n );\n }\n\n return { accessToken, expiresAt, userId, email: str(user.email) };\n}\n\nexport async function request(\n url: string,\n init: RequestInit,\n): Promise<Response> {\n try {\n return await fetch(url, {\n ...init,\n redirect: 'manual',\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n\n throw networkError(\n `Could not reach ${new URL(url).origin}: ${reason}`,\n `Check the host is correct and reachable from this machine ` +\n `(proxy, VPN, DNS), then retry.`,\n );\n }\n}\n\n/**\n * Best-effort body read for a response whose status may be an error. Returns\n * an empty object rather than throwing, because the caller needs to inspect\n * the body BEFORE deciding what the status means — and a 500 from a proxy may\n * carry no JSON at all.\n */\nasync function readOptionalJson(\n response: Response,\n): Promise<Record<string, unknown>> {\n try {\n const parsed: unknown = await response.json();\n\n return typeof parsed === 'object' && parsed !== null\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nasync function readJson(\n response: Response,\n what: string,\n): Promise<Record<string, unknown>> {\n let parsed: unknown;\n\n try {\n parsed = await response.json();\n } catch {\n throw networkError(\n `${what} did not return JSON.`,\n `Confirm the host is an Ekanos deployment and not a proxy or captive ` +\n `portal sitting in front of one.`,\n );\n }\n\n if (typeof parsed !== 'object' || parsed === null) {\n throw networkError(\n `${what} returned an unexpected payload.`,\n `Confirm the host is an Ekanos deployment, then retry.`,\n );\n }\n\n return parsed as Record<string, unknown>;\n}\n\n/**\n * 503 means the deployment is not provisioned for CLI login — an operator\n * action that has not happened, not a fault in the request.\n *\n * Every route that reads the Fusion CLI Auth0 config can answer this, so every\n * caller has to check for it. Falling through to `unexpectedStatus` would tell\n * a partner \"confirm the host is an Ekanos deployment\" when the host is a\n * perfectly good Ekanos deployment that is simply missing one env var — and\n * would exit 8 (network, retryable) instead of 9 (precondition, not).\n */\nfunction throwIfNotConfigured(\n response: Response,\n host: string,\n body?: Record<string, unknown>,\n): void {\n if (response.status !== 503) return;\n\n // 503 carries two meanings on these routes. Only CLI_NOT_CONFIGURED is a\n // precondition; REFRESH_INCOMPLETE is transient and handled by its caller.\n if (body && body.code !== 'CLI_NOT_CONFIGURED') return;\n\n throw preconditionError(\n `${host} does not have CLI login configured.`,\n `Ask the Ekanos operator to provision the \"Fusion CLI\" Auth0 ` +\n `application and set AUTH0_CLI_CLIENT_ID on that deployment.`,\n );\n}\n\nfunction unexpectedStatus(host: string, route: string, status: number) {\n return networkError(\n `${host}${route} responded ${status}.`,\n status >= 500\n ? `The Ekanos deployment returned a server error. Retry shortly; if it ` +\n `persists, report it with the status code.`\n : `Confirm the host is an Ekanos deployment running a build that ` +\n `includes ${route}.`,\n );\n}\n\nfunction assertOnDomain(endpoint: string, domain: string): void {\n let url: URL;\n\n try {\n url = new URL(endpoint);\n } catch {\n throw preconditionError(\n `The login configuration contains a malformed endpoint.`,\n `Report this to the operator of the Ekanos deployment.`,\n );\n }\n\n if (\n url.protocol !== 'https:' ||\n url.host.toLowerCase() !== domain.toLowerCase()\n ) {\n throw preconditionError(\n `The login configuration points at an endpoint outside its own Auth0 ` +\n `domain (${url.host}).`,\n `Do not continue. Report this to the operator of the Ekanos ` +\n `deployment — it may be misconfigured or compromised.`,\n );\n }\n}\n\nfunction isRedirect(status: number): boolean {\n return status >= 300 && status < 400;\n}\n\nfunction str(value: unknown): string | null {\n return typeof value === 'string' && value.length > 0 ? value : null;\n}\n"]}
1
+ {"version":3,"file":"ekanos-api.js","sourceRoot":"","sources":["../../src/auth/ekanos-api.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,cAAc,EACd,YAAY,EACZ,iBAAiB,GAClB,MAAM,WAAW,CAAC;AAEnB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsGG;AAEH,MAAM,kBAAkB,GAAG,KAAM,CAAC;AAuBlC,mDAAmD;AACnD,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,IAAY;IACnD,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,GAAG,IAAI,sBAAsB,EAAE;QAC5D,MAAM,EAAE,KAAK;QACb,OAAO,EAAE,EAAE,MAAM,EAAE,kBAAkB,EAAE;KACxC,CAAC,CAAC;IAEH,oBAAoB,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;IAErC,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACjB,MAAM,gBAAgB,CAAC,IAAI,EAAE,sBAAsB,EAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;IACxE,CAAC;IAED,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,QAAQ,EAAE,GAAG,IAAI,sBAAsB,CAAC,CAAC;IAErE,MAAM,MAAM,GAAG;QACb,WAAW,EAAE,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC;QACnC,QAAQ,EAAE,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC;QAC7B,KAAK,EAAE,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC;QACtB,2BAA2B,EAAE,GAAG,CAAC,IAAI,CAAC,6BAA6B,CAAC;QACpE,aAAa,EAAE,GAAG,CAAC,IAAI,CAAC,cAAc,CAAC;KACxC,C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CAAC,CAAC,sEAAsE;YACpE,2CAA2C;QAC/C,CAAC,CAAC,gEAAgE;YAC9D,YAAY,KAAK,GAAG,CAC3B,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,iBAAiB,CAAC,MAAc;IACvC,MAAM,QAAQ,GAAG,MAAM,CAAC,WAAW,EAAE,CAAC;IAEtC,IAAI,yCAAyC,CAAC,IAAI,CAAC,QAAQ,CAAC;QAAE,OAAO;IAErE,MAAM,iBAAiB,CACrB,qEAAqE,MAAM,IAAI,EAC/E,6DAA6D;QAC3D,sDAAsD,CACzD,CAAC;AACJ,CAAC;AAED,SAAS,cAAc,CAAC,QAAgB,EAAE,MAAc;IACtD,IAAI,GAAQ,CAAC;IAEb,IAAI,CAAC;QACH,GAAG,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC1B,CAAC;eAAO,CAAC;QACP,MAAM,iBAAiB,CACrB,wDAAwD,EACxD,uDAAuD,CACxD,CAAC;IACJ,CAAC;IAED,IACE,GAAG,CAAC,QAAQ,KAAK,QAAQ;QACzB,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC,WAAW,EAAE,EAC/C,CAAC;QACD,MAAM,iBAAiB,CACrB,sEAAsE;YACpE,WAAW,GAAG,CAAC,IAAI,IAAI,EACzB,6DAA6D;YAC3D,sDAAsD,CACzD,CAAC;IACJ,CAAC;AACH,CAAC;AAED,SAAS,UAAU,CAAC,MAAc;IAChC,OAAO,MAAM,IAAI,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC;AACvC,CAAC;AAED,SAAS,GAAG,CAAC,KAAc;IACzB,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AACtE,CAAC","sourcesContent":["import {\n authRequiredError,\n forbiddenError,\n networkError,\n preconditionError,\n} from '../errors';\n\n/**\n * The CLI's client for the five Ekanos auth routes.\n *\n * ---------------------------------------------------------------------------\n * WIRE CONTRACT — the seam between this package and the Ekanos web app.\n *\n * The server side is the host's `/api/auth/cli-<verb>` routes, and it ships on\n * a DIFFERENT BRANCH from this file. This block is the single place the shapes\n * are written down on the client side; if you change one side, change the\n * other and update this block. Nothing here imports host code — the two\n * halves are coupled only by HTTP, and the tests stub `fetch`, never the route.\n *\n * GET /api/auth/cli-config [no auth]\n * → 200 { auth0_domain, client_id, scope,\n * device_authorization_endpoint, token_endpoint } all strings\n * → 503 { error, code: \"CLI_NOT_CONFIGURED\" } deployment not provisioned\n *\n * POST /api/auth/cli-session [no auth]\n * ← { auth0_access_token: string }\n * → 200 { access_token, expires_at, user: { id, email } }\n * → 400 { error, code: \"INVALID_REQUEST\" } malformed / wrong shape\n * → 401 { error, code: \"SESSION_EXPIRED\" } Auth0 said no, OR no\n * Ekanos account for it\n * → 403 { error, code: \"NO_DEVELOPER_SEAT\" } no developer/admin seat\n * → 403 { error, code: \"EMAIL_UNVERIFIED\" } Auth0 email unverified\n * → 429 { error, code: \"RATE_LIMITED\" } + Retry-After header\n * → 503 { error, code: \"CLI_NOT_CONFIGURED\" } deployment not provisioned\n * → 500 { error, code: \"INTERNAL_ERROR\" }\n * `error` on a 403 is a sentence written for the person; show it.\n *\n * POST /api/auth/cli-refresh [no auth]\n * ← { auth0_refresh_token: string, access_token: string }\n * access_token is the PREVIOUS Ekanos JWT (expired is fine): it names\n * the server-side session this refresh continues. Required: without\n * it the server answers 401 SESSION_EXPIRED, reason\n * \"previous_token_missing\" (an older CLI is told to log in again).\n * → 200 { access_token, expires_at, user: { id, email },\n * auth0_refresh_token } ← ROTATED; the presented one is dead\n * → 400 { error, code: \"INVALID_REQUEST\" }\n * → 401 { error, code: \"SESSION_EXPIRED\", reason? }\n * expired, revoked, idle\n * or past the session's\n * maximum age; checked\n * BEFORE rotation, so no\n * rotated token comes back\n * → 403 { error, code: \"EMAIL_UNVERIFIED\",\n * auth0_refresh_token }\n * → 404 { error, code: \"ACCOUNT_NOT_FOUND\",\n * auth0_refresh_token } no Ekanos account\n * → 429 { error, code: \"RATE_LIMITED\" } + Retry-After header\n * → 502 { error, code: \"TOKEN_EXCHANGE_FAILED\" } Auth0 returned no\n * rotated token\n * → 503 { error, code: \"CLI_NOT_CONFIGURED\" } deployment not provisioned\n * → 503 { error, code: \"REFRESH_INCOMPLETE\",\n * auth0_refresh_token } rotated, but /userinfo\n * did not answer; RETRYABLE\n * → 500 { error, code: \"INTERNAL_ERROR\",\n * auth0_refresh_token? } present iff rotation\n * completed before the throw\n *\n * !! cli-refresh MAY RETURN `auth0_refresh_token` ON ERROR RESPONSES, and a\n * client MUST persist it before surfacing the error. Once the server's\n * exchange with Auth0 succeeds the presented token is dead and the value\n * in that body is the ONLY copy in existence; discarding it on a failure\n * path destroys the session permanently. Note 503 has TWO codes here —\n * branch on `code`, not on the status alone.\n *\n * All three routes above read the Fusion CLI Auth0 application config, so all\n * three can answer 503 CLI_NOT_CONFIGURED. cli-whoami and cli-logout cannot\n * — they read no Auth0 config, only an Ekanos token.\n *\n * POST /api/auth/cli-logout [no auth]\n * ← { access_token: string } the stored Ekanos JWT; expired is fine\n * → 200 { revoked: boolean } false = already revoked / no session row\n * → 400 { error, code: \"INVALID_REQUEST\" }\n * → 401 { error, code: \"AUTH_REQUIRED\" } not a valid Ekanos token\n * → 429 { error, code: \"RATE_LIMITED\" }\n * → 500 { error, code: \"INTERNAL_ERROR\" }\n *\n * GET /api/auth/cli-whoami [Authorization: Bearer <access_token>]\n * → 200 { user: { id, email, name } }\n * → 401 { error, code: \"AUTH_REQUIRED\" } token absent or invalid\n * → 403 { error, code: \"MFA_REQUIRED\" }\n * → 404 { error, code: \"ACCOUNT_NOT_FOUND\" }\n * → 3xx treated as 401, see below\n *\n * `access_token` is an Ekanos HS256 JWT. Every authenticated Ekanos route\n * accepts it as `Authorization: Bearer` — see `resolveRequestSupabaseJwt` in\n * `@kit/supabase`, which both `requireUser` and the RLS server client consume.\n * ---------------------------------------------------------------------------\n *\n * Two rules hold everywhere in this file:\n *\n * - `redirect: 'manual'`. Ekanos answers an unauthenticated page request with\n * a 307 to `/auth/sign-in`; Node's fetch follows redirects by default, so\n * without this a stale token would come back as a 200 full of HTML and be\n * read as success. A 3xx here is treated as \"not authenticated\", full stop.\n *\n * - No token is ever interpolated into an error message. The server's error\n * bodies are `{ error, code }` documents that do not echo credentials, and\n * the request bodies that DO carry credentials are never included in a\n * thrown message.\n */\n\nconst REQUEST_TIMEOUT_MS = 15_000;\n\nexport interface CliAuthConfig {\n auth0Domain: string;\n clientId: string;\n scope: string;\n deviceAuthorizationEndpoint: string;\n tokenEndpoint: string;\n}\n\nexport interface EkanosSession {\n accessToken: string;\n expiresAt: string;\n userId: string;\n email: string | null;\n}\n\nexport interface EkanosIdentity {\n id: string;\n email: string | null;\n name: string | null;\n}\n\n/** Fetch the device-flow parameters for a host. */\nexport async function fetchCliAuthConfig(host: string): Promise<CliAuthConfig> {\n const response = await request(`${host}/api/auth/cli-config`, {\n method: 'GET',\n headers: { accept: 'application/json' },\n });\n\n throwIfNotConfigured(response, host);\n\n if (!response.ok) {\n throw unexpectedStatus(host, '/api/auth/cli-config', response.status);\n }\n\n const body = await readJson(response, `${host}/api/auth/cli-config`);\n\n const config = {\n auth0Domain: str(body.auth0_domain),\n clientId: str(body.client_id),\n scope: str(body.scope),\n deviceAuthorizationEndpoint: str(body.device_authorization_endpoint),\n tokenEndpoint: str(body.token_endpoint),\n };\n\n if (Object.values(config).some((value) => value === null)) {\n throw preconditionError(\n `${host} returned an incomplete CLI login configuration.`,\n `Confirm the deployment is running an Ekanos build that includes the ` +\n `/api/auth/cli-config route.`,\n );\n }\n\n // The endpoints come from the server, so they are attacker-controlled if the\n // host is. Pin the declared domain to Auth0 itself, then pin the endpoints\n // to that domain, so a compromised or misconfigured Ekanos cannot redirect\n // the device flow — and the resulting credentials — to an arbitrary origin.\n // This does not prove the host is genuine: any Auth0 tenant passes, and a\n // hostile host can name Ekanos's own. That is `login`'s new-host question.\n assertAuth0Domain(config.auth0Domain!);\n assertOnDomain(config.deviceAuthorizationEndpoint!, config.auth0Domain!);\n assertOnDomain(config.tokenEndpoint!, config.auth0Domain!);\n\n return config as CliAuthConfig;\n}\n\n/** Exchange a verified Auth0 access token for an Ekanos JWT. */\nexport async function createEkanosSession(\n host: string,\n auth0AccessToken: string,\n): Promise<EkanosSession> {\n const response = await request(`${host}/api/auth/cli-session`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({ auth0_access_token: auth0AccessToken }),\n });\n\n throwIfNotConfigured(response, host);\n\n if (response.status === 401) {\n throw authRequiredError(\n `${host} rejected the Auth0 identity.`,\n `Run \"ekanos login\" again. If it keeps failing, confirm your account ` +\n `exists on ${host} — the browser login can succeed for an identity ` +\n `that has no Ekanos account.`,\n );\n }\n\n if (response.status === 403) {\n const body = await readOptionalJson(response);\n\n throw forbiddenError(\n str(body.error) ?? `${host} refused a CLI session for this account.`,\n body.code === 'EMAIL_UNVERIFIED'\n ? `Verify your email address, then run \"ekanos login\" again.`\n : `The Ekanos CLI needs a developer seat. Ask your administrator ` +\n `for one, then run \"ekanos login\" again.`,\n );\n }\n\n throwIfRateLimited(response, host);\n\n if (!response.ok) {\n throw unexpectedStatus(host, '/api/auth/cli-session', response.status);\n }\n\n return toSession(\n await readJson(response, `${host}/api/auth/cli-session`),\n host,\n );\n}\n\nexport interface RefreshedSession extends EkanosSession {\n /** The ROTATED refresh token. The presented one is already invalid. */\n auth0RefreshToken: string;\n}\n\nexport interface RefreshOptions {\n /**\n * Called the INSTANT a rotated refresh token is seen in the response — on\n * success and on failure alike, before anything is thrown.\n *\n * Persist-on-learn, not persist-on-success. Once the server's exchange with\n * Auth0 succeeds the presented token is dead and the replacement in that\n * body is the only copy in existence, so a client that only saves it on the\n * happy path destroys the partner's credential the first time /userinfo\n * blips. The callback runs before any throw so no error path can skip it.\n */\n onRotatedToken?: (rotated: string) => void;\n}\n\n/**\n * Re-mint an Ekanos JWT from the stored Auth0 refresh token. `accessToken` is\n * the previous Ekanos JWT (usually expired): the server reads the session id\n * from it to enforce that session's idle timeout, maximum age and revocation.\n */\nexport async function refreshEkanosSession(\n host: string,\n credentials: { auth0RefreshToken: string; accessToken: string },\n options: RefreshOptions = {},\n): Promise<RefreshedSession> {\n const response = await request(`${host}/api/auth/cli-refresh`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({\n auth0_refresh_token: credentials.auth0RefreshToken,\n access_token: credentials.accessToken,\n }),\n });\n\n // Read the body FIRST, whatever the status: the rotated token can arrive on\n // a 503, a 404 or a 500 just as readily as on a 200, and it must be captured\n // before any branch below throws.\n const body = await readOptionalJson(response);\n const rotated = str(body.auth0_refresh_token);\n\n if (rotated) {\n options.onRotatedToken?.(rotated);\n }\n\n throwIfNotConfigured(response, host, body);\n\n if (response.status === 401) {\n throw authRequiredError(\n `The stored session for ${host} is no longer valid` +\n (str(body.error) ? ` (${str(body.error)}).` : '.'),\n `Run \"ekanos login\" to sign in again. This is expected after the ` +\n `session's idle timeout or maximum age, after \"ekanos logout\", after ` +\n `the refresh token is revoked in Auth0, or if two machines used the ` +\n `same credentials file.`,\n );\n }\n\n if (response.status === 403) {\n throw forbiddenError(\n str(body.error) ?? `${host} refused to renew the session.`,\n `Verify your email address, then run \"ekanos login\" again.`,\n );\n }\n\n throwIfRateLimited(response, host);\n\n if (response.status === 503 && body.code === 'REFRESH_INCOMPLETE') {\n // NOT an auth failure. The credential was renewed — and, thanks to the\n // callback above, already saved. Auth0's /userinfo is simply not answering.\n throw networkError(\n `${host} renewed the session but could not verify the identity with Auth0.`,\n `Retry in a moment — your credentials are still valid and have been ` +\n `updated. You do NOT need to run \"ekanos login\" again.`,\n );\n }\n\n if (response.status === 404) {\n throw authRequiredError(\n `${host} has no Ekanos account for the signed-in identity.`,\n `Sign in to ${host} in a browser once to have the account created, ` +\n `then retry.`,\n );\n }\n\n if (!response.ok) {\n throw unexpectedStatus(host, '/api/auth/cli-refresh', response.status);\n }\n\n if (!rotated) {\n throw networkError(\n `${host} refreshed the session without returning a rotated refresh token.`,\n `Run \"ekanos login\" to start a fresh session, and report this — the ` +\n `deployment's Auth0 CLI application may not have rotation enabled.`,\n );\n }\n\n return { ...toSession(body, host), auth0RefreshToken: rotated };\n}\n\n/**\n * Prove the Ekanos JWT authenticates. Returns null on 401 so the caller can\n * decide whether to refresh and retry — an expired access token is an ordinary\n * event, not an error.\n */\nexport async function fetchIdentity(\n host: string,\n accessToken: string,\n): Promise<EkanosIdentity | null> {\n const response = await request(`${host}/api/auth/cli-whoami`, {\n method: 'GET',\n headers: {\n accept: 'application/json',\n authorization: `Bearer ${accessToken}`,\n },\n });\n\n // 401, or the 307 that an auth-gated Ekanos route answers with. Both mean\n // \"this token did not authenticate\".\n if (response.status === 401 || isRedirect(response.status)) {\n return null;\n }\n\n if (response.status === 403) {\n throw authRequiredError(\n `${host} requires multi-factor authentication for this account.`,\n `Complete MFA in the browser, then run \"ekanos login\" again.`,\n );\n }\n\n if (response.status === 404) {\n throw authRequiredError(\n `${host} has no account for the signed-in identity.`,\n `Sign in to ${host} in a browser once to have the account created, ` +\n `then run \"ekanos login\" again.`,\n );\n }\n\n if (!response.ok) {\n throw unexpectedStatus(host, '/api/auth/cli-whoami', response.status);\n }\n\n const body = await readJson(response, `${host}/api/auth/cli-whoami`);\n const user = (body.user ?? {}) as Record<string, unknown>;\n const id = str(user.id);\n\n if (!id) {\n throw networkError(\n `${host} returned an identity without a user id.`,\n `Confirm the deployment is running an Ekanos build that includes the ` +\n `/api/auth/cli-whoami route.`,\n );\n }\n\n return { id, email: str(user.email), name: str(user.name) };\n}\n\n/**\n * End the server-side session behind an Ekanos JWT (`ekanos logout`). Returns\n * whether the server answered — `true` also when the session was already\n * revoked, since either way it can no longer be refreshed. Never throws for\n * an HTTP status: logout must always reach the local delete.\n */\nexport async function revokeEkanosSession(\n host: string,\n accessToken: string,\n): Promise<boolean> {\n const response = await request(`${host}/api/auth/cli-logout`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/json' },\n body: JSON.stringify({ access_token: accessToken }),\n });\n\n return response.ok;\n}\n\nfunction toSession(body: Record<string, unknown>, host: string): EkanosSession {\n const user = (body.user ?? {}) as Record<string, unknown>;\n\n const accessToken = str(body.access_token);\n const expiresAt = str(body.expires_at);\n const userId = str(user.id);\n\n if (!accessToken || !expiresAt || !userId) {\n throw networkError(\n `${host} returned an incomplete session.`,\n `Confirm the deployment is running an Ekanos build that includes the ` +\n `CLI auth routes, then retry.`,\n );\n }\n\n return { accessToken, expiresAt, userId, email: str(user.email) };\n}\n\nexport async function request(\n url: string,\n init: RequestInit,\n): Promise<Response> {\n try {\n return await fetch(url, {\n ...init,\n redirect: 'manual',\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n\n throw networkError(\n `Could not reach ${new URL(url).origin}: ${reason}`,\n `Check the host is correct and reachable from this machine ` +\n `(proxy, VPN, DNS), then retry.`,\n );\n }\n}\n\n/**\n * Best-effort body read for a response whose status may be an error. Returns\n * an empty object rather than throwing, because the caller needs to inspect\n * the body BEFORE deciding what the status means — and a 500 from a proxy may\n * carry no JSON at all.\n */\nasync function readOptionalJson(\n response: Response,\n): Promise<Record<string, unknown>> {\n try {\n const parsed: unknown = await response.json();\n\n return typeof parsed === 'object' && parsed !== null\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nasync function readJson(\n response: Response,\n what: string,\n): Promise<Record<string, unknown>> {\n let parsed: unknown;\n\n try {\n parsed = await response.json();\n } catch {\n throw networkError(\n `${what} did not return JSON.`,\n `Confirm the host is an Ekanos deployment and not a proxy or captive ` +\n `portal sitting in front of one.`,\n );\n }\n\n if (typeof parsed !== 'object' || parsed === null) {\n throw networkError(\n `${what} returned an unexpected payload.`,\n `Confirm the host is an Ekanos deployment, then retry.`,\n );\n }\n\n return parsed as Record<string, unknown>;\n}\n\n/**\n * 503 means the deployment is not provisioned for CLI login — an operator\n * action that has not happened, not a fault in the request.\n *\n * Every route that reads the Fusion CLI Auth0 config can answer this, so every\n * caller has to check for it. Falling through to `unexpectedStatus` would tell\n * a partner \"confirm the host is an Ekanos deployment\" when the host is a\n * perfectly good Ekanos deployment that is simply missing one env var — and\n * would exit 8 (network, retryable) instead of 9 (precondition, not).\n */\nfunction throwIfNotConfigured(\n response: Response,\n host: string,\n body?: Record<string, unknown>,\n): void {\n if (response.status !== 503) return;\n\n // 503 carries two meanings on these routes. Only CLI_NOT_CONFIGURED is a\n // precondition; REFRESH_INCOMPLETE is transient and handled by its caller.\n if (body && body.code !== 'CLI_NOT_CONFIGURED') return;\n\n throw preconditionError(\n `${host} does not have CLI login configured.`,\n `Ask the Ekanos operator to provision the \"Fusion CLI\" Auth0 ` +\n `application and set AUTH0_CLI_CLIENT_ID on that deployment.`,\n );\n}\n\n/** 429: the deployment is throttling this machine's address. Retryable. */\nfunction throwIfRateLimited(response: Response, host: string): void {\n if (response.status !== 429) return;\n\n const retryAfter = Number.parseInt(\n response.headers.get('retry-after') ?? '',\n 10,\n );\n\n throw networkError(\n `${host} is rate-limiting sign-in requests from this address.`,\n Number.isFinite(retryAfter) && retryAfter > 0\n ? `Retry in ${retryAfter} seconds.`\n : `Retry in a few minutes.`,\n );\n}\n\nfunction unexpectedStatus(host: string, route: string, status: number) {\n return networkError(\n `${host}${route} responded ${status}.`,\n status >= 500\n ? `The Ekanos deployment returned a server error. Retry shortly; if it ` +\n `persists, report it with the status code.`\n : `Confirm the host is an Ekanos deployment running a build that ` +\n `includes ${route}.`,\n );\n}\n\n/**\n * Every Ekanos tenant signs in on an `*.auth0.com` domain today\n * (`fusion-{dev,stage,prod}.us.auth0.com`). If one moves to an Auth0 custom\n * domain, add that domain here.\n */\nfunction assertAuth0Domain(domain: string): void {\n const hostname = domain.toLowerCase();\n\n if (/^[a-z0-9-]+(\\.[a-z0-9-]+)*\\.auth0\\.com$/.test(hostname)) return;\n\n throw preconditionError(\n `The login configuration names a sign-in domain that is not Auth0 (${domain}).`,\n `Do not continue. Report this to the operator of the Ekanos ` +\n `deployment — it may be misconfigured or compromised.`,\n );\n}\n\nfunction assertOnDomain(endpoint: string, domain: string): void {\n let url: URL;\n\n try {\n url = new URL(endpoint);\n } catch {\n throw preconditionError(\n `The login configuration contains a malformed endpoint.`,\n `Report this to the operator of the Ekanos deployment.`,\n );\n }\n\n if (\n url.protocol !== 'https:' ||\n url.host.toLowerCase() !== domain.toLowerCase()\n ) {\n throw preconditionError(\n `The login configuration points at an endpoint outside its own Auth0 ` +\n `domain (${url.host}).`,\n `Do not continue. Report this to the operator of the Ekanos ` +\n `deployment — it may be misconfigured or compromised.`,\n );\n }\n}\n\nfunction isRedirect(status: number): boolean {\n return status >= 300 && status < 400;\n}\n\nfunction str(value: unknown): string | null {\n return typeof value === 'string' && value.length > 0 ? value : null;\n}\n"]}
@@ -0,0 +1,46 @@
1
+ import type { CredentialStore } from './credential-store.js';
2
+ /**
3
+ * Which hosts the CLI may send a login, or a token, to without asking.
4
+ *
5
+ * A host the CLI resolved is not a host the developer chose: `ekanos.json`
6
+ * is a committed file, so its `host` can be set by anyone who can land a
7
+ * change in the repo. Three rules follow, and this file holds all three:
8
+ *
9
+ * - a hint never tells anyone to log in to a host that is neither stored
10
+ * nor a known Ekanos host (`loginHint`);
11
+ * - credentials never cross plaintext HTTP to a remote host
12
+ * (`assertSecureTransport`);
13
+ * - `ekanos login` to a host that is not known asks first (`isKnownHost`,
14
+ * used by `commands/login.ts`).
15
+ *
16
+ * "Known" is a stored host, a loopback host, or one under Vastly's own root
17
+ * domains. A Source can serve Ekanos on its own custom domain
18
+ * (`source_configs.custom_domains`), which no static list can name, so a
19
+ * custom domain is known only once you have logged in to it.
20
+ */
21
+ /** Vastly's own root domains; every Source slug is a subdomain of one. */
22
+ export declare const EKANOS_ROOT_DOMAINS: readonly ['vastlyfusion.site', 'vastlyfusion-stage.site', 'vastlyfusion-dev.site'];
23
+ /** Where a resolved host came from, in `resolveHost`'s order. */
24
+ export type HostOrigin = 'flag' | 'env' | 'project' | 'stored';
25
+ export declare function isLoopbackHost(host: string): boolean;
26
+ /** An https host under one of `EKANOS_ROOT_DOMAINS`, or a loopback host. */
27
+ export declare function isEkanosHost(host: string): boolean;
28
+ export declare function isKnownHost(store: CredentialStore, host: string): boolean;
29
+ export declare function isPlaintextRemoteHost(host: string): boolean;
30
+ /**
31
+ * Refuse to send credentials to a remote host over plaintext HTTP. Loopback
32
+ * stays allowed, because local development needs `http://localhost:3000`.
33
+ */
34
+ export declare function assertSecureTransport(host: string): void;
35
+ /**
36
+ * The hint for "log in to this host", the one place it is written.
37
+ *
38
+ * To a known host it names the command. To any other host it does not: a
39
+ * coding agent follows a hint, and following this one would sign the
40
+ * developer in to whatever a committed file named.
41
+ */
42
+ export declare function loginHint(env: {
43
+ host: string;
44
+ store: CredentialStore;
45
+ hostOrigin: HostOrigin;
46
+ }, then?: string): string;
@@ -0,0 +1,79 @@
1
+ import { preconditionError } from '../errors.js';
2
+ /**
3
+ * Which hosts the CLI may send a login, or a token, to without asking.
4
+ *
5
+ * A host the CLI resolved is not a host the developer chose: `ekanos.json`
6
+ * is a committed file, so its `host` can be set by anyone who can land a
7
+ * change in the repo. Three rules follow, and this file holds all three:
8
+ *
9
+ * - a hint never tells anyone to log in to a host that is neither stored
10
+ * nor a known Ekanos host (`loginHint`);
11
+ * - credentials never cross plaintext HTTP to a remote host
12
+ * (`assertSecureTransport`);
13
+ * - `ekanos login` to a host that is not known asks first (`isKnownHost`,
14
+ * used by `commands/login.ts`).
15
+ *
16
+ * "Known" is a stored host, a loopback host, or one under Vastly's own root
17
+ * domains. A Source can serve Ekanos on its own custom domain
18
+ * (`source_configs.custom_domains`), which no static list can name, so a
19
+ * custom domain is known only once you have logged in to it.
20
+ */
21
+ /** Vastly's own root domains; every Source slug is a subdomain of one. */
22
+ export const EKANOS_ROOT_DOMAINS = [
23
+ 'vastlyfusion.site',
24
+ 'vastlyfusion-stage.site',
25
+ 'vastlyfusion-dev.site',
26
+ ];
27
+ const ORIGIN_LABEL = {
28
+ flag: '--host',
29
+ env: 'EKANOS_HOST',
30
+ project: 'the "host" field in ekanos.json',
31
+ stored: 'your stored login',
32
+ };
33
+ export function isLoopbackHost(host) {
34
+ const { hostname } = new URL(host);
35
+ return (['localhost', '127.0.0.1', '[::1]', '0.0.0.0'].includes(hostname) ||
36
+ hostname.endsWith('.localhost'));
37
+ }
38
+ /** An https host under one of `EKANOS_ROOT_DOMAINS`, or a loopback host. */
39
+ export function isEkanosHost(host) {
40
+ if (isLoopbackHost(host))
41
+ return true;
42
+ const url = new URL(host);
43
+ return (url.protocol === 'https:' &&
44
+ EKANOS_ROOT_DOMAINS.some((root) => url.hostname === root || url.hostname.endsWith(`.${root}`)));
45
+ }
46
+ export function isKnownHost(store, host) {
47
+ return isEkanosHost(host) || store.hosts().includes(host);
48
+ }
49
+ export function isPlaintextRemoteHost(host) {
50
+ return new URL(host).protocol === 'http:' && !isLoopbackHost(host);
51
+ }
52
+ /**
53
+ * Refuse to send credentials to a remote host over plaintext HTTP. Loopback
54
+ * stays allowed, because local development needs `http://localhost:3000`.
55
+ */
56
+ export function assertSecureTransport(host) {
57
+ if (!isPlaintextRemoteHost(host))
58
+ return;
59
+ throw preconditionError(`${host} is plaintext HTTP, and your credentials would cross the network unencrypted.`, `Use the https:// URL of the host. Plain http:// is allowed only for ` +
60
+ `localhost, 127.0.0.1, [::1] and *.localhost.`);
61
+ }
62
+ /**
63
+ * The hint for "log in to this host", the one place it is written.
64
+ *
65
+ * To a known host it names the command. To any other host it does not: a
66
+ * coding agent follows a hint, and following this one would sign the
67
+ * developer in to whatever a committed file named.
68
+ */
69
+ export function loginHint(env, then = 'and retry.') {
70
+ const { host } = env;
71
+ if (isKnownHost(env.store, host)) {
72
+ return `Run "ekanos login --host ${host}" ${then}`;
73
+ }
74
+ return (`${host} came from ${ORIGIN_LABEL[env.hostOrigin]}, and you have never ` +
75
+ `logged in to it. Check it is the Ekanos deployment you meant to use ` +
76
+ `before you run "ekanos login --host ${host}" yourself. An agent should ` +
77
+ `ask the person it works for rather than log in to it.`);
78
+ }
79
+ //# sourceMappingURL=host-trust.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host-trust.js","sourceRoot":"","sources":["../../src/auth/host-trust.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAG9C;;;;;;;;;;;;;;;;;;GAkBG;AAEH,0EAA0E;AAC1E,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC,mBAAmB;IACnB,yBAAyB;IACzB,uBAAuB;CACf,CAAC;AAKX,MAAM,YAAY,GAA+B;IAC/C,IAAI,EAAE,QAAQ;IACd,GAAG,EAAE,aAAa;IAClB,OAAO,EAAE,iCAAiC;IAC1C,MAAM,EAAE,mBAAmB;CAC5B,CAAC;AAEF,MAAM,UAAU,cAAc,CAAC,IAAY;IACzC,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC;IAEnC,OAAO,CACL,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC;QACjE,QAAQ,CAAC,QAAQ,CAAC,YAAY,CAAC,CAChC,CAAC;AACJ,CAAC;AAED,4EAA4E;AAC5E,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,IAAI,cAAc,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IAEtC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC;IAE1B,OAAO,CACL,GAAG,CAAC,QAAQ,KAAK,QAAQ;QACzB,mBAAmB,CAAC,IAAI,CACtB,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,CAAC,QAAQ,KAAK,IAAI,IAAI,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,IAAI,EAAE,CAAC,CACrE,CACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,KAAsB,EAAE,IAAY;IAC9D,OAAO,YAAY,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AAC5D,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,IAAY;IAChD,OAAO,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC,QAAQ,KAAK,OAAO,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;AACrE,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,IAAY;IAChD,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC;QAAE,OAAO;IAEzC,MAAM,iBAAiB,CACrB,GAAG,IAAI,+EAA+E,EACtF,sEAAsE;QACpE,8CAA8C,CACjD,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CACvB,GAAqE,EACrE,IAAI,GAAG,YAAY;IAEnB,MAAM,EAAE,IAAI,EAAE,GAAG,GAAG,CAAC;IAErB,IAAI,WAAW,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,CAAC;QACjC,OAAO,4BAA4B,IAAI,KAAK,IAAI,EAAE,CAAC;IACrD,CAAC;IAED,OAAO,CACL,GAAG,IAAI,cAAc,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,uBAAuB;QACxE,sEAAsE;QACtE,uCAAuC,IAAI,8BAA8B;QACzE,uDAAuD,CACxD,CAAC;AACJ,CAAC","sourcesContent":["import { preconditionError } from '../errors';\nimport type { CredentialStore } from './credential-store';\n\n/**\n * Which hosts the CLI may send a login, or a token, to without asking.\n *\n * A host the CLI resolved is not a host the developer chose: `ekanos.json`\n * is a committed file, so its `host` can be set by anyone who can land a\n * change in the repo. Three rules follow, and this file holds all three:\n *\n * - a hint never tells anyone to log in to a host that is neither stored\n * nor a known Ekanos host (`loginHint`);\n * - credentials never cross plaintext HTTP to a remote host\n * (`assertSecureTransport`);\n * - `ekanos login` to a host that is not known asks first (`isKnownHost`,\n * used by `commands/login.ts`).\n *\n * \"Known\" is a stored host, a loopback host, or one under Vastly's own root\n * domains. A Source can serve Ekanos on its own custom domain\n * (`source_configs.custom_domains`), which no static list can name, so a\n * custom domain is known only once you have logged in to it.\n */\n\n/** Vastly's own root domains; every Source slug is a subdomain of one. */\nexport const EKANOS_ROOT_DOMAINS = [\n 'vastlyfusion.site',\n 'vastlyfusion-stage.site',\n 'vastlyfusion-dev.site',\n] as const;\n\n/** Where a resolved host came from, in `resolveHost`'s order. */\nexport type HostOrigin = 'flag' | 'env' | 'project' | 'stored';\n\nconst ORIGIN_LABEL: Record<HostOrigin, string> = {\n flag: '--host',\n env: 'EKANOS_HOST',\n project: 'the \"host\" field in ekanos.json',\n stored: 'your stored login',\n};\n\nexport function isLoopbackHost(host: string): boolean {\n const { hostname } = new URL(host);\n\n return (\n ['localhost', '127.0.0.1', '[::1]', '0.0.0.0'].includes(hostname) ||\n hostname.endsWith('.localhost')\n );\n}\n\n/** An https host under one of `EKANOS_ROOT_DOMAINS`, or a loopback host. */\nexport function isEkanosHost(host: string): boolean {\n if (isLoopbackHost(host)) return true;\n\n const url = new URL(host);\n\n return (\n url.protocol === 'https:' &&\n EKANOS_ROOT_DOMAINS.some(\n (root) => url.hostname === root || url.hostname.endsWith(`.${root}`),\n )\n );\n}\n\nexport function isKnownHost(store: CredentialStore, host: string): boolean {\n return isEkanosHost(host) || store.hosts().includes(host);\n}\n\nexport function isPlaintextRemoteHost(host: string): boolean {\n return new URL(host).protocol === 'http:' && !isLoopbackHost(host);\n}\n\n/**\n * Refuse to send credentials to a remote host over plaintext HTTP. Loopback\n * stays allowed, because local development needs `http://localhost:3000`.\n */\nexport function assertSecureTransport(host: string): void {\n if (!isPlaintextRemoteHost(host)) return;\n\n throw preconditionError(\n `${host} is plaintext HTTP, and your credentials would cross the network unencrypted.`,\n `Use the https:// URL of the host. Plain http:// is allowed only for ` +\n `localhost, 127.0.0.1, [::1] and *.localhost.`,\n );\n}\n\n/**\n * The hint for \"log in to this host\", the one place it is written.\n *\n * To a known host it names the command. To any other host it does not: a\n * coding agent follows a hint, and following this one would sign the\n * developer in to whatever a committed file named.\n */\nexport function loginHint(\n env: { host: string; store: CredentialStore; hostOrigin: HostOrigin },\n then = 'and retry.',\n): string {\n const { host } = env;\n\n if (isKnownHost(env.store, host)) {\n return `Run \"ekanos login --host ${host}\" ${then}`;\n }\n\n return (\n `${host} came from ${ORIGIN_LABEL[env.hostOrigin]}, and you have never ` +\n `logged in to it. Check it is the Ekanos deployment you meant to use ` +\n `before you run \"ekanos login --host ${host}\" yourself. An agent should ` +\n `ask the person it works for rather than log in to it.`\n );\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import type { CliContext } from '../context.js';
2
2
  import { CredentialStore, type StoredSession } from './credential-store.js';
3
3
  import { type EkanosIdentity } from './ekanos-api.js';
4
+ import { type HostOrigin } from './host-trust.js';
4
5
  /**
5
6
  * Session plumbing shared by `login`, `logout` and `whoami`: where the Ekanos
6
7
  * host comes from, where credentials live, and how a stale access token is
@@ -9,6 +10,8 @@ import { type EkanosIdentity } from './ekanos-api.js';
9
10
  export interface AuthEnvironment {
10
11
  store: CredentialStore;
11
12
  host: string;
13
+ /** Where `host` came from — what `loginHint` names for an unknown host. */
14
+ hostOrigin: HostOrigin;
12
15
  }
13
16
  /**
14
17
  * Resolve the Ekanos host, in this order:
@@ -36,11 +39,17 @@ export declare function resolveHost(ctx: CliContext, flag: string | undefined, e
36
39
  export interface ResolveAuthOptions {
37
40
  /** Directory whose ekanos.json may carry a `host` field. */
38
41
  projectDir?: string;
42
+ /**
43
+ * Let a remote `http://` host through with a warning instead of refusing
44
+ * it. Only `logout` sets this: deleting local credentials must still work
45
+ * for a host stored before plaintext remote hosts were refused.
46
+ */
47
+ allowPlaintext?: boolean;
39
48
  }
40
49
  export declare function resolveAuthEnvironment(ctx: CliContext, hostFlag: string | undefined, env: Record<string, string | undefined>, options?: ResolveAuthOptions): AuthEnvironment;
41
50
  /** A store with no host attached — for `logout --all`. */
42
51
  export declare function newStore(ctx: CliContext, env: Record<string, string | undefined>): CredentialStore;
43
- export declare function requireSession(store: CredentialStore, host: string): StoredSession;
52
+ export declare function requireSession(env: AuthEnvironment): StoredSession;
44
53
  /**
45
54
  * Resolve the caller's identity, refreshing the access token once if the
46
55
  * stored one no longer authenticates.
@@ -4,6 +4,7 @@ import { authRequiredError, usageError } from '../errors.js';
4
4
  import { shortHost } from '../ui.js';
5
5
  import { CredentialStore, normalizeHost, resolveEkanosHome, } from './credential-store.js';
6
6
  import { fetchIdentity, refreshEkanosSession, } from './ekanos-api.js';
7
+ import { assertSecureTransport, isPlaintextRemoteHost, loginHint, } from './host-trust.js';
7
8
  /**
8
9
  * Resolve the Ekanos host, in this order:
9
10
  *
@@ -22,11 +23,17 @@ import { fetchIdentity, refreshEkanosSession, } from './ekanos-api.js';
22
23
  * ambiguity, so it stays a usage error that LISTS them rather than a guess.
23
24
  */
24
25
  export function resolveHost(ctx, flag, env, options = {}) {
26
+ return resolveHostWithOrigin(ctx, flag, env, options).host;
27
+ }
28
+ function resolveHostWithOrigin(ctx, flag, env, options) {
25
29
  var _a;
26
30
  var _b;
27
31
  const raw = flag !== null && flag !== void 0 ? flag : env.EKANOS_HOST;
28
32
  if (raw && raw.trim().length > 0) {
29
- return normalizeHost(raw.trim());
33
+ return {
34
+ host: normalizeHost(raw.trim()),
35
+ origin: flag === undefined ? 'env' : 'flag',
36
+ };
30
37
  }
31
38
  if (options.projectDir) {
32
39
  const declared = readProjectHost(options.projectDir);
@@ -45,7 +52,7 @@ export function resolveHost(ctx, flag, env, options = {}) {
45
52
  `Pass --host to override for one command.`
46
53
  : ctx.ui.dim(`Using ${shortHost(host)} from ekanos.json. ` +
47
54
  `Pass --host to override for one command.`));
48
- return host;
55
+ return { host, origin: 'project' };
49
56
  }
50
57
  }
51
58
  const stored = (_b = (_a = options.store) === null || _a === void 0 ? void 0 : _a.hosts()) !== null && _b !== void 0 ? _b : [];
@@ -58,7 +65,7 @@ export function resolveHost(ctx, flag, env, options = {}) {
58
65
  ctx.log(`ekanos: using ${host} — the only host you are logged in to. ` +
59
66
  `Pass --host to target a different one.`);
60
67
  }
61
- return host;
68
+ return { host, origin: 'stored' };
62
69
  }
63
70
  throw usageError('No Ekanos host given.', stored.length > 1
64
71
  ? `You are logged in to ${stored.length} hosts (${stored.join(', ')}) — ` +
@@ -100,12 +107,18 @@ function readProjectHost(projectDir) {
100
107
  }
101
108
  export function resolveAuthEnvironment(ctx, hostFlag, env, options = {}) {
102
109
  const store = newStore(ctx, env);
103
- const host = resolveHost(ctx, hostFlag, env, {
110
+ const { host, origin } = resolveHostWithOrigin(ctx, hostFlag, env, {
104
111
  projectDir: options.projectDir,
105
112
  store,
106
113
  });
107
- warnOnPlaintextHost(ctx, host);
108
- return { host, store };
114
+ if (!options.allowPlaintext) {
115
+ assertSecureTransport(host);
116
+ }
117
+ else if (isPlaintextRemoteHost(host)) {
118
+ ctx.warn(`ekanos: ${host} is plaintext HTTP. Your credentials will cross the ` +
119
+ `network unencrypted. Use https:// unless this is a local host.`);
120
+ }
121
+ return { host, store, hostOrigin: origin };
109
122
  }
110
123
  /** A store with no host attached — for `logout --all`. */
111
124
  export function newStore(ctx, env) {
@@ -115,27 +128,10 @@ export function newStore(ctx, env) {
115
128
  warn: (message) => ctx.warn(message),
116
129
  });
117
130
  }
118
- /**
119
- * `http://` is allowed because local development needs it, but sending a
120
- * bearer token to a plaintext REMOTE host puts it on the wire in the clear.
121
- * Warn rather than refuse: refusing would break `--host http://localhost:3000`
122
- * for anyone whose loopback resolves to something other than the names below.
123
- */
124
- function warnOnPlaintextHost(ctx, host) {
125
- const url = new URL(host);
126
- if (url.protocol !== 'http:')
127
- return;
128
- const loopback = ['localhost', '127.0.0.1', '[::1]', '0.0.0.0'];
129
- if (loopback.includes(url.hostname) || url.hostname.endsWith('.localhost')) {
130
- return;
131
- }
132
- ctx.warn(`ekanos: ${host} is plaintext HTTP. Your credentials will cross the ` +
133
- `network unencrypted. Use https:// unless this is a local host.`);
134
- }
135
- export function requireSession(store, host) {
136
- const session = store.read(host);
131
+ export function requireSession(env) {
132
+ const session = env.store.read(env.host);
137
133
  if (!session) {
138
- throw authRequiredError(`Not logged in to ${host}.`, `Run "ekanos login --host ${host}".`);
134
+ throw authRequiredError(`Not logged in to ${env.host}.`, loginHint(env, 'to sign in.'));
139
135
  }
140
136
  return session;
141
137
  }
@@ -157,7 +153,8 @@ export async function resolveIdentity(env, session) {
157
153
  const refreshed = await refreshStoredSession(env, session);
158
154
  const retried = await fetchIdentity(env.host, refreshed.accessToken);
159
155
  if (!retried) {
160
- throw authRequiredError(`The session for ${env.host} could not be renewed.`, `Run "ekanos logout --host ${env.host}" then "ekanos login --host ${env.host}".`);
156
+ throw authRequiredError(`The session for ${env.host} could not be renewed.`, `Run "ekanos logout --host ${env.host}" first. ` +
157
+ loginHint(env, 'to sign in again.'));
161
158
  }
162
159
  return { identity: retried, session: refreshed };
163
160
  }
@@ -182,7 +179,10 @@ export async function refreshStoredSession(env, session) {
182
179
  const persistRotated = (rotated) => {
183
180
  env.store.write(env.host, Object.assign(Object.assign({}, session), { auth0RefreshToken: rotated, updatedAt: new Date().toISOString() }));
184
181
  };
185
- const refreshed = await refreshEkanosSession(env.host, session.auth0RefreshToken, { onRotatedToken: persistRotated });
182
+ const refreshed = await refreshEkanosSession(env.host, {
183
+ auth0RefreshToken: session.auth0RefreshToken,
184
+ accessToken: session.accessToken,
185
+ }, { onRotatedToken: persistRotated });
186
186
  const next = {
187
187
  auth0RefreshToken: refreshed.auth0RefreshToken,
188
188
  accessToken: refreshed.accessToken,
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","sourceRoot":"","sources":["../../src/auth/session.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAA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,KAAK,UAAU,oBAAoB,CACxC,GAAoB,EACpB,OAAsB;IAEtB,MAAM,cAAc,GAAG,CAAC,OAAe,EAAE,EAAE;QACzC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,kCACnB,OAAO,KACV,iBAAiB,EAAE,OAAO,EAC1B,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,IACnC,CAAC;IACL,CAAC,CAAC;IAEF,MAAM,SAAS,GAAG,MAAM,oBAAoB,CAC1C,GAAG,CAAC,IAAI,EACR,OAAO,CAAC,iBAAiB,EACzB,EAAE,cAAc,EAAE,cAAc,EAAE,CACnC,CAAC;IAEF,MAAM,IAAI,GAAkB;QAC1B,iBAAiB,EAAE,SAAS,CAAC,iBAAiB;QAC9C,WAAW,EAAE,SAAS,CAAC,WAAW;QAClC,SAAS,EAAE,SAAS,CAAC,SAAS;QAC9B,MAAM,EAAE,SAAS,CAAC,MAAM;QACxB,KAAK,EAAE,SAAS,CAAC,KAAK;QACtB,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;KACpC,CAAC;IAEF,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAEhC,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport type { CliContext } from '../context';\nimport { authRequiredError, usageError } from '../errors';\nimport { shortHost } from '../ui';\nimport {\n CredentialStore,\n type StoredSession,\n normalizeHost,\n resolveEkanosHome,\n} from './credential-store';\nimport {\n type EkanosIdentity,\n fetchIdentity,\n refreshEkanosSession,\n} from './ekanos-api';\n\n/**\n * Session plumbing shared by `login`, `logout` and `whoami`: where the Ekanos\n * host comes from, where credentials live, and how a stale access token is\n * silently replaced.\n */\n\nexport interface AuthEnvironment {\n store: CredentialStore;\n host: string;\n}\n\n/**\n * Resolve the Ekanos host, in this order:\n *\n * 1. the `--host` flag\n * 2. the `EKANOS_HOST` environment variable\n * 3. the `host` field of the project's `ekanos.json` (written by the first\n * successful `ekanos publish`, or by hand)\n * 4. the credential store, when it holds EXACTLY one host — a partner logged\n * in to a single deployment should not have to repeat its URL on every\n * verb, and one stored host is unambiguous\n *\n * Deliberately no default beyond those. A baked-in default would be wrong for\n * every partner running against their own sandbox, and — worse — a CLI that\n * silently picks a host is a CLI that can send a developer's credentials\n * somewhere they did not intend. Two or more stored hosts is exactly that\n * ambiguity, so it stays a usage error that LISTS them rather than a guess.\n */\nexport function resolveHost(\n ctx: CliContext,\n flag: string | undefined,\n env: Record<string, string | undefined>,\n options: {\n /** Directory whose ekanos.json may carry a `host` field. */\n projectDir?: string;\n /** The credential store, for the sole-stored-host fallback. */\n store?: CredentialStore;\n } = {},\n): string {\n const raw = flag ?? env.EKANOS_HOST;\n\n if (raw && raw.trim().length > 0) {\n return normalizeHost(raw.trim());\n }\n\n if (options.projectDir) {\n const declared = readProjectHost(options.projectDir);\n\n if (declared) {\n // normalizeHost throws a precondition error for a malformed value —\n // an EXPLICIT host in ekanos.json that is wrong deserves an error\n // naming it, never a silent fall-through to a different host.\n const host = normalizeHost(declared);\n\n // Announce the choice, like the sole-stored-host branch below. This\n // source deserves it MOST: ekanos.json is a committed file, so its\n // host can change under a developer via an ordinary merge or an\n // agent-applied patch — and this is where login sends the OAuth flow\n // and publish sends the bearer token and archive.\n ctx.log(\n ctx.jsonMode\n ? `ekanos: using ${host} — the host saved in ekanos.json. ` +\n `Pass --host to override for one command.`\n : ctx.ui.dim(\n `Using ${shortHost(host)} from ekanos.json. ` +\n `Pass --host to override for one command.`,\n ),\n );\n\n return host;\n }\n }\n\n const stored = options.store?.hosts() ?? [];\n\n if (stored.length === 1) {\n const host = stored[0]!;\n\n // A person at a terminal sees this host in the result block of every\n // verb, and it is the only one they are signed in to, so naming it\n // again is noise. JSON callers get no result block, so they keep it.\n if (ctx.jsonMode) {\n ctx.log(\n `ekanos: using ${host} — the only host you are logged in to. ` +\n `Pass --host to target a different one.`,\n );\n }\n\n return host;\n }\n\n throw usageError(\n 'No Ekanos host given.',\n stored.length > 1\n ? `You are logged in to ${stored.length} hosts (${stored.join(', ')}) — ` +\n `pass \"--host <url>\" to choose one, or set EKANOS_HOST.`\n : 'Pass \"--host https://<your-ekanos-host>\" or set EKANOS_HOST. ' +\n '\"ekanos login --host <url>\" stores the host, so later commands ' +\n 'can omit it.',\n );\n}\n\n/**\n * Best-effort read of the `host` field from a directory's ekanos.json.\n *\n * Lenient on purpose: host resolution runs for verbs like `login` that are\n * routinely run OUTSIDE a project, so a missing, unparseable, or host-less\n * ekanos.json is simply \"no answer here\", never an error — the verbs that\n * require a valid project (`publish`, `validate`) load it strictly themselves.\n */\nfunction readProjectHost(projectDir: string): string | null {\n const configPath = path.join(projectDir, 'ekanos.json');\n\n let raw: string;\n try {\n raw = fs.readFileSync(configPath, 'utf8');\n } catch {\n return null;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n\n const host =\n typeof parsed === 'object' && parsed !== null\n ? (parsed as { host?: unknown }).host\n : undefined;\n\n return typeof host === 'string' && host.trim().length > 0\n ? host.trim()\n : null;\n}\n\nexport interface ResolveAuthOptions {\n /** Directory whose ekanos.json may carry a `host` field. */\n projectDir?: string;\n}\n\nexport function resolveAuthEnvironment(\n ctx: CliContext,\n hostFlag: string | undefined,\n env: Record<string, string | undefined>,\n options: ResolveAuthOptions = {},\n): AuthEnvironment {\n const store = newStore(ctx, env);\n const host = resolveHost(ctx, hostFlag, env, {\n projectDir: options.projectDir,\n store,\n });\n\n warnOnPlaintextHost(ctx, host);\n\n return { host, store };\n}\n\n/** A store with no host attached — for `logout --all`. */\nexport function newStore(\n ctx: CliContext,\n env: Record<string, string | undefined>,\n): CredentialStore {\n return new CredentialStore({\n home: resolveEkanosHome(env),\n // Permission warnings are diagnostics, not results: stderr, always.\n warn: (message) => ctx.warn(message),\n });\n}\n\n/**\n * `http://` is allowed because local development needs it, but sending a\n * bearer token to a plaintext REMOTE host puts it on the wire in the clear.\n * Warn rather than refuse: refusing would break `--host http://localhost:3000`\n * for anyone whose loopback resolves to something other than the names below.\n */\nfunction warnOnPlaintextHost(ctx: CliContext, host: string): void {\n const url = new URL(host);\n\n if (url.protocol !== 'http:') return;\n\n const loopback = ['localhost', '127.0.0.1', '[::1]', '0.0.0.0'];\n\n if (loopback.includes(url.hostname) || url.hostname.endsWith('.localhost')) {\n return;\n }\n\n ctx.warn(\n `ekanos: ${host} is plaintext HTTP. Your credentials will cross the ` +\n `network unencrypted. Use https:// unless this is a local host.`,\n );\n}\n\nexport function requireSession(\n store: CredentialStore,\n host: string,\n): StoredSession {\n const session = store.read(host);\n\n if (!session) {\n throw authRequiredError(\n `Not logged in to ${host}.`,\n `Run \"ekanos login --host ${host}\".`,\n );\n }\n\n return session;\n}\n\n/**\n * Resolve the caller's identity, refreshing the access token once if the\n * stored one no longer authenticates.\n *\n * Validity is decided by the SERVER, not by comparing `expiresAt` to the local\n * clock. A container with a skewed clock — the exact environment this flow\n * exists to support — would otherwise either refuse a perfectly good token or\n * keep presenting a dead one. A 401 is the authoritative answer; one refresh\n * and one retry is the whole recovery.\n */\nexport async function resolveIdentity(\n env: AuthEnvironment,\n session: StoredSession,\n): Promise<{ identity: EkanosIdentity; session: StoredSession }> {\n const identity = await fetchIdentity(env.host, session.accessToken);\n\n if (identity) {\n return { identity, session };\n }\n\n const refreshed = await refreshStoredSession(env, session);\n const retried = await fetchIdentity(env.host, refreshed.accessToken);\n\n if (!retried) {\n throw authRequiredError(\n `The session for ${env.host} could not be renewed.`,\n `Run \"ekanos logout --host ${env.host}\" then \"ekanos login --host ${env.host}\".`,\n );\n }\n\n return { identity: retried, session: refreshed };\n}\n\n/**\n * Refresh and persist.\n *\n * The rotated refresh token is written the MOMENT the server reports it, not\n * when the refresh finishes. Auth0 rotates as soon as the server's exchange\n * succeeds, so from that instant the presented token is dead and the\n * replacement is the only copy in existence — and `cli-refresh` can still fail\n * afterwards (a `/userinfo` blip, a missing account, an unexpected throw) and\n * return that replacement on an ERROR response. Saving only on success would\n * discard it and lock the partner out for good over a transient upstream\n * hiccup: one process, no concurrency needed.\n *\n * So `onRotatedToken` writes it immediately and `refreshEkanosSession` invokes\n * that before it throws. The write keeps the OLD access token, which is\n * correct: that token is merely expired, while the refresh token is current\n * and is what the next attempt needs.\n */\nexport async function refreshStoredSession(\n env: AuthEnvironment,\n session: StoredSession,\n): Promise<StoredSession> {\n const persistRotated = (rotated: string) => {\n env.store.write(env.host, {\n ...session,\n auth0RefreshToken: rotated,\n updatedAt: new Date().toISOString(),\n });\n };\n\n const refreshed = await refreshEkanosSession(\n env.host,\n session.auth0RefreshToken,\n { onRotatedToken: persistRotated },\n );\n\n const next: StoredSession = {\n auth0RefreshToken: refreshed.auth0RefreshToken,\n accessToken: refreshed.accessToken,\n expiresAt: refreshed.expiresAt,\n userId: refreshed.userId,\n email: refreshed.email,\n updatedAt: new Date().toISOString(),\n };\n\n env.store.write(env.host, next);\n\n return next;\n}\n"]}
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../../src/auth/session.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAGlC,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAC1D,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAClC,OAAO,EACL,eAAe,EAEf,aAAa,EACb,iBAAiB,GAClB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAEL,aAAa,EACb,oBAAoB,GACrB,MAAM,cAAc,CAAC;AACtB,OAAO,EAEL,qBAAqB,EACrB,qBAAqB,EACrB,SAAS,GACV,MAAM,cAAc,CAAC;AAetB;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,WAAW,CACzB,GAAe,EACf,IAAwB,EACxB,GAAuC,EACv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,CAAC;IACL,CAAC,CAAC;IAEF,MAAM,SAAS,GAAG,MAAM,oBAAoB,CAC1C,GAAG,CAAC,IAAI,EACR;QACE,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;QAC5C,WAAW,EAAE,OAAO,CAAC,WAAW;KACjC,EACD,EAAE,cAAc,EAAE,cAAc,EAAE,CACnC,CAAC;IAEF,MAAM,IAAI,GAAkB;QAC1B,iBAAiB,EAAE,SAAS,CAAC,iBAAiB;QAC9C,WAAW,EAAE,SAAS,CAAC,WAAW;QAClC,SAAS,EAAE,SAAS,CAAC,SAAS;QAC9B,MAAM,EAAE,SAAS,CAAC,MAAM;QACxB,KAAK,EAAE,SAAS,CAAC,KAAK;QACtB,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;KACpC,CAAC;IAEF,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAEhC,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport type { CliContext } from '../context';\nimport { authRequiredError, usageError } from '../errors';\nimport { shortHost } from '../ui';\nimport {\n CredentialStore,\n type StoredSession,\n normalizeHost,\n resolveEkanosHome,\n} from './credential-store';\nimport {\n type EkanosIdentity,\n fetchIdentity,\n refreshEkanosSession,\n} from './ekanos-api';\nimport {\n type HostOrigin,\n assertSecureTransport,\n isPlaintextRemoteHost,\n loginHint,\n} from './host-trust';\n\n/**\n * Session plumbing shared by `login`, `logout` and `whoami`: where the Ekanos\n * host comes from, where credentials live, and how a stale access token is\n * silently replaced.\n */\n\nexport interface AuthEnvironment {\n store: CredentialStore;\n host: string;\n /** Where `host` came from — what `loginHint` names for an unknown host. */\n hostOrigin: HostOrigin;\n}\n\n/**\n * Resolve the Ekanos host, in this order:\n *\n * 1. the `--host` flag\n * 2. the `EKANOS_HOST` environment variable\n * 3. the `host` field of the project's `ekanos.json` (written by the first\n * successful `ekanos publish`, or by hand)\n * 4. the credential store, when it holds EXACTLY one host — a partner logged\n * in to a single deployment should not have to repeat its URL on every\n * verb, and one stored host is unambiguous\n *\n * Deliberately no default beyond those. A baked-in default would be wrong for\n * every partner running against their own sandbox, and — worse — a CLI that\n * silently picks a host is a CLI that can send a developer's credentials\n * somewhere they did not intend. Two or more stored hosts is exactly that\n * ambiguity, so it stays a usage error that LISTS them rather than a guess.\n */\nexport function resolveHost(\n ctx: CliContext,\n flag: string | undefined,\n env: Record<string, string | undefined>,\n options: {\n /** Directory whose ekanos.json may carry a `host` field. */\n projectDir?: string;\n /** The credential store, for the sole-stored-host fallback. */\n store?: CredentialStore;\n } = {},\n): string {\n return resolveHostWithOrigin(ctx, flag, env, options).host;\n}\n\nfunction resolveHostWithOrigin(\n ctx: CliContext,\n flag: string | undefined,\n env: Record<string, string | undefined>,\n options: { projectDir?: string; store?: CredentialStore },\n): { host: string; origin: HostOrigin } {\n const raw = flag ?? env.EKANOS_HOST;\n\n if (raw && raw.trim().length > 0) {\n return {\n host: normalizeHost(raw.trim()),\n origin: flag === undefined ? 'env' : 'flag',\n };\n }\n\n if (options.projectDir) {\n const declared = readProjectHost(options.projectDir);\n\n if (declared) {\n // normalizeHost throws a precondition error for a malformed value —\n // an EXPLICIT host in ekanos.json that is wrong deserves an error\n // naming it, never a silent fall-through to a different host.\n const host = normalizeHost(declared);\n\n // Announce the choice, like the sole-stored-host branch below. This\n // source deserves it MOST: ekanos.json is a committed file, so its\n // host can change under a developer via an ordinary merge or an\n // agent-applied patch — and this is where login sends the OAuth flow\n // and publish sends the bearer token and archive.\n ctx.log(\n ctx.jsonMode\n ? `ekanos: using ${host} — the host saved in ekanos.json. ` +\n `Pass --host to override for one command.`\n : ctx.ui.dim(\n `Using ${shortHost(host)} from ekanos.json. ` +\n `Pass --host to override for one command.`,\n ),\n );\n\n return { host, origin: 'project' };\n }\n }\n\n const stored = options.store?.hosts() ?? [];\n\n if (stored.length === 1) {\n const host = stored[0]!;\n\n // A person at a terminal sees this host in the result block of every\n // verb, and it is the only one they are signed in to, so naming it\n // again is noise. JSON callers get no result block, so they keep it.\n if (ctx.jsonMode) {\n ctx.log(\n `ekanos: using ${host} — the only host you are logged in to. ` +\n `Pass --host to target a different one.`,\n );\n }\n\n return { host, origin: 'stored' };\n }\n\n throw usageError(\n 'No Ekanos host given.',\n stored.length > 1\n ? `You are logged in to ${stored.length} hosts (${stored.join(', ')}) — ` +\n `pass \"--host <url>\" to choose one, or set EKANOS_HOST.`\n : 'Pass \"--host https://<your-ekanos-host>\" or set EKANOS_HOST. ' +\n '\"ekanos login --host <url>\" stores the host, so later commands ' +\n 'can omit it.',\n );\n}\n\n/**\n * Best-effort read of the `host` field from a directory's ekanos.json.\n *\n * Lenient on purpose: host resolution runs for verbs like `login` that are\n * routinely run OUTSIDE a project, so a missing, unparseable, or host-less\n * ekanos.json is simply \"no answer here\", never an error — the verbs that\n * require a valid project (`publish`, `validate`) load it strictly themselves.\n */\nfunction readProjectHost(projectDir: string): string | null {\n const configPath = path.join(projectDir, 'ekanos.json');\n\n let raw: string;\n try {\n raw = fs.readFileSync(configPath, 'utf8');\n } catch {\n return null;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n\n const host =\n typeof parsed === 'object' && parsed !== null\n ? (parsed as { host?: unknown }).host\n : undefined;\n\n return typeof host === 'string' && host.trim().length > 0\n ? host.trim()\n : null;\n}\n\nexport interface ResolveAuthOptions {\n /** Directory whose ekanos.json may carry a `host` field. */\n projectDir?: string;\n /**\n * Let a remote `http://` host through with a warning instead of refusing\n * it. Only `logout` sets this: deleting local credentials must still work\n * for a host stored before plaintext remote hosts were refused.\n */\n allowPlaintext?: boolean;\n}\n\nexport function resolveAuthEnvironment(\n ctx: CliContext,\n hostFlag: string | undefined,\n env: Record<string, string | undefined>,\n options: ResolveAuthOptions = {},\n): AuthEnvironment {\n const store = newStore(ctx, env);\n const { host, origin } = resolveHostWithOrigin(ctx, hostFlag, env, {\n projectDir: options.projectDir,\n store,\n });\n\n if (!options.allowPlaintext) {\n assertSecureTransport(host);\n } else if (isPlaintextRemoteHost(host)) {\n ctx.warn(\n `ekanos: ${host} is plaintext HTTP. Your credentials will cross the ` +\n `network unencrypted. Use https:// unless this is a local host.`,\n );\n }\n\n return { host, store, hostOrigin: origin };\n}\n\n/** A store with no host attached — for `logout --all`. */\nexport function newStore(\n ctx: CliContext,\n env: Record<string, string | undefined>,\n): CredentialStore {\n return new CredentialStore({\n home: resolveEkanosHome(env),\n // Permission warnings are diagnostics, not results: stderr, always.\n warn: (message) => ctx.warn(message),\n });\n}\n\nexport function requireSession(env: AuthEnvironment): StoredSession {\n const session = env.store.read(env.host);\n\n if (!session) {\n throw authRequiredError(\n `Not logged in to ${env.host}.`,\n loginHint(env, 'to sign in.'),\n );\n }\n\n return session;\n}\n\n/**\n * Resolve the caller's identity, refreshing the access token once if the\n * stored one no longer authenticates.\n *\n * Validity is decided by the SERVER, not by comparing `expiresAt` to the local\n * clock. A container with a skewed clock — the exact environment this flow\n * exists to support — would otherwise either refuse a perfectly good token or\n * keep presenting a dead one. A 401 is the authoritative answer; one refresh\n * and one retry is the whole recovery.\n */\nexport async function resolveIdentity(\n env: AuthEnvironment,\n session: StoredSession,\n): Promise<{ identity: EkanosIdentity; session: StoredSession }> {\n const identity = await fetchIdentity(env.host, session.accessToken);\n\n if (identity) {\n return { identity, session };\n }\n\n const refreshed = await refreshStoredSession(env, session);\n const retried = await fetchIdentity(env.host, refreshed.accessToken);\n\n if (!retried) {\n throw authRequiredError(\n `The session for ${env.host} could not be renewed.`,\n `Run \"ekanos logout --host ${env.host}\" first. ` +\n loginHint(env, 'to sign in again.'),\n );\n }\n\n return { identity: retried, session: refreshed };\n}\n\n/**\n * Refresh and persist.\n *\n * The rotated refresh token is written the MOMENT the server reports it, not\n * when the refresh finishes. Auth0 rotates as soon as the server's exchange\n * succeeds, so from that instant the presented token is dead and the\n * replacement is the only copy in existence — and `cli-refresh` can still fail\n * afterwards (a `/userinfo` blip, a missing account, an unexpected throw) and\n * return that replacement on an ERROR response. Saving only on success would\n * discard it and lock the partner out for good over a transient upstream\n * hiccup: one process, no concurrency needed.\n *\n * So `onRotatedToken` writes it immediately and `refreshEkanosSession` invokes\n * that before it throws. The write keeps the OLD access token, which is\n * correct: that token is merely expired, while the refresh token is current\n * and is what the next attempt needs.\n */\nexport async function refreshStoredSession(\n env: AuthEnvironment,\n session: StoredSession,\n): Promise<StoredSession> {\n const persistRotated = (rotated: string) => {\n env.store.write(env.host, {\n ...session,\n auth0RefreshToken: rotated,\n updatedAt: new Date().toISOString(),\n });\n };\n\n const refreshed = await refreshEkanosSession(\n env.host,\n {\n auth0RefreshToken: session.auth0RefreshToken,\n accessToken: session.accessToken,\n },\n { onRotatedToken: persistRotated },\n );\n\n const next: StoredSession = {\n auth0RefreshToken: refreshed.auth0RefreshToken,\n accessToken: refreshed.accessToken,\n expiresAt: refreshed.expiresAt,\n userId: refreshed.userId,\n email: refreshed.email,\n updatedAt: new Date().toISOString(),\n };\n\n env.store.write(env.host, next);\n\n return next;\n}\n"]}
@@ -42,8 +42,12 @@ export declare function areaRows(subcommand: TemplateEditSubcommand, body: Agent
42
42
  export declare function describeTrigger(trigger: AgentTemplateTrigger): string;
43
43
  export declare function describeLink(link: AgentTemplateLink): string;
44
44
  /**
45
- * `--filter field=value`, repeatable. A value with a comma is a list
46
- * (`tags=vip,urgent`), `true`/`false` a switch, anything else text.
45
+ * `--filter`, the same at the template and the team level. Repeatable
46
+ * `field=value`: a value with a comma is a list (`tags=vip,urgent`),
47
+ * `true`/`false` a switch, anything else text. Or one JSON object, the team
48
+ * level's older form. Both are accepted at both levels, and may be mixed
49
+ * (a later field wins).
47
50
  */
48
51
  export declare function parseFilters(raw: readonly string[]): Record<string, string | boolean | string[]>;
52
+ export declare const TEMPLATE_EDIT_HELP: Record<TemplateEditSubcommand, string>;
49
53
  export declare function isTemplateEditSubcommand(value: string): value is TemplateEditSubcommand;