TypeScript client for deCDN: verified fetches, bundles, loopback capabilities and namespace pointers.
Website · Docs · Gateway spec · deCDN · Discord
TypeScript client for deCDN, for Node.js
20.19+ and evergreen browsers. It speaks HTTP to a decdn gateway, which pays
for every pull and verifies it, and it hashes the bytes again with BLAKE3
wherever it holds a whole blob named by its hash. No native code, no iroh, no
wallet library.
- Verified streaming. A blob, or a whole bundle entry, is hashed with
BLAKE3 as it streams; a body that does not hash to its name ends with
HASH_MISMATCHinstead ofdone. Ranges and rendered pages are"skipped"(Verification). - Bundles. Entries are checked against the bundle manifest, which is itself verified and cached per client.
- Byte ranges of sized entries, for large files such as model weights. A
window does not hash to anything, so its
verifiedis"skipped". - Pages on a site origin.
DecdnClient.open()with no URL works from a page on a bundle's site origin (<hash32>.<host>); a namespace host needsgatewayUrl. - Loopback gateways. Read the pending delegate key and register
capabilities on a local
decdn gateway. - Namespace pointers. Point a
PublisherRegistrynamespace at a bundle on a public gateway, signing EIP-712 typed data with a private key or a viem-stylesignTypedData(typedData)signer. - Small and typed. ESM, CJS and declarations; runtime dependencies
@noble/hashesand@noble/curvesonly; namespaces, seq, caps and expiries arebigint.
- Install
- Gateways
- Compatibility
- Public gateway
- Loopback gateway (Node)
- Pages on a site origin
- Verification
- Errors
- Namespace pointers
- API at a glance
- Development
- License
pnpm add @decdn/client
# or
npm install @decdn/client
# or
yarn add @decdn/clientThe client talks to one of two kinds of gateway:
| Gateway | Where it runs | Who pays |
|---|---|---|
Public (decdn gateway --public-url https://decdn.link) |
Node or any web page | The first registered capability that can pay |
Loopback (decdn gateway, http://127.0.0.1:8484) |
Node, or a page on one of its site origins | The first registered capability that can pay |
The gateway's HTTP contract is appendix-gateway; bundles and their manifests are appendix-bundles.
Node.js 20.19 or later, and evergreen browsers.
@decdn/client |
decdn gateway |
|---|---|
| 0.3 | v0.3.0 or later for browser pages and public gateways; a release after v0.3.1 for loopback gateways (pending-key capabilities) |
| 0.1, 0.2 | v0.3.0 or later for browser pages and public gateways (cross-origin reads); any loopback gateway from Node |
CI runs the contract suite against the floor and the latest decdn release, with each release's signed binaries (CONTRIBUTING.md).
import { DecdnClient } from "@decdn/client";
const client = await DecdnClient.open({ gatewayUrl: "https://decdn.link" });
// A blob, streamed and hashed as it arrives.
const blob = await client.get("decdn:<64 hex>");
blob.verified; // true
const bytes = await blob.bytes(); // rejects with HASH_MISMATCH on bad bytes
// One file of a bundle, checked against the bundle's manifest.
const page = await client.get("decdn:<manifest hash>/docs/index.html");
const text = await page.text();
// A window of a sized entry: 206, not verifiable.
const part = await client.get("decdn:<manifest hash>/model.bin", {
range: { offset: 0, length: 1 << 20 },
});
part.contentRange; // { offset, length, size }The same code runs in a browser on any origin: a public gateway answers every
origin, Range preflights included.
A public gateway pays every pull with the capabilities its operator
registered on its bare host (GET /_delegate, PUT /_capability), in the
order a loopback gateway pays with them, except that
only a namespace pointer selects a namespace scope: a request on <ns>.<host>
for the bundle the pointer names. ?ns= and a <ns>.<hash32> label select
none there, since anyone can write them (scope). When none can pay,
a request fails with PAYMENT_REQUIRED (503, retryAfterSecs and
fallbackUri set); a blob its cache holds whole is still served.
A loopback gateway pays with capabilities pool owners issued to its delegate
keys. It holds one pending key at a time: delegate() names the same address
until a capability claims it. Have the owner assign that address, and
register the capability:
import { DecdnClient } from "@decdn/client";
const client = await DecdnClient.open({ gatewayUrl: "http://127.0.0.1:8484" });
const { address } = await client.loopback.delegate();
// The pool owner: decdn pool assign --pool <id> --signer <address> ...
await client.loopback.registerCapability({
capability: "dcap1:...",
scope: "any",
});
// → { signer, pool, expiry }
const r = await client.get("decdn:<64 hex>");Every registration states the content its capability pays for. "any" pays
for any content. A namespace scope pays only for requests that name one of
its namespaces (?ns=<id>, or the site label <ns>.<hash32>.localhost), and
carries the pool owner's EIP-712 signature over
CapabilityScope(address signer,bytes32 poolId,uint256[] namespaces) (domain
decdn-capability-scope, version 1, the chain id, and the PaymentPool as
verifying contract). The SDK passes the signature through:
await client.loopback.registerCapability({
capability: "dcap1:...",
scope: { namespaces: [7n, 9n], signature: "0x..." },
});
// → { signer, pool, expiry, namespaces: [7n, 9n] }A key holds one capability per pool, and may hold capabilities from several
pools. Of the capabilities that are not spent and not within the nodes'
expiry margin (one redeem interval plus 120 s, 420 s by default), the gateway
pays a request that names a namespace with the earliest registered one scoped
to it, else with the earliest registered "any" one; a request that names no
namespace is paid only by an "any" capability
(capabilities).
client.loopback.capabilities() lists them in registration order. With none that can
pay, content the gateway must pull fails with PAYMENT_REQUIRED; a blob its
cache holds whole is served at no cost. The gateway keeps its keys and
capabilities in memory, so a restart loses them. A dcap1: token decodes
offline with parseCapability.
A loopback gateway takes no credential. Every request it answers passes a
browser-header gate instead, so a web page on another origin cannot spend its
capabilities (cross-origin reads). A top-level GET
navigation (Sec-Fetch-Mode: navigate, Sec-Fetch-Dest: document) passes
from any page, so a link opens content. Otherwise it refuses, with
FORBIDDEN (403), a request marked Sec-Fetch-Site: cross-site, an Origin
that is not one of the gateway's own (its bare host and its site origins),
and a browser request (an Origin, or a Mozilla/ user agent) with no
Sec-Fetch-Site. On a site origin, a page's request must also be the site's
own (same-origin), the user's (none), or a top-level navigation. A client
outside a browser passes: from Node, the SDK sends no Origin and no
Mozilla/ user agent. In a browser, the page's own headers decide, so a page
on another origin is refused; the browser reports that refusal, which carries
no CORS headers, as NETWORK.
The SDK does not start the gateway. Run it yourself (decdn gateway, or the
decdn/decdn Docker image). open() treats a URL on localhost or a
loopback address (127.0.0.0/8, [::1]) as a loopback gateway; a public
gateway you run locally needs another host name, such as decdn.localhost.
A bundle opened as a website lives on its own origin,
https://<hash32>.decdn.link/ or http://<hash32>.localhost:8484/. A page
there opens the client with no URL:
const client = await DecdnClient.open();
client.context; // "site"
const style = await client.get("/css/site.css"); // its own bundle, verified
const other = await client.get("decdn:<64 hex>"); // through /_decdn/On a namespace host (https://<ns>.decdn.link/), pass the gateway URL so
the host is recognised: DecdnClient.open({ gatewayUrl: "https://decdn.link" }).
The bundle there is whatever the pointer names, so the page's own paths are
not verified and manifest() needs a hash.
get takes verify: "auto" | true | false (default "auto", or the
client's own default from open). response.verified says what happened:
| Request | verified |
How |
|---|---|---|
| A blob by hash | true |
The whole body hashes to the URI's hash. |
| A bundle entry | true |
The client reads the bundle manifest (cached per client, itself verified) and the body hashes to the entry's hash. |
| A page or stylesheet entry | true |
A site rewrites HTML and CSS as it serves them, so the client fetches these by their entry hash instead. |
A range of a bundle entry |
"skipped" |
A window does not hash to anything. A blob has no declared size, so a range on one is refused with CONFIG. A range the gateway answers whole (200) has the window cut from the body as served: for a page a site rewrites, a window of the rewritten page, whose contentRange holds the offset alone, since the page streams with no length. A window past the end fails with RANGE_NOT_SATISFIABLE, as on a 206. |
| A bundle's index or listing | "skipped" |
The gateway renders it. |
Any, with verify: false |
false |
Nothing is hashed and no manifest is read. |
verify: true refuses a request that cannot be verified with CONFIG.
A verified body is hashed as it streams: response.body ends with an error
(HASH_MISMATCH, or TRUNCATED when the gateway cuts it) instead of done,
and bytes(), text() and json() reject. Bytes read before the end are not
yet verified; act on them only once the stream is done.
Every failure is a DecdnError with a stable code:
| Code | When | Extra fields |
|---|---|---|
PAYMENT_REQUIRED |
402 (loopback) or 503 (public): nothing the gateway holds can pay right now | body; on a 503, retryAfterSecs and fallbackUri |
RANGE_NOT_SATISFIABLE |
416 | size |
CONFLICT |
409: a pointer seq that is not newer; a capability for a key not held, or a second from one pool on a key |
seq |
NOT_FOUND, FORBIDDEN, RATE_LIMITED, UPSTREAM, PAYLOAD_TOO_LARGE, UNPROCESSABLE |
404, 403, 429, 502, 413, 422 | status, body |
BAD_URI |
A decdn: URI that does not parse, or 400 |
|
HASH_MISMATCH, TRUNCATED |
The body does not hash to its hash, or is shorter or longer than declared | |
MALFORMED_MANIFEST, BAD_CAPABILITY |
A manifest or dcap1: token that does not decode |
|
NETWORK, CONFIG, HTTP |
The gateway is unreachable; the client cannot do what was asked; another status |
fallbackUri is the canonical decdn: URI: fetch it with a paying client of
your own (decdn get <uri>), or wait retryAfterSecs. The SDK retries
nothing on its own; get(uri, { retry: true }) waits out one Retry-After
and tries once more.
On a public gateway, the owner of a namespace on the PublisherRegistry
points it at a bundle, and https://<ns>.<host>/ serves that bundle:
const client = await DecdnClient.open({
gatewayUrl: "https://decdn.link",
pointer: { chainId: 421614, publisherRegistry: "0x..." },
});
const set = await client.pointer.set({
namespace: 42n,
root: "decdn:<manifest hash>/",
signer: { privateKey: "0x..." }, // or a viem account: anything with signTypedData
});
set.url; // https://42.decdn.link/The pointer is EIP-712 typed data (pointerTypedData gives it to a wallet),
seq defaults to the current Unix second, and the gateway takes only a seq
above the last one it holds from the same signer. The chain id and registry
are the deployment the gateway verifies against.
| Export | What it does |
|---|---|
DecdnClient.open(opts?) |
Opens a client on a public or loopback gateway, or on the site origin a page is served from |
client.get(uri, opts?) |
Fetches a blob, a bundle, a bundle entry or a range (or, on a site page, a path of its own bundle) as a DecdnResponse (verified, body, bytes, text, json) |
client.head(uri) |
The size, hash and content type of what a URI names, without its bytes |
client.resolve(uri) |
A URI's kind, hash, bare and site URLs, and its manifest entry (reads the manifest for a bundle or entry) |
client.manifest(hashOrUri?, signal?) |
A bundle's verified manifest, read with the URI's ?ns= hint (a bare hash has none) and cached per client; on a site page, the page's own bundle under its host's namespace when omitted |
client.siteUrl(uri), client.namespaceUrl(ns) |
The site URL of a bundle or entry; the URL a namespace's pointer serves at (https://<ns>.<host>/). Neither makes a request |
client.loopback.delegate() |
The loopback gateway's pending delegate key: the same address until a capability claims it |
client.loopback.registerCapability({ capability, scope }), .capabilities() |
Registers a dcap1: capability issued to a key the gateway holds, for any content or for named namespaces ({ signer, pool, expiry, namespaces? }); lists the capabilities the gateway holds, in registration order |
client.pointer.set(args) |
Signs and publishes a namespace pointer on a public gateway |
pointerTypedData, pointerSigningHash, signPointer, recoverPointerSigner |
The pointer's EIP-712 typed data and signing hash, its signature, and the signer a signature recovers to |
parseUri, formatUri |
Parse and canonically format a decdn: URI, following the Rust client's grammar exactly (BAD_URI on anything it refuses) |
hashToBase32, base32ToHash |
A hash to and from its site label |
blake3Hex, createBlake3 |
BLAKE3, one-shot and incremental |
parseManifest, parseCapability |
Decodes a v1 bundle manifest, checking its hash when given one; decodes a dcap1: token without checking its signature |
DecdnError |
Every failure, with a stable code (Errors) |
Namespaces, sequence numbers, caps and expiries are bigint.
pnpm install
pnpm lint # eslint, prettier, tsc
pnpm test # unit tests and the contract suite against the fake gateway
pnpm test:browser # Chromium smoke run (pnpm exec playwright install chromium-headless-shell)
pnpm build # dist/: ESM, CJS and typestest/fake-gateway.ts reproduces the gateway's HTTP contract. The contract
suite in test/contract runs against it by default, and against a real
gateway in decdn's CI
(sdk_contract.rs),
so the two cannot drift apart. See CONTRIBUTING.md.
Releases are cut from signed v* tags (RELEASING.md); the
keys that sign them are in KEYS (gpg --import KEYS, then
git verify-tag vX.Y.Z).
Dual-licensed under either MIT or Apache-2.0, at your option.