Skip to content

Commit 1dab70e

Browse files
alpergundogduclaude
andcommitted
feat!: scoped capability registration, PAYMENT_REQUIRED for 503
registerCapability takes a required scope: "any", or a namespace scope { namespaces, signature } whose pool-owner signature the SDK passes through. The registration result and capability listing entries carry optional namespaces, read as bigints. The fake gateway requires the scope, checks its shape, echoes namespaces, and pays with a namespace scope only for requests that name one of its namespaces. A 503 maps to PAYMENT_REQUIRED, like a 402; POOL_UNFUNDED is gone. The ./node subpath export and defaultDataDir are removed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 951ba4c commit 1dab70e

17 files changed

Lines changed: 396 additions & 174 deletions

‎.github/workflows/ci.yml‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,10 @@ jobs:
5959
- run: pnpm build
6060
# From the repo root, `@decdn/client` resolves to this package through
6161
# its own `exports`, as it does for a consumer.
62-
- name: Load the built entry points
62+
- name: Load the built entry point
6363
run: |
64-
node -e 'require("@decdn/client"); require("@decdn/client/node")'
65-
node --input-type=module -e 'await import("@decdn/client"); await import("@decdn/client/node")'
64+
node -e 'require("@decdn/client")'
65+
node --input-type=module -e 'await import("@decdn/client")'
6666
6767
# The unit, script and contract tests with coverage of src/. The run fails
6868
# below the thresholds in vitest.config.ts; the upload after it is

‎README.md‎

Lines changed: 53 additions & 34 deletions
Large diffs are not rendered by default.

‎package.json‎

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -58,19 +58,6 @@
5858
"default": "./dist/index.cjs"
5959
}
6060
},
61-
"./node": {
62-
"node": {
63-
"import": {
64-
"types": "./dist/node.d.ts",
65-
"default": "./dist/node.js"
66-
},
67-
"require": {
68-
"types": "./dist/node.d.cts",
69-
"default": "./dist/node.cjs"
70-
}
71-
},
72-
"types": "./dist/node.d.ts"
73-
},
7461
"./package.json": "./package.json"
7562
},
7663
"scripts": {

‎scripts/build.mjs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { execFileSync } from "node:child_process";
44
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
55
import { build } from "esbuild";
66

7-
const ENTRIES = ["index", "node"];
7+
const ENTRIES = ["index"];
88

99
rmSync("dist", { recursive: true, force: true });
1010
mkdirSync("dist");
@@ -18,7 +18,6 @@ for (const [format, ext] of [
1818
outExtension: { ".js": `.${ext}` },
1919
bundle: true,
2020
packages: "external",
21-
external: ["node:*"],
2221
format,
2322
platform: "neutral",
2423
target: "es2022",

‎scripts/check-package.sh‎

Lines changed: 5 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,18 @@
11
#!/usr/bin/env bash
22
# Checks the package as npm would ship it: publint on `package.json` and the
3-
# packed files, and arethetypeswrong on how each entry point's types resolve.
4-
# Run after `pnpm build`.
5-
#
6-
# `.` must resolve under every resolution attw knows. `./node` has JavaScript
7-
# only under the `node` condition, with a type-only fallback for TypeScript's
8-
# `bundler` resolution, which does not set `node`. Its types must resolve to
9-
# `dist/node.d.cts` under node16 from CJS and to `dist/node.d.ts` under node16
10-
# from ESM and bundler; only node10, which does not read `exports`, is ignored.
3+
# packed files, and arethetypeswrong on how the entry point's types resolve
4+
# under every resolution attw knows. Run after `pnpm build`.
115
#
126
# Usage: scripts/check-package.sh
137
set -euo pipefail
148

159
die() { echo "error: $*" >&2; exit 1; }
1610

1711
cd "$(dirname "${BASH_SOURCE[0]}")/.."
18-
[[ -f dist/index.js && -f dist/node.js ]] || die "no dist/: run \`pnpm build\` first"
19-
command -v jq >/dev/null || die "jq is required"
12+
[[ -f dist/index.js ]] || die "no dist/: run \`pnpm build\` first"
2013

2114
echo "==> publint"
2215
pnpm exec publint --strict
2316

24-
echo "==> attw: ."
25-
pnpm exec attw --pack . --exclude-entrypoints ./node
26-
27-
echo "==> attw: ./node (node16, bundler)"
28-
# attw exits 1 when it finds problems (node10's are expected) and above 1 when
29-
# it cannot check the package; the JSON decides only in the first case. A
30-
# resolution that is missing or lands on another file counts as a problem, so
31-
# an attw that stops reporting one fails here rather than passing.
32-
rc=0
33-
json=$(pnpm exec attw --pack . --entrypoints ./node --format json) || rc=$?
34-
((rc <= 1)) || die "attw could not check ./node (exit $rc)"
35-
problems=$(jq -c '
36-
.analysis as $a
37-
| if ($a.problems | type) != "array" then error("no .analysis.problems") else . end
38-
| {"node16-cjs": "node.d.cts", "node16-esm": "node.d.ts", "bundler": "node.d.ts"}
39-
| [to_entries[]
40-
| .key as $kind
41-
| ("/dist/" + .value) as $want
42-
| ($a.entrypoints["./node"].resolutions[$kind].resolution.fileName // "nothing") as $got
43-
| select($got | endswith($want) | not)
44-
| "\($kind) types resolve to \($got), not \($want)"]
45-
+ [$a.problems[] | select(.resolutionKind != "node10") | tojson]
46-
' <<<"$json") || die "attw's JSON for ./node is not in the shape this script reads"
47-
if [[ "$problems" != "[]" ]]; then
48-
pnpm exec attw --pack . --entrypoints ./node --profile node16 || true
49-
die "./node does not resolve under node16 or bundler: $problems"
50-
fi
51-
echo "./node resolves under node16 (ESM and CJS); its types resolve under bundler"
17+
echo "==> attw"
18+
pnpm exec attw --pack .

‎src/client.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -854,7 +854,7 @@ export class DecdnClient {
854854
} catch (e) {
855855
const retryable =
856856
e instanceof DecdnError &&
857-
["PAYMENT_REQUIRED", "POOL_UNFUNDED", "RATE_LIMITED"].includes(e.code);
857+
["PAYMENT_REQUIRED", "RATE_LIMITED"].includes(e.code);
858858
if (!opts.retry || !retryable || e.retryAfterSecs === undefined) throw e;
859859
await sleep(e.retryAfterSecs * 1000, opts.signal);
860860
return this.request(url, "GET", headers, opts.signal);

‎src/errors.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
/** What went wrong, as a stable code a caller can branch on. */
22
export type DecdnErrorCode =
3-
/** 402: no capability a loopback gateway holds can pay for a pull. */
3+
/** 402 or 503: nothing the gateway holds can pay for a pull right now. */
44
| "PAYMENT_REQUIRED"
5-
/** 503: nothing a public gateway holds can pay for a pull right now. */
6-
| "POOL_UNFUNDED"
75
/** 404. */
86
| "NOT_FOUND"
97
/** 416: the range starts past the end; `size` holds the entry's size. */

‎src/http.ts‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ const CODES: Record<number, DecdnErrorCode> = {
1717
422: "UNPROCESSABLE",
1818
429: "RATE_LIMITED",
1919
502: "UPSTREAM",
20-
503: "POOL_UNFUNDED",
20+
503: "PAYMENT_REQUIRED",
2121
};
2222

2323
/** `fetch`, with a failure to reach the gateway as `NETWORK` and an abort passed through. */
@@ -109,19 +109,21 @@ export async function errorOf(response: Response): Promise<DecdnError> {
109109
}
110110

111111
/**
112-
* `text` parsed as JSON with the integer values of `fields` read as `bigint`:
113-
* the gateway writes u64 ids, caps and expiries as JSON numbers, which may
114-
* exceed 2^53.
112+
* `text` parsed as JSON with the integer values of `fields`, and the integers
113+
* of a list under one of `fields`, read as `bigint`: the gateway writes u64
114+
* ids, caps and expiries as JSON numbers, which may exceed 2^53.
115115
*/
116116
export function parseWithBigInts(text: string, fields: string[]): unknown {
117117
const names = fields.join("|");
118118
const quoted = text.replace(
119-
new RegExp(`("(?:${names})"\\s*:\\s*)(\\d+)`, "g"),
120-
'$1"$2"',
121-
);
122-
return JSON.parse(quoted, (key, value: unknown) =>
123-
fields.includes(key) && typeof value === "string" && /^\d+$/.test(value)
124-
? BigInt(value)
125-
: value,
119+
new RegExp(`("(?:${names})"\\s*:\\s*)(\\d+|\\[[\\d\\s,]*\\])`, "g"),
120+
(_match, head: string, value: string) =>
121+
`${head}${value.replace(/\d+/g, '"$&"')}`,
126122
);
123+
const big = (value: unknown) =>
124+
typeof value === "string" && /^\d+$/.test(value) ? BigInt(value) : value;
125+
return JSON.parse(quoted, (key, value: unknown) => {
126+
if (!fields.includes(key)) return value;
127+
return Array.isArray(value) ? value.map(big) : big(value);
128+
});
127129
}

‎src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ export {
4040
} from "./pointer.js";
4141
export {
4242
LoopbackApi,
43+
type CapabilityScope,
4344
type RegisteredCapability,
4445
type Registration,
4546
} from "./loopback.js";

‎src/loopback.ts‎

Lines changed: 69 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,32 @@
77
import type { DecdnClient } from "./client.js";
88
import { DecdnError } from "./errors.js";
99
import { parseWithBigInts, sendOk } from "./http.js";
10+
import { integer } from "./pointer.js";
11+
12+
/**
13+
* The content a registered capability pays for: `"any"`, or only the
14+
* content of `namespaces`. A namespace scope carries the pool owner's EIP-712
15+
* `CapabilityScope(address signer,bytes32 poolId,uint256[] namespaces)`
16+
* signature (domain `decdn-capability-scope`, version `1`, the chain id, and
17+
* the PaymentPool as verifying contract), which the SDK passes through.
18+
*/
19+
export type CapabilityScope =
20+
| "any"
21+
| {
22+
/** Namespace ids, each at least 1; at least one. */
23+
namespaces: readonly (bigint | number)[];
24+
/** `0x` + the 65-byte signature, in hex. */
25+
signature: string;
26+
};
1027

1128
/** A capability the gateway holds. */
1229
export interface RegisteredCapability {
1330
/** The spending cap, in USDC base units. */
1431
cap: bigint;
1532
/** Unix-seconds expiry. */
1633
expiry: bigint;
34+
/** The namespaces a namespace-scoped capability pays for; absent when it pays for any content. */
35+
namespaces?: bigint[];
1736
pool: string;
1837
signer: string;
1938
/** Whether a pull stopped for funding on it. */
@@ -24,6 +43,8 @@ export interface RegisteredCapability {
2443
export interface Registration {
2544
/** Unix-seconds expiry. */
2645
expiry: bigint;
46+
/** The namespaces a namespace-scoped capability pays for; absent when it pays for any content. */
47+
namespaces?: bigint[];
2748
pool: string;
2849
signer: string;
2950
}
@@ -35,7 +56,7 @@ export class LoopbackApi {
3556
private async call(
3657
method: string,
3758
path: string,
38-
body?: unknown,
59+
body?: string,
3960
): Promise<string> {
4061
if (this.client.context !== "loopback") {
4162
throw new DecdnError(
@@ -45,7 +66,7 @@ export class LoopbackApi {
4566
}
4667
const init: RequestInit = { method };
4768
if (body !== undefined) {
48-
init.body = JSON.stringify(body);
69+
init.body = body;
4970
init.headers = { "content-type": "application/json" };
5071
}
5172
const response = await sendOk(
@@ -69,18 +90,34 @@ export class LoopbackApi {
6990
}
7091

7192
/**
72-
* Register `capability`, a `dcap1:` issued to a key the gateway holds. A key
73-
* holds one capability per pool. `CONFLICT` when the gateway does not hold
74-
* the signer's key, or that key already holds a capability from that pool.
93+
* Register `capability`, a `dcap1:` issued to a key the gateway holds, to
94+
* pay for the content `scope` names. A key holds one capability per pool.
95+
* `CONFLICT` when the gateway does not hold the signer's key, or that key
96+
* already holds a capability from that pool; `UNPROCESSABLE` for a scope
97+
* the gateway refuses, among them a namespace scope whose signature does
98+
* not recover the pool's owner.
7599
*/
76100
async registerCapability(args: {
77101
capability: string;
102+
scope: CapabilityScope;
78103
}): Promise<Registration> {
79-
const text = await this.call("PUT", "/_capability", {
80-
capability: args.capability,
81-
});
82-
const parsed = parseWithBigInts(text, ["expiry"]) as Registration;
83-
return { signer: parsed.signer, pool: parsed.pool, expiry: parsed.expiry };
104+
const text = await this.call(
105+
"PUT",
106+
"/_capability",
107+
`{"capability":${JSON.stringify(args.capability)},"scope":${scopeJson(args.scope)}}`,
108+
);
109+
const parsed = parseWithBigInts(text, [
110+
"expiry",
111+
"namespaces",
112+
]) as Registration;
113+
const registration: Registration = {
114+
signer: parsed.signer,
115+
pool: parsed.pool,
116+
expiry: parsed.expiry,
117+
};
118+
if (parsed.namespaces !== undefined)
119+
registration.namespaces = parsed.namespaces;
120+
return registration;
84121
}
85122

86123
/**
@@ -89,6 +126,27 @@ export class LoopbackApi {
89126
*/
90127
async capabilities(): Promise<RegisteredCapability[]> {
91128
const text = await this.call("GET", "/_capability");
92-
return parseWithBigInts(text, ["cap", "expiry"]) as RegisteredCapability[];
129+
return parseWithBigInts(text, [
130+
"cap",
131+
"expiry",
132+
"namespaces",
133+
]) as RegisteredCapability[];
134+
}
135+
}
136+
137+
/** `scope` as the JSON `PUT /_capability` carries, its namespace ids as integers. */
138+
function scopeJson(scope: CapabilityScope): string {
139+
if (scope === "any") return '"any"';
140+
if (
141+
typeof scope !== "object" ||
142+
scope === null ||
143+
!Array.isArray(scope.namespaces)
144+
) {
145+
throw new DecdnError(
146+
"CONFIG",
147+
'a capability scope is "any" or { namespaces, signature }',
148+
);
93149
}
150+
const ids = scope.namespaces.map((n) => integer(n, "a namespace id"));
151+
return `{"namespaces":[${ids.join(",")}],"signature":${JSON.stringify(scope.signature)}}`;
94152
}

0 commit comments

Comments
 (0)