@experiture/xyra-cli 0.4.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 (66) hide show
  1. package/README.md +119 -0
  2. package/dist/auth/browser.js +22 -0
  3. package/dist/auth/browser.js.map +1 -0
  4. package/dist/auth/loopbackServer.js +92 -0
  5. package/dist/auth/loopbackServer.js.map +1 -0
  6. package/dist/auth/oauthClient.js +98 -0
  7. package/dist/auth/oauthClient.js.map +1 -0
  8. package/dist/auth/pkce.js +22 -0
  9. package/dist/auth/pkce.js.map +1 -0
  10. package/dist/auth/session.js +122 -0
  11. package/dist/auth/session.js.map +1 -0
  12. package/dist/auth/tokenStore.js +93 -0
  13. package/dist/auth/tokenStore.js.map +1 -0
  14. package/dist/commands/aliasResolver.js +118 -0
  15. package/dist/commands/aliasResolver.js.map +1 -0
  16. package/dist/commands/docs.js +43 -0
  17. package/dist/commands/docs.js.map +1 -0
  18. package/dist/commands/env.js +41 -0
  19. package/dist/commands/env.js.map +1 -0
  20. package/dist/commands/generatedCommandRegistry.js +76 -0
  21. package/dist/commands/generatedCommandRegistry.js.map +1 -0
  22. package/dist/commands/login.js +66 -0
  23. package/dist/commands/login.js.map +1 -0
  24. package/dist/commands/mcp.js +45 -0
  25. package/dist/commands/mcp.js.map +1 -0
  26. package/dist/commands/mcpContext.js +66 -0
  27. package/dist/commands/mcpContext.js.map +1 -0
  28. package/dist/commands/session.js +89 -0
  29. package/dist/commands/session.js.map +1 -0
  30. package/dist/commands/tools.js +204 -0
  31. package/dist/commands/tools.js.map +1 -0
  32. package/dist/config/configStore.js +102 -0
  33. package/dist/config/configStore.js.map +1 -0
  34. package/dist/config/environments.js +27 -0
  35. package/dist/config/environments.js.map +1 -0
  36. package/dist/docs/jsonExporter.js +52 -0
  37. package/dist/docs/jsonExporter.js.map +1 -0
  38. package/dist/docs/markdownExporter.js +66 -0
  39. package/dist/docs/markdownExporter.js.map +1 -0
  40. package/dist/errors/CliError.js +35 -0
  41. package/dist/errors/CliError.js.map +1 -0
  42. package/dist/index.js +159 -0
  43. package/dist/index.js.map +1 -0
  44. package/dist/mcp/confirmation.js +57 -0
  45. package/dist/mcp/confirmation.js.map +1 -0
  46. package/dist/mcp/mcpClient.js +126 -0
  47. package/dist/mcp/mcpClient.js.map +1 -0
  48. package/dist/mcp/mcpError.js +20 -0
  49. package/dist/mcp/mcpError.js.map +1 -0
  50. package/dist/mcp/resourceMetadata.js +34 -0
  51. package/dist/mcp/resourceMetadata.js.map +1 -0
  52. package/dist/metadata/commandAliasSchema.js +51 -0
  53. package/dist/metadata/commandAliasSchema.js.map +1 -0
  54. package/dist/metadata/xyraToolDescriptor.js +20 -0
  55. package/dist/metadata/xyraToolDescriptor.js.map +1 -0
  56. package/dist/output/console.js +36 -0
  57. package/dist/output/console.js.map +1 -0
  58. package/dist/output/formatters.js +73 -0
  59. package/dist/output/formatters.js.map +1 -0
  60. package/dist/output/mcpErrorFormatter.js +55 -0
  61. package/dist/output/mcpErrorFormatter.js.map +1 -0
  62. package/dist/prompt/confirmPrompt.js +31 -0
  63. package/dist/prompt/confirmPrompt.js.map +1 -0
  64. package/dist/version.js +10 -0
  65. package/dist/version.js.map +1 -0
  66. package/package.json +59 -0
package/README.md ADDED
@@ -0,0 +1,119 @@
1
+ # @experiture/xyra-cli
2
+
3
+ Headless command-line client for the **Xyra MCP** server. It signs in as a
4
+ delegated user via OAuth 2.0 Authorization Code + PKCE, then discovers and
5
+ invokes Xyra tools over MCP JSON-RPC. Tool visibility and execution are governed
6
+ by the signed-in user's real product roles and concrete permissions.
7
+
8
+ > CLI-0 … CLI-9 are implemented. CLI-10 is the remaining enterprise-maturity
9
+ > backlog (completion, richer non-secret config/profile commands, optional
10
+ > metadata cache, CI/service-principal mode, release trust, and diagnostics).
11
+ > Spec: `docs/todo/MCP/TODO-XYRA-CLI-HEADLESS-APPLICATION-RUNNER.md` (in the
12
+ > monorepo).
13
+
14
+ ## Build
15
+
16
+ ```bash
17
+ npm install # from the ExperitureAI-Headless workspace root
18
+ npm run build --workspace=apps/xyra-cli
19
+ ```
20
+
21
+ The `xyra` binary is `dist/index.js`.
22
+
23
+ ## Install
24
+
25
+ Install the public package from npm:
26
+
27
+ ```bash
28
+ npm install -g @experiture/xyra-cli
29
+ xyra --version
30
+ ```
31
+
32
+ Releases are published to public npm from a versioned `xyra-cli-v*` Git tag.
33
+ The workflow builds, tests, packs, publishes with npm trusted publishing, and
34
+ smoke-installs the exact public package. The first public release is published
35
+ manually by an Experiture npm owner, then the package's npm settings should be
36
+ connected to `.github/workflows/publish-xyra-cli.yml` as its trusted publisher.
37
+
38
+ For local smoke testing before publishing, install from a packed tarball
39
+ (keychain support installs automatically where the native module builds,
40
+ otherwise the CLI falls back per the security model below):
41
+
42
+ ```bash
43
+ npm pack --workspace=apps/xyra-cli --pack-destination /tmp
44
+ npm install -g /tmp/experiture-xyra-cli-0.4.0.tgz
45
+ xyra --version
46
+ ```
47
+
48
+ For development, `npm link` from `apps/xyra-cli` keeps the global `xyra`
49
+ pointing at your working tree.
50
+
51
+ ## Security model
52
+
53
+ - **Public client, no secret.** `experiture-xyra-mcp-delegated` uses PKCE
54
+ (S256); no client secret is stored or sent.
55
+ - **Exact loopback redirect.** RFC 8252 loopback with a dynamic port and the
56
+ exact registered path `/callback/QYfSVwRg9okE`. State is verified on callback;
57
+ a mismatch aborts and stores nothing.
58
+ - **Short access tokens + refresh.** 300 s access tokens refreshed silently via
59
+ `offline_access`. The access-token lifetime is intentionally *not* raised.
60
+ Auth rotates refresh tokens on every refresh, so the CLI serializes refresh
61
+ per environment/client and re-reads the token store under lock before
62
+ exchanging. The lock is heartbeat-backed so slow refreshes are not mistaken
63
+ for abandoned work. Parallel CLI commands must not consume and revoke the
64
+ same refresh-token family.
65
+ - **Token storage.** OS keychain (keytar, loaded dynamically) by default. The
66
+ encrypted-file fallback is disabled unless
67
+ `XYRA_CLI_ALLOW_INSECURE_TOKEN_STORE=true` (dev only). Tokens are never
68
+ printed or logged; diagnostic output is redacted.
69
+ - **MCP-only.** The CLI talks only to the MCP endpoint — no direct
70
+ Journey/CDP/Auth/Billing API bypass, no fabricated identity headers.
71
+
72
+ ## Commands
73
+
74
+ ```bash
75
+ xyra env list | env use <name> | env show # connection profiles (dev, local)
76
+ xyra login [--no-browser] # delegated OAuth sign-in
77
+ xyra whoami [--json] # identity, tenant/product, roles, OAuth client and expiry (no token)
78
+ xyra logout # remove the stored token
79
+ xyra mcp metadata [--json] # public OAuth resource metadata (no login)
80
+ xyra mcp initialize [--json] # MCP handshake / capabilities
81
+ xyra tools list [--domain <id>] [--task <k>] [--limit <n>] [--json]
82
+ xyra tools describe <toolKey> [--json]
83
+ xyra tools schema <toolKey> # JSON input schema only
84
+ xyra tools call <toolKey> --arg k=v [--input <json>|--input-file <path>] [--json|--raw]
85
+ ```
86
+
87
+ Live tool visibility is owned by MCP, not by a duplicated CLI policy layer:
88
+ `tools/list` returns only the tools visible to the current token's concrete
89
+ permissions, and `tools/call` still goes through the governed MCP execution rail
90
+ with Tool Registry guardrails, operation permissions, confirmations,
91
+ idempotency, and audit. Future CLI-10 work may improve cached help/completion,
92
+ but actual calls always go back through MCP.
93
+
94
+ `--env <name>` targets a specific environment for a single command **without
95
+ persisting** it — the active environment on disk is unchanged. Use
96
+ `xyra env use <name>` to change the persistent default.
97
+
98
+ Canonical Xyra error codes and correlation IDs from MCP results are preserved
99
+ verbatim; local failures use stable `XYRA.CLI.*` codes. Any tool that returns
100
+ `isError` yields exit code 1 while still printing its payload.
101
+
102
+ `--json` and `--raw` reproduce the structured payload exactly, with one
103
+ safety-net exception: fields whose **names** are secret-bearing (`access_token`,
104
+ `refresh_token`, `authorization`, `cookie`, `password`, …) are replaced with
105
+ `***redacted***`. MCP tool results do not normally contain such fields, so in
106
+ practice output is byte-for-byte the server payload; the redaction only ever
107
+ triggers on genuinely secret-named keys.
108
+
109
+ ## Test
110
+
111
+ ```bash
112
+ npm test --workspace=apps/xyra-cli
113
+ ```
114
+
115
+ Covers PKCE (S256/length), secret redaction, config validation (gates G1/G2),
116
+ encrypted token round-trip, silent refresh, rotated refresh-token persistence,
117
+ concurrent refresh serialization, loopback state-mismatch rejection, JSON-RPC
118
+ 401 auth handling, `tools/list` pagination, and canonical error/correlation-id
119
+ preservation.
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.openBrowser = openBrowser;
4
+ const node_child_process_1 = require("node:child_process");
5
+ /**
6
+ * Best-effort cross-platform browser open with no external dependency.
7
+ * Returns false if it could not launch (caller then prints the URL).
8
+ */
9
+ function openBrowser(url) {
10
+ try {
11
+ const platform = process.platform;
12
+ const command = platform === 'darwin' ? 'open' : platform === 'win32' ? 'cmd' : 'xdg-open';
13
+ const args = platform === 'win32' ? ['/c', 'start', '""', url] : [url];
14
+ const child = (0, node_child_process_1.spawn)(command, args, { detached: true, stdio: 'ignore' });
15
+ child.unref();
16
+ return true;
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ }
22
+ //# sourceMappingURL=browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser.js","sourceRoot":"","sources":["../../src/auth/browser.ts"],"names":[],"mappings":";;AAMA,kCAYC;AAlBD,2DAA2C;AAE3C;;;GAGG;AACH,SAAgB,WAAW,CAAC,GAAW;IACrC,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;QAClC,MAAM,OAAO,GACX,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,UAAU,CAAC;QAC7E,MAAM,IAAI,GAAG,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;QACvE,MAAM,KAAK,GAAG,IAAA,0BAAK,EAAC,OAAO,EAAE,IAAI,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC;QACxE,KAAK,CAAC,KAAK,EAAE,CAAC;QACd,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC"}
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LoopbackListener = void 0;
4
+ const node_http_1 = require("node:http");
5
+ const CliError_1 = require("../errors/CliError");
6
+ const SUCCESS_HTML = `<!doctype html><html><head><meta charset="utf-8"><title>Xyra CLI</title></head>
7
+ <body style="font-family:system-ui;max-width:32rem;margin:6rem auto;text-align:center">
8
+ <h2>Authentication complete</h2><p>You may close this window and return to your terminal.</p></body></html>`;
9
+ function failureHtml(reason) {
10
+ return `<!doctype html><html><head><meta charset="utf-8"><title>Xyra CLI</title></head>
11
+ <body style="font-family:system-ui;max-width:32rem;margin:6rem auto;text-align:center">
12
+ <h2>Authentication failed</h2><p>${reason.replace(/[<>]/g, '')}</p><p>Return to your terminal.</p></body></html>`;
13
+ }
14
+ /**
15
+ * One-shot loopback listener. `start()` binds 127.0.0.1 on a dynamic port and
16
+ * returns the exact redirect_uri (with that port and the required exact path -
17
+ * gate G1). `waitForCode()` resolves once the browser calls back with a code
18
+ * whose state matches; state mismatch or an error param rejects and stores nothing.
19
+ */
20
+ class LoopbackListener {
21
+ callbackPath;
22
+ expectedState;
23
+ server;
24
+ redirectUri;
25
+ constructor(callbackPath, expectedState) {
26
+ this.callbackPath = callbackPath;
27
+ this.expectedState = expectedState;
28
+ }
29
+ start() {
30
+ return new Promise((resolve, reject) => {
31
+ this.server = (0, node_http_1.createServer)();
32
+ this.server.on('error', reject);
33
+ this.server.listen(0, '127.0.0.1', () => {
34
+ const info = this.server.address();
35
+ this.redirectUri = `http://127.0.0.1:${info.port}${this.callbackPath}`;
36
+ resolve(this.redirectUri);
37
+ });
38
+ });
39
+ }
40
+ waitForCode(timeoutMs = 180_000) {
41
+ if (!this.server || !this.redirectUri) {
42
+ return Promise.reject(new CliError_1.CliError(CliError_1.CliErrorCodes.OAuthCallbackError, 'Loopback listener was not started.'));
43
+ }
44
+ return new Promise((resolve, reject) => {
45
+ const timer = setTimeout(() => {
46
+ this.close();
47
+ reject(new CliError_1.CliError(CliError_1.CliErrorCodes.OAuthCallbackError, `Login timed out after ${Math.round(timeoutMs / 1000)}s.`));
48
+ }, timeoutMs);
49
+ timer.unref();
50
+ const done = (status, html, res, err, code) => {
51
+ res.writeHead(status, { 'content-type': 'text/html' });
52
+ res.end(html);
53
+ clearTimeout(timer);
54
+ this.close();
55
+ if (err)
56
+ reject(err);
57
+ else
58
+ resolve(code);
59
+ };
60
+ this.server.on('request', (req, res) => {
61
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
62
+ if (url.pathname !== this.callbackPath) {
63
+ res.writeHead(404, { 'content-type': 'text/plain' });
64
+ res.end('Not found');
65
+ return;
66
+ }
67
+ const error = url.searchParams.get('error');
68
+ const code = url.searchParams.get('code');
69
+ const state = url.searchParams.get('state');
70
+ if (error) {
71
+ done(400, failureHtml(`Authorization error: ${error}`), res, new CliError_1.CliError(CliError_1.CliErrorCodes.OAuthCallbackError, `Authorization server returned error: ${error}`));
72
+ return;
73
+ }
74
+ if (!state || state !== this.expectedState) {
75
+ done(400, failureHtml('State mismatch.'), res, new CliError_1.CliError(CliError_1.CliErrorCodes.OAuthStateMismatch, 'OAuth state did not match. Aborting login; no token stored.'));
76
+ return;
77
+ }
78
+ if (!code) {
79
+ done(400, failureHtml('Missing authorization code.'), res, new CliError_1.CliError(CliError_1.CliErrorCodes.OAuthCallbackError, 'Callback did not include an authorization code.'));
80
+ return;
81
+ }
82
+ done(200, SUCCESS_HTML, res, undefined, code);
83
+ });
84
+ });
85
+ }
86
+ close() {
87
+ this.server?.close();
88
+ this.server = undefined;
89
+ }
90
+ }
91
+ exports.LoopbackListener = LoopbackListener;
92
+ //# sourceMappingURL=loopbackServer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loopbackServer.js","sourceRoot":"","sources":["../../src/auth/loopbackServer.ts"],"names":[],"mappings":";;;AAAA,yCAAkF;AAElF,iDAA6D;AAE7D,MAAM,YAAY,GAAG;;4GAEuF,CAAC;AAE7G,SAAS,WAAW,CAAC,MAAc;IACjC,OAAO;;mCAE0B,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,mDAAmD,CAAC;AAClH,CAAC;AAED;;;;;GAKG;AACH,MAAa,gBAAgB;IAKR;IACA;IALX,MAAM,CAAU;IAChB,WAAW,CAAU;IAE7B,YACmB,YAAoB,EACpB,aAAqB;QADrB,iBAAY,GAAZ,YAAY,CAAQ;QACpB,kBAAa,GAAb,aAAa,CAAQ;IACrC,CAAC;IAEJ,KAAK;QACH,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,IAAI,CAAC,MAAM,GAAG,IAAA,wBAAY,GAAE,CAAC;YAC7B,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;YAChC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,WAAW,EAAE,GAAG,EAAE;gBACtC,MAAM,IAAI,GAAG,IAAI,CAAC,MAAO,CAAC,OAAO,EAAiB,CAAC;gBACnD,IAAI,CAAC,WAAW,GAAG,oBAAoB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;gBACvE,OAAO,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;YAC5B,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;IAED,WAAW,CAAC,SAAS,GAAG,OAAO;QAC7B,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,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AE,CAAC;QACrB,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;IAC1B,CAAC;CACF;AAxED,4CAwEC"}
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildAuthorizeUrl = buildAuthorizeUrl;
4
+ exports.exchangeCode = exchangeCode;
5
+ exports.refreshToken = refreshToken;
6
+ exports.decodeJwtClaims = decodeJwtClaims;
7
+ exports.toStoredToken = toStoredToken;
8
+ const CliError_1 = require("../errors/CliError");
9
+ /** Build the browser authorization URL (authorization_code + PKCE, public client). */
10
+ function buildAuthorizeUrl(env, params) {
11
+ const url = new URL(env.authorizationEndpoint);
12
+ url.searchParams.set('response_type', 'code');
13
+ url.searchParams.set('client_id', env.clientId);
14
+ url.searchParams.set('redirect_uri', params.redirectUri);
15
+ url.searchParams.set('resource', env.oauthResource);
16
+ url.searchParams.set('scope', params.scopes.join(' '));
17
+ url.searchParams.set('state', params.state);
18
+ url.searchParams.set('code_challenge', params.codeChallenge);
19
+ url.searchParams.set('code_challenge_method', 'S256');
20
+ return url.toString();
21
+ }
22
+ async function postToken(env, body) {
23
+ let response;
24
+ try {
25
+ response = await fetch(env.tokenEndpoint, {
26
+ method: 'POST',
27
+ headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
28
+ body: body.toString(),
29
+ });
30
+ }
31
+ catch (cause) {
32
+ throw new CliError_1.CliError(CliError_1.CliErrorCodes.TokenExchangeFailed, `Could not reach token endpoint ${env.tokenEndpoint}.`, cause?.message);
33
+ }
34
+ const text = await response.text();
35
+ if (!response.ok) {
36
+ // Never surface the raw body verbatim (may echo sensitive params); extract error code only.
37
+ let errCode = `HTTP ${response.status}`;
38
+ try {
39
+ const parsed = JSON.parse(text);
40
+ if (parsed.error)
41
+ errCode = parsed.error_description ? `${parsed.error}: ${parsed.error_description}` : parsed.error;
42
+ }
43
+ catch {
44
+ /* non-JSON body; keep HTTP status only */
45
+ }
46
+ throw new CliError_1.CliError(CliError_1.CliErrorCodes.TokenExchangeFailed, `Token exchange failed (${errCode}).`);
47
+ }
48
+ return JSON.parse(text);
49
+ }
50
+ /** Exchange an authorization code for tokens (public client: no client_secret). */
51
+ function exchangeCode(env, input) {
52
+ const body = new URLSearchParams({
53
+ grant_type: 'authorization_code',
54
+ client_id: env.clientId,
55
+ code: input.code,
56
+ code_verifier: input.codeVerifier,
57
+ redirect_uri: input.redirectUri,
58
+ resource: env.oauthResource,
59
+ });
60
+ return postToken(env, body);
61
+ }
62
+ /** Refresh the access token using a refresh token (gate G2). */
63
+ function refreshToken(env, refresh) {
64
+ const body = new URLSearchParams({
65
+ grant_type: 'refresh_token',
66
+ client_id: env.clientId,
67
+ refresh_token: refresh,
68
+ resource: env.oauthResource,
69
+ });
70
+ return postToken(env, body);
71
+ }
72
+ /** Decode a JWT payload without verifying (local display only; never trusted for authz). */
73
+ function decodeJwtClaims(accessToken) {
74
+ const parts = accessToken.split('.');
75
+ if (parts.length !== 3)
76
+ return {};
77
+ try {
78
+ const json = Buffer.from(parts[1].replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');
79
+ return JSON.parse(json);
80
+ }
81
+ catch {
82
+ return {};
83
+ }
84
+ }
85
+ function toStoredToken(response) {
86
+ const claims = decodeJwtClaims(response.access_token);
87
+ const subjectType = claims['sub_type'] === 'client' ? 'client' : 'user';
88
+ return {
89
+ accessToken: response.access_token,
90
+ refreshToken: response.refresh_token,
91
+ tokenType: response.token_type || 'Bearer',
92
+ scope: response.scope,
93
+ // 30s safety skew so we refresh before the server considers it expired.
94
+ expiresAt: Date.now() + Math.max(0, (response.expires_in - 30)) * 1000,
95
+ subjectType,
96
+ };
97
+ }
98
+ //# sourceMappingURL=oauthClient.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauthClient.js","sourceRoot":"","sources":["../../src/auth/oauthClient.ts"],"names":[],"mappings":";;AAoBA,8CAWC;AA6BD,oCAaC;AAGD,oCAQC;AAGD,0CASC;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Q;QAC1C,KAAK,EAAE,QAAQ,CAAC,KAAK;QACrB,wEAAwE;QACxE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,QAAQ,CAAC,UAAU,GAAG,EAAE,CAAC,CAAC,GAAG,IAAI;QACtE,WAAW;KACZ,CAAC;AACJ,CAAC"}
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createPkcePair = createPkcePair;
4
+ exports.createState = createState;
5
+ const node_crypto_1 = require("node:crypto");
6
+ function base64Url(buffer) {
7
+ return buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
8
+ }
9
+ /**
10
+ * RFC 7636 PKCE. Verifier is 43-128 chars of the unreserved alphabet;
11
+ * we use 32 random bytes -> 43 base64url chars. Challenge is S256.
12
+ */
13
+ function createPkcePair() {
14
+ const codeVerifier = base64Url((0, node_crypto_1.randomBytes)(32));
15
+ const codeChallenge = base64Url((0, node_crypto_1.createHash)('sha256').update(codeVerifier).digest());
16
+ return { codeVerifier, codeChallenge, codeChallengeMethod: 'S256' };
17
+ }
18
+ /** Opaque CSRF state for the authorization request. */
19
+ function createState() {
20
+ return base64Url((0, node_crypto_1.randomBytes)(24));
21
+ }
22
+ //# sourceMappingURL=pkce.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pkce.js","sourceRoot":"","sources":["../../src/auth/pkce.ts"],"names":[],"mappings":";;AAgBA,wCAIC;AAGD,kCAEC;AAzBD,6CAAsD;AAEtD,SAAS,SAAS,CAAC,MAAc;IAC/B,OAAO,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AAC9F,CAAC;AAQD;;;GAGG;AACH,SAAgB,cAAc;IAC5B,MAAM,YAAY,GAAG,SAAS,CAAC,IAAA,yBAAW,EAAC,EAAE,CAAC,CAAC,CAAC;IAChD,MAAM,aAAa,GAAG,SAAS,CAAC,IAAA,wBAAU,EAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC;IACpF,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,EAAE,CAAC;AACtE,CAAC;AAED,uDAAuD;AACvD,SAAgB,WAAW;IACzB,OAAO,SAAS,CAAC,IAAA,yBAAW,EAAC,EAAE,CAAC,CAAC,CAAC;AACpC,CAAC"}
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.accountKey = accountKey;
4
+ exports.getValidToken = getValidToken;
5
+ const CliError_1 = require("../errors/CliError");
6
+ const oauthClient_1 = require("./oauthClient");
7
+ const node_crypto_1 = require("node:crypto");
8
+ const node_fs_1 = require("node:fs");
9
+ const node_os_1 = require("node:os");
10
+ const node_path_1 = require("node:path");
11
+ /** Account key under which a token is stored (one login per environment). */
12
+ function accountKey(env) {
13
+ return `${env.name}:${env.clientId}`;
14
+ }
15
+ const REFRESH_LOCK_TIMEOUT_MS = 20_000;
16
+ const REFRESH_LOCK_STALE_MS = 60_000;
17
+ const REFRESH_LOCK_HEARTBEAT_MS = 5_000;
18
+ const REFRESH_LOCK_DIR = (0, node_path_1.join)((0, node_os_1.tmpdir)(), 'xyra-cli-refresh-locks');
19
+ function sleep(ms) {
20
+ return new Promise((resolve) => setTimeout(resolve, ms));
21
+ }
22
+ function refreshLockPath(account) {
23
+ const digest = (0, node_crypto_1.createHash)('sha256').update(account).digest('hex').slice(0, 32);
24
+ return (0, node_path_1.join)(REFRESH_LOCK_DIR, `${digest}.lock`);
25
+ }
26
+ function writeRefreshLockHeartbeat(fd) {
27
+ (0, node_fs_1.ftruncateSync)(fd, 0);
28
+ (0, node_fs_1.writeSync)(fd, JSON.stringify({ pid: process.pid, updatedAt: new Date().toISOString() }), 0, 'utf8');
29
+ }
30
+ async function withRefreshLock(account, action) {
31
+ const path = refreshLockPath(account);
32
+ (0, node_fs_1.mkdirSync)(REFRESH_LOCK_DIR, { recursive: true, mode: 0o700 });
33
+ const startedAt = Date.now();
34
+ let fd = null;
35
+ let heartbeat = null;
36
+ while (fd === null) {
37
+ try {
38
+ fd = (0, node_fs_1.openSync)(path, 'wx', 0o600);
39
+ writeRefreshLockHeartbeat(fd);
40
+ heartbeat = setInterval(() => {
41
+ if (fd !== null)
42
+ writeRefreshLockHeartbeat(fd);
43
+ }, REFRESH_LOCK_HEARTBEAT_MS);
44
+ heartbeat.unref?.();
45
+ }
46
+ catch (error) {
47
+ if (error?.code !== 'EEXIST')
48
+ throw error;
49
+ try {
50
+ const ageMs = Date.now() - Number((0, node_fs_1.statSync)(path).mtimeMs);
51
+ if (ageMs > REFRESH_LOCK_STALE_MS) {
52
+ (0, node_fs_1.unlinkSync)(path);
53
+ continue;
54
+ }
55
+ }
56
+ catch {
57
+ continue;
58
+ }
59
+ if (Date.now() - startedAt > REFRESH_LOCK_TIMEOUT_MS) {
60
+ throw new CliError_1.CliError(CliError_1.CliErrorCodes.TokenExchangeFailed, 'Timed out waiting for another Xyra CLI process to refresh the session.', 'Retry the command. If this repeats, run xyra logout then xyra login.');
61
+ }
62
+ await sleep(150);
63
+ }
64
+ }
65
+ try {
66
+ return await action();
67
+ }
68
+ finally {
69
+ if (heartbeat)
70
+ clearInterval(heartbeat);
71
+ try {
72
+ if (fd !== null)
73
+ (0, node_fs_1.closeSync)(fd);
74
+ }
75
+ finally {
76
+ try {
77
+ (0, node_fs_1.unlinkSync)(path);
78
+ }
79
+ catch {
80
+ /* lock already gone */
81
+ }
82
+ }
83
+ }
84
+ }
85
+ /**
86
+ * Return a non-expired access token for the environment, silently refreshing
87
+ * with the refresh token when the 300s access token has lapsed (gate G2).
88
+ * Throws NotAuthenticated when there is no usable session.
89
+ */
90
+ async function getValidToken(env, store) {
91
+ const key = accountKey(env);
92
+ const stored = await store.get(key);
93
+ if (!stored) {
94
+ throw new CliError_1.CliError(CliError_1.CliErrorCodes.NotAuthenticated, `Not signed in to '${env.name}'.`, "Run 'xyra login'.");
95
+ }
96
+ if (Date.now() < stored.expiresAt) {
97
+ return stored;
98
+ }
99
+ if (!stored.refreshToken) {
100
+ throw new CliError_1.CliError(CliError_1.CliErrorCodes.NotAuthenticated, `Session for '${env.name}' expired and no refresh token is available.`, "Run 'xyra login' again (ensure 'offline_access' scope).");
101
+ }
102
+ return withRefreshLock(key, async () => {
103
+ const latest = await store.get(key);
104
+ if (!latest) {
105
+ throw new CliError_1.CliError(CliError_1.CliErrorCodes.NotAuthenticated, `Not signed in to '${env.name}'.`, "Run 'xyra login'.");
106
+ }
107
+ if (Date.now() < latest.expiresAt) {
108
+ return latest;
109
+ }
110
+ if (!latest.refreshToken) {
111
+ throw new CliError_1.CliError(CliError_1.CliErrorCodes.NotAuthenticated, `Session for '${env.name}' expired and no refresh token is available.`, "Run 'xyra login' again (ensure 'offline_access' scope).");
112
+ }
113
+ const refreshed = (0, oauthClient_1.toStoredToken)(await (0, oauthClient_1.refreshToken)(env, latest.refreshToken));
114
+ // Keep the prior refresh token only for non-rotating providers. Auth returns
115
+ // a rotated refresh_token; persisting it here is mandatory.
116
+ if (!refreshed.refreshToken)
117
+ refreshed.refreshToken = latest.refreshToken;
118
+ await store.set(key, refreshed);
119
+ return refreshed;
120
+ });
121
+ }
122
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../../src/auth/session.ts"],"names":[],"mappings":";;AAUA,gCAEC;AAkFD,sCAwCC;AAtID,iDAA6D;AAE7D,+CAA4D;AAE5D,6CAAyC;AACzC,qCAAyG;AACzG,qCAAiC;AACjC,yCAAiC;AAEjC,6EAA6E;AAC7E,SAAgB,UAAU,CAAC,GAAoB;IAC7C,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AAI,EAAE,mBAAmB,CAAC,CAAC;QAC7G,CAAC;QACD,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;YAClC,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,IAAI,CAAC,MAAM,CAAC,YAAY,EAAE,CAAC;YACzB,MAAM,IAAI,mBAAQ,CAChB,wBAAa,CAAC,gBAAgB,EAC9B,gBAAgB,GAAG,CAAC,IAAI,8CAA8C,EACtE,yDAAyD,CAC1D,CAAC;QACJ,CAAC;QAED,MAAM,SAAS,GAAG,IAAA,2BAAa,EAAC,MAAM,IAAA,0BAAY,EAAC,GAAG,EAAE,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC;QAC9E,6EAA6E;QAC7E,4DAA4D;QAC5D,IAAI,CAAC,SAAS,CAAC,YAAY;YAAE,SAAS,CAAC,YAAY,GAAG,MAAM,CAAC,YAAY,CAAC;QAC1E,MAAM,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;QAChC,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createTokenStore = createTokenStore;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const node_fs_1 = require("node:fs");
6
+ const node_os_1 = require("node:os");
7
+ const node_path_1 = require("node:path");
8
+ const CliError_1 = require("../errors/CliError");
9
+ const SERVICE = 'xyra-cli';
10
+ /** OS keychain via keytar, loaded dynamically so the package never hard-depends on the native module. */
11
+ async function tryKeychainStore() {
12
+ try {
13
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
14
+ const keytar = require('keytar');
15
+ return {
16
+ backend: 'os-keychain',
17
+ async get(account) {
18
+ const raw = await keytar.getPassword(SERVICE, account);
19
+ return raw ? JSON.parse(raw) : null;
20
+ },
21
+ async set(account, token) {
22
+ await keytar.setPassword(SERVICE, account, JSON.stringify(token));
23
+ },
24
+ async delete(account) {
25
+ await keytar.deletePassword(SERVICE, account);
26
+ },
27
+ };
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ /**
34
+ * Encrypted-file fallback. Explicitly opt-in via XYRA_CLI_ALLOW_INSECURE_TOKEN_STORE.
35
+ * AES-256-GCM with a per-install key kept in a sibling 0600 file. This is
36
+ * obfuscation, not hardware-backed secrecy (the key sits next to the data),
37
+ * which is precisely why it is gated behind an insecure flag.
38
+ */
39
+ class FileTokenStore {
40
+ backend = 'encrypted-file';
41
+ dir;
42
+ keyPath;
43
+ constructor(dir) {
44
+ this.dir = dir ?? (0, node_path_1.join)((0, node_os_1.homedir)(), '.config', 'xyra', 'tokens');
45
+ this.keyPath = (0, node_path_1.join)(this.dir, '.key');
46
+ }
47
+ key() {
48
+ (0, node_fs_1.mkdirSync)(this.dir, { recursive: true });
49
+ if (!(0, node_fs_1.existsSync)(this.keyPath)) {
50
+ (0, node_fs_1.writeFileSync)(this.keyPath, (0, node_crypto_1.randomBytes)(32).toString('base64'), { mode: 0o600 });
51
+ }
52
+ return (0, node_crypto_1.scryptSync)((0, node_fs_1.readFileSync)(this.keyPath, 'utf8'), 'xyra-cli-token', 32);
53
+ }
54
+ file(account) {
55
+ return (0, node_path_1.join)(this.dir, `${Buffer.from(account).toString('hex')}.enc`);
56
+ }
57
+ async get(account) {
58
+ const file = this.file(account);
59
+ if (!(0, node_fs_1.existsSync)(file))
60
+ return null;
61
+ const [ivB64, tagB64, dataB64] = (0, node_fs_1.readFileSync)(file, 'utf8').split(':');
62
+ const decipher = (0, node_crypto_1.createDecipheriv)('aes-256-gcm', this.key(), Buffer.from(ivB64, 'base64'));
63
+ decipher.setAuthTag(Buffer.from(tagB64, 'base64'));
64
+ const plain = Buffer.concat([decipher.update(Buffer.from(dataB64, 'base64')), decipher.final()]);
65
+ return JSON.parse(plain.toString('utf8'));
66
+ }
67
+ async set(account, token) {
68
+ (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(this.file(account)), { recursive: true });
69
+ const iv = (0, node_crypto_1.randomBytes)(12);
70
+ const cipher = (0, node_crypto_1.createCipheriv)('aes-256-gcm', this.key(), iv);
71
+ const enc = Buffer.concat([cipher.update(JSON.stringify(token), 'utf8'), cipher.final()]);
72
+ const payload = [iv.toString('base64'), cipher.getAuthTag().toString('base64'), enc.toString('base64')].join(':');
73
+ (0, node_fs_1.writeFileSync)(this.file(account), payload, { mode: 0o600 });
74
+ }
75
+ async delete(account) {
76
+ const file = this.file(account);
77
+ if ((0, node_fs_1.existsSync)(file))
78
+ (0, node_fs_1.rmSync)(file);
79
+ }
80
+ }
81
+ async function createTokenStore(options) {
82
+ if (!options?.forceFile) {
83
+ const keychain = await tryKeychainStore();
84
+ if (keychain)
85
+ return keychain;
86
+ }
87
+ const allowInsecure = options?.forceFile || process.env.XYRA_CLI_ALLOW_INSECURE_TOKEN_STORE === 'true';
88
+ if (!allowInsecure) {
89
+ throw new CliError_1.CliError(CliError_1.CliErrorCodes.TokenStoreUnavailable, 'Secure OS keychain is unavailable and the encrypted-file fallback is disabled.', 'Set XYRA_CLI_ALLOW_INSECURE_TOKEN_STORE=true to use the encrypted-file store (dev only).');
90
+ }
91
+ return new FileTokenStore(options?.dir);
92
+ }
93
+ //# sourceMappingURL=tokenStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tokenStore.js","sourceRoot":"","sources":["../../src/auth/tokenStore.ts"],"names":[],"mappings":";;AAyGA,4CAeC;AAxHD,6CAAwF;AACxF,qCAAqF;AACrF,qCAAkC;AAClC,yCAA0C;AAC1C,iDAA6D;AAmB7D,MAAM,OAAO,GAAG,UAAU,CAAC;AAE3B,yGAAyG;AACzG,KAAK,UAAU,gBAAgB;IAC7B,IAAI,CAAC;QACH,8DAA8D;QAC9D,MAAM,MAAM,GAAG,OAAO,CAAC,QAAQ,CAI9B,CAAC;QACF,OAAO;YACL,OAAO,EAAE,aAAa;YACtB,KAAK,CAAC,GAAG,CA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