From b2d255a43019231e7c9abaed809419142741a543 Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Fri, 27 Nov 2026 14:05:16 +0200 Subject: [PATCH 1/2] feat: scoped auth tokens (ocean.js #2214) on lib v11 Adds node-scoped, self-expiring auth tokens for the breaking v11 generateAuthToken, plus discovery/decoding helpers: - generateAuthToken gains --ttl/--valid-until/--audience/--scope/ --allow-unverified-issuer; supplies a default validUntil; clamps the default TTL to the node policy; token to stdout, summary+warnings to stderr. - new getNodeAuthTokenPolicy (node-gated) and listScopableCommands + decodeAuthToken (node-free, credential-free via a CREDENTIAL_FREE_COMMANDS startup skip, since rc_3.0.0 has no CONFIG_BOOTSTRAP mechanism). - pins @oceanprotocol/lib to 11.0.0-next.2. Based on rc_3.0.0 (post-#215 Aquarius -> ProviderInstance migration). Scope is auth-tokens only; the unified global config refactor is PR #225. tsc clean; 32 no-infra tests pass against 11.0.0-next.2. Co-Authored-By: Claude Opus 4.8 --- README.md | 40 +++++++- package-lock.json | 10 +- package.json | 2 +- src/cli.ts | 145 ++++++++++++++++++++++++++- src/commands.ts | 87 ++++++++++++++++- src/helpers.ts | 119 +++++++++++++++++++++++ test/authTokenCommands.test.ts | 124 ++++++++++++++++++++++++ test/authTokenOptions.test.ts | 172 +++++++++++++++++++++++++++++++++ 8 files changed, 686 insertions(+), 13 deletions(-) create mode 100644 test/authTokenCommands.test.ts create mode 100644 test/authTokenOptions.test.ts diff --git a/README.md b/README.md index c86a6a7..178c094 100644 --- a/README.md +++ b/README.md @@ -366,11 +366,46 @@ ocean-cli deleteFile ### Auth tokens +`generateAuthToken` mints a **scoped, self-expiring** JWT (ocean.js v11 / scoped-auth-tokens). +By default the token is **node-scoped** (usable only at the current node) and the CLI gives it a +1-hour lifetime (capped to the node's advertised `maxTokenLifetime`). Before signing, ocean.js +verifies the node's identity (OJ-03 challenge-response). + ```bash +# node-scoped, 1h default lifetime ocean-cli generateAuthToken + +# custom lifetime +ocean-cli generateAuthToken --ttl 900 # 15 minutes +ocean-cli generateAuthToken --valid-until 1990000000000 # absolute epoch-ms expiry (future) + +# restrict the commands the token may perform +ocean-cli generateAuthToken --scope download,getDDO + +# multi-node / unrestricted audience +ocean-cli generateAuthToken --audience 16Uiu2HA...,16Uiu2HB... +ocean-cli generateAuthToken --audience any # reusable, network-wide (warned) + +# talk to a node that predates OJ-03 (insecure) +ocean-cli generateAuthToken --allow-unverified-issuer + ocean-cli invalidateAuthToken myAuthToken123 # or --token + +# inspect / discover +ocean-cli getNodeAuthTokenPolicy # node's max lifetime, cross-node, revocation +ocean-cli listScopableCommands # commands valid in --scope (node-free) +ocean-cli decodeAuthToken myAuthToken123 # decode claims locally (node-free) ``` +> **Breaking change:** v2 tokens require an expiry. If you call ocean.js directly, pass +> `{ validUntil }`; the CLI supplies a default. An `--audience any` token is a reusable bearer — +> use HTTPS/Noise transport and a short lifetime. + +`generateAuthToken` prints the token to **stdout**; the expiry/audience/scope summary and any +warnings go to **stderr**, so `ocean-cli generateAuthToken | …` captures only the token. Note that +`decodeAuthToken` only *decodes* a token locally — it does **not** verify its signature, so treat +the printed claims as untrusted. + ### Admin ```bash @@ -423,8 +458,11 @@ ocean-cli mintOcean [--token 0xOcean] [--chainId 8996] # mint test Ocean tok | `restartService` | | `` | `-u, --user-data`, `--user-data-file`, `--cmd`, `--entrypoint`, `--image`, `--tag`, `--checksum`, `--dockerfile`, `--additional-docker-files`, `--wait`, `--timeout` | | `stopService` | | `[serviceId]` | `-s, --service` | | `mintOcean` | | | `-t, --token`, `--chainId` | -| `generateAuthToken` | | | | +| `generateAuthToken` | | | `--ttl`, `--valid-until`, `--audience`, `--scope`, `--allow-unverified-issuer` | | `invalidateAuthToken` | | `[token]` | `-t, --token` | +| `getNodeAuthTokenPolicy` | `authTokenPolicy` | | | +| `listScopableCommands` | `scopableCommands` | | | +| `decodeAuthToken` | `decodeToken` | `[token]` | `-t, --token` | | `depositEscrow` | | `[token] [amount]` | `-t, --token`, `-a, --amount`, `--chainId` | | `getUserFundsEscrow` | | `[token]` | `-t, --token`, `--chainId` | | `withdrawFromEscrow` | | `[token] [amount]` | `-t, --token`, `-a, --amount`, `--chainId` | diff --git a/package-lock.json b/package-lock.json index 3a608b6..b700113 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,7 @@ "@oasisprotocol/sapphire-ethers-v6": "^6.0.1", "@oceanprotocol/contracts": "^3.2.0-rc.1", "@oceanprotocol/ddo-js": "^1.1.0", - "@oceanprotocol/lib": "^10.1.0", + "@oceanprotocol/lib": "11.0.0-next.2", "chalk": "^6.0.1", "commander": "^15.0.0", "enquirer": "^2.4.1", @@ -1948,9 +1948,9 @@ } }, "node_modules/@oceanprotocol/lib": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/@oceanprotocol/lib/-/lib-10.1.0.tgz", - "integrity": "sha512-cZue8rqPFgPeC1yuht1A1j5nL9M9C/GQVtHYMk4GhoYpkOzAfPMBqHw2gscmf9r8sdtBZEpSXq2TviZdXwamag==", + "version": "11.0.0-next.2", + "resolved": "https://registry.npmjs.org/@oceanprotocol/lib/-/lib-11.0.0-next.2.tgz", + "integrity": "sha512-GL25UcuKX851JBD3uXnyuhIMMoDAT2/Xj10DkryTXmSktAl0UaGBDv8quiJQWdB7+9qaWWR1NNxWn2/u1uOSGQ==", "license": "Apache-2.0", "dependencies": { "@chainsafe/libp2p-noise": "^17.0.0", @@ -1967,7 +1967,7 @@ "@libp2p/websockets": "^10.1.21", "@multiformats/multiaddr": "^13.0.3", "@oasisprotocol/sapphire-ethers-v6": "^6.0.1", - "@oceanprotocol/ddo-js": "^1.0.0", + "@oceanprotocol/ddo-js": "^1.1.0", "bignumber.js": "^11.1.5", "cross-fetch": "^4.1.0", "crypto-js": "^4.2.0", diff --git a/package.json b/package.json index 64f4ee3..e84b36c 100644 --- a/package.json +++ b/package.json @@ -77,7 +77,7 @@ "@oasisprotocol/sapphire-ethers-v6": "^6.0.1", "@oceanprotocol/contracts": "^3.2.0-rc.1", "@oceanprotocol/ddo-js": "^1.1.0", - "@oceanprotocol/lib": "^10.1.0", + "@oceanprotocol/lib": "11.0.0-next.2", "chalk": "^6.0.1", "commander": "^15.0.0", "enquirer": "^2.4.1", diff --git a/src/cli.ts b/src/cli.ts index bfc3dde..9cf9da2 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -10,6 +10,8 @@ import { isP2pUri, ServiceStatusNumber, ServiceRestartParams, + decodeJwt, + listScopableCommands, } from "@oceanprotocol/lib"; import { parseComputeInput, @@ -72,6 +74,10 @@ const NODE_FREE_COMMANDS = new Set([ "listChains", "setChain", "getChain", + // Pure auth-token helpers — a static command catalog and a local JWT decoder. + // Neither touches the node, RPC, or signer. + "listScopableCommands", + "decodeAuthToken", ]); // Topic grouping for the help listing. Purely presentational: it only changes how the command @@ -143,7 +149,14 @@ const HELP_GROUPS: HelpGroup[] = [ }, { heading: "Tokens & auth", - commands: ["mintOcean", "generateAuthToken", "invalidateAuthToken"], + commands: [ + "mintOcean", + "generateAuthToken", + "invalidateAuthToken", + "getNodeAuthTokenPolicy", + "listScopableCommands", + "decodeAuthToken", + ], }, { heading: "Escrow payments", @@ -427,7 +440,20 @@ export async function createCLI() { argv[0] === "help" || argv[0] === "h"; - if (!isHelpOrVersion) { + // The pure auth-token helpers — a static command catalog (`listScopableCommands`) + // and a local JWT decoder (`decodeAuthToken`) — touch no node, RPC, or signer, so + // like help/version they must run with no configuration at all. Matched against the + // raw argv[0], so this lists canonical names AND aliases. + const CREDENTIAL_FREE_COMMANDS = new Set([ + "listScopableCommands", + "scopableCommands", + "decodeAuthToken", + "decodeToken", + ]); + const skipStartupConfig = + isHelpOrVersion || CREDENTIAL_FREE_COMMANDS.has(argv[0]); + + if (!skipStartupConfig) { if (!process.env.MNEMONIC && !process.env.PRIVATE_KEY) { console.error( chalk.red("Have you forgot to set MNEMONIC or PRIVATE_KEY?"), @@ -451,7 +477,7 @@ export async function createCLI() { // NODE_URL is optional: without it the CLI still starts, but only the commands in // NODE_FREE_COMMANDS are accepted until `setNode` picks a node (see the gate below). - if (!isHelpOrVersion) { + if (!skipStartupConfig) { if (process.env.DISABLE_P2P === "true" && isP2pUri(getCurrentNodeUrl())) { console.error( chalk.red( @@ -2169,11 +2195,120 @@ export async function createCLI() { // Generate new auth token program .command("generateAuthToken") - .description("Generate new auth token") + .description( + "Generate a new (node-scoped, self-expiring) auth token. v2 tokens require an expiry; the CLI defaults to 1h.", + ) + .option( + "--ttl ", + "Token lifetime in seconds (default 3600; the default is capped to the node's policy)", + ) + .option( + "--valid-until ", + "Absolute expiry as epoch-milliseconds (overrides --ttl)", + ) + .option( + "--audience ", + "Comma-separated node peerIds the token is valid at, or 'any' for an unrestricted (reusable, network-wide) token. Omit for node-scoped.", + ) + .option( + "--scope ", + "Comma-separated protocol commands the token may perform (see listScopableCommands). Omit for any command.", + ) + .option( + "--allow-unverified-issuer", + "Skip the OJ-03 node-identity check (insecure; only for nodes that predate it)", + ) + .action(async (options) => { + const { signer, chainId } = await initializeSigner(); + const commands = new Commands(signer, chainId); + await commands.generateAuthToken({ + ttl: options.ttl, + validUntil: options.validUntil, + audience: options.audience, + scope: options.scope, + allowUnverifiedIssuer: options.allowUnverifiedIssuer, + }); + }); + + // Show the current node's auth-token policy + program + .command("getNodeAuthTokenPolicy") + .alias("authTokenPolicy") + .description( + "Show the current node's auth-token policy (max lifetime, cross-node federation, revocation posture)", + ) .action(async () => { const { signer, chainId } = await initializeSigner(); const commands = new Commands(signer, chainId); - await commands.generateAuthToken(); + await commands.getNodeAuthTokenPolicy(); + }); + + // List the commands that may appear in an auth-token --scope (node-free, static catalog) + program + .command("listScopableCommands") + .alias("scopableCommands") + .description( + "List the protocol commands that may appear in an auth-token --scope", + ) + .action(() => { + const commands = listScopableCommands(); + console.log(`Scopable commands (${commands.length}):`); + for (const c of commands) { + console.log( + ` ${c.command.padEnd(28)} ${String(c.category).padEnd(10)} ${c.description}`, + ); + } + }); + + // Decode an auth token locally (node-free; pure, no signer/RPC needed) + program + .command("decodeAuthToken") + .alias("decodeToken") + .description( + "Decode an auth token locally and print its claims (scope, audience, expiry)", + ) + .argument("[token]", "Auth token (JWT) to decode") + .option("-t, --token ", "Auth token to decode") + .action((token, options) => { + const authToken = options.token || token; + if (!authToken) { + throw new Error( + "An auth token is required. Pass it positionally or with --token.", + ); + } + // decodeJwt throws "Error decoding JWT" on a malformed token (or one with + // no string `address` claim); turn that into an actionable message. + let claims; + try { + claims = decodeJwt(authToken); + } catch { + throw new Error( + "Could not decode the token (not a valid JWT, or missing the address claim).", + ); + } + console.log(JSON.stringify(claims, null, 2)); + // Local decode only — the signature is NOT checked here. Anyone can craft + // a JWT with any payload, so the claims above are untrusted. + console.log( + chalk.yellow( + "Decoded locally — signature NOT verified; treat these claims as untrusted.", + ), + ); + // `validUntil` is signed epoch-ms on a v2 token. Guard against missing, + // malformed, or out-of-Date-range values so a bad token can't throw here. + const vu = claims.validUntil; + if (Number.isFinite(vu) && Math.abs(vu as number) <= 8.64e15) { + const expired = (vu as number) < Date.now(); + console.log( + `Valid until: ${new Date(vu as number).toISOString()}${ + expired ? chalk.yellow(" (expired)") : "" + }`, + ); + } else if (vu !== undefined) { + console.log( + chalk.yellow(`Valid until: unparseable validUntil value (${vu}).`), + ); + } }); // Invalidate auth token diff --git a/src/commands.ts b/src/commands.ts index 25939a3..f31f463 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -15,6 +15,8 @@ import { summarizeComputeEnvFees, prefundedLockUnits, resolveSubsidyProviderAddresses, + parseAuthTokenOptions, + AuthTokenCliOptions, } from "./helpers.js"; import { getConfigFor, @@ -55,6 +57,10 @@ import { ServiceStartParams, ServiceStatusNumber, ServiceTemplatePublic, + AuthTokenOptions, + AuthTokenPolicy, + UNRESTRICTED_AUDIENCE, + decodeJwt, } from "@oceanprotocol/lib"; import { Asset, @@ -3198,12 +3204,91 @@ export class Commands { } } - public async generateAuthToken() { + public async generateAuthToken(rawOptions: AuthTokenCliOptions = {}) { + // Read the node's policy first (same status call the lib's OJ-03 challenge + // uses) so we can clamp the default lifetime to the node's cap and give a + // precise error up front. Best-effort: a node that is briefly unreachable + // or predates scoped tokens just yields no cap, and the mint call below + // still surfaces any hard failure. + let policy: AuthTokenPolicy | undefined; + try { + policy = await ProviderInstance.getNodeAuthTokenPolicy(this.oceanNodeUrl); + } catch { + policy = undefined; + } + + const options = parseAuthTokenOptions(rawOptions, policy?.maxTokenLifetime); + + // Warnings go to stderr so the token stays the only thing on stdout + // (`generateAuthToken | …` stays parseable). + if (options.audience === UNRESTRICTED_AUDIENCE) { + console.error( + "Warning: minting an UNRESTRICTED token (audience 'any') — it is a reusable, network-wide bearer. Use HTTPS/Noise and a short lifetime.", + ); + } + if (options.allowUnverifiedIssuer) { + console.error( + "Warning: node-identity verification (OJ-03) disabled via --allow-unverified-issuer — the token may be issued to a spoofed or MITM node. Only use this against a node that predates OJ-03, over a trusted channel.", + ); + } + const authToken = await ProviderInstance.generateAuthToken( this.signer, this.oceanNodeUrl, + options, ); console.log(`Auth token successfully generated: ${authToken}`); + this.printAuthTokenSummary(authToken, options); + } + + /** + * Print a short, human-readable summary (expiry / audience / scope) of a + * freshly minted token. Best-effort: the token was already printed in full, + * so a decode failure is swallowed. + */ + private printAuthTokenSummary(token: string, options: AuthTokenOptions) { + // Diagnostic summary → stderr, so stdout carries only the token line above. + try { + const claims = decodeJwt(token); + const validUntil = claims?.validUntil ?? options.validUntil; + if (Number.isFinite(validUntil) && Math.abs(validUntil) <= 8.64e15) { + console.error( + ` Valid until: ${new Date(validUntil).toISOString()} (${validUntil})`, + ); + } + if (options.audience === UNRESTRICTED_AUDIENCE) { + console.error(" Audience: any (unrestricted — reusable at any node)"); + } else { + const audience = + claims?.audience ?? + (Array.isArray(options.audience) ? options.audience : undefined); + console.error( + ` Audience: ${ + audience?.length ? audience.join(", ") : "this node (node-scoped)" + }`, + ); + } + const scope = claims?.scope ?? options.scope; + console.error( + ` Scope: ${scope?.length ? scope.join(", ") : "any command"}`, + ); + } catch { + // decoding is best-effort; the full token is already printed above. + } + } + + public async getNodeAuthTokenPolicy() { + const policy = await ProviderInstance.getNodeAuthTokenPolicy( + this.oceanNodeUrl, + ); + if (!policy) { + console.log( + "This node did not report an auth-token policy (it may predate scoped auth tokens).", + ); + return; + } + console.log(`Auth-token policy for ${this.oceanNodeUrl}:`); + console.log(JSON.stringify(policy, null, 2)); } public async invalidateAuthToken(args: string[]) { diff --git a/src/helpers.ts b/src/helpers.ts index 829effa..5eeef6d 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -29,6 +29,8 @@ import { createAsset, LoggerInstance, JobSubsidyEstimate, + AuthTokenOptions, + UNRESTRICTED_AUDIENCE, } from "@oceanprotocol/lib"; import { createRequire } from "module"; @@ -759,6 +761,123 @@ export function parseSubsidyProviders(raw?: string): string[] | undefined { return trimmed.split(",").map((a) => ethers.getAddress(a.trim())); } +/** + * Default lifetime (seconds) the CLI applies to a minted auth token when the + * user passes neither `--ttl` nor `--valid-until`. ocean.js (v11) deliberately + * refuses to default `validUntil` for a v2 token, so the CLI — a UX layer — + * supplies a sensible one here. It is still capped to the node's advertised + * `maxTokenLifetime` when that is known (see {@link parseAuthTokenOptions}). + */ +export const DEFAULT_AUTH_TOKEN_TTL_SECONDS = 3600; + +/** Raw, string-shaped auth-token options as they arrive from Commander flags. */ +export interface AuthTokenCliOptions { + /** Lifetime in seconds (string from the CLI or a number). */ + ttl?: string | number; + /** Absolute expiry as epoch-milliseconds; overrides `ttl` when set. */ + validUntil?: string | number; + /** Comma-separated node peerIds, or the literal `any` for an unrestricted token. */ + audience?: string; + /** Comma-separated protocol commands the token may perform. */ + scope?: string; + /** Skip the OJ-03 node-identity check (insecure; for pre-OJ-03 nodes only). */ + allowUnverifiedIssuer?: boolean; +} + +/** + * Turn the raw CLI auth-token flags into the ocean.js {@link AuthTokenOptions} + * object. Pure (no network): the optional `maxTokenLifetimeSeconds` is the + * node's advertised cap, used only to clamp the *default* lifetime so a bare + * `generateAuthToken` keeps working against a node with a short cap. An + * explicit `--ttl`/`--valid-until` is never silently clamped — the lib surfaces + * a precise cap error instead. + */ +export function parseAuthTokenOptions( + raw: AuthTokenCliOptions = {}, + maxTokenLifetimeSeconds?: number, +): AuthTokenOptions { + // --- validUntil (epoch ms), from --valid-until or --ttl, else the default TTL --- + let validUntil: number; + const hasValidUntil = + raw.validUntil !== undefined && `${raw.validUntil}`.trim() !== ""; + if (hasValidUntil) { + validUntil = Number(raw.validUntil); + if (!Number.isInteger(validUntil) || validUntil <= 0) { + throw new Error( + "--valid-until must be a positive epoch-milliseconds integer.", + ); + } + // Reject a value that is already in the past. This also catches the common + // mistake of passing epoch *seconds* (~1.7e9 ⇒ a 1970 date), which would + // otherwise mint a token that is born expired. + if (validUntil <= Date.now()) { + throw new Error( + "--valid-until is in the past — it must be a FUTURE epoch-milliseconds value (did you pass seconds instead of milliseconds?).", + ); + } + } else { + const ttlExplicit = raw.ttl !== undefined && `${raw.ttl}`.trim() !== ""; + let ttl = ttlExplicit + ? Number(raw.ttl) + : DEFAULT_AUTH_TOKEN_TTL_SECONDS; + if (!Number.isFinite(ttl) || ttl <= 0) { + throw new Error("--ttl must be a positive number of seconds."); + } + // Clamp only the default, so the bare command still works against a node + // whose cap is shorter than our default; respect an explicit --ttl verbatim. + if ( + !ttlExplicit && + maxTokenLifetimeSeconds && + maxTokenLifetimeSeconds > 0 && + ttl > maxTokenLifetimeSeconds + ) { + ttl = maxTokenLifetimeSeconds; + } + validUntil = Date.now() + Math.floor(ttl * 1000); + } + + const options: AuthTokenOptions = { validUntil }; + + // --- audience: 'any' (unrestricted) or a peerId list (node-scoped) --- + if (raw.audience !== undefined && `${raw.audience}`.trim() !== "") { + const trimmed = `${raw.audience}`.trim(); + if (trimmed.toLowerCase() === UNRESTRICTED_AUDIENCE) { + options.audience = UNRESTRICTED_AUDIENCE; + } else { + const list = trimmed + .split(",") + .map((s) => s.trim()) + .filter(Boolean); + if (list.length === 0) { + throw new Error( + `--audience must be '${UNRESTRICTED_AUDIENCE}' or a comma-separated list of node peerIds.`, + ); + } + options.audience = list; + } + } + + // --- scope: list of protocol commands (validated server-side / by the lib) --- + if (raw.scope !== undefined && `${raw.scope}`.trim() !== "") { + const list = `${raw.scope}` + .split(",") + .map((s) => s.trim()) + .filter(Boolean); + if (list.length === 0) { + throw new Error( + "--scope must be a comma-separated list of protocol commands.", + ); + } + options.scope = list; + } + + if (raw.allowUnverifiedIssuer) { + options.allowUnverifiedIssuer = true; + } + + return options; +} + /** * Resolve the job id for the job-only compute commands (`getJobStatus`, * `stopCompute`) from their positional arguments and `--job` option. diff --git a/test/authTokenCommands.test.ts b/test/authTokenCommands.test.ts new file mode 100644 index 0000000..90c60cd --- /dev/null +++ b/test/authTokenCommands.test.ts @@ -0,0 +1,124 @@ +import { expect } from "chai"; +import { runRepl } from "./util.js"; + +/** + * Infra-free CLI-level tests for the auth-token commands. They exercise command + * registration (node-free vs node-gated, bootstrap env-free), the Commander + * flag→option wiring, and the local decode path — none of which need a running + * Ocean stack. The default runRepl env points NODE_URL/RPC at an unreachable + * 127.0.0.1:1 (instant connection-refused) and disables P2P. + * + * NOTE: these run the real CLI, which imports @oceanprotocol/lib. They require + * the v11 line that ships scoped auth tokens (decodeJwt / listScopableCommands); + * under lib 10.1.0 the CLI fails to import, same gate as the whole feature. + */ +describe("Auth-token CLI commands (infra-free)", function () { + this.timeout(60000); + + // A locally-built, UNSIGNED JWT (alg:none). decodeJwt only base64-decodes the + // payload, so the signature is irrelevant for the decode path. + const b64url = (o: unknown): string => + Buffer.from(JSON.stringify(o)) + .toString("base64") + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); + // decodeJwt (jsonwebtoken) requires a string `address` claim; include it plus + // the other base claims a real token carries. + const makeJwt = (payload: Record): string => + `${b64url({ alg: "none", typ: "JWT" })}.${b64url({ + address: "0x1234567890123456789012345678901234567890", + nonce: "1", + createdAt: Date.now(), + ...payload, + })}.`; + + describe("listScopableCommands (node-free, bootstrap)", function () { + it("runs with no node selected", async function () { + const { output } = await runRepl(["listScopableCommands", "exit"], { + env: { NODE_URL: undefined }, + }); + expect(output).to.match(/Scopable commands \(\d+\)/); + expect(output).to.contain("download"); + expect(output).to.not.contain("no Ocean Node"); + }); + + it("runs with no RPC/PRIVATE_KEY configured (alias scopableCommands)", async function () { + // Driven through argv (how `ocean-cli scopableCommands` is really invoked) so the + // credential-free startup skip applies: this pure command must run with no + // MNEMONIC/PRIVATE_KEY/RPC at all. + const { output } = await runRepl(["exit"], { + extraArgs: ["scopableCommands"], + env: { NODE_URL: undefined, RPC: undefined, PRIVATE_KEY: undefined }, + }); + expect(output).to.match(/Scopable commands \(\d+\)/); + expect(output).to.not.contain("Have you forgot to set env RPC?"); + }); + }); + + describe("decodeAuthToken (node-free, pure)", function () { + it("decodes a token passed positionally and flags it unverified", async function () { + const future = Date.now() + 3_600_000; + const token = makeJwt({ + validUntil: future, + audience: ["peerA"], + scope: ["download"], + }); + // Driven through argv so the credential-free startup skip applies — a local JWT + // decode must work with no MNEMONIC/PRIVATE_KEY/RPC. + const { output } = await runRepl(["exit"], { + extraArgs: ["decodeAuthToken", token], + env: { NODE_URL: undefined, RPC: undefined, PRIVATE_KEY: undefined }, + }); + expect(output).to.contain("download"); + expect(output).to.contain("signature NOT verified"); + expect(output).to.contain("Valid until:"); + }); + + it("accepts --token and the decodeToken alias, and marks an expired token", async function () { + const token = makeJwt({ validUntil: Date.now() - 1000 }); + const { output } = await runRepl( + [`decodeToken --token ${token}`, "exit"], + { env: { NODE_URL: undefined } }, + ); + expect(output).to.contain("(expired)"); + }); + + it("errors when no token is given", async function () { + const { output } = await runRepl(["decodeAuthToken", "exit"], { + env: { NODE_URL: undefined }, + }); + expect(output).to.contain("An auth token is required"); + }); + + it("reports an undecodable token and keeps the REPL alive", async function () { + const { output } = await runRepl( + ["decodeAuthToken not.a.jwt", "listScopableCommands", "exit"], + { env: { NODE_URL: undefined } }, + ); + expect(output).to.contain("Could not decode the token"); + // The REPL survived the error and ran the next command. + expect(output).to.match(/Scopable commands \(\d+\)/); + }); + }); + + describe("getNodeAuthTokenPolicy (node-gated)", function () { + it("is refused when no node is selected", async function () { + const { output } = await runRepl(["getNodeAuthTokenPolicy", "exit"], { + env: { NODE_URL: undefined }, + }); + // Not in NODE_FREE_COMMANDS → the preAction gate refuses it. + expect(output.toLowerCase()).to.contain("node"); + expect(output).to.not.contain("Auth-token policy for"); + }); + }); + + // NOTE: `generateAuthToken` / `getNodeAuthTokenPolicy` run `initializeSigner()` + // first, which verifies the RPC against the chain — so they cannot be driven + // past signer-init against the default dead RPC. The flag→option wiring and + // the parse/validation rules are covered infra-free by + // test/authTokenOptions.test.ts (parseAuthTokenOptions); the end-to-end mint + // path (bare command, --ttl/--audience/--scope round-trips, over-cap error, + // unrestricted warning) is a Barge integration follow-up needing a lib-v11 + // node. +}); diff --git a/test/authTokenOptions.test.ts b/test/authTokenOptions.test.ts new file mode 100644 index 0000000..ee0218f --- /dev/null +++ b/test/authTokenOptions.test.ts @@ -0,0 +1,172 @@ +import { expect } from "chai"; +import { + parseAuthTokenOptions, + DEFAULT_AUTH_TOKEN_TTL_SECONDS, +} from "../src/helpers.js"; + +/** + * Infra-free unit tests for the pure `parseAuthTokenOptions` helper that turns + * the raw `generateAuthToken` CLI flags into the ocean.js `AuthTokenOptions`. + * No network, no node, no signer — just the parsing/clamping rules. + */ +describe("parseAuthTokenOptions (pure)", function () { + const nowish = (ms: number) => Math.abs(ms - Date.now()) < 5000; + + it("defaults to a 1h lifetime when nothing is passed", function () { + const o = parseAuthTokenOptions({}); + expect(nowish(o.validUntil - DEFAULT_AUTH_TOKEN_TTL_SECONDS * 1000)).to.be + .true; + expect(o.audience).to.equal(undefined); + expect(o.scope).to.equal(undefined); + expect(o.allowUnverifiedIssuer).to.equal(undefined); + }); + + it("honors an explicit --ttl (seconds)", function () { + const o = parseAuthTokenOptions({ ttl: "900" }); + expect(nowish(o.validUntil - 900 * 1000)).to.be.true; + }); + + it("--valid-until overrides --ttl and is taken verbatim", function () { + const abs = Date.now() + 2 * 3600 * 1000; // a clearly-future epoch-ms + const o = parseAuthTokenOptions({ ttl: "900", validUntil: String(abs) }); + expect(o.validUntil).to.equal(abs); + }); + + it("clamps only the DEFAULT lifetime to the node cap", function () { + const o = parseAuthTokenOptions({}, 600); // cap 10 min < 1h default + expect(nowish(o.validUntil - 600 * 1000)).to.be.true; + }); + + it("does NOT clamp an explicit --ttl (lib surfaces the cap error)", function () { + const o = parseAuthTokenOptions({ ttl: "7200" }, 600); + expect(nowish(o.validUntil - 7200 * 1000)).to.be.true; + }); + + it("parses an audience peerId list", function () { + const o = parseAuthTokenOptions({ audience: "peerA, peerB ,peerC" }); + expect(o.audience).to.deep.equal(["peerA", "peerB", "peerC"]); + }); + + it("maps audience 'any' (any case) to the unrestricted sentinel", function () { + expect(parseAuthTokenOptions({ audience: "any" }).audience).to.equal("any"); + expect(parseAuthTokenOptions({ audience: "ANY" }).audience).to.equal("any"); + }); + + it("parses a scope command list", function () { + const o = parseAuthTokenOptions({ scope: "download, getDDO" }); + expect(o.scope).to.deep.equal(["download", "getDDO"]); + }); + + it("passes allowUnverifiedIssuer through only when truthy", function () { + expect( + parseAuthTokenOptions({ allowUnverifiedIssuer: true }).allowUnverifiedIssuer, + ).to.equal(true); + expect(parseAuthTokenOptions({}).allowUnverifiedIssuer).to.equal(undefined); + }); + + it("rejects a non-positive / non-integer --valid-until", function () { + expect(() => parseAuthTokenOptions({ validUntil: "0" })).to.throw( + "--valid-until", + ); + expect(() => parseAuthTokenOptions({ validUntil: "-5" })).to.throw( + "--valid-until", + ); + expect(() => parseAuthTokenOptions({ validUntil: "abc" })).to.throw( + "--valid-until", + ); + }); + + it("rejects a non-positive --ttl", function () { + expect(() => parseAuthTokenOptions({ ttl: "0" })).to.throw("--ttl"); + expect(() => parseAuthTokenOptions({ ttl: "nope" })).to.throw("--ttl"); + }); + + it("rejects a --valid-until in the past (seconds-vs-ms footgun)", function () { + // ~epoch seconds for a current date ⇒ a 1970 ms date + expect(() => parseAuthTokenOptions({ validUntil: "1793456789" })).to.throw( + /future/i, + ); + expect(() => + parseAuthTokenOptions({ validUntil: String(Date.now() - 1000) }), + ).to.throw(/future/i); + }); + + it("falls back to the default when ttl/validUntil are blank/whitespace", function () { + for (const raw of [ + { ttl: "" }, + { ttl: " " }, + { validUntil: "" }, + ]) { + const o = parseAuthTokenOptions(raw); + expect(nowish(o.validUntil - DEFAULT_AUTH_TOKEN_TTL_SECONDS * 1000)).to.be + .true; + } + }); + + it("invalid --valid-until throws even when a valid --ttl is present (no silent fallthrough)", function () { + expect(() => + parseAuthTokenOptions({ validUntil: "abc", ttl: "900" }), + ).to.throw("--valid-until"); + }); + + it("accepts numeric (non-string) ttl and validUntil inputs", function () { + expect(nowish(parseAuthTokenOptions({ ttl: 900 }).validUntil - 900 * 1000)) + .to.be.true; + const abs = Date.now() + 10 * 60 * 1000; + expect(parseAuthTokenOptions({ validUntil: abs }).validUntil).to.equal(abs); + }); + + it("leaves audience/scope undefined for blank input (never an empty array)", function () { + const o = parseAuthTokenOptions({ audience: " ", scope: "" }); + expect(o.audience).to.equal(undefined); + expect(o.scope).to.equal(undefined); + }); + + it("throws when audience/scope are only separators (empty after filtering)", function () { + expect(() => parseAuthTokenOptions({ audience: " , " })).to.throw( + "--audience", + ); + expect(() => parseAuthTokenOptions({ scope: ",," })).to.throw("--scope"); + }); + + it("clamp only triggers for the default and only when cap is shorter", function () { + // cap >= default: no clamp + expect( + nowish( + parseAuthTokenOptions({}, 7200).validUntil - + DEFAULT_AUTH_TOKEN_TTL_SECONDS * 1000, + ), + ).to.be.true; + // cap 0 / undefined: ignored + expect( + nowish( + parseAuthTokenOptions({}, 0).validUntil - + DEFAULT_AUTH_TOKEN_TTL_SECONDS * 1000, + ), + ).to.be.true; + // explicit ttl is never clamped even below cap + expect(nowish(parseAuthTokenOptions({ ttl: "3600" }, 600).validUntil - 3600 * 1000)) + .to.be.true; + }); + + it("always produces an integer validUntil", function () { + expect(Number.isInteger(parseAuthTokenOptions({ ttl: "0.5" }).validUntil)).to + .be.true; + }); + + it("builds a fully-populated options object", function () { + const abs = Date.now() + 60_000; + const o = parseAuthTokenOptions({ + validUntil: String(abs), + audience: "peerA,peerB", + scope: "download", + allowUnverifiedIssuer: true, + }); + expect(o).to.deep.equal({ + validUntil: abs, + audience: ["peerA", "peerB"], + scope: ["download"], + allowUnverifiedIssuer: true, + }); + }); +}); From d0c59ec1f29852655542f9e343ab4e530b06a7b2 Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Fri, 27 Nov 2026 14:22:36 +0200 Subject: [PATCH 2/2] address review: keep stdout = token only; tighten node-gate test - Commands constructor: route the "Using Ocean Node URL" diagnostic to stderr (it runs for every command and polluted generateAuthToken stdout). - generateAuthToken: print only the token to stdout (drop the "Auth token successfully generated:" prefix) so `generateAuthToken | ...` is parseable. Summary and warnings remain on stderr. - authTokenCommands test: assert the specific "No Ocean Node set" gate message instead of a bare "node" substring (the command name itself contains "node", so an unknown-command error could have satisfied it). Co-Authored-By: Claude Opus 4.8 --- src/commands.ts | 6 ++++-- test/authTokenCommands.test.ts | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/commands.ts b/src/commands.ts index f31f463..ebac660 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -176,7 +176,7 @@ export class Commands { } this.oceanNodeUrl = process.env.NODE_URL; this.indexingParams = getIndexingWaitSettings(); - console.log("Using Ocean Node URL :", this.oceanNodeUrl); + console.error("Using Ocean Node URL :", this.oceanNodeUrl); this.config.nodeUri = this.oceanNodeUrl; } @@ -3237,7 +3237,9 @@ export class Commands { this.oceanNodeUrl, options, ); - console.log(`Auth token successfully generated: ${authToken}`); + // Only the token goes to stdout, so `generateAuthToken | …` stays parseable; + // the human-readable summary below is written to stderr. + console.log(authToken); this.printAuthTokenSummary(authToken, options); } diff --git a/test/authTokenCommands.test.ts b/test/authTokenCommands.test.ts index 90c60cd..31103cf 100644 --- a/test/authTokenCommands.test.ts +++ b/test/authTokenCommands.test.ts @@ -107,8 +107,10 @@ describe("Auth-token CLI commands (infra-free)", function () { const { output } = await runRepl(["getNodeAuthTokenPolicy", "exit"], { env: { NODE_URL: undefined }, }); - // Not in NODE_FREE_COMMANDS → the preAction gate refuses it. - expect(output.toLowerCase()).to.contain("node"); + // Not in NODE_FREE_COMMANDS → the preAction gate refuses it with this exact + // message. Asserting the specific text (not just "node", which the command + // name itself contains) means an unknown-command error can't satisfy it. + expect(output).to.contain("No Ocean Node set"); expect(output).to.not.contain("Auth-token policy for"); }); });