@deque/axe-auth 1.1.0-next.789db6ed → 1.1.0-next.8e9934f2

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 (70) hide show
  1. package/README.md +59 -12
  2. package/credits.json +42 -0
  3. package/dist/cli/commonArgs.d.ts +82 -0
  4. package/dist/cli/commonArgs.help.d.ts +2 -0
  5. package/dist/cli/commonArgs.help.js +20 -0
  6. package/dist/cli/commonArgs.js +90 -0
  7. package/dist/cli/confirm.d.ts +17 -0
  8. package/dist/cli/confirm.js +56 -0
  9. package/dist/cli/errors.d.ts +20 -0
  10. package/dist/cli/errors.js +37 -0
  11. package/dist/cli/testUtils.d.ts +52 -0
  12. package/dist/cli/testUtils.js +100 -0
  13. package/dist/cli/types.d.ts +79 -0
  14. package/dist/cli/types.js +2 -0
  15. package/dist/commands/login.d.ts +44 -0
  16. package/dist/commands/login.help.d.ts +2 -0
  17. package/dist/commands/login.help.js +41 -0
  18. package/dist/commands/login.js +117 -0
  19. package/dist/commands/logout.d.ts +24 -0
  20. package/dist/commands/logout.help.d.ts +2 -0
  21. package/dist/commands/logout.help.js +38 -0
  22. package/dist/commands/logout.js +70 -0
  23. package/dist/commands/token.d.ts +21 -0
  24. package/dist/commands/token.help.d.ts +2 -0
  25. package/dist/commands/token.help.js +41 -0
  26. package/dist/commands/token.js +44 -0
  27. package/dist/index.js +114 -22
  28. package/dist/oauth/authorizationURL.d.ts +29 -0
  29. package/dist/oauth/authorizationURL.js +52 -0
  30. package/dist/oauth/authorize.d.ts +91 -0
  31. package/dist/oauth/authorize.js +119 -0
  32. package/dist/oauth/discoverOIDC.d.ts +50 -0
  33. package/dist/oauth/discoverOIDC.js +173 -0
  34. package/dist/oauth/discoverSSOConfig.d.ts +47 -0
  35. package/dist/oauth/discoverSSOConfig.js +105 -0
  36. package/dist/oauth/errors.d.ts +55 -2
  37. package/dist/oauth/errors.js +35 -1
  38. package/dist/oauth/getValidAccessToken.d.ts +89 -0
  39. package/dist/oauth/getValidAccessToken.js +140 -0
  40. package/dist/oauth/index.d.ts +14 -2
  41. package/dist/oauth/index.js +13 -1
  42. package/dist/oauth/issuerURL.d.ts +22 -0
  43. package/dist/oauth/issuerURL.js +38 -0
  44. package/dist/oauth/keyringBinding.d.ts +22 -0
  45. package/dist/oauth/keyringBinding.js +41 -0
  46. package/dist/oauth/openBrowser.d.ts +19 -0
  47. package/dist/oauth/openBrowser.js +78 -0
  48. package/dist/oauth/pkce.d.ts +17 -0
  49. package/dist/oauth/pkce.js +43 -0
  50. package/dist/oauth/predicates.d.ts +7 -0
  51. package/dist/oauth/predicates.js +15 -0
  52. package/dist/oauth/refreshTokens.d.ts +30 -0
  53. package/dist/oauth/refreshTokens.js +63 -0
  54. package/dist/oauth/revokeToken.d.ts +28 -0
  55. package/dist/oauth/revokeToken.js +63 -0
  56. package/dist/oauth/testUtils.d.ts +35 -0
  57. package/dist/oauth/testUtils.js +61 -0
  58. package/dist/oauth/tokenExchange.d.ts +26 -0
  59. package/dist/oauth/tokenExchange.js +44 -0
  60. package/dist/oauth/tokenResponse.d.ts +54 -0
  61. package/dist/oauth/tokenResponse.js +121 -0
  62. package/dist/oauth/tokenStore.d.ts +116 -0
  63. package/dist/oauth/tokenStore.js +202 -0
  64. package/dist/userAgent.d.ts +12 -0
  65. package/dist/userAgent.js +18 -0
  66. package/docs/architecture.md +201 -0
  67. package/docs/callback-page.md +24 -0
  68. package/docs/callback-server.md +21 -0
  69. package/docs/oauth-flow.md +15 -0
  70. package/package.json +16 -3
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @deque/axe-auth
2
2
 
3
- CLI for authenticating with Deque's axe MCP server and other services.
3
+ CLI for authenticating with Deque services via the OAuth 2.0 Authorization Code + PKCE flow (RFC 6749, RFC 7636, RFC 8252 §7.3). Tokens are persisted to the OS keychain so subsequent invocations can refresh silently.
4
4
 
5
5
  ## Installation
6
6
 
@@ -17,22 +17,69 @@ npx @deque/axe-auth
17
17
  ## Usage
18
18
 
19
19
  ```sh
20
- axe-auth [options]
20
+ axe-auth <command> [options]
21
21
  ```
22
22
 
23
- ### Options
23
+ Commands:
24
24
 
25
- | Flag | Description |
26
- | ----------------- | ------------------- |
27
- | `-v`, `--version` | Show version number |
28
- | `-h`, `--help` | Show help message |
25
+ | Command | Description |
26
+ | -------- | ------------------------------------------------------------------------------- |
27
+ | `login` | Open a browser, complete the OAuth flow, persist tokens to the OS keychain. |
28
+ | `logout` | Revoke the stored refresh token server-side and clear the local keychain entry. |
29
+ | `token` | Print a currently-valid access token to stdout, refreshing silently if needed. |
29
30
 
30
- > Login, token exchange, and keychain storage are owned by sibling issues under epic [#410](https://github.com/dequelabs/axe-mcp-server/issues/410). This package currently ships only the loopback callback server module; see the architecture docs below.
31
+ Run `axe-auth <command> --help` for command-specific options.
32
+
33
+ ### Common configuration
34
+
35
+ `axe-auth` discovers its OAuth coordinates by calling `<server>/api/sso-config` on the axe server. Users only supply (or default to) the axe server URL — never the underlying Keycloak URL, realm, or client ID.
36
+
37
+ | Flag | Env var | Notes |
38
+ | ---------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
39
+ | `--server` | `AXE_SERVER_URL` | axe server URL. Defaults to `https://axe.deque.com` (SaaS prod) when neither flag nor env var is set, so SaaS users pass no flags at all. Customers on other deployments override with their own axe server URL. |
40
+ | `--allow-insecure-issuer` | — | Permit non-loopback http URLs (default is https only; loopback http is always allowed). Applies to `login` only; `token` and `logout` use the policy persisted at login. |
41
+ | `--no-allow-insecure-issuer` | — | Force `allowInsecureIssuer=false` for the new `login` (and the entry it persists). Mutually exclusive with `--allow-insecure-issuer`. `token` and `logout` ignore this flag. |
42
+
43
+ `axe-auth` stores one set of credentials per machine. On a successful `login`, the discovered issuer / client / insecure-issuer values are persisted alongside the tokens, so subsequent `axe-auth token` and `axe-auth logout` invocations work flag-free — a typical scripted call is just `$(axe-auth token)`.
44
+
45
+ There is no concurrent multi-issuer support. Logging in to a second deployment overwrites the previous tokens; an interactive prompt confirms the switch before destroying the existing session, and `--force` skips the prompt.
46
+
47
+ ### Exit codes
48
+
49
+ | Code | Meaning |
50
+ | ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
51
+ | `0` | Success. |
52
+ | `1` | Not authenticated: `axe-auth token` with no stored credentials, or stored credentials are unusable (corrupt, version-mismatch, expired without a usable refresh token, or refresh rejected by the server). Branch on this in scripts that need to trigger a `login`. |
53
+ | `2` | Usage or runtime error: unknown command, bad flag, missing required configuration, OAuth flow failure, or keychain failure. Details written to stderr. |
54
+ | `3` | Cancelled: `axe-auth login` declined at the re-authentication prompt. Distinct from `1` so scripts can tell "needs login" from "user bailed." |
55
+
56
+ ### Examples
57
+
58
+ ```sh
59
+ # First-time login on Deque SaaS prod (opens your browser, no flags needed)
60
+ axe-auth login
61
+
62
+ # First-time login on a non-SaaS-prod deployment
63
+ axe-auth login --server https://axe.customer.dequecloud.com
64
+
65
+ # Pull a fresh access token for use in shell substitution
66
+ docker run -e AXE_ACCESS_TOKEN="$(axe-auth token)" axe-mcp-server
67
+
68
+ # Sign out
69
+ axe-auth logout
70
+ ```
31
71
 
32
72
  ## Architecture
33
73
 
34
- Design notes live in the repository under [`packages/axe-auth/docs/`](https://github.com/dequelabs/axe-mcp-server/tree/develop/packages/axe-auth/docs):
74
+ See [`docs/architecture.md`](./docs/architecture.md) for the system architecture: components, per-verb data flow, communication security, and persisted data.
75
+
76
+ Deeper design notes:
77
+
78
+ - [`oauth-flow.md`](./docs/oauth-flow.md) — protocol-level walkthrough of the OAuth 2.0 + PKCE flow.
79
+ - [`callback-server.md`](./docs/callback-server.md) — `startCallbackServer` API and RFC 8252 conformance.
80
+ - [`callback-page.md`](./docs/callback-page.md) — HTML response design, branding, and CSP rationale.
81
+
82
+ ## Caveats
35
83
 
36
- - [`oauth-flow.md`](https://github.com/dequelabs/axe-mcp-server/blob/develop/packages/axe-auth/docs/oauth-flow.md) high-level OAuth 2.0 + PKCE flow and where each concern lives.
37
- - [`callback-server.md`](https://github.com/dequelabs/axe-mcp-server/blob/develop/packages/axe-auth/docs/callback-server.md) `startCallbackServer` API, error codes, and RFC 8252 conformance.
38
- - [`callback-page.md`](https://github.com/dequelabs/axe-mcp-server/blob/develop/packages/axe-auth/docs/callback-page.md) — HTML response design, branding, and CSP rationale.
84
+ - **`axe-auth token` exposes the access token in the shell process list and terminal scrollback.** When used as `$(axe-auth token)` the token briefly appears in the parent process's argument list (observable via `ps`); printed directly to a terminal it also persists in the scrollback buffer (iTerm2, Terminal.app, tmux all retain output by default), which can outlast the token's TTL on a shared machine. OAuth access tokens are short-lived (typically minutes), which limits exposure compared to a static API key. Prefer redirecting into a file (`axe-auth token > /tmp/tok && chmod 600 /tmp/tok`) or directly into an env var (`export AXE_ACCESS_TOKEN=$(axe-auth token)`) on platforms where this matters.
85
+ - **Linux keychain support is untested.** `@napi-rs/keyring` requires a working D-Bus Secret Service (GNOME Keyring, KWallet, etc.). Users on headless or minimal-desktop Linux environments may see `KEYRING_UNAVAILABLE`; a file-backed `TokenStore` fallback is tracked as a follow-up (internal issue #464).
package/credits.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "@napi-rs/keyring@1.2.0": {
3
+ "name": "@napi-rs/keyring",
4
+ "version": "1.2.0",
5
+ "licenses": "MIT",
6
+ "path": "/home/runner/work/axe-mcp-server/axe-mcp-server/node_modules/.pnpm/@napi-rs+keyring@1.2.0/node_modules/@napi-rs/keyring",
7
+ "licenseText": "MIT License\n\nCopyright (c) 2020 N-API for Rust\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n",
8
+ "licenseFile": "/home/runner/work/axe-mcp-server/axe-mcp-server/node_modules/.pnpm/@napi-rs+keyring@1.2.0/node_modules/@napi-rs/keyring/LICENSE",
9
+ "copyright": "Copyright (c) 2020 N-API for Rust"
10
+ },
11
+ "@napi-rs/keyring-linux-x64-gnu@1.2.0": {
12
+ "name": "@napi-rs/keyring-linux-x64-gnu",
13
+ "version": "1.2.0",
14
+ "licenses": "MIT",
15
+ "path": "/home/runner/work/axe-mcp-server/axe-mcp-server/node_modules/.pnpm/@napi-rs+keyring-linux-x64-gnu@1.2.0/node_modules/@napi-rs/keyring-linux-x64-gnu",
16
+ "licenseText": "# `@napi-rs/keyring-linux-x64-gnu`\n\nThis is the **x86_64-unknown-linux-gnu** binary for `@napi-rs/keyring`\n",
17
+ "licenseFile": "/home/runner/work/axe-mcp-server/axe-mcp-server/node_modules/.pnpm/@napi-rs+keyring-linux-x64-gnu@1.2.0/node_modules/@napi-rs/keyring-linux-x64-gnu/README.md"
18
+ },
19
+ "remove-trailing-slash@0.1.1": {
20
+ "name": "remove-trailing-slash",
21
+ "version": "0.1.1",
22
+ "licenses": "MIT",
23
+ "path": "/home/runner/work/axe-mcp-server/axe-mcp-server/node_modules/.pnpm/remove-trailing-slash@0.1.1/node_modules/remove-trailing-slash",
24
+ "licenseText": "# remove-trailing-slash\n\nremoves trailing slashes\n\n## Installation\n\nwith [component(1)](http://component.io):\n\n $ component install stephenmathieson/remove-trailing-slash\n\nwith [npm](https://npmjs.org/):\n\n $ npm install remove-trailing-slash\n\n## API\n\n### `removeTrailingSlash(str)`\n\nRemoves trailing slashes from the given `str`\n\n## Example\n\n```js\nvar slashes = require('remove-trailing-slash')\n\nslashes('http://google.com/').should.be.equal('http://google.com');\n```\n\n## License\n\nMIT\n",
25
+ "licenseFile": "/home/runner/work/axe-mcp-server/axe-mcp-server/node_modules/.pnpm/remove-trailing-slash@0.1.1/node_modules/remove-trailing-slash/readme.md",
26
+ "repository": "https://github.com/stephenmathieson/remove-trailing-slash",
27
+ "publisher": "Stephen Mathieson",
28
+ "email": "me@stephenmathieson.com"
29
+ },
30
+ "ts-dedent@2.2.0": {
31
+ "name": "ts-dedent",
32
+ "version": "2.2.0",
33
+ "licenses": "MIT",
34
+ "path": "/home/runner/work/axe-mcp-server/axe-mcp-server/node_modules/.pnpm/ts-dedent@2.2.0/node_modules/ts-dedent",
35
+ "licenseText": "MIT License\n\nCopyright (c) 2018 Tamino Martinius\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n",
36
+ "licenseFile": "/home/runner/work/axe-mcp-server/axe-mcp-server/node_modules/.pnpm/ts-dedent@2.2.0/node_modules/ts-dedent/LICENSE",
37
+ "repository": "https://github.com/tamino-martinius/node-ts-dedent",
38
+ "publisher": "Tamino Martinius",
39
+ "email": "dev@zaku.eu",
40
+ "copyright": "Copyright (c) 2018 Tamino Martinius"
41
+ }
42
+ }
@@ -0,0 +1,82 @@
1
+ import type { ParseArgsConfig } from "node:util";
2
+ /**
3
+ * Default axe server URL for `axe-auth` users on Deque's SaaS prod
4
+ * deployment. The CLI's `--server` flag (and `AXE_SERVER_URL` env)
5
+ * override this; non-prod customers must supply their own walnut URL.
6
+ */
7
+ export declare const DEFAULT_WALNUT_URL = "https://axe.deque.com";
8
+ /** Common configuration the CLI verbs share. */
9
+ export interface CommonArgs {
10
+ /**
11
+ * axe server URL (walnut). Used by `login` to fetch
12
+ * `/api/sso-config` and derive the OAuth issuer / realm / client
13
+ * coordinates. `token` and `logout` operate on the stored entry
14
+ * alone and ignore this value.
15
+ */
16
+ walnutURL: string;
17
+ /**
18
+ * Whether to permit non-loopback http walnut/issuer URLs. Loopback
19
+ * hosts (`localhost` / `127.0.0.1` / `[::1]`) are always allowed
20
+ * over http; this flag is the opt-in for non-loopback http
21
+ * deployments.
22
+ */
23
+ allowInsecureIssuer: boolean;
24
+ }
25
+ /**
26
+ * `parseArgs`-shaped options describing the flags every CLI verb
27
+ * accepts (--server, --allow-insecure-issuer, --no-allow-insecure-issuer).
28
+ * Subcommands spread this into their own `options` so they can add
29
+ * verb-specific flags alongside.
30
+ *
31
+ * Node's `parseArgs` doesn't support `--no-` boolean negation
32
+ * natively, so the opt-out is registered as its own flag. Passing
33
+ * both `--allow-insecure-issuer` and `--no-allow-insecure-issuer` is
34
+ * treated as user error and rejected.
35
+ */
36
+ export declare const COMMON_OPTIONS: NonNullable<ParseArgsConfig["options"]>;
37
+ /** Subset of `parseArgs(...).values` this helper consumes. */
38
+ export interface ParsedCommonValues {
39
+ server?: string;
40
+ "allow-insecure-issuer"?: boolean;
41
+ "no-allow-insecure-issuer"?: boolean;
42
+ }
43
+ /**
44
+ * Subset of a stored entry used as a fallback for
45
+ * `allowInsecureIssuer` when the user passes neither
46
+ * `--allow-insecure-issuer` nor `--no-allow-insecure-issuer`.
47
+ * Sourced from `KeyringTokenStore.load()` by the dispatcher.
48
+ *
49
+ * `walnutURL` is carried alongside so the fallback only applies when
50
+ * the user is targeting the same deployment as the stored entry —
51
+ * otherwise a dev-time HTTP-allow setting would silently carry over
52
+ * to a prod login.
53
+ */
54
+ export interface StoredCommonDefaults {
55
+ walnutURL: string;
56
+ allowInsecureIssuer: boolean;
57
+ }
58
+ /**
59
+ * Resolves common configuration from parsed flag values, falling
60
+ * back to `AXE_SERVER_URL` when `--server` is absent and finally to
61
+ * the SaaS prod walnut URL when neither is set.
62
+ *
63
+ * `allowInsecureIssuer` is consumed by `login` (it is forwarded to
64
+ * SSO discovery and the OAuth flow). The fallback to a stored value
65
+ * exists so an interactive re-login on a private dev instance does
66
+ * not need the flag re-passed when the previous login set it. The
67
+ * fallback is gated on the resolved walnut URL matching the stored
68
+ * one: a user logging in to a different deployment must opt back in
69
+ * with `--allow-insecure-issuer` explicitly. The `token` and `logout`
70
+ * verbs do **not** consume this resolved value — they read
71
+ * `allowInsecureIssuer` directly from the keychain entry's metadata,
72
+ * so flag/env input is silently ignored there (and the help text for
73
+ * those verbs documents that).
74
+ *
75
+ * @param values The `values` object returned from `parseArgs`.
76
+ * @param env Environment to consult for fallback. Defaults to
77
+ * `process.env`; injected for test determinism.
78
+ * @param defaults Stored fallback for `allowInsecureIssuer` plus the
79
+ * `walnutURL` it was minted against. Pass `null` (or omit) when
80
+ * nothing is stored.
81
+ */
82
+ export declare function parseCommonArgs(values: ParsedCommonValues, env?: NodeJS.ProcessEnv, defaults?: StoredCommonDefaults | null): CommonArgs;
@@ -0,0 +1,2 @@
1
+ /** Help-text fragment describing the flags every CLI verb shares. */
2
+ export declare const HELP_COMMON_OPTIONS = " --server <url> axe server URL. Used by `login` to fetch\n /api/sso-config and derive the OAuth\n coordinates. Falls back to AXE_SERVER_URL,\n then to https://axe.deque.com (SaaS prod).\n --allow-insecure-issuer Permit non-loopback http URLs (default is\n https only; loopback http is always\n allowed). Applies to `login` only;\n `token` and `logout` use the policy\n persisted at login.\n --no-allow-insecure-issuer\n Force allowInsecureIssuer=false for the new\n `login` (and the entry it persists).\n Ignored by `token` and `logout`.\n Mutually exclusive with\n --allow-insecure-issuer.\n -h, --help Show this help.";
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HELP_COMMON_OPTIONS = void 0;
4
+ /** Help-text fragment describing the flags every CLI verb shares. */
5
+ exports.HELP_COMMON_OPTIONS = ` --server <url> axe server URL. Used by \`login\` to fetch
6
+ /api/sso-config and derive the OAuth
7
+ coordinates. Falls back to AXE_SERVER_URL,
8
+ then to https://axe.deque.com (SaaS prod).
9
+ --allow-insecure-issuer Permit non-loopback http URLs (default is
10
+ https only; loopback http is always
11
+ allowed). Applies to \`login\` only;
12
+ \`token\` and \`logout\` use the policy
13
+ persisted at login.
14
+ --no-allow-insecure-issuer
15
+ Force allowInsecureIssuer=false for the new
16
+ \`login\` (and the entry it persists).
17
+ Ignored by \`token\` and \`logout\`.
18
+ Mutually exclusive with
19
+ --allow-insecure-issuer.
20
+ -h, --help Show this help.`;
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.COMMON_OPTIONS = exports.DEFAULT_WALNUT_URL = void 0;
7
+ exports.parseCommonArgs = parseCommonArgs;
8
+ const remove_trailing_slash_1 = __importDefault(require("remove-trailing-slash"));
9
+ /**
10
+ * Default axe server URL for `axe-auth` users on Deque's SaaS prod
11
+ * deployment. The CLI's `--server` flag (and `AXE_SERVER_URL` env)
12
+ * override this; non-prod customers must supply their own walnut URL.
13
+ */
14
+ exports.DEFAULT_WALNUT_URL = "https://axe.deque.com";
15
+ /**
16
+ * `parseArgs`-shaped options describing the flags every CLI verb
17
+ * accepts (--server, --allow-insecure-issuer, --no-allow-insecure-issuer).
18
+ * Subcommands spread this into their own `options` so they can add
19
+ * verb-specific flags alongside.
20
+ *
21
+ * Node's `parseArgs` doesn't support `--no-` boolean negation
22
+ * natively, so the opt-out is registered as its own flag. Passing
23
+ * both `--allow-insecure-issuer` and `--no-allow-insecure-issuer` is
24
+ * treated as user error and rejected.
25
+ */
26
+ exports.COMMON_OPTIONS = {
27
+ server: { type: "string" },
28
+ "allow-insecure-issuer": { type: "boolean" },
29
+ "no-allow-insecure-issuer": { type: "boolean" },
30
+ };
31
+ /**
32
+ * Resolves common configuration from parsed flag values, falling
33
+ * back to `AXE_SERVER_URL` when `--server` is absent and finally to
34
+ * the SaaS prod walnut URL when neither is set.
35
+ *
36
+ * `allowInsecureIssuer` is consumed by `login` (it is forwarded to
37
+ * SSO discovery and the OAuth flow). The fallback to a stored value
38
+ * exists so an interactive re-login on a private dev instance does
39
+ * not need the flag re-passed when the previous login set it. The
40
+ * fallback is gated on the resolved walnut URL matching the stored
41
+ * one: a user logging in to a different deployment must opt back in
42
+ * with `--allow-insecure-issuer` explicitly. The `token` and `logout`
43
+ * verbs do **not** consume this resolved value — they read
44
+ * `allowInsecureIssuer` directly from the keychain entry's metadata,
45
+ * so flag/env input is silently ignored there (and the help text for
46
+ * those verbs documents that).
47
+ *
48
+ * @param values The `values` object returned from `parseArgs`.
49
+ * @param env Environment to consult for fallback. Defaults to
50
+ * `process.env`; injected for test determinism.
51
+ * @param defaults Stored fallback for `allowInsecureIssuer` plus the
52
+ * `walnutURL` it was minted against. Pass `null` (or omit) when
53
+ * nothing is stored.
54
+ */
55
+ function parseCommonArgs(values, env = process.env, defaults = null) {
56
+ const walnutURL = (0, remove_trailing_slash_1.default)(values.server ?? env.AXE_SERVER_URL ?? exports.DEFAULT_WALNUT_URL);
57
+ // Only inherit the stored `allowInsecureIssuer` when the incoming
58
+ // walnut URL matches the stored one. A user logging in to a
59
+ // different deployment must opt back in via `--allow-insecure-issuer`
60
+ // explicitly; otherwise a dev-time HTTP-allow setting would silently
61
+ // carry over to a prod login.
62
+ const matchingDefaults = defaults && defaults.walnutURL === walnutURL ? defaults : null;
63
+ const allowInsecureIssuer = resolveAllowInsecureIssuer(values, matchingDefaults);
64
+ return { walnutURL, allowInsecureIssuer };
65
+ }
66
+ /**
67
+ * Resolves `allowInsecureIssuer` from the positive flag, its
68
+ * negation, and the keychain default — in that precedence order.
69
+ * Throws when both flags are passed together.
70
+ */
71
+ function resolveAllowInsecureIssuer(values, defaults) {
72
+ // Truthy checks (rather than `!== undefined`) are deliberate:
73
+ // `parseArgs` with `type: "boolean"` only ever produces `true` or
74
+ // `undefined`, but `ParsedCommonValues` types these as
75
+ // `boolean | undefined` so a programmatic caller could thread in
76
+ // `false`. Treating `false` as "flag not set" lets such a caller
77
+ // mix `{ "allow-insecure-issuer": false, "no-allow-insecure-issuer":
78
+ // true }` without tripping the mutex — `false` here is equivalent
79
+ // to "absent", which is what parseArgs would have produced anyway.
80
+ const allow = values["allow-insecure-issuer"];
81
+ const deny = values["no-allow-insecure-issuer"];
82
+ if (allow && deny) {
83
+ throw new Error("--allow-insecure-issuer and --no-allow-insecure-issuer are mutually exclusive.");
84
+ }
85
+ if (allow)
86
+ return true;
87
+ if (deny)
88
+ return false;
89
+ return defaults?.allowInsecureIssuer ?? false;
90
+ }
@@ -0,0 +1,17 @@
1
+ import type { Readable, Writable } from "node:stream";
2
+ /** Options for `confirm`. */
3
+ export interface ConfirmOptions {
4
+ /** Question to display. A trailing space is added if absent. */
5
+ question: string;
6
+ /** Stream to read the answer from. Defaults to `process.stdin`. */
7
+ input?: Readable;
8
+ /** Stream to print the question on. Defaults to `process.stderr`. */
9
+ output?: Writable;
10
+ }
11
+ /**
12
+ * Reads a single line from `input` and returns `true` for an
13
+ * affirmative answer (`y` / `yes`, case-insensitive), `false`
14
+ * otherwise. Empty / EOF / Ctrl-C are all treated as "no" so the
15
+ * default action stays conservative.
16
+ */
17
+ export declare function confirm(options: ConfirmOptions): Promise<boolean>;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.confirm = confirm;
4
+ const node_readline_1 = require("node:readline");
5
+ /**
6
+ * Reads a single line from `input` and returns `true` for an
7
+ * affirmative answer (`y` / `yes`, case-insensitive), `false`
8
+ * otherwise. Empty / EOF / Ctrl-C are all treated as "no" so the
9
+ * default action stays conservative.
10
+ */
11
+ async function confirm(options) {
12
+ // Annotate after the ?? fallbacks so the union of `Writable |
13
+ // NodeJS.WriteStream` (from `process.stderr`) collapses to the
14
+ // base class — otherwise `output.write(...)` is ambiguous.
15
+ const input = options.input ?? process.stdin;
16
+ const output = options.output ?? process.stderr;
17
+ const question = options.question.endsWith(" ")
18
+ ? options.question
19
+ : `${options.question} `;
20
+ // Use createInterface rather than the higher-level `rl.question`
21
+ // promise API because the latter wires up SIGINT handling that
22
+ // doesn't compose well when this is called from a CLI dispatcher
23
+ // that owns its own signals.
24
+ const rl = (0, node_readline_1.createInterface)({ input, output });
25
+ try {
26
+ output.write(question);
27
+ const line = await waitForLineOrClose(rl);
28
+ if (line === null)
29
+ return false;
30
+ const trimmed = line.trim().toLowerCase();
31
+ return trimmed === "y" || trimmed === "yes";
32
+ }
33
+ finally {
34
+ rl.close();
35
+ }
36
+ }
37
+ /**
38
+ * Resolves with the next line emitted by `rl`, or `null` if the
39
+ * underlying stream closes first (EOF / Ctrl-D / Ctrl-C). Both
40
+ * listeners detach themselves on the other event so we never hold
41
+ * references to a closed interface.
42
+ */
43
+ function waitForLineOrClose(rl) {
44
+ return new Promise((resolve) => {
45
+ const onLine = (line) => {
46
+ rl.off("close", onClose);
47
+ resolve(line);
48
+ };
49
+ const onClose = () => {
50
+ rl.off("line", onLine);
51
+ resolve(null);
52
+ };
53
+ rl.once("line", onLine);
54
+ rl.once("close", onClose);
55
+ });
56
+ }
@@ -0,0 +1,20 @@
1
+ /** Discriminator for `CLIError`, used by tests and the dispatcher. */
2
+ export type CLIErrorCode = "NOT_AUTHENTICATED" | "USER_CANCELLED" | "ALREADY_AUTHENTICATED" | "OAUTH_FAILED" | "KEYCHAIN_FAILURE";
3
+ /**
4
+ * Thrown from a verb's `run` to signal a known failure. The
5
+ * dispatcher in `src/index.ts` writes `message` to stderr and exits
6
+ * with `exitCode`. The `code` field is the load-bearing
7
+ * discriminator; `exitCode` is derived for shell scripts and is
8
+ * documented in the README.
9
+ */
10
+ export declare class CLIError extends Error {
11
+ readonly code: CLIErrorCode;
12
+ readonly exitCode: number;
13
+ constructor(code: CLIErrorCode, message: string);
14
+ }
15
+ /**
16
+ * Returns the `message` of an `Error`-shaped value, or its `String`
17
+ * coercion otherwise. Used in user-facing error templates so
18
+ * callers don't inline the `instanceof` ternary every time.
19
+ */
20
+ export declare function describeError(err: unknown): string;
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CLIError = void 0;
4
+ exports.describeError = describeError;
5
+ const EXIT_CODE_BY_ERROR_CODE = {
6
+ NOT_AUTHENTICATED: 1,
7
+ USER_CANCELLED: 3,
8
+ ALREADY_AUTHENTICATED: 2,
9
+ OAUTH_FAILED: 2,
10
+ KEYCHAIN_FAILURE: 2,
11
+ };
12
+ /**
13
+ * Thrown from a verb's `run` to signal a known failure. The
14
+ * dispatcher in `src/index.ts` writes `message` to stderr and exits
15
+ * with `exitCode`. The `code` field is the load-bearing
16
+ * discriminator; `exitCode` is derived for shell scripts and is
17
+ * documented in the README.
18
+ */
19
+ class CLIError extends Error {
20
+ code;
21
+ exitCode;
22
+ constructor(code, message) {
23
+ super(message);
24
+ this.name = "CLIError";
25
+ this.code = code;
26
+ this.exitCode = EXIT_CODE_BY_ERROR_CODE[code];
27
+ }
28
+ }
29
+ exports.CLIError = CLIError;
30
+ /**
31
+ * Returns the `message` of an `Error`-shaped value, or its `String`
32
+ * coercion otherwise. Used in user-facing error templates so
33
+ * callers don't inline the `instanceof` ternary every time.
34
+ */
35
+ function describeError(err) {
36
+ return err instanceof Error ? err.message : String(err);
37
+ }
@@ -0,0 +1,52 @@
1
+ import { Readable, Writable } from "node:stream";
2
+ import type { CommonArgs } from "./commonArgs";
3
+ import type { CommandDeps } from "./types";
4
+ import type { LoadResult, StoredEntry, TokenStore } from "../oauth/tokenStore";
5
+ import type { TokenSet } from "../oauth/tokenResponse";
6
+ /** A `Writable` that accumulates everything written into a string. */
7
+ export interface CapturedStream extends Writable {
8
+ /** Concatenation of every chunk written to the stream so far. */
9
+ readonly value: string;
10
+ }
11
+ /**
12
+ * Returns a `Writable` that records every write into a string for
13
+ * assertion. Reads via `.value`. Defined as a real `Writable`
14
+ * subclass so it can be passed straight into `CommandDeps.stdout` /
15
+ * `CommandDeps.stderr` without casts.
16
+ */
17
+ export declare function captureStream(): CapturedStream;
18
+ /** Convenience: an empty `Readable` to stand in for stdin in tests. */
19
+ export declare function emptyStdin(): Readable;
20
+ /** A `TokenStore` plus instrumentation for assertions. */
21
+ export interface FakeStore extends TokenStore {
22
+ /** Number of times `load()` was called. */
23
+ readonly loadedTimes: number;
24
+ /** Number of times `clear()` was called. */
25
+ readonly clearedTimes: number;
26
+ /** Current state, observable from tests. */
27
+ readonly current: LoadResult;
28
+ }
29
+ /**
30
+ * In-memory `TokenStore` that starts in `initial`, accepts
31
+ * `save()` / `clear()`, and exposes `loadedTimes` / `clearedTimes`
32
+ * / `current` for assertions.
33
+ */
34
+ export declare function makeStore(initial: LoadResult): FakeStore;
35
+ /**
36
+ * Builds a `StoredEntry` for the standard test issuer/client. Pass a
37
+ * `TokenSet` (from a per-test fixture) and override the
38
+ * issuer/client/insecure fields when a test cares about them.
39
+ */
40
+ export declare function entry(tokens: TokenSet, overrides?: Partial<Omit<StoredEntry, "tokens">>): StoredEntry;
41
+ /** A `CommandDeps` shape with the captured streams exposed. */
42
+ export interface CapturedDeps extends CommandDeps {
43
+ stdout: CapturedStream;
44
+ stderr: CapturedStream;
45
+ }
46
+ /** Returns a `CommandDeps` populated with capturing streams. */
47
+ export declare function captureDeps(overrides?: Partial<CapturedDeps>): CapturedDeps;
48
+ /**
49
+ * Returns a fully-resolved `CommonArgs` for the standard test
50
+ * issuer/client. Override individual fields as needed.
51
+ */
52
+ export declare function commonArgs(overrides?: Partial<CommonArgs>): CommonArgs;
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ // Shared test helpers for the command tests. Excluded from c8
3
+ // coverage in `.c8rc.json` since this is test-only code.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.captureStream = captureStream;
6
+ exports.emptyStdin = emptyStdin;
7
+ exports.makeStore = makeStore;
8
+ exports.entry = entry;
9
+ exports.captureDeps = captureDeps;
10
+ exports.commonArgs = commonArgs;
11
+ const node_stream_1 = require("node:stream");
12
+ /**
13
+ * Returns a `Writable` that records every write into a string for
14
+ * assertion. Reads via `.value`. Defined as a real `Writable`
15
+ * subclass so it can be passed straight into `CommandDeps.stdout` /
16
+ * `CommandDeps.stderr` without casts.
17
+ */
18
+ function captureStream() {
19
+ let value = "";
20
+ const stream = new node_stream_1.Writable({
21
+ write(chunk, _encoding, cb) {
22
+ value +=
23
+ typeof chunk === "string" ? chunk : Buffer.from(chunk).toString();
24
+ cb();
25
+ },
26
+ });
27
+ Object.defineProperty(stream, "value", { get: () => value });
28
+ return stream;
29
+ }
30
+ /** Convenience: an empty `Readable` to stand in for stdin in tests. */
31
+ function emptyStdin() {
32
+ return node_stream_1.Readable.from([]);
33
+ }
34
+ /**
35
+ * In-memory `TokenStore` that starts in `initial`, accepts
36
+ * `save()` / `clear()`, and exposes `loadedTimes` / `clearedTimes`
37
+ * / `current` for assertions.
38
+ */
39
+ function makeStore(initial) {
40
+ let current = initial;
41
+ let loadedTimes = 0;
42
+ let clearedTimes = 0;
43
+ return {
44
+ save: async (entry) => {
45
+ current = { ok: true, entry };
46
+ },
47
+ load: async () => {
48
+ loadedTimes++;
49
+ return current;
50
+ },
51
+ clear: async () => {
52
+ clearedTimes++;
53
+ current = { ok: false, reason: "empty" };
54
+ },
55
+ get loadedTimes() {
56
+ return loadedTimes;
57
+ },
58
+ get clearedTimes() {
59
+ return clearedTimes;
60
+ },
61
+ get current() {
62
+ return current;
63
+ },
64
+ };
65
+ }
66
+ /**
67
+ * Builds a `StoredEntry` for the standard test issuer/client. Pass a
68
+ * `TokenSet` (from a per-test fixture) and override the
69
+ * issuer/client/insecure fields when a test cares about them.
70
+ */
71
+ function entry(tokens, overrides = {}) {
72
+ return {
73
+ tokens,
74
+ issuerURL: "https://auth.example.com/auth/realms/prod",
75
+ clientId: "axe-auth",
76
+ allowInsecureIssuer: false,
77
+ walnutURL: "https://axe.example.com",
78
+ ...overrides,
79
+ };
80
+ }
81
+ /** Returns a `CommandDeps` populated with capturing streams. */
82
+ function captureDeps(overrides = {}) {
83
+ return {
84
+ stdin: emptyStdin(),
85
+ stdout: captureStream(),
86
+ stderr: captureStream(),
87
+ ...overrides,
88
+ };
89
+ }
90
+ /**
91
+ * Returns a fully-resolved `CommonArgs` for the standard test
92
+ * issuer/client. Override individual fields as needed.
93
+ */
94
+ function commonArgs(overrides = {}) {
95
+ return {
96
+ walnutURL: "https://axe.example.com",
97
+ allowInsecureIssuer: false,
98
+ ...overrides,
99
+ };
100
+ }