Skip to content

feat!: speak the gateway's pending-key and scoped capability API - #15

Merged
thiras merged 10 commits into
mainfrom
claude/gateway-pending-key
Nov 24, 2026
Merged

thiras merged 10 commits into
mainfrom
claude/gateway-pending-key

Conversation

@alpergundogdu

@alpergundogdu alpergundogdu commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

The decdn gateway changes how it pays and who may use it.

  • Loopback: no token. Every route passes a browser-header gate.
    • The gateway holds one pending delegate key.
    • A capability is registered with a required scope: "any" or an owner-signed namespace scope.
    • A key holds one capability per pool, and capabilities from several pools.
  • Public: no pool and no daily allowance. It pays only with capabilities registered through the same API on its bare host, and answers 503 when none can pay.
  • Payment order: among usable capabilities, the earliest registered one scoped to the request's namespace pays. Failing that, the earliest registered "any" one pays. On loopback, the request's namespace is the one its URI names. On public, it is the namespace whose pointer serves the request.

decdn/decdn's gateway change pins this branch in .github/sdk-python.sha.

Public API changes (breaking)

  • Opening a client: Client(...) and AsyncClient(...) lose token and host. A localhost URL, or one on a loopback address (127.0.0.0/8, ::1), opens a loopback client; any other URL opens a public one. Requests carry no x-decdn-token, x-decdn-host, Origin or Sec-Fetch-*, and use httpx's own user agent, so the loopback gate serves them.
  • Removed: decdn.local (read_loopback_token, default_data_dir), the UNAUTHORIZED error code (a 401 maps to HTTP) and POOL_UNFUNDED.
  • client.loopback.delegate() returns the gateway's pending key. It is the same address until a capability claims it.
  • client.loopback.register_capability(capability, scope): scope is "any" or a NamespaceScope(namespaces, signature) that the pool's owner signed. The SDK sends {"capability", "scope"} and passes the signature through unchanged.
  • client.loopback.capabilities() lists the held capabilities in registration order.
  • Registration has signer, pool, expiry and namespaces.
  • RegisteredCapability has signer, pool, cap, expiry, spent and namespaces.
    • In Registration, RegisteredCapability and NamespaceScope, namespaces is a tuple[int, ...] (None for "any").
  • PAYMENT_REQUIRED now covers both "nothing can pay" cases: a loopback 402 and a public 503. It carries retry_after_secs and fallback_uri.
  • Bad answers: a delegate, capability or pointer answer that is not the JSON the contract names raises HTTP, not a raw KeyError or JSONDecodeError. That covers a missing field and one of the wrong type, including a u64 that is fractional, negative or too large.
  • Manifests under a namespace: a namespaced URI's manifest is read with its ?ns=, so a capability scoped to that namespace pays for it. This applies to get, head, resolve and manifest(uri).

Fake gateway

  • API, both modes:

    • A single pending key (pend).
    • Held capabilities in registration order (grant(..., namespaces=), capabilities).
    • GET /_delegate, PUT /_capability, GET /_capability and GET /_status on the bare host; 404 on site and namespace hosts.
    • 409 for a key it does not hold, or for a second capability from one pool on one key.
    • 422 for unknown body fields, a missing or malformed scope, a cap of 0, or an expiry inside the 420 s margin. A scope's shape is checked while the body is parsed: a non-empty list of u64s, 0 included, and a hex signature (0x optional).
    • 422 the scope signature is malformed for a signature that isn't 65 bytes. As on the real gateway, this comes after both 409 checks.
    • 413 over 64 KiB.
    • A public preflight advertises GET, PUT for /_capability, GET for /_delegate and /_status, and PUT for /_pointer.
    • List entries in contract key order, with expired ones dropped.
  • Payment:

    • Ranked as described above.
    • unfunded_pools retires the paying capability, and the next one pays.
    • cached blobs are served when nothing can pay.
    • unfunded hashes are refused without retiring anything.
  • Loopback gate: it runs on every route before anything pays. A top-level GET navigation (Sec-Fetch-Mode: navigate, Sec-Fetch-Dest: document) passes from any site. Anything else is checked in this order:

    1. Sec-Fetch-Site: cross-site → 403.
    2. An Origin that is neither the bare host nor one of its sites → 403.
    3. No Sec-Fetch-Site, on a request with an Origin or a Mozilla/ user agent → 403.

    A site spends only on its own pages (same-origin), on the user's own requests (none), and on a top-level navigation. A navigation counts only when it loads a whole page (Sec-Fetch-Dest: document); a missing Sec-Fetch-Mode counts as a navigation. Anything else → 403.

    When nothing can pay → 402 the gateway holds no capability that can pay: register one with PUT /_capability.

  • Public: no gate. When nothing can pay → 503 JSON {"error": "the gateway cannot pay right now", "retry_after_secs": 60, "uri": ...}, with Retry-After: 60 and the Link fallback. CORS * on everything, and the API paths answer a preflight with 204.

Contract suite and released gateways

  • Loopback fixture: no token. capabilities is one {"capability": "dcap1:..."} per flavour, each from its own pool, all issued to the gateway's one pending key. The suite registers each with "any".
  • Public fixture: unchanged. decdn's harness registers the public gateway's capability before the suite runs.

Every test of the new behaviour sits inside if shipped_after("0.3.1"):, the mechanism CONTRIBUTING.md describes (decdn 0.3.1 is the latest release):

  • scripts/decdn-contract.sh --tag sets DECDN_CONTRACT_RELEASE, so a run against 0.3.1 or older never collects those tests. The fake and any --ref run them.
  • Against 0.3.1, the loopback file runs only the unknown-Host 403 test.
  • The public file runs its existing content, site, pointer and CORS tests, none of which checks how the gateway pays.

Namespace scopes against the real gateway: the suite tests only that a scope-less registration gets 422. Echoing a namespace scope is tested against the fake only, because a real gateway needs a pool-owner signature.

Floors: gateway-floor stays at 0.3.0 because no released gateway has the new API yet. Until one does, the floor covers public clients only; against 0.3.0 or 0.3.1, a loopback client gets the gateway's 401 as HTTP. The README says so, and the floor rises to the release that ships this API before the SDK's next release. harness-floor is still empty.

Gates

ruff check, ruff format --check, mypy and pytest tests/unit tests/contract (385 passed) pass. The contract suite with DECDN_CONTRACT_RELEASE=0.3.1 passes (30 tests). tests/scripts fails on macOS (no sha256sum, gpg key generation, no tomllib in the system python3), as it does on main; CI runs it on Linux.

🤖 Generated with Claude Code

alpergundogdu and others added 3 commits November 16, 2026 18:13
The loopback gateway holds one pending delegate key, registers a capability
without a scope, and pays with the capabilities it holds in registration
order. `delegate()` returns the pending key, `register_capability` takes the
capability alone and returns `{signer, pool, expiry}`, `capabilities()`
entries carry no `origin` or `scope`, and the clients drop `host` and the
`x-decdn-host` header. The fake gateway and the contract suite follow; tests
of the new behaviour are declared only for gateways after release 0.3.1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A public gateway holds no pool and no daily allowance: it pays with the
capabilities registered through the API on its bare host and answers 503
`the gateway cannot pay right now` when none can. The fake drops its
allowance, answers the capability API and `/_status` on the public bare host,
and serves cached blobs for free; a loopback refusal is always the 402. The
public contract suite checks the API on the bare host for gateways after
release 0.3.1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A loopback client needs no token: the clients drop `token`, a loopback
address alone selects the loopback context, and no request carries
`x-decdn-token`. `decdn.local` (`read_loopback_token`, `default_data_dir`)
and the `UNAUTHORIZED` code are removed. The fake gates every loopback route
on browser headers (cross-site, a foreign origin, a browser with no
Sec-Fetch-Site), counts its own sites as own origins, keeps a site's own
spending rule, and redirects only a navigation to a bundle on the bare host.
The loopback contract suite drops the token and checks the gate for gateways
after release 0.3.1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…POOL_UNFUNDED

`register_capability(capability, scope)` takes a required scope: "any", or a
`NamespaceScope(namespaces, signature)` the pool's owner signed, which the SDK
passes through. `Registration` and `RegisteredCapability` carry the optional
`namespaces` the gateway echoes. A 503 from a public gateway maps to
`PAYMENT_REQUIRED`, as a 402 does; the `POOL_UNFUNDED` code is gone.

The fake gateway requires `scope`, checks a namespace scope's shape and echoes
its namespaces in the 201 and the listing. The loopback contract suite
registers with scope "any" and checks a registration without a scope is 422.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alpergundogdu added a commit to decdn/decdn that referenced this pull request Nov 17, 2026
…oken (#2910)

* feat(gateway)!: one pending delegate key, capabilities on both gateway modes

The gateway holds at most one pending delegate key: GET /_delegate returns
it until a capability claims it. PUT /_capability takes {"capability"}
only, for a key the gateway holds, one capability per pool per key. The
gateway pays every pull with the first registered capability that no
funding stop retired and that sits outside the node expiry margin, and
serves a cache hit with nothing that can pay. /_delegate, /_capability and
/_status need no token and no Origin; a loopback gateway answers nothing
cross-origin. A public gateway answers the same API on its bare host and
pays with capabilities first, then from its own pool when it names a
keystore.

Removes the per-page scope, x-decdn-host selection, per-site delegate
bounds, the pending-key TTL and the psl dependency.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(gateway)!: pay only with capabilities, no keystore and no allowance

A gateway, loopback or public, pays only with the capabilities pool owners
register to its in-memory delegate keys: --keystore and --capability are
refused, it opens no pool and keeps no buyer store past its run. The daily
allowance (--allowance-bytes-per-day, --allowance) is gone; the caps of the
capabilities bound what a gateway spends. A public gateway with nothing
that can pay answers 503 with the canonical decdn: URI. The counter
requests_allowance_exhausted is renamed requests_payment_required, /_status
loses its allowance field, and an active pull's payer is {signer, pool}.

The e2e journeys fund their gateways through decdn_e2e::pool_owner.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(gateway)!: a loopback gateway takes no token; browser headers gate it

A loopback gateway writes no token file and reads no x-decdn-token. Every
request passes a browser-header check after the Host check: a cross-site
page, an Origin that is none of the gateway's own (the bare host and its
site origins), and a browser that sends no Sec-Fetch-Site (an Origin, or a
Mozilla/ User-Agent) get 403. A client outside a browser passes. On the
bare host, a browser's navigation to a bundle or entry redirects to its
site; any other request is served there. Site pages may connect to their
own origin only. decdn dashboard reads the gateway's /_status with no
token.

Moves the SDK pins to decdn/sdk-typescript#28 and decdn/sdk-python#15,
whose contract suites pass against this gateway.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(gateway): a pool owner scopes a capability to its namespaces

A capability registered with a scope that its pool's owner signed
(EIP-712 CapabilityScope, domain decdn-capability-scope) pays only for
requests that one of the scope's namespace pointers serves: the
pointed bundle on <ns>.<host>. Scoped matches pay before unscoped
capabilities. The listing, /_status and the dashboard show each
capability's namespaces. `decdn pool assign --namespace` signs the
scope and prints the whole PUT /_capability body.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(gateway)!: every capability registration states its scope

`PUT /_capability` requires `scope`: "any" for a capability that pays
for any content, or a pool owner's signed namespace scope. A body with
no scope is refused, so no capability pays for everything by accident.
`decdn pool assign --any-namespace` prints the "any" registration.

A loopback gateway selects a scoped capability by the namespace the
request's decdn: URI names (`?ns=`, or the site label). A top-level GET
navigation passes its browser check from any site, so a link on any
page opens loopback content.

The gateway_pointer journey funds its gateway with a namespace-scoped
capability. Moves the SDK pins to decdn/sdk-typescript@1dab70e and
decdn/sdk-python@3b502a9, which send the scope and map 503 to
PAYMENT_REQUIRED.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(adr): point ADR 003 and the overview at the gateway's capability scope

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
@yigitdot

Copy link
Copy Markdown
Contributor

PR review: #15 (feat!: speak the gateway's pending-key capability API)

Context

Read-only review of branch claude/gateway-pending-key (4 commits, +1008/−697) by four agents (code, tests, docs, error handling), checked against the real gateway in the local decdn checkout. The code follows the last commit (3b502a9): register_capability(capability, scope) with a required scope; POOL_UNFUNDED and UNAUTHORIZED are removed; 503 maps to PAYMENT_REQUIRED. README, docstrings and errors.py agree with the code. CHANGELOG is rightly untouched (post-0.1.0).

Critical (fix before merge)

  1. The fake gateway ignores namespace scope when paying. tests/fake_gateway.py:469 _pay(uri) pays with the first usable capability. The real gateway (decdn/crates/cli/src/commands/gateway/delegates.rs:209 paying(..., namespace)) never uses a scoped capability outside its namespaces, and prefers a scoped one inside them. A namespace-only capability gets 200 from the fake where the real gateway answers 402 (loopback) or 503 (public). This breaks the AGENTS.md "fake mirrors the real one" rule. Fix: pass the request namespace into _pay, copy the ranking, and add unit tests for both cases.
  2. The PR description contradicts itself. "Public API changes" says scope is gone, Registration has no namespaces and 503 is POOL_UNFUNDED; the last section says the opposite. PRs are squash-merged, so the title and body are the changelog entry. Rewrite them to the final API (for example, the title "feat!: speak the gateway's pending-key and scoped capability API").

Important

  1. Loopback detection uses a fixed host list with no override (src/decdn/_core.py:36, :148). 127.0.0.2, localhost., [0:0:0:0:0:0:0:1] and ::ffff:127.0.0.1 are classed as public. The real gateway accepts any is_loopback listen address. Fix: ipaddress.ip_address(host).is_loopback, plus a trailing-dot localhost.. Optionally make the _check CONFIG message name the detection.
  2. Loopback JSON parsing raises raw Python exceptions (src/decdn/loopback.py _delegate, _registration, _capabilities). KeyError, JSONDecodeError and TypeError escape instead of DecdnError, for example a 0.3.x gateway's registration body without pool. Wrap them in one helper. pointer.py:304 has the same flaw, which predates this PR.
  3. gateway-floor stays 0.3.0, but loopback no longer works against 0.3.0 or 0.3.1. Those gateways answer 401, which this PR now maps to generic HTTP. The PR body says this is intentional until the release exists. Record in the README floor section that 0.3.0 covers public reads only, and track raising the floor before the next SDK release.
  4. Payment-order docs are imprecise (loopback.py:157,185, README "in the order it pays with them"). Registration order holds only within a rank; a scoped capability wins for its namespaces. Reword after fix 1.

Suggestions

  • namespaces: list[int] inside frozen dataclasses (NamespaceScope, Registration, RegisteredCapability). They are unhashable and mutable. Use tuple[int, ...], and consider a __post_init__ shape check: non-bool ints 1..2^64−1, non-empty, and a 0x signature of 130 hex digits.
  • namespaces in responses is read untyped (loopback.py:103,116). Validate it as absent or a list of ints.
  • Any 503, including a proxy's plain-text one, now reads as PAYMENT_REQUIRED. The real gateway's only 503 is cannot_pay, so this matters only behind proxies. Optionally require the JSON body or the Link header.
  • Wrong error message in _check. "the delegate and capability API is a loopback gateway's alone" is false: a public bare host serves it too. Say the SDK exposes it only on a loopback client.
  • Missing ADR citations. Cite the decdn ADR for the EIP-712 CapabilityScope claims (README.md:173-181, the NamespaceScope docstring), per AGENTS.md.
  • Test hygiene:
    • Rename test_..._pool_unfunded... (two tests in tests/unit/test_client.py).
    • Fold the now-redundant half of test_maps_a_raw_blobs_head_refusals_as_its_gets.
    • Add a gate-before-402 ordering test, and a gated public contract test for 503 Retry-After/Link.
  • Stale comment. "The API takes no token" (tests/fake_gateway.py:528) describes history.

Strengths

  • Headers. The client sends no token, Origin, Sec-Fetch-* or Mozilla/ user agent, and unit tests assert it.
  • Contract tests. All match the real gateway (409, 422 without scope, 503 JSON with Retry-After and Link). shipped_after("0.3.1") gating is correct, and the ungated unknown-Host test is safe against 0.3.1.
  • Parity and exactness. Sync and async match, and every test runs through both flavours. Namespaces stay exact ints. The scope wire format matches the gateway's RawScope.

Not verified

The test suite was not run (plan mode). The decdn harness change (one pending key, a pool per flavour, public pre-registration) must land with this PR.

yigitdot and others added 4 commits November 24, 2026 01:37
…irst

As the gateway's Delegates::paying does: the earliest usable capability scoped to the namespace (the URI's on loopback, the serving pointer's on public), else the earliest "any" one. A scope may name namespace 0. The browser-header gate refuses before anything pays.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…or an answer outside the contract

localhost and every address the gateway counts as loopback (127.0.0.0/8, ::1) open a loopback client. A delegate, capability or pointer answer that is not the JSON the contract names raises DecdnError HTTP. NamespaceScope, Registration and RegisteredCapability keep namespaces as tuples.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@yigitdot yigitdot changed the title feat!: speak the gateway's pending-key capability API feat!: speak the gateway's pending-key and scoped capability API Nov 23, 2026
…ture order

The loopback gate lets a top-level GET navigation through from any site,
a site spends on a navigation only when it loads a whole page, and a
scope signature's length is checked after the key and pool 409s, as the
gateway's browser_gate, may_spend and verify_owner do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Manifest fetches lose namespace scope and can break scoped-only reads, response readers accept invalid field types, and the fake gateway advertises incorrect CORS methods.

3 open issues
What changed in this PR

This PR updates the Python SDK to the gateway’s pending-key and scoped-capability API, replacing token-based loopback access and public daily allowances.

Changes:

  • Removes token and host options, adds namespace scopes, and updates capability result types.
  • Unifies payment errors and adds handling for malformed JSON success responses.
  • Updates the fake gateway, contract tests, documentation, and packaging checks for the new API.
File Description
tests/​unit/​test_pointer.py Funds the public fake used by pointer tests.
tests/​unit/​test_loopback.py Tests pending keys, scopes, registration, and malformed responses.
tests/​unit/​test_local.py Removes obsolete token-helper tests.
tests/​unit/​test_http.py Updates status-to-error mapping assertions.
tests/​unit/​test_fake_gateway.py Tests capability payments, browser gates, and registration rules.
tests/​unit/​test_exports.py Checks the new scope exports.
tests/​unit/​test_client.py Updates client classification, payment, and credential-free request tests.
tests/​support/​flavour.py Supports scoped registration across both client flavours.
tests/​fake_gateway.py Models pending keys, scoped payments, and browser-header gating.
tests/​contract/​test_public.py Adds release-gated public capability API tests.
tests/​contract/​test_loopback.py Replaces token tests with release-gated capability and gate tests.
tests/​contract/​fixture.py Adapts fixtures to shared pending keys and separate pools.
src/​decdn/​pointer.py Routes pointer responses through the JSON error wrapper.
src/​decdn/​loopback.py Adds scope types and revises capability requests and results.
src/​decdn/​local.py Removes local token helpers.
src/​decdn/​errors.py Removes obsolete authentication and pool-funding error codes.
src/​decdn/​client.py Removes token and host options and authentication headers.
src/​decdn/​_http.py Unifies payment status mapping and wraps JSON decoding errors.
src/​decdn/​_core.py Detects loopback addresses and removes authentication state.
src/​decdn/​__init__.py Exports capability scope types.
scripts/​check-package.sh Replaces the removed module in the wheel import check.
README.md Documents the breaking API changes and gateway compatibility limits.
CONTRIBUTING.md Documents the revised loopback contract fixture.

Review effort: Balanced

Comment thread src/decdn/_http.py Resolved
Comment thread src/decdn/loopback.py Resolved
Comment thread tests/fake_gateway.py Resolved
thiras pushed a commit to decdn/sdk-typescript that referenced this pull request Nov 24, 2026
…ly public gateways, no loopback token (#28)

The `decdn gateway` changes how it pays and who may use it. This PR
updates the SDK, the fake gateway and the contract suite to match.

- **Loopback:** no token. Every route passes a browser-header gate.
  - The gateway holds one pending delegate key.
- A capability is registered with a required scope: `"any"` or an
owner-signed namespace scope.
- A key holds one capability per pool, and capabilities from several
pools.
- **Public:** no daily allowance. It pays only with capabilities
registered through the same API on its bare host, and answers 503 when
none can pay.
- **Payment order:** among usable capabilities (not spent, not inside
the expiry margin), the earliest one scoped to the request's namespace
pays. Failing that, the earliest `"any"` one pays.
- On loopback, the request's namespace is the one its URI names (`?ns=`
or the site's label).
- On public, it is the namespace whose pointer serves the request, and
only for that pointer's own bundle: site entries, and `/_decdn/` for the
site's own hash. `?ns=` and `<ns>.<hash32>` select no scope.

The gateway change is on decdn `main`, which pins this branch in
`.github/sdk-typescript.sha`. sdk-python makes the same change in
[decdn/sdk-python#15](decdn/sdk-python#15), and
the two SDKs behave the same.

## Public API changes (breaking)

- **Opening a client:**
  - `OpenOptions.token` and `OpenOptions.host` are removed.
- A URL on `localhost` or a loopback address (127.0.0.0/8, `[::1]` in
any spelling) opens a loopback client. Any other URL opens a public one,
including an IPv4-mapped address, `0.0.0.0` and `decdn.localhost`.
- In a page on a site origin, `open()` opens that site, whatever
`gatewayUrl` names.
- The client sends no `x-decdn-token`, no `x-decdn-host` and no
`Origin`. From Node, `fetch` sends `User-Agent: node`, which the gate
passes.
- **Removed:**
- The `@decdn/client/node` subpath, with `readLoopbackToken` and
`defaultDataDir`.
  - The `UNAUTHORIZED` error code: a 401 maps to `HTTP`.
  - `POOL_UNFUNDED`.
- **`client.loopback.delegate()`** returns the gateway's pending key. It
is the same address on every call until a capability claims it. The
gateway keeps keys in memory, so a restart loses them.
- **`client.loopback.registerCapability({ capability, scope })`:**
- `scope` is `"any"` or `{ namespaces, signature }`, exported as
`CapabilityScope`.
- It returns `Registration`, newly exported: `{ signer, pool, expiry,
namespaces? }`.
- Before sending anything, it refuses with `CONFIG` an empty
`namespaces`, an id that is not a u64 of at least 1, or a signature that
is not `0x` plus 65 bytes. Otherwise it sends the signature as given,
and the gateway checks it.
- **`client.loopback.capabilities()`** lists the held capabilities in
registration order, as `RegisteredCapability` entries `{ cap, expiry,
namespaces?, pool, signer, spent }`. `namespaces` is present only on a
namespace-scoped capability.
- **`client.loopback` on a non-loopback client** throws `CONFIG`: "the
SDK offers the delegate and capability API on a loopback client alone:
open one on a localhost or loopback-address URL".
- **`PAYMENT_REQUIRED`** is a loopback gateway's plain-text 402, and a
public gateway's 503 that names a fallback URI. It carries
`retryAfterSecs` and `fallbackUri`. Any other 503 is `HTTP`.
- **Bad answers:** a delegate, capability or pointer answer that is not
JSON, lacks a field its contract names, or has a field of another type
raises `HTTP`: "the gateway's answer to `<path>` is not the JSON its
contract names: …". The error carries the body. It no longer surfaces as
a raw `SyntaxError` or a silent `undefined`.

## Fake gateway

**Loopback gate.** A top-level `GET` (`Sec-Fetch-Mode: navigate` and
`Sec-Fetch-Dest: document`) passes first. Otherwise, in this order:
1. `Sec-Fetch-Site: cross-site` gives 403.
2. An `Origin` that is neither the bare host nor a site origin
`http://[<ns>.]<hash32>.localhost:<port>` gives 403.
3. No `Sec-Fetch-Site`, on a request with an `Origin` or a `Mozilla/`
user agent, gives 403.

**Loopback routing.**
- A site origin spends only for its own pages, for the user
(`same-origin`, `none`, or no `Sec-Fetch-Site`), and for a navigation to
a document.
- On the bare host, a browser's navigation to a bundle or entry
redirects to its site.

**API, both modes:**
- `/_delegate` keeps a single pending key.
- `PUT /_capability`, in the real gateway's check order:
1. 422 for a body that does not parse, an unknown field, or a missing or
malformed scope. The scope must be `"any"` or a non-empty list of u64s
(0 included) with an even-length hex signature.
  2. 422 for a cap of 0, or an expiry inside the 420 s margin.
3. 409 for a key the gateway does not hold, or a second capability from
one pool on one key.
  4. 422 for a signature that is not 65 bytes.
- The registration and the listing echo `namespaces` for a namespace
scope.
- On a loopback gateway, the API answers no cross-origin `OPTIONS`. On a
public gateway, `/_delegate`, `/_capability` and `/_status` answer on
the bare host to any origin, with a 204 preflight, and answer 404 on
site hosts.

**Paying.**
- Payment is ranked as described above.
- A pool in `drained` retires its capability, and the next one pays.
- A raw blob the cache holds whole, and the empty root, need nothing
that pays.
- When nothing can pay:
- Loopback answers 402: `the gateway holds no capability that can pay:
register one with PUT /_capability`.
- Public answers 503 JSON `{"error": "the gateway cannot pay right now",
"retry_after_secs": 60, "uri": ...}`, with `Retry-After: 60` and the
`Link` fallback.
- `fake.fund()` gives a test a capability that pays.

## Contract suite and released gateways

- **Loopback** (`describe.skipIf(!shippedAfter("0.3.1"))`):
- The fixture has no `token`. Its `capabilities` field is one `{
capability }` per flavour, each from its own pool, all issued to the
pending key. Real-gateway registrations pass `scope: "any"`.
  - The suite covers:
    - the pending key;
    - the 402 when nothing pays;
    - 422 for a missing or unknown scope, or an extra field;
    - 409 for an unheld key and for a second capability from one pool;
    - the listing's exact keys;
    - verified blob, entry, window and `head` reads;
    - each gate refusal, and the order the gate checks them;
- a top-level navigation from another site passing while a frame's is
refused;
    - the redirect of a navigation to its site.
- Registering a namespace scope runs against the fake only, since a real
gateway needs a pool-owner signature.
- **Public** (`if (shippedAfter("0.3.1"))`): `/_delegate`,
`/_capability` and `/_status` (with no `allowance`) on the bare host to
any origin, and the API preflight on the bare host only. The fixture
registers a capability before the suite, as decdn's harness does.
- **Released gateways:**
- The floor (v0.3.0) and the latest release (v0.3.1) have the old
scoped, token-holding loopback API, so `scripts/decdn-contract.sh --tag`
leaves out the loopback journey for any release at or before v0.3.1.
  - The public journey still runs against both.
- Script tests check the script's `released_after` against
`shippedAfter`.
- The floor stays at 0.3.0 until decdn releases this API. Against 0.3.0
or 0.3.1, a loopback client gets the gateway's 401 as `HTTP`. The README
says so.

## Docs

The README covers:
- the payment order and the expiry margin (one redeem interval plus 120
s, 420 s by default);
- that only a pointer selects a scope on a public gateway;
- the navigation exception and the site-origin rule;
- that a browser sees a gate refusal as `NETWORK`;
- the loopback hosts;
- a `0.1, 0.2` row in the compatibility table.

The docs link the ADR sections `#capabilities`, `#scope` and
`#cross-origin-reads`.

## Gates

Local, on b9ae4e2:
- `pnpm lint` (eslint, prettier, tsc) passes.
- `pnpm test:coverage`: 285 passed, 43 skipped, 94.3% statement
coverage. One test fails: `publish.test.ts` "stops on a version npm has
from another tarball", which fails on macOS because its `tar` has no
`--mtime`. CI runs it on Linux.
- `pnpm test:browser` did not run locally, because Playwright's Chromium
is not installed here. CI's browser job runs it.

Real gateway (`scripts/decdn-contract.sh --ref main`):
- The loopback journey passes.
- The public journey passes except "serves a directory under a site's
/_decdn/ as its index.html". That test is unchanged from sdk `main`, and
decdn `main`'s harness does not write its `docs/index.html` fixture yet
(decdn/decdn#2818).

On b9ae4e2, all 17 CI checks pass, including Node 20.19/22/24/26,
browser (Chromium), coverage, package and the v0.3.0/v0.3.1 release
contracts.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Yigit Gurbulak <[email protected]>
… answers

A namespaced URI's manifest is read with its ?ns=, so a capability scoped
to that namespace pays for it. Delegate, capability and pointer answers
whose fields have the wrong type raise HTTP. The fake's preflight
advertises GET alone for /_delegate and /_status, as the gateway does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@thiras
thiras enabled auto-merge (squash) November 24, 2026 23:57
@thiras
thiras merged commit 55aceec into main Nov 24, 2026
13 checks passed
@thiras
thiras deleted the claude/gateway-pending-key branch November 24, 2026 23:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants