@ekanos/cli 0.28.0 → 0.29.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 (39) hide show
  1. package/README.md +5 -1
  2. package/dist/auth/ekanos-api.d.ts +8 -1
  3. package/dist/auth/ekanos-api.js +14 -2
  4. package/dist/auth/ekanos-api.js.map +1 -1
  5. package/dist/bin.js +4 -1
  6. package/dist/bin.js.map +1 -1
  7. package/dist/commands/feedback.d.ts +38 -0
  8. package/dist/commands/feedback.js +234 -0
  9. package/dist/commands/feedback.js.map +1 -0
  10. package/dist/commands/sources.js +4 -1
  11. package/dist/commands/sources.js.map +1 -1
  12. package/dist/context.d.ts +10 -0
  13. package/dist/context.js +10 -0
  14. package/dist/context.js.map +1 -1
  15. package/dist/feedback-api.d.ts +70 -0
  16. package/dist/feedback-api.js +111 -0
  17. package/dist/feedback-api.js.map +1 -0
  18. package/dist/feedback-context.d.ts +31 -0
  19. package/dist/feedback-context.js +209 -0
  20. package/dist/feedback-context.js.map +1 -0
  21. package/dist/feedback-updates.d.ts +16 -0
  22. package/dist/feedback-updates.js +174 -0
  23. package/dist/feedback-updates.js.map +1 -0
  24. package/dist/http-trace.d.ts +19 -0
  25. package/dist/http-trace.js +47 -0
  26. package/dist/http-trace.js.map +1 -0
  27. package/dist/index.d.ts +12 -0
  28. package/dist/index.js +143 -10
  29. package/dist/index.js.map +1 -1
  30. package/dist/last-error.d.ts +17 -0
  31. package/dist/last-error.js +56 -0
  32. package/dist/last-error.js.map +1 -0
  33. package/package.json +2 -2
  34. package/templates/AGENTS.md.tmpl +19 -0
  35. package/templates/claude-skill.md.tmpl +18 -0
  36. package/templates/experience/package.json.tmpl +4 -4
  37. package/templates/package.json.tmpl +4 -4
  38. package/templates/skills/build-agent/SKILL.md +18 -0
  39. package/templates/skills/build-integration/SKILL.md +18 -0
package/README.md CHANGED
@@ -26,7 +26,7 @@ npx @ekanos/cli dev
26
26
  | `logout` | Revoke the session at Auth0 and delete the local credentials. |
27
27
  | `whoami` | Print the identity the stored session authenticates as, plus a compact `seats` list (slug + roles) from the same endpoint `sources` uses — degrades to `seats: null` rather than failing if that lookup is unavailable. |
28
28
  | `status` | The read verb: login state for the resolved host, this project's `ekanos.json`, and its submissions on the host (`GET /api/partner/submissions`). Never fails just because you are logged out — it reports `authenticated: false` instead. |
29
- | `sources` | List every Ekanos source you hold a developer or source-admin seat on (`GET /api/partner/sources`), with a marker on this project's current publish target; for a Source admin also `products`, `scopes`, `roles [create\|update\|delete <role>]` (the Source's team roles) and `people` (everyone on the Source, one row per person). |
29
+ | `sources` | List every Ekanos source you hold a developer or source-admin seat on (`GET /api/partner/sources`), with a marker on this project's current publish target; for a Source admin also `products`, `scopes`, `roles [create\|update\|delete <role>]` (the Source's team roles) `people` (everyone on the Source, one row per person) and `feedback [status|enable|disable]` (whether `ekanos feedback` reaches Vastly from the Source; on until its admin turns it off, each change in the Admin Audit log). |
30
30
  | `catalog` | `ekanos catalog [<product-slug>] [--all]` — what a source can build on (`GET /api/partner/catalog`): the SDK packages (an integration with a contract, or an experience) that are global or attached to it. `--all`: every product, Experiences then Integrations as `sources products` splits them (the two list the same products), enabled, switched off or available to enable, with its tools and their input schemas, whose connection an agent run uses, agent triggers and generated setup steps. Check it before building something the source may already have. |
31
31
  | `agents` | `ekanos agents init | list | show | pull | apply | publish | rollback | archive | unarchive` — the source's agents, held by Ekanos (`/api/partner/agents`). `init` sets up a folder for designing agents with Claude (the `build-agent` and `ekanos-platform` skills, the docs MCP server, a CLAUDE.md) without scaffolding an integration. `apply` stores a new version as a draft, `publish` makes a version the one every team runs, `rollback` publishes an earlier one, `archive` retires one no team has on. Either seat applies; only the source admin publishes or archives.
32
32
  | `teams` | A Source admin's teams (`/api/partner/teams`): members, connections, and each team's agents. `ekanos teams agents create <team> --from <dir> [--personal]` builds the team's own agent — or, with `--personal`, your own, which acts for you and only you change — from the same `agent.json` (+ `AGENT.md`, + `skills/<slug>/`) that `agents apply` reads; `teams agents apply <team> <dir> [--base-version <n>]` creates or changes it from that file. You become its creator, so you must be an active member of the team. `teams triggers add <team> <key> schedule\|webhook …` starts it; a webhook token goes to a `0600` file under `~/.ekanos/secrets`, never the output. Someone else's personal agent is refused for every write (`PERSONAL_AGENT_CREATOR_ONLY`). |
@@ -36,6 +36,7 @@ npx @ekanos/cli dev
36
36
  | `use` | `ekanos use <source-slug>` — set this project's publish target to a source you hold a seat on. Refuses (`forbidden`, with your actual seats in the hint) for a slug you don't hold a seat on, so a typo can't silently repoint a project. |
37
37
  | `publish` | Validate, pack and submit the integration to an Ekanos host — refusing (`forbidden`) a target you hold no seat on, and confirming an ambiguous multi-seat target before submitting. See [Publish target verification](#publish-target-verification). |
38
38
  | `upgrade` | Move this toolchain to a coherent target version, with verify-and-rollback. `--check` reports current vs. target and changes nothing; a bare `upgrade` installs, verifies (`validate` + the test script), and rolls back automatically on any failure. See [Keeping the toolchain current](#keeping-the-toolchain-current). |
39
+ | `feedback` | `ekanos feedback "<what you tried, what happened, what you expected>" [--kind bug\|confusing\|missing\|other] [--last-error] [--command "<the ekanos command>"]` and `feedback list` — report a problem to Vastly, and see your own reports and any fix that shipped. `--last-error` attaches the last failed command's path, flag names, codes, HTTP status and request id from `~/.ekanos/last-error.json` (0600). Never sends argument or flag values, files or the environment; the message is redacted first. Nothing is sent unless you run it. A later command tells you, once, when a fix ships. See the commands reference. |
39
40
 
40
41
  ### Installing: global is fine
41
42
 
@@ -84,6 +85,9 @@ written only when `--json` is passed or a coding agent is detected
84
85
  a person at a terminal, or piping into another program, gets the readable error
85
86
  alone. An unknown command suggests the closest one, and a whole command passed
86
87
  as one argument (`ekanos "teams list"`) is answered with `ekanos teams list`.
88
+ A failed command's line (except a validation or publish-gate failure, which is
89
+ about your own code) carries `"report": "ekanos feedback --last-error \"<what
90
+ you were trying to do>\""`, the command that reports it to Vastly.
87
91
 
88
92
  The CLI never prompts, with **one deliberate exception**: `publish` asks for a
89
93
  y/N confirm at a real terminal when the publish target is _ambiguous_ — an
@@ -60,7 +60,14 @@ export declare function fetchIdentity(host: string, accessToken: string): Promis
60
60
  * an HTTP status: logout must always reach the local delete.
61
61
  */
62
62
  export declare function revokeEkanosSession(host: string, accessToken: string): Promise<boolean>;
63
- export declare function request(url: string, init: RequestInit): Promise<Response>;
63
+ export interface RequestOptions {
64
+ /** Leave this call out of the run's trace (`http-trace.ts`): a background check. */
65
+ untraced?: boolean;
66
+ /** Abort it early, as well as at the usual timeout. */
67
+ signal?: AbortSignal;
68
+ timeoutMs?: number;
69
+ }
70
+ export declare function request(url: string, init: RequestInit, options?: RequestOptions): Promise<Response>;
64
71
  /**
65
72
  * 503 means the deployment is not provisioned for CLI login — an operator
66
73
  * action that has not happened, not a fault in the request.
@@ -1,4 +1,5 @@
1
1
  import { authRequiredError, forbiddenError, networkError, preconditionError, } from '../errors.js';
2
+ import { recordHttpResponse } from '../http-trace.js';
2
3
  /**
3
4
  * The CLI's client for the five Ekanos auth routes.
4
5
  *
@@ -282,9 +283,20 @@ function toSession(body, host) {
282
283
  }
283
284
  return { accessToken, expiresAt, userId, email: str(user.email) };
284
285
  }
285
- export async function request(url, init) {
286
+ export async function request(url, init, options = {}) {
287
+ var _a;
288
+ const timeout = AbortSignal.timeout((_a = options.timeoutMs) !== null && _a !== void 0 ? _a : REQUEST_TIMEOUT_MS);
286
289
  try {
287
- return await fetch(url, Object.assign(Object.assign({}, init), { redirect: 'manual', signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }));
290
+ const response = await fetch(url, Object.assign(Object.assign({}, init), { redirect: 'manual', signal: options.signal
291
+ ? AbortSignal.any([timeout, options.signal])
292
+ : timeout }));
293
+ if (!options.untraced) {
294
+ const authorized = new Headers(init.headers).has('authorization');
295
+ recordHttpResponse(url, response, authorized &&
296
+ response.status !== 401 &&
297
+ !(response.status >= 300 && response.status < 400));
298
+ }
299
+ return response;
288
300
  }
289
301
  catch (error) {
290
302
  const reason = error instanceof Error ? error.message : String(error);
@@ -1 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AM,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 type CliError,\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 * reason\n * \"auth0_mfa_required\":\n * Auth0 demanded MFA on\n * the refresh grant\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 sessionExpiredError(host, str(body.error), str(body.reason));\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 */\n/**\n * What the server's CLI session policy is, said once for every \"log in\n * again\" message. The server owns the numbers (`CLI_SESSION_LIFETIME` in the\n * web app, equal to the Fusion CLI Auth0 refresh token); this is the sentence.\n */\nexport const CLI_SESSION_LIFETIME_TEXT =\n 'A CLI session lasts up to 30 days and ends after 7 days without use; ' +\n 'within that window an expired access token is renewed silently.';\n\n/**\n * A 401 from `cli-refresh`: the session really is over (or Auth0 asked for\n * something a refresh cannot give). Says why, how long sessions last, and the\n * one command that fixes it.\n */\nexport function sessionExpiredError(\n host: string,\n serverMessage: string | null,\n reason: string | null,\n): CliError {\n const why =\n reason === 'auth0_mfa_required'\n ? 'Auth0 asked for multi-factor authentication to renew it, which a ' +\n 'refresh cannot answer.'\n : reason === 'session_revoked'\n ? 'It was signed out (\"ekanos logout\" or an administrator).'\n : reason === 'session_idle_expired'\n ? 'It went unused for longer than 7 days.'\n : reason === 'session_max_age_exceeded'\n ? 'It reached its 30-day maximum age.'\n : serverMessage\n ? `${serverMessage}.`\n : 'The server no longer accepts it.';\n\n return authRequiredError(\n `The CLI session for ${host} has ended. ${why} ${CLI_SESSION_LIFETIME_TEXT}`,\n `Run: ekanos login --host ${host}`,\n );\n}\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"]}
1
+ {"version":3,"file":"ekanos-api.js","sourceRoot":"","sources":["../../src/auth/ekanos-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,iBAAiB,EACjB,cAAc,EACd,YAAY,EACZ,iBAAiB,GAClB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAEnD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0GG;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;QACj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6D;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 type CliError,\n authRequiredError,\n forbiddenError,\n networkError,\n preconditionError,\n} from '../errors';\nimport { recordHttpResponse } from '../http-trace';\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 * reason\n * \"auth0_mfa_required\":\n * Auth0 demanded MFA on\n * the refresh grant\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 sessionExpiredError(host, str(body.error), str(body.reason));\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 interface RequestOptions {\n /** Leave this call out of the run's trace (`http-trace.ts`): a background check. */\n untraced?: boolean;\n /** Abort it early, as well as at the usual timeout. */\n signal?: AbortSignal;\n timeoutMs?: number;\n}\n\nexport async function request(\n url: string,\n init: RequestInit,\n options: RequestOptions = {},\n): Promise<Response> {\n const timeout = AbortSignal.timeout(options.timeoutMs ?? REQUEST_TIMEOUT_MS);\n try {\n const response = await fetch(url, {\n ...init,\n redirect: 'manual',\n signal: options.signal\n ? AbortSignal.any([timeout, options.signal])\n : timeout,\n });\n if (!options.untraced) {\n const authorized = new Headers(init.headers).has('authorization');\n recordHttpResponse(\n url,\n response,\n authorized &&\n response.status !== 401 &&\n !(response.status >= 300 && response.status < 400),\n );\n }\n return response;\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 */\n/**\n * What the server's CLI session policy is, said once for every \"log in\n * again\" message. The server owns the numbers (`CLI_SESSION_LIFETIME` in the\n * web app, equal to the Fusion CLI Auth0 refresh token); this is the sentence.\n */\nexport const CLI_SESSION_LIFETIME_TEXT =\n 'A CLI session lasts up to 30 days and ends after 7 days without use; ' +\n 'within that window an expired access token is renewed silently.';\n\n/**\n * A 401 from `cli-refresh`: the session really is over (or Auth0 asked for\n * something a refresh cannot give). Says why, how long sessions last, and the\n * one command that fixes it.\n */\nexport function sessionExpiredError(\n host: string,\n serverMessage: string | null,\n reason: string | null,\n): CliError {\n const why =\n reason === 'auth0_mfa_required'\n ? 'Auth0 asked for multi-factor authentication to renew it, which a ' +\n 'refresh cannot answer.'\n : reason === 'session_revoked'\n ? 'It was signed out (\"ekanos logout\" or an administrator).'\n : reason === 'session_idle_expired'\n ? 'It went unused for longer than 7 days.'\n : reason === 'session_max_age_exceeded'\n ? 'It reached its 30-day maximum age.'\n : serverMessage\n ? `${serverMessage}.`\n : 'The server no longer accepts it.';\n\n return authRequiredError(\n `The CLI session for ${host} has ended. ${why} ${CLI_SESSION_LIFETIME_TEXT}`,\n `Run: ekanos login --host ${host}`,\n );\n}\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"]}
package/dist/bin.js CHANGED
@@ -16,7 +16,10 @@ async function main() {
16
16
  announceDelegation(plan, argv, process.env, process.stdout.isTTY === true);
17
17
  return delegate(plan, argv, process.env);
18
18
  }
19
- return run(argv);
19
+ // The two run-level courtesies only a real invocation turns on: recording
20
+ // a failure for `ekanos feedback --last-error`, and the background check
21
+ // for fixes to your own reports. Tests opt in, against their own home.
22
+ return run(argv, { recordLastError: true, feedbackUpdates: true });
20
23
  }
21
24
  main()
22
25
  .then((code) => {
package/dist/bin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"bin.js","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,kBAAkB,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC1E,OAAO,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAE9B;;;;;;;GAOG;AACH,KAAK,UAAU,IAAI;IACjB,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACnC,MAAM,IAAI,GAAG,cAAc,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;IAE9D,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;QACxB,kBAAkB,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,MAAM,CAAC,KAAK,KAAK,IAAI,CAAC,CAAC;QAC3E,OAAO,QAAQ,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC;IAC3C,CAAC;IAED,OAAO,GAAG,CAAC,IAAI,CAAC,CAAC;AACnB,CAAC;AAED,IAAI,EAAE;KACH,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE;IACb,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;AAC1B,CAAC,CAAC;KACD,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;;IACxB,2EAA2E;IAC3E,oEAAoE;IACpE,uCAAuC;IACvC,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,iCACE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,OAAC,KAAK,CAAC,KAAK,mCAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CACxE,IAAI,CACL,CAAC;IACF,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { announceDelegation, delegate, planDelegation } from './delegate';\nimport { run } from './index';\n\n/**\n * The bin entry — the ONLY place that calls process.exit, so `run()` stays a\n * pure, testable function that returns an exit code. Argv is sliced to drop\n * the node executable and this script path.\n *\n * Before dispatching, check whether this invocation should delegate to the\n * current project's OWN pinned `@ekanos/cli` — see `delegate.ts` for why.\n */\nasync function main(): Promise<number> {\n const argv = process.argv.slice(2);\n const plan = planDelegation(argv, process.env, process.cwd());\n\n if (plan.shouldDelegate) {\n announceDelegation(plan, argv, process.env, process.stdout.isTTY === true);\n return delegate(plan, argv, process.env);\n }\n\n return run(argv);\n}\n\nmain()\n .then((code) => {\n process.exitCode = code;\n })\n .catch((error: unknown) => {\n // run() catches its own errors and emits the envelope; reaching here means\n // the envelope machinery itself threw. Fail loudly on stderr (never\n // stdout) with the internal exit code.\n process.stderr.write(\n `ekanos: fatal internal error: ${\n error instanceof Error ? (error.stack ?? error.message) : String(error)\n }\\n`,\n );\n process.exitCode = 1;\n });\n"]}
1
+ {"version":3,"file":"bin.js","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,kBAAkB,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC1E,OAAO,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAE9B;;;;;;;GAOG;AACH,KAAK,UAAU,IAAI;IACjB,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACnC,MAAM,IAAI,GAAG,cAAc,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;IAE9D,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;QACxB,kBAAkB,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,MAAM,CAAC,KAAK,KAAK,IAAI,CAAC,CAAC;QAC3E,OAAO,QAAQ,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC;IAC3C,CAAC;IAED,0EAA0E;IAC1E,yEAAyE;IACzE,uEAAuE;IACvE,OAAO,GAAG,CAAC,IAAI,EAAE,EAAE,eAAe,EAAE,IAAI,EAAE,eAAe,EAAE,IAAI,EAAE,CAAC,CAAC;AACrE,CAAC;AAED,IAAI,EAAE;KACH,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE;IACb,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;AAC1B,CAAC,CAAC;KACD,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;;IACxB,2EAA2E;IAC3E,oEAAoE;IACpE,uCAAuC;IACvC,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,iCACE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,OAAC,KAAK,CAAC,KAAK,mCAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CACxE,IAAI,CACL,CAAC;IACF,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;AACvB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\nimport { announceDelegation, delegate, planDelegation } from './delegate';\nimport { run } from './index';\n\n/**\n * The bin entry — the ONLY place that calls process.exit, so `run()` stays a\n * pure, testable function that returns an exit code. Argv is sliced to drop\n * the node executable and this script path.\n *\n * Before dispatching, check whether this invocation should delegate to the\n * current project's OWN pinned `@ekanos/cli` — see `delegate.ts` for why.\n */\nasync function main(): Promise<number> {\n const argv = process.argv.slice(2);\n const plan = planDelegation(argv, process.env, process.cwd());\n\n if (plan.shouldDelegate) {\n announceDelegation(plan, argv, process.env, process.stdout.isTTY === true);\n return delegate(plan, argv, process.env);\n }\n\n // The two run-level courtesies only a real invocation turns on: recording\n // a failure for `ekanos feedback --last-error`, and the background check\n // for fixes to your own reports. Tests opt in, against their own home.\n return run(argv, { recordLastError: true, feedbackUpdates: true });\n}\n\nmain()\n .then((code) => {\n process.exitCode = code;\n })\n .catch((error: unknown) => {\n // run() catches its own errors and emits the envelope; reaching here means\n // the envelope machinery itself threw. Fail loudly on stderr (never\n // stdout) with the internal exit code.\n process.stderr.write(\n `ekanos: fatal internal error: ${\n error instanceof Error ? (error.stack ?? error.message) : String(error)\n }\\n`,\n );\n process.exitCode = 1;\n });\n"]}
@@ -0,0 +1,38 @@
1
+ import type { CliContext } from '../context.js';
2
+ import type { ExitCode } from '../exit-codes.js';
3
+ export interface FeedbackArgs {
4
+ host?: string;
5
+ source?: string;
6
+ /** `[<message>]`, or `list`. */
7
+ positionals: readonly string[];
8
+ kind?: string;
9
+ lastError: boolean;
10
+ command?: string;
11
+ dir: string;
12
+ env: Record<string, string | undefined>;
13
+ stdinIsTTY?: boolean;
14
+ readStdin?: () => Promise<string>;
15
+ }
16
+ /**
17
+ * `feedback` — tell Vastly about a problem with the CLI or the platform:
18
+ * a command that failed unexpectedly, a confusing message, something
19
+ * missing. Nothing is ever sent on its own; a report is this command, run
20
+ * by a person or their agent. The message is redacted before it leaves
21
+ * this machine (and again on the host), and what is attached about the
22
+ * command is its path and flag NAMES, codes and versions: never an
23
+ * argument, a value, a file or the environment.
24
+ *
25
+ * `feedback list` shows your own reports, with any fix that has shipped.
26
+ */
27
+ export declare function runFeedback(ctx: CliContext, args: FeedbackArgs): Promise<ExitCode>;
28
+ /**
29
+ * `sources feedback [status|enable|disable]` — whether this Source takes
30
+ * reports from `ekanos feedback`. On unless its Source admin turns it off;
31
+ * every change is recorded in the Admin Audit log.
32
+ */
33
+ export declare function runSourceFeedback(ctx: CliContext, args: {
34
+ host?: string;
35
+ source?: string;
36
+ dir: string;
37
+ env: Record<string, string | undefined>;
38
+ }, rest: readonly string[]): Promise<ExitCode>;
@@ -0,0 +1,234 @@
1
+ import { FEEDBACK_KINDS, FEEDBACK_MESSAGE_MAX_LENGTH, redactFeedbackText, } from '@ekanos/integration-schema';
2
+ import * as fs from 'node:fs';
3
+ import { loginHint } from '../auth/host-trust.js';
4
+ import { refreshStoredSession, requireSession, resolveAuthEnvironment, } from '../auth/session.js';
5
+ import { cliVersion } from '../compatibility.js';
6
+ import { authRequiredError, preconditionError, usageError } from '../errors.js';
7
+ import { listOwnFeedback, sourceFeedbackSetting, submitFeedback, } from '../feedback-api.js';
8
+ import { baseFeedbackContext, describeCommandLine } from '../feedback-context.js';
9
+ import { readLastError } from '../last-error.js';
10
+ import { resolveSourceTarget } from '../source-target.js';
11
+ import { shortHost } from '../ui.js';
12
+ const USAGE = 'Run "ekanos feedback \\"<what you tried, what happened, what you expected>\\" [--kind bug|confusing|missing|other] [--last-error] [--command \\"<the ekanos command>\\"]", or "ekanos feedback list".';
13
+ /**
14
+ * `feedback` — tell Vastly about a problem with the CLI or the platform:
15
+ * a command that failed unexpectedly, a confusing message, something
16
+ * missing. Nothing is ever sent on its own; a report is this command, run
17
+ * by a person or their agent. The message is redacted before it leaves
18
+ * this machine (and again on the host), and what is attached about the
19
+ * command is its path and flag NAMES, codes and versions: never an
20
+ * argument, a value, a file or the environment.
21
+ *
22
+ * `feedback list` shows your own reports, with any fix that has shipped.
23
+ */
24
+ export async function runFeedback(ctx, args) {
25
+ var _a;
26
+ if (args.positionals[0] === 'list' && args.positionals.length === 1) {
27
+ if (args.lastError || args.kind || args.command) {
28
+ throw usageError('"feedback list" takes no report flags.', USAGE);
29
+ }
30
+ return runFeedbackList(ctx, args);
31
+ }
32
+ const kind = feedbackKind(args.kind, args.lastError);
33
+ const typed = ((_a = args.positionals[0]) === null || _a === void 0 ? void 0 : _a.trim()) || (await readPipedMessage(args));
34
+ if (!typed && !args.lastError) {
35
+ throw usageError('Say what happened: a message, or --last-error.', USAGE);
36
+ }
37
+ let context = baseFeedbackContext({
38
+ cliVersion: cliVersion(),
39
+ env: args.env,
40
+ });
41
+ if (args.lastError) {
42
+ const last = readLastError(args.env);
43
+ if (!last) {
44
+ throw preconditionError('No failed command is recorded on this machine.', 'Run the command that failed again, then "ekanos feedback --last-error \\"<what you were trying to do>\\"" — or describe it: "ekanos feedback \\"<what happened>\\" --command \\"<the command>\\"".');
45
+ }
46
+ context = Object.assign(Object.assign({}, context), { command: last.command, flags: last.flags, errorCode: last.errorCode, exitCode: last.exitCode, httpStatus: last.httpStatus, requestId: last.requestId, failedAt: last.failedAt });
47
+ }
48
+ if (args.command !== undefined) {
49
+ const described = describeCommandLine(args.command);
50
+ if (!described.command) {
51
+ throw usageError(`"${args.command.slice(0, 60)}" names no ekanos command.`, 'Pass the command it concerns, e.g. --command "ekanos teams connect".');
52
+ }
53
+ context = Object.assign(Object.assign({}, context), described);
54
+ }
55
+ const raw = typed ||
56
+ 'Filed with --last-error; the reporter gave no description of what they were doing.';
57
+ const redactedText = redactFeedbackText(raw);
58
+ const truncated = redactedText.length > FEEDBACK_MESSAGE_MAX_LENGTH;
59
+ const message = redactedText.slice(0, FEEDBACK_MESSAGE_MAX_LENGTH);
60
+ const env = resolveAuthEnvironment(ctx, args.host, args.env, {
61
+ projectDir: args.dir,
62
+ });
63
+ const resolved = await resolveSourceTarget(env, requireSession(env), {
64
+ source: args.source,
65
+ dir: args.dir,
66
+ });
67
+ const client = new FeedbackClient(env, resolved.session);
68
+ const filed = await client.call((token) => submitFeedback(env.host, token, resolved.source, {
69
+ message,
70
+ kind,
71
+ context,
72
+ }));
73
+ return ctx.succeed({
74
+ host: env.host,
75
+ source: resolved.source,
76
+ id: filed.id,
77
+ number: filed.number,
78
+ kind,
79
+ redacted: redactedText !== raw,
80
+ truncated,
81
+ context,
82
+ }, ctx.ui.result({
83
+ title: `Filed feedback #${filed.number}`,
84
+ rows: [
85
+ ['Id', filed.id],
86
+ ['Kind', kind],
87
+ ['Host', shortHost(env.host)],
88
+ ...(context.command
89
+ ? [['About', `ekanos ${context.command}`]]
90
+ : []),
91
+ ],
92
+ notes: [
93
+ ...(redactedText !== raw
94
+ ? [
95
+ 'Something that looked like a secret or an email was replaced with [redacted] before it was sent.',
96
+ ]
97
+ : []),
98
+ ...(truncated
99
+ ? [
100
+ `The message was cut to ${FEEDBACK_MESSAGE_MAX_LENGTH} characters.`,
101
+ ]
102
+ : []),
103
+ 'When a fix ships, a later command tells you; "ekanos feedback list" shows your reports.',
104
+ ],
105
+ }));
106
+ }
107
+ async function runFeedbackList(ctx, args) {
108
+ const env = resolveAuthEnvironment(ctx, args.host, args.env, {
109
+ projectDir: args.dir,
110
+ });
111
+ const client = new FeedbackClient(env, requireSession(env));
112
+ const list = await client.call((token) => listOwnFeedback(env.host, token));
113
+ return ctx.succeed(Object.assign({ host: env.host }, list), ctx.ui.result({
114
+ title: list.reports.length === 0
115
+ ? 'You have filed no feedback'
116
+ : `Your feedback on ${shortHost(env.host)}`,
117
+ rows: list.reports.map((report) => [
118
+ `#${report.number}`,
119
+ [
120
+ `${report.kind} · ${statusLabel(report)} · ${report.createdAt.slice(0, 10)}`,
121
+ report.excerpt,
122
+ ...(report.note ? [`Note: ${report.note}`] : []),
123
+ ],
124
+ ]),
125
+ notes: list.reports.length === 0
126
+ ? ['"ekanos feedback \\"<what happened>\\"" files one.']
127
+ : [],
128
+ }));
129
+ }
130
+ function statusLabel(report) {
131
+ var _a, _b;
132
+ if (((_a = report.fix) === null || _a === void 0 ? void 0 : _a.kind) === 'cli') {
133
+ return `fixed in @ekanos/cli ${report.fix.version}`;
134
+ }
135
+ if (((_b = report.fix) === null || _b === void 0 ? void 0 : _b.kind) === 'host')
136
+ return 'fixed on the host';
137
+ return report.status.replace('_', ' ');
138
+ }
139
+ function feedbackKind(value, lastError) {
140
+ if (value === undefined)
141
+ return lastError ? 'bug' : 'other';
142
+ const kind = FEEDBACK_KINDS.find((entry) => entry === value.trim());
143
+ if (kind)
144
+ return kind;
145
+ throw usageError(`"${value}" is not a kind of feedback.`, `Pass --kind ${FEEDBACK_KINDS.join('|')}.`);
146
+ }
147
+ /**
148
+ * The message from stdin, when something is piped in. A terminal, or a
149
+ * stdin that is neither a pipe nor a file (an agent's empty one), is never
150
+ * waited on.
151
+ */
152
+ async function readPipedMessage(args) {
153
+ var _a;
154
+ if (args.readStdin) {
155
+ return args.stdinIsTTY ? '' : (await args.readStdin()).trim();
156
+ }
157
+ if ((_a = args.stdinIsTTY) !== null && _a !== void 0 ? _a : process.stdin.isTTY)
158
+ return '';
159
+ try {
160
+ const stat = fs.fstatSync(0);
161
+ if (!stat.isFIFO() && !stat.isFile())
162
+ return '';
163
+ // Read a byte past the cap, so an over-long message is cut, not refused.
164
+ return fs
165
+ .readFileSync(0, 'utf8')
166
+ .slice(0, FEEDBACK_MESSAGE_MAX_LENGTH * 4)
167
+ .trim();
168
+ }
169
+ catch (_b) {
170
+ return '';
171
+ }
172
+ }
173
+ /**
174
+ * `sources feedback [status|enable|disable]` — whether this Source takes
175
+ * reports from `ekanos feedback`. On unless its Source admin turns it off;
176
+ * every change is recorded in the Admin Audit log.
177
+ */
178
+ export async function runSourceFeedback(ctx, args, rest) {
179
+ var _a;
180
+ const [verb = 'status', ...extra] = rest;
181
+ const usage = 'Run "ekanos sources feedback [status|enable|disable] [--source <slug>]".';
182
+ if (extra.length > 0) {
183
+ throw usageError(`Unexpected argument "${extra[0]}".`, usage);
184
+ }
185
+ if (verb !== 'status' && verb !== 'enable' && verb !== 'disable') {
186
+ throw usageError(`Unknown sources feedback subcommand "${verb}".`, usage);
187
+ }
188
+ const env = resolveAuthEnvironment(ctx, args.host, args.env, {
189
+ projectDir: args.dir,
190
+ });
191
+ const resolved = await resolveSourceTarget(env, requireSession(env), {
192
+ source: args.source,
193
+ dir: args.dir,
194
+ });
195
+ const client = new FeedbackClient(env, resolved.session);
196
+ const setting = await client.call((token) => sourceFeedbackSetting(env.host, token, resolved.source, verb === 'status' ? undefined : verb === 'enable'));
197
+ const state = setting.enabled ? 'on' : 'off';
198
+ return ctx.succeed(Object.assign({ host: env.host }, setting), ctx.ui.result({
199
+ title: verb === 'status'
200
+ ? `Feedback from the CLI is ${state} for ${setting.source.slug}`
201
+ : setting.changed
202
+ ? `Turned feedback from the CLI ${state} for ${setting.source.slug}`
203
+ : `Feedback from the CLI was already ${state} for ${setting.source.slug}`,
204
+ tone: setting.enabled ? 'ok' : 'warn',
205
+ rows: [['Source', (_a = setting.source.name) !== null && _a !== void 0 ? _a : setting.source.slug]],
206
+ notes: [
207
+ setting.enabled
208
+ ? '"ekanos feedback" sends a report to Vastly when someone, or their agent, runs it; nothing is sent on its own.'
209
+ : '"ekanos feedback" is refused for this Source, and no fix updates are shown.',
210
+ ...(verb === 'status'
211
+ ? [
212
+ `Its Source admin changes it: "ekanos sources feedback ${setting.enabled ? 'disable' : 'enable'}".`,
213
+ ]
214
+ : []),
215
+ ],
216
+ }));
217
+ }
218
+ class FeedbackClient {
219
+ constructor(env, session) {
220
+ this.env = env;
221
+ this.session = session;
222
+ }
223
+ async call(send) {
224
+ let result = await send(this.session.accessToken);
225
+ if (result.status === 'unauthorized') {
226
+ this.session = await refreshStoredSession(this.env, this.session);
227
+ result = await send(this.session.accessToken);
228
+ }
229
+ if (result.status === 'ok')
230
+ return result.data;
231
+ throw authRequiredError(`The session for ${this.env.host} could not authorize the feedback call.`, loginHint(this.env));
232
+ }
233
+ }
234
+ //# sourceMappingURL=feedback.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"feedback.js","sourceRoot":"","sources":["../../src/commands/feedback.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,2BAA2B,EAI3B,kBAAkB,GACnB,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAG9B,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAEL,oBAAoB,EACpB,cAAc,EACd,sBAAsB,GACvB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAE7E,OAAO,EAEL,eAAe,EACf,qBAAqB,EACrB,cAAc,GACf,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC/E,OAAO,EAAE,a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;YACL,OAAO,CAAC,OAAO;gBACb,CAAC,CAAC,+GAA+G;gBACjH,CAAC,CAAC,6EAA6E;YACjF,GAAG,CAAC,IAAI,KAAK,QAAQ;gBACnB,CAAC,CAAC;oBACE,yDAAyD,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ,IAAI;iBACpG;gBACH,CAAC,CAAC,EAAE,CAAC;SACR;KACF,CAAC,CACH,CAAC;AACJ,CAAC;AAED,MAAM,cAAc;IAClB,YACmB,GAAoB,EAC7B,OAAsB;mBADb,GAAG;uBACZ,OAAO;IACd,CAAC;IAEJ,KAAK,CAAC,IAAI,CACR,IAA4D;QAE5D,IAAI,MAAM,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;QAClD,IAAI,MAAM,CAAC,MAAM,KAAK,cAAc,EAAE,CAAC;YACrC,IAAI,CAAC,OAAO,GAAG,MAAM,oBAAoB,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;YAClE,MAAM,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;QAChD,CAAC;QACD,IAAI,MAAM,CAAC,MAAM,KAAK,IAAI;YAAE,OAAO,MAAM,CAAC,IAAI,CAAC;QAC/C,MAAM,iBAAiB,CACrB,mBAAmB,IAAI,CAAC,GAAG,CAAC,IAAI,yCAAyC,EACzE,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CACpB,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {\n FEEDBACK_KINDS,\n FEEDBACK_MESSAGE_MAX_LENGTH,\n type FeedbackContext,\n type FeedbackKind,\n type FeedbackOwnEntry,\n redactFeedbackText,\n} from '@ekanos/integration-schema';\nimport * as fs from 'node:fs';\n\nimport type { StoredSession } from '../auth/credential-store';\nimport { loginHint } from '../auth/host-trust';\nimport {\n type AuthEnvironment,\n refreshStoredSession,\n requireSession,\n resolveAuthEnvironment,\n} from '../auth/session';\nimport { cliVersion } from '../compatibility';\nimport type { CliContext } from '../context';\nimport { authRequiredError, preconditionError, usageError } from '../errors';\nimport type { ExitCode } from '../exit-codes';\nimport {\n type FeedbackApiResult,\n listOwnFeedback,\n sourceFeedbackSetting,\n submitFeedback,\n} from '../feedback-api';\nimport { baseFeedbackContext, describeCommandLine } from '../feedback-context';\nimport { readLastError } from '../last-error';\nimport { resolveSourceTarget } from '../source-target';\nimport { shortHost } from '../ui';\n\nexport interface FeedbackArgs {\n host?: string;\n source?: string;\n /** `[<message>]`, or `list`. */\n positionals: readonly string[];\n kind?: string;\n lastError: boolean;\n command?: string;\n dir: string;\n env: Record<string, string | undefined>;\n stdinIsTTY?: boolean;\n readStdin?: () => Promise<string>;\n}\n\nconst USAGE =\n 'Run \"ekanos feedback \\\\\"<what you tried, what happened, what you expected>\\\\\" [--kind bug|confusing|missing|other] [--last-error] [--command \\\\\"<the ekanos command>\\\\\"]\", or \"ekanos feedback list\".';\n\n/**\n * `feedback` — tell Vastly about a problem with the CLI or the platform:\n * a command that failed unexpectedly, a confusing message, something\n * missing. Nothing is ever sent on its own; a report is this command, run\n * by a person or their agent. The message is redacted before it leaves\n * this machine (and again on the host), and what is attached about the\n * command is its path and flag NAMES, codes and versions: never an\n * argument, a value, a file or the environment.\n *\n * `feedback list` shows your own reports, with any fix that has shipped.\n */\nexport async function runFeedback(\n ctx: CliContext,\n args: FeedbackArgs,\n): Promise<ExitCode> {\n if (args.positionals[0] === 'list' && args.positionals.length === 1) {\n if (args.lastError || args.kind || args.command) {\n throw usageError('\"feedback list\" takes no report flags.', USAGE);\n }\n return runFeedbackList(ctx, args);\n }\n\n const kind = feedbackKind(args.kind, args.lastError);\n const typed = args.positionals[0]?.trim() || (await readPipedMessage(args));\n if (!typed && !args.lastError) {\n throw usageError('Say what happened: a message, or --last-error.', USAGE);\n }\n\n let context: FeedbackContext = baseFeedbackContext({\n cliVersion: cliVersion(),\n env: args.env,\n });\n if (args.lastError) {\n const last = readLastError(args.env);\n if (!last) {\n throw preconditionError(\n 'No failed command is recorded on this machine.',\n 'Run the command that failed again, then \"ekanos feedback --last-error \\\\\"<what you were trying to do>\\\\\"\" — or describe it: \"ekanos feedback \\\\\"<what happened>\\\\\" --command \\\\\"<the command>\\\\\"\".',\n );\n }\n context = {\n ...context,\n command: last.command,\n flags: last.flags,\n errorCode: last.errorCode,\n exitCode: last.exitCode,\n httpStatus: last.httpStatus,\n requestId: last.requestId,\n failedAt: last.failedAt,\n };\n }\n if (args.command !== undefined) {\n const described = describeCommandLine(args.command);\n if (!described.command) {\n throw usageError(\n `\"${args.command.slice(0, 60)}\" names no ekanos command.`,\n 'Pass the command it concerns, e.g. --command \"ekanos teams connect\".',\n );\n }\n context = { ...context, ...described };\n }\n\n const raw =\n typed ||\n 'Filed with --last-error; the reporter gave no description of what they were doing.';\n const redactedText = redactFeedbackText(raw);\n const truncated = redactedText.length > FEEDBACK_MESSAGE_MAX_LENGTH;\n const message = redactedText.slice(0, FEEDBACK_MESSAGE_MAX_LENGTH);\n\n const env = resolveAuthEnvironment(ctx, args.host, args.env, {\n projectDir: args.dir,\n });\n const resolved = await resolveSourceTarget(env, requireSession(env), {\n source: args.source,\n dir: args.dir,\n });\n const client = new FeedbackClient(env, resolved.session);\n const filed = await client.call((token) =>\n submitFeedback(env.host, token, resolved.source, {\n message,\n kind,\n context,\n }),\n );\n\n return ctx.succeed(\n {\n host: env.host,\n source: resolved.source,\n id: filed.id,\n number: filed.number,\n kind,\n redacted: redactedText !== raw,\n truncated,\n context,\n },\n ctx.ui.result({\n title: `Filed feedback #${filed.number}`,\n rows: [\n ['Id', filed.id],\n ['Kind', kind],\n ['Host', shortHost(env.host)],\n ...(context.command\n ? ([['About', `ekanos ${context.command}`]] as Array<\n [string, string]\n >)\n : []),\n ],\n notes: [\n ...(redactedText !== raw\n ? [\n 'Something that looked like a secret or an email was replaced with [redacted] before it was sent.',\n ]\n : []),\n ...(truncated\n ? [\n `The message was cut to ${FEEDBACK_MESSAGE_MAX_LENGTH} characters.`,\n ]\n : []),\n 'When a fix ships, a later command tells you; \"ekanos feedback list\" shows your reports.',\n ],\n }),\n );\n}\n\nasync function runFeedbackList(\n ctx: CliContext,\n args: FeedbackArgs,\n): Promise<ExitCode> {\n const env = resolveAuthEnvironment(ctx, args.host, args.env, {\n projectDir: args.dir,\n });\n const client = new FeedbackClient(env, requireSession(env));\n const list = await client.call((token) => listOwnFeedback(env.host, token));\n\n return ctx.succeed(\n { host: env.host, ...list },\n ctx.ui.result({\n title:\n list.reports.length === 0\n ? 'You have filed no feedback'\n : `Your feedback on ${shortHost(env.host)}`,\n rows: list.reports.map((report): [string, string[]] => [\n `#${report.number}`,\n [\n `${report.kind} · ${statusLabel(report)} · ${report.createdAt.slice(0, 10)}`,\n report.excerpt,\n ...(report.note ? [`Note: ${report.note}`] : []),\n ],\n ]),\n notes:\n list.reports.length === 0\n ? ['\"ekanos feedback \\\\\"<what happened>\\\\\"\" files one.']\n : [],\n }),\n );\n}\n\nfunction statusLabel(report: FeedbackOwnEntry): string {\n if (report.fix?.kind === 'cli') {\n return `fixed in @ekanos/cli ${report.fix.version}`;\n }\n if (report.fix?.kind === 'host') return 'fixed on the host';\n return report.status.replace('_', ' ');\n}\n\nfunction feedbackKind(\n value: string | undefined,\n lastError: boolean,\n): FeedbackKind {\n if (value === undefined) return lastError ? 'bug' : 'other';\n const kind = FEEDBACK_KINDS.find((entry) => entry === value.trim());\n if (kind) return kind;\n throw usageError(\n `\"${value}\" is not a kind of feedback.`,\n `Pass --kind ${FEEDBACK_KINDS.join('|')}.`,\n );\n}\n\n/**\n * The message from stdin, when something is piped in. A terminal, or a\n * stdin that is neither a pipe nor a file (an agent's empty one), is never\n * waited on.\n */\nasync function readPipedMessage(args: FeedbackArgs): Promise<string> {\n if (args.readStdin) {\n return args.stdinIsTTY ? '' : (await args.readStdin()).trim();\n }\n if (args.stdinIsTTY ?? process.stdin.isTTY) return '';\n try {\n const stat = fs.fstatSync(0);\n if (!stat.isFIFO() && !stat.isFile()) return '';\n // Read a byte past the cap, so an over-long message is cut, not refused.\n return fs\n .readFileSync(0, 'utf8')\n .slice(0, FEEDBACK_MESSAGE_MAX_LENGTH * 4)\n .trim();\n } catch {\n return '';\n }\n}\n\n/**\n * `sources feedback [status|enable|disable]` — whether this Source takes\n * reports from `ekanos feedback`. On unless its Source admin turns it off;\n * every change is recorded in the Admin Audit log.\n */\nexport async function runSourceFeedback(\n ctx: CliContext,\n args: {\n host?: string;\n source?: string;\n dir: string;\n env: Record<string, string | undefined>;\n },\n rest: readonly string[],\n): Promise<ExitCode> {\n const [verb = 'status', ...extra] = rest;\n const usage =\n 'Run \"ekanos sources feedback [status|enable|disable] [--source <slug>]\".';\n if (extra.length > 0) {\n throw usageError(`Unexpected argument \"${extra[0]}\".`, usage);\n }\n if (verb !== 'status' && verb !== 'enable' && verb !== 'disable') {\n throw usageError(`Unknown sources feedback subcommand \"${verb}\".`, usage);\n }\n\n const env = resolveAuthEnvironment(ctx, args.host, args.env, {\n projectDir: args.dir,\n });\n const resolved = await resolveSourceTarget(env, requireSession(env), {\n source: args.source,\n dir: args.dir,\n });\n const client = new FeedbackClient(env, resolved.session);\n const setting = await client.call((token) =>\n sourceFeedbackSetting(\n env.host,\n token,\n resolved.source,\n verb === 'status' ? undefined : verb === 'enable',\n ),\n );\n\n const state = setting.enabled ? 'on' : 'off';\n return ctx.succeed(\n { host: env.host, ...setting },\n ctx.ui.result({\n title:\n verb === 'status'\n ? `Feedback from the CLI is ${state} for ${setting.source.slug}`\n : setting.changed\n ? `Turned feedback from the CLI ${state} for ${setting.source.slug}`\n : `Feedback from the CLI was already ${state} for ${setting.source.slug}`,\n tone: setting.enabled ? 'ok' : 'warn',\n rows: [['Source', setting.source.name ?? setting.source.slug]],\n notes: [\n setting.enabled\n ? '\"ekanos feedback\" sends a report to Vastly when someone, or their agent, runs it; nothing is sent on its own.'\n : '\"ekanos feedback\" is refused for this Source, and no fix updates are shown.',\n ...(verb === 'status'\n ? [\n `Its Source admin changes it: \"ekanos sources feedback ${setting.enabled ? 'disable' : 'enable'}\".`,\n ]\n : []),\n ],\n }),\n );\n}\n\nclass FeedbackClient {\n constructor(\n private readonly env: AuthEnvironment,\n private session: StoredSession,\n ) {}\n\n async call<T>(\n send: (accessToken: string) => Promise<FeedbackApiResult<T>>,\n ): Promise<T> {\n let result = await send(this.session.accessToken);\n if (result.status === 'unauthorized') {\n this.session = await refreshStoredSession(this.env, this.session);\n result = await send(this.session.accessToken);\n }\n if (result.status === 'ok') return result.data;\n throw authRequiredError(\n `The session for ${this.env.host} could not authorize the feedback call.`,\n loginHint(this.env),\n );\n }\n}\n"]}
@@ -12,6 +12,7 @@ import { resolveSourceTarget } from '../source-target.js';
12
12
  import { stillUnauthorizedSourceSeats } from '../sources-api.js';
13
13
  import { listProductScopes, setScopeProduct } from '../teams-api.js';
14
14
  import { pluralize, shortHost } from '../ui.js';
15
+ import { runSourceFeedback } from './feedback.js';
15
16
  import { scopeDeprecationNotice } from './scope-notice.js';
16
17
  import { runSourcePeople, runSourceRoles } from './sources-roles.js';
17
18
  /**
@@ -32,8 +33,10 @@ export async function runSources(ctx, args) {
32
33
  return runSourceRoles(ctx, args, rest);
33
34
  if (subcommand === 'people')
34
35
  return runSourcePeople(ctx, args, rest);
36
+ if (subcommand === 'feedback')
37
+ return runSourceFeedback(ctx, args, rest);
35
38
  if (subcommand !== 'products') {
36
- throw usageError(`Unknown sources subcommand "${subcommand}".`, 'Run "ekanos sources" to list your sources, "ekanos sources products [enable|disable <product>]", "ekanos sources scopes [add|remove <scope> <product>]", "ekanos sources roles [list|create|update|delete <role>]" or "ekanos sources people".');
39
+ throw usageError(`Unknown sources subcommand "${subcommand}".`, 'Run "ekanos sources" to list your sources, "ekanos sources products [enable|disable <product>]", "ekanos sources scopes [add|remove <scope> <product>]", "ekanos sources roles [list|create|update|delete <role>]", "ekanos sources people" or "ekanos sources feedback [status|enable|disable]".');
37
40
  }
38
41
  return runProducts(ctx, args, rest);
39
42
  }