diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2d19198..0295a45 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,9 +36,24 @@ jobs: node-version: ${{ matrix.node }} cache: npm + # ocean.js#2216 build; remove with the link step after its release + - name: Checkout ocean.js + uses: actions/checkout@v7 + with: + persist-credentials: false + repository: 'oceanprotocol/ocean.js' + ref: 'rc_11.0.0' + path: 'ocean.js' + - name: Build and link ocean.js + working-directory: ${{ github.workspace }}/ocean.js + run: npm ci && npm run build && npm link + - name: Install dependencies run: npm ci + - name: Use the ocean.js build + run: npm link @oceanprotocol/lib + - name: Run build run: npm run build @@ -143,6 +158,9 @@ jobs: test_system: runs-on: ubuntu-latest + env: + # ocean-node#1601 image; remove after its release + NODE_VERSION: pr-1601 strategy: fail-fast: false matrix: @@ -183,8 +201,23 @@ jobs: working-directory: ${{ github.workspace }}/barge run: | bash -x start_ocean.sh --with-typesense 2>&1 > start_ocean.log & + # ocean.js#2216 build; remove with the link step after its release + - name: Checkout ocean.js + uses: actions/checkout@v7 + with: + persist-credentials: false + repository: 'oceanprotocol/ocean.js' + ref: 'rc_11.0.0' + path: 'ocean.js' + - name: Build and link ocean.js + working-directory: ${{ github.workspace }}/ocean.js + run: npm ci && npm run build && npm link + - name: Install dependencies run: npm ci + - name: Use the ocean.js build + run: npm link @oceanprotocol/lib + - run: npm run build - run: docker image ls - name: Wait for node to be ready @@ -219,7 +252,7 @@ jobs: attempt=1 echo "Waiting for node HTTP API to be ready..." while [ $attempt -le $max_attempts ]; do - PEER_ID=$(curl -s http://127.0.0.1:8001 | jq -r '.nodeId // empty' 2>/dev/null) + PEER_ID=$(curl -s http://127.0.0.1:8001 | jq -r '.id // empty' 2>/dev/null) if [ -n "$PEER_ID" ]; then echo "Got peer ID: $PEER_ID" echo "NODE_URL=${PEER_ID}" >> $GITHUB_ENV diff --git a/CLAUDE.md b/CLAUDE.md index d4342a7..deb9426 100755 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -118,7 +118,7 @@ One big class holding all command logic. The constructor: - sets `this.config = config || new ConfigHelper().getConfig(network)` — ocean.js's `ConfigHelper` maps a chainId (or name) to a network config object, - sets `this.oceanNodeUrl = process.env.NODE_URL` and `this.config.nodeUri = this.oceanNodeUrl`, -- creates `this.aquarius = new Aquarius(this.oceanNodeUrl)` (the Ocean Node also serves the Aquarius/indexer API), +- resolves and validates DDOs with `ProviderInstance` against `this.oceanNodeUrl` (`waitForIndexer`, `validateDdo`), - loads `this.indexingParams` from `getIndexingWaitSettings()`. ### Config & chain selection — one mechanism (important) @@ -157,9 +157,9 @@ uses directly. `destroyProviders()` tears providers down on exit (next to `stopP `helpers.ts` is the seam between the CLI and ocean.js: - `createAssetUtil(...)` wraps ocean.js `createAsset` (used by publish/publishAlgo and the interactive publisher). It resolves the active ERC20 template (`calculateActiveTemplateIndex` reads and `JSON.parse`s the `@oceanprotocol/contracts` `ERC20Template.json` ABI, resolved via `createRequire`/`require.resolve` so it works from any cwd — e.g. a global install — not a cwd-relative `node_modules` path), and for **Oasis Sapphire** (`config.sdk === 'oasis'`) wraps the signer with `wrapEthersSigner` from `@oasisprotocol/sapphire-ethers-v6` (`getSignerAccordingSdk`; sapphire-paratime v2 moved its ethers integration into that package, and it throws `SignerHasNoProviderError` for a provider-less signer) and deploys an allow access list before creating the asset. -- `updateAssetMetadata(...)` — used by `editAsset`, `allowAlgo`, `disallowAlgo` and the interactive publisher. It validates the DDO via `aquarius.validate`, then either `ProviderInstance.encrypt`s the DDO (flags = 2) or hexlifies raw JSON (flags = 0) depending on the `encryptDDO` flag, then calls `nft.setMetadata`. +- `updateAssetMetadata(...)` — used by `editAsset`, `allowAlgo`, `disallowAlgo` and the interactive publisher. It validates the DDO via `ProviderInstance.validateDdo`, then either `ProviderInstance.encrypt`s the DDO (flags = 2) or hexlifies raw JSON (flags = 0) depending on the `encryptDDO` flag, then calls `nft.setMetadata`. - `handleComputeOrder(...)` — the ordering state machine used in compute: validOrder + no fees → reuse as-is; validOrder + fees → `datatoken.reuseOrder` paying only provider fees; no order → `orderAsset` (pay 1 datatoken + fees). Approves provider-fee tokens first when the fee amount > 0. -- `resolveComputeInputs(...)` + `parseComputeInput(...)` — parse the datasets/algo CLI strings (DID | JSON object | array | mixed | legacy `[did:a,did:b]`), resolve DID entries through `aquarius.waitForIndexer`, pass raw entries through (a `fileObject`, or for an algorithm inline `meta.rawcode`; aligned with a `null` DDO slot), and pick `providerURI` from the first DID-based DDO's `serviceEndpoint` (else fall back to `NODE_URL`). +- `resolveComputeInputs(...)` + `parseComputeInput(...)` — parse the datasets/algo CLI strings (DID | JSON object | array | mixed | legacy `[did:a,did:b]`), resolve DID entries through `ProviderInstance.waitForIndexer` on the node, pass raw entries through (a `fileObject`, or for an algorithm inline `meta.rawcode`; aligned with a `null` DDO slot), and pick `providerURI` from the first DID-based DDO's `serviceEndpoint` (else fall back to `NODE_URL`). - `fixAndParseProviderFees(...)` — regex-based repair of the stringified provider-initialize response that is round-tripped from `initializeCompute` into `computeStart` (adds quotes to keys, DIDs, hex addresses). Fragile by design; touch carefully. - `getIndexingWaitSettings()` — reads the `INDEXING_*` env vars. - Signing/encryption is always done via the `Signer` and `ProviderInstance` from ocean.js; the CLI never handles raw keys beyond constructing the `ethers.Wallet`. @@ -231,7 +231,7 @@ Most tests are **integration/system tests that require a running Ocean stack** ( - `test/setup.test.ts` — asserts `npm run cli h` help output and the env-var validation error messages. - `test/consumeFlow.test.ts`, `paidComputeFlow.test.ts`, `escrow.test.ts`, `accessList.test.ts`, `storage.test.ts` — end-to-end flows against the live node. - `test/http.test.ts` — hits the node HTTP API (`localhost:8001`) directly. -- `test/resolveComputeInputs.test.ts` — a **true unit test** using a fake `Aquarius`; runs with no infra. +- `test/resolveComputeInputs.test.ts` — a **true unit test** that stubs `ProviderInstance.waitForIndexer`; runs with no infra. - `test/interactivePublishFlow.ts` — the enquirer wizard (note: no `.test.ts` suffix, so it is not picked up by the `test:system` glob). CI (`.github/workflows/ci.yml`) has three jobs: `build`, `lint`, and `test_system` (matrix over `transport: [http, p2p]`), which checks out `oceanprotocol/barge`, runs `start_ocean.sh --with-typesense`, waits for `ocean-node-1`, sets `NODE_URL` (HTTP `http://127.0.0.1:8001`, or the peer id for P2P), and runs `npm run test:system` with `AVOID_LOOP_RUN=true` and `INDEXING_RETRY_INTERVAL=4000` / `INDEXING_MAX_RETRIES=120`. 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 9640fe8..ebac660 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -15,6 +15,8 @@ import { summarizeComputeEnvFees, prefundedLockUnits, resolveSubsidyProviderAddresses, + parseAuthTokenOptions, + AuthTokenCliOptions, } from "./helpers.js"; import { getConfigFor, @@ -24,7 +26,6 @@ import { listChains, } from "./rpcRegistry.js"; import { - Aquarius, ComputeAsset, ComputeJob, Config, @@ -56,6 +57,10 @@ import { ServiceStartParams, ServiceStatusNumber, ServiceTemplatePublic, + AuthTokenOptions, + AuthTokenPolicy, + UNRESTRICTED_AUDIENCE, + decodeJwt, } from "@oceanprotocol/lib"; import { Asset, @@ -152,7 +157,6 @@ function formatAmountDiff(total: number, share: string): string { export class Commands { public signer: Signer; public config: Config; - public aquarius: Aquarius; public oceanNodeUrl: string; // optional settings for indexing wait time private indexingParams: IndexerWaitParams; @@ -172,9 +176,8 @@ 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; - this.aquarius = new Aquarius(this.oceanNodeUrl); } // --------------------------------------------------------------------------- @@ -310,7 +313,7 @@ export class Commands { public async start() { console.log("Starting the interactive CLI flow...\n\n"); const data = await interactiveFlow(this.oceanNodeUrl); // Collect data via CLI - await publishAsset(this.aquarius, data, this.signer, this.config); // Publish asset with collected data + await publishAsset(data, this.signer, this.config); // Publish asset with collected data } // utils @@ -349,7 +352,6 @@ export class Commands { asset, this.oceanNodeUrl, this.config, - this.aquarius, encryptDDO, ); console.log("Asset published. ID: " + urlAssetId); @@ -387,7 +389,6 @@ export class Commands { algoAsset, this.oceanNodeUrl, this.config, - this.aquarius, encryptDDO, ); // add some more checks @@ -400,7 +401,8 @@ export class Commands { } public async editAsset(args: string[]) { - const asset = await this.aquarius.waitForIndexer( + const asset = await ProviderInstance.waitForIndexer( + this.oceanNodeUrl, args[1], null, null, @@ -435,7 +437,6 @@ export class Commands { this.signer, asset, this.oceanNodeUrl, - this.aquarius, encryptDDO, ); console.log("Asset updated. Tx: " + JSON.stringify(updateAssetTx, null, 2)); @@ -443,7 +444,8 @@ export class Commands { public async getDDO(args: string[]) { console.log("Resolving Asset with DID: " + args[1]); - const resolvedDDO = await this.aquarius.waitForIndexer( + const resolvedDDO = await ProviderInstance.waitForIndexer( + this.oceanNodeUrl, args[1], null, null, @@ -512,7 +514,8 @@ export class Commands { public async download(args: string[]) { const did = args[1]; - const dataDdo = await this.aquarius.waitForIndexer( + const dataDdo = await ProviderInstance.waitForIndexer( + this.oceanNodeUrl, did, null, null, @@ -635,7 +638,6 @@ export class Commands { const resolved = await resolveComputeInputs( args[1], args[2], - this.aquarius, this.indexingParams, this.oceanNodeUrl, ); @@ -1038,7 +1040,6 @@ export class Commands { const resolved = await resolveComputeInputs( args[1], args[2], - this.aquarius, this.indexingParams, this.oceanNodeUrl, ); @@ -1657,7 +1658,6 @@ export class Commands { const resolved = await resolveComputeInputs( args[1], args[2], - this.aquarius, this.indexingParams, this.oceanNodeUrl, ); @@ -2949,7 +2949,8 @@ export class Commands { } public async allowAlgo(args: string[]) { - const asset = await this.aquarius.waitForIndexer( + const asset = await ProviderInstance.waitForIndexer( + this.oceanNodeUrl, args[1], null, null, @@ -2982,7 +2983,8 @@ export class Commands { ); return; } - const algoAsset = await this.aquarius.waitForIndexer( + const algoAsset = await ProviderInstance.waitForIndexer( + this.oceanNodeUrl, args[2], null, null, @@ -3034,7 +3036,6 @@ export class Commands { this.signer, asset, this.oceanNodeUrl, - this.aquarius, encryptDDO, ); console.log("Successfully updated asset metadata: " + txid); @@ -3045,7 +3046,8 @@ export class Commands { } public async disallowAlgo(args: string[]) { - const asset = await this.aquarius.waitForIndexer( + const asset = await ProviderInstance.waitForIndexer( + this.oceanNodeUrl, args[1], null, null, @@ -3103,7 +3105,6 @@ export class Commands { this.signer, asset, this.oceanNodeUrl, - this.aquarius, encryptDDO, ); console.log("Asset updated " + txid); @@ -3203,12 +3204,93 @@ 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, + ); + // 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); + } + + /** + * 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, ); - console.log(`Auth token successfully generated: ${authToken}`); + 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 fc7e3de..5eeef6d 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -11,7 +11,6 @@ import { } from "@oceanprotocol/ddo-js"; import { AccesslistFactory, - Aquarius, Nft, NftFactory, ProviderInstance, @@ -30,6 +29,8 @@ import { createAsset, LoggerInstance, JobSubsidyEstimate, + AuthTokenOptions, + UNRESTRICTED_AUDIENCE, } from "@oceanprotocol/lib"; import { createRequire } from "module"; @@ -141,7 +142,6 @@ export async function createAssetUtil( ddo: DDO, oceanNodeUrl: string, config: Config, - aquariusInstance: Aquarius, encryptDDO: boolean = true, templateIDorAddress: string | number = 1, // If string, it's template address , otherwise, it's templateId, providerFeeToken: string = ZERO_ADDRESS, @@ -184,7 +184,6 @@ export async function createAssetUtil( encryptDDO, oceanNodeUrl, providerFeeToken, - aquariusInstance, accessListFactory, allowAccessList, denyAccessList, @@ -200,7 +199,6 @@ export async function createAssetUtil( encryptDDO, oceanNodeUrl, providerFeeToken, - aquariusInstance, ); } @@ -208,7 +206,6 @@ export async function updateAssetMetadata( owner: Signer, updatedDdo: Asset, oceanNodeUrl: string, - aquariusInstance: Aquarius, encryptDDO: boolean = true, ): Promise { const nft = new Nft( @@ -217,11 +214,12 @@ export async function updateAssetMetadata( ); let flags; let metadata; - const validateResult = await aquariusInstance.validate( + const validateResult = await ProviderInstance.validateDdo( + oceanNodeUrl, updatedDdo, owner, - oceanNodeUrl, ); + if (!validateResult) throw new Error("DDO validation failed"); const ddoInstance = DDOManager.getDDOClass(updatedDdo); const { chainId, nftAddress } = ddoInstance.getDDOFields(); if (encryptDDO) { @@ -424,14 +422,13 @@ export function parseComputeInput( // Resolves the raw datasets/algo CLI strings into fully-built ComputeAsset[] and // ComputeAlgorithm, plus index-aligned DDO arrays (null where the entry is raw). -// DID entries are resolved via Aquarius; raw (fileObject) entries are passed through +// DID entries are resolved on nodeUri; raw (fileObject) entries are passed through // untouched. Returns null (after logging) when a DID cannot be resolved. export async function resolveComputeInputs( datasetsInput: string, algoInput: string, - aquarius: Aquarius, indexingParams: IndexerWaitParams, - fallbackProviderURI: string, + nodeUri: string, ): Promise { const datasetTokens = parseComputeInput(datasetsInput); @@ -440,7 +437,8 @@ export async function resolveComputeInputs( for (const token of datasetTokens) { if (typeof token === "string") { - const dataDdo = await aquarius.waitForIndexer( + const dataDdo = await ProviderInstance.waitForIndexer( + nodeUri, token, undefined, undefined, @@ -484,7 +482,7 @@ export async function resolveComputeInputs( } } - let providerURI = fallbackProviderURI; + let providerURI = nodeUri; const firstDdo = ddos.find((d) => d !== null); if (firstDdo) { providerURI = @@ -498,7 +496,8 @@ export async function resolveComputeInputs( let algoDdo: Asset | DDO | null = null; if (typeof algoToken === "string") { - algoDdo = await aquarius.waitForIndexer( + algoDdo = await ProviderInstance.waitForIndexer( + nodeUri, algoToken, undefined, undefined, @@ -762,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/src/publishAsset.ts b/src/publishAsset.ts index 75e078c..05199a4 100644 --- a/src/publishAsset.ts +++ b/src/publishAsset.ts @@ -1,6 +1,6 @@ // src/publishAsset.ts import { Signer } from "ethers"; -import { Config, Aquarius } from "@oceanprotocol/lib"; +import { Config } from "@oceanprotocol/lib"; import { Asset } from "@oceanprotocol/ddo-js"; import { createAssetUtil, updateAssetMetadata } from "./helpers.js"; @@ -21,7 +21,6 @@ export interface PublishAssetParams { } export async function publishAsset( - aquarius: Aquarius, params: PublishAssetParams, signer: Signer, config: Config, @@ -105,7 +104,6 @@ export async function publishAsset( metadata, params.providerUrl, config, - aquarius, ); console.log(`Asset successfully published with DID: ${did}`); @@ -116,7 +114,7 @@ export async function publishAsset( metadata.services[0].datatokenAddress = assetUrl.datatokenAddress; // Update with the correct Datatoken address // Use the helper function to update the metadata on the NFT - await updateAssetMetadata(signer, metadata, params.providerUrl, aquarius); + await updateAssetMetadata(signer, metadata, params.providerUrl); console.log(`Metadata successfully updated for DID: ${did}`); } catch (error) { diff --git a/test/authTokenCommands.test.ts b/test/authTokenCommands.test.ts new file mode 100644 index 0000000..31103cf --- /dev/null +++ b/test/authTokenCommands.test.ts @@ -0,0 +1,126 @@ +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 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"); + }); + }); + + // 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, + }); + }); +}); diff --git a/test/http.test.ts b/test/http.test.ts index 20c59d8..1fd6172 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -6,14 +6,11 @@ describe("Ocean Node Root Endpoint", () => { const responseBody = await response.json(); expect(response.status).to.equal(200); - expect(responseBody).to.have.property("chainIds"); - expect(responseBody).to.have.property("providerAddress"); - expect(responseBody).to.have.property("software"); + expect(responseBody).to.have.property("id"); + expect(responseBody).to.have.property("address"); + expect(responseBody).to.have.property("provider"); expect(responseBody).to.have.property("version"); - // You can also check the values of the properties - expect(responseBody.software).to.equal("Ocean-Node"); - // Check if version is "0.0.1" or greater const [major, minor, patch] = responseBody.version.split(".").map(Number); expect(major).to.be.at.least(0); diff --git a/test/resolveComputeInputs.test.ts b/test/resolveComputeInputs.test.ts index 3b4b28c..7d9c07f 100644 --- a/test/resolveComputeInputs.test.ts +++ b/test/resolveComputeInputs.test.ts @@ -1,26 +1,23 @@ import { expect } from "chai"; -import { Aquarius } from "@oceanprotocol/lib"; +import { ProviderInstance } from "@oceanprotocol/lib"; import { resolveComputeInputs, IndexerWaitParams } from "../src/helpers.js"; -// A fake Aquarius whose waitForIndexer returns a deterministic DDO per DID, -// so the resolver can be exercised without a live indexer. -function makeAquarius(known?: Set): Aquarius { +const realWaitForIndexer = ProviderInstance.waitForIndexer; + +// a node that knows every DID except did:op:missing +async function fakeWaitForIndexer(nodeUri: string, did: string) { + if (did === "did:op:missing") return null; return { - waitForIndexer: async (did: string) => { - if (known && !known.has(did)) return null; - return { - id: did, - version: "4.1.0", - services: [ - { - id: `service-${did}`, - serviceEndpoint: `http://provider-for-${did}`, - }, - ], - metadata: { algorithm: { container: { image: "img" } } }, - }; - }, - } as unknown as Aquarius; + id: did, + version: "4.1.0", + services: [ + { + id: `service-${did}`, + serviceEndpoint: `http://provider-for-${did}`, + }, + ], + metadata: { algorithm: { container: { image: "img" } } }, + }; } const indexingParams: IndexerWaitParams = { @@ -46,11 +43,18 @@ const RAW_ALGO = { }; describe("resolveComputeInputs", function () { + before(function () { + ProviderInstance.waitForIndexer = + fakeWaitForIndexer as unknown as typeof realWaitForIndexer; + }); + after(function () { + ProviderInstance.waitForIndexer = realWaitForIndexer; + }); + it("resolves a single dataset DID and a single algorithm DID", async function () { const res = await resolveComputeInputs( "did:op:dataset1", "did:op:algo1", - makeAquarius(), indexingParams, FALLBACK, ); @@ -68,7 +72,6 @@ describe("resolveComputeInputs", function () { const res = await resolveComputeInputs( "[did:op:a,did:op:b]", "did:op:algo1", - makeAquarius(), indexingParams, FALLBACK, ); @@ -84,7 +87,6 @@ describe("resolveComputeInputs", function () { const res = await resolveComputeInputs( "did:op:a,did:op:b", "did:op:algo1", - makeAquarius(), indexingParams, FALLBACK, ); @@ -100,7 +102,6 @@ describe("resolveComputeInputs", function () { const res = await resolveComputeInputs( JSON.stringify(RAW_DATASET), "did:op:algo1", - makeAquarius(), indexingParams, FALLBACK, ); @@ -115,7 +116,6 @@ describe("resolveComputeInputs", function () { const res = await resolveComputeInputs( JSON.stringify(["did:op:dataset1", RAW_DATASET]), "did:op:algo1", - makeAquarius(), indexingParams, FALLBACK, ); @@ -131,7 +131,6 @@ describe("resolveComputeInputs", function () { const res = await resolveComputeInputs( JSON.stringify([RAW_DATASET, "did:op:dataset1"]), "did:op:algo1", - makeAquarius(), indexingParams, FALLBACK, ); @@ -144,7 +143,6 @@ describe("resolveComputeInputs", function () { const res = await resolveComputeInputs( "did:op:dataset1", JSON.stringify(RAW_ALGO), - makeAquarius(), indexingParams, FALLBACK, ); @@ -157,7 +155,6 @@ describe("resolveComputeInputs", function () { const res = await resolveComputeInputs( "[]", "did:op:algo1", - makeAquarius(), indexingParams, FALLBACK, ); @@ -169,7 +166,6 @@ describe("resolveComputeInputs", function () { const res = await resolveComputeInputs( JSON.stringify({ documentId: "x" }), "did:op:algo1", - makeAquarius(), indexingParams, FALLBACK, ); @@ -182,7 +178,6 @@ describe("resolveComputeInputs", function () { JSON.stringify({ meta: { rawcode: "print(1)", container: { image: "python" } }, }), - makeAquarius(), indexingParams, FALLBACK, ); @@ -196,7 +191,6 @@ describe("resolveComputeInputs", function () { const res = await resolveComputeInputs( "did:op:dataset1", JSON.stringify({ meta: { container: {} } }), - makeAquarius(), indexingParams, FALLBACK, ); @@ -207,7 +201,6 @@ describe("resolveComputeInputs", function () { const res = await resolveComputeInputs( "did:op:missing", "did:op:algo1", - makeAquarius(new Set(["did:op:algo1"])), indexingParams, FALLBACK, );