Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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`.
Expand Down Expand Up @@ -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`.
Expand Down
40 changes: 39 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,11 +366,46 @@ ocean-cli deleteFile <bucketId> <fileName>

### 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
Expand Down Expand Up @@ -423,8 +458,11 @@ ocean-cli mintOcean [--token 0xOcean] [--chainId 8996] # mint test Ocean tok
| `restartService` | | `<serviceId>` | `-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` |
Expand Down
10 changes: 5 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
145 changes: 140 additions & 5 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import {
isP2pUri,
ServiceStatusNumber,
ServiceRestartParams,
decodeJwt,
listScopableCommands,
} from "@oceanprotocol/lib";
import {
parseComputeInput,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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?"),
Expand All @@ -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(
Expand Down Expand Up @@ -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 <seconds>",
"Token lifetime in seconds (default 3600; the default is capped to the node's policy)",
)
.option(
"--valid-until <epochMs>",
"Absolute expiry as epoch-milliseconds (overrides --ttl)",
)
.option(
"--audience <peerIds>",
"Comma-separated node peerIds the token is valid at, or 'any' for an unrestricted (reusable, network-wide) token. Omit for node-scoped.",
)
.option(
"--scope <commands>",
"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 <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
Expand Down
Loading
Loading