@vaam-apps/vpay-sdk 0.14.2 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,9 +1,12 @@
1
1
  # @vaam-apps/vpay-sdk
2
2
 
3
- The Node.js merchant SDK for vpay's `/v1` API. Implements the wire contract in
4
- [`docs/flows/merchant-auth.md`](../../docs/flows/merchant-auth.md) exactly —
5
- `private_key_jwt` client assertions, `client_credentials` token exchange and
6
- caching, the form-encoded resource calls, and outbound-webhook verification.
3
+ The Node.js merchant SDK for vpay's `/v1` API. Every call is a COSE_Sign1
4
+ message signed with your Ed25519 key, every answer is opened under vpay's
5
+ pinned response keys, and the signing is **the Rust SDK's own**, compiled to
6
+ WebAssembly (`sdks/rust/wasm`) — see "How a call is signed" below. The wire
7
+ contract is [`docs/flows/signed-transport.md`](../../docs/flows/signed-transport.md);
8
+ the resource calls, the form-encoded bodies and outbound-webhook verification
9
+ are as documented in [`docs/flows/merchant-auth.md`](../../docs/flows/merchant-auth.md).
7
10
 
8
11
  **On the registry since 2026-09-19.** `release.yml`'s `publish-node-sdk` job
9
12
  (added 2026-09-18) publishes it on every `v*` tag, and `npm view
@@ -16,13 +19,16 @@ server it talks to serves; see "Status" below.
16
19
 
17
20
  ## Install
18
21
 
19
- Inside this workspace:
22
+ Inside this workspace (needs Rust, the `wasm32-unknown-unknown` target and
23
+ `wasm-bindgen-cli` at the version `Cargo.lock` pins — `just wasm-build` says
24
+ which to install if it is missing):
20
25
 
21
26
  ```bash
22
27
  pnpm --filter @vaam-apps/vpay-sdk build
23
28
  ```
24
29
 
25
- From the registry:
30
+ From the registry (the published package ships the compiled `.wasm`; nothing to
31
+ build):
26
32
 
27
33
  ```bash
28
34
  pnpm add @vaam-apps/vpay-sdk
@@ -30,30 +36,35 @@ pnpm add @vaam-apps/vpay-sdk
30
36
 
31
37
  Requires Node.js `>=22.11.0`.
32
38
 
33
- ## The handshake, in prose
34
-
35
- `/v1` never accepts an API key ([ADR-0010](../../docs/adr/0010-merchant-auth-private-key-jwt.md)).
36
- Every merchant is a statically registered OAuth2 client authenticating with
37
- `client_credentials` (RFC 6749 §4.4) via a signed `private_key_jwt` assertion
38
- (RFC 7523). Concretely:
39
-
40
- 1. **Mint an assertion.** The SDK signs a short-lived RS256 JWT with your
41
- private key: `iss`/`sub` are your `client_id`, `aud` is the OP's own token
42
- endpoint (see `assertionAudience`), `jti` is a fresh UUIDv4, and `exp` is
43
- `now + assertionLifetimeSeconds` (default 60s, capped at 300s — the OP
44
- refuses anything further out).
45
- 2. **Exchange it for an access token.** The SDK `POST`s the assertion to the
46
- token endpoint alongside `grant_type=client_credentials` and
47
- `audience=vpay:v1`. No `client_secret` is ever sent — there is nothing to
48
- send; vpay stores only your **public** key.
49
- 3. **Call `/v1` with the token.** Every resource call carries
50
- `Authorization: Bearer <access_token>`. The SDK caches the token until
51
- shortly before it expires and reuses it across calls; concurrent calls
52
- share one in-flight token request.
53
- 4. **Re-authenticate on expiry or a 401.** There is no refresh token by
54
- design. On a `401` from a resource route, the SDK discards the cached
55
- token, repeats steps 1–2 once, and retries the original request exactly
56
- once. A second `401` is returned to you as a `VpayApiError`.
39
+ ## How a call is signed
40
+
41
+ `/v1` accepts no API key, and this SDK sends no token: it only seals
42
+ ([ADR-0035](../../docs/adr/0035-v1-is-a-signed-message-not-a-token.md)). A
43
+ deployment whose `auth.methods` also permits `machine_tokens` accepts a bearer
44
+ token from other callers beside a signed request
45
+ ([ADR-0037](../../docs/adr/0037-authentication-methods-are-deployment-configuration.md));
46
+ this SDK does not speak that half.
47
+ A merchant is a registered **Ed25519 public key** (`merchant_clients[].cose_keys`
48
+ in vpay's configuration); vpay finds you by the key that signed. Concretely:
49
+
50
+ 1. **Seal.** For each call the SDK builds a COSE_Sign1 message over the
51
+ payload and binds the audience, method, route template, path parameters,
52
+ canonical query, the operation's contract digest, the payload type and the
53
+ `Idempotency-Key`. The message **is the request body** — even for a `GET`.
54
+ 2. **Send.** On `node:http`/`node:https`, because `fetch` refuses a body on
55
+ `GET`. One attempt: a signed request is never retried by the SDK.
56
+ 3. **Open.** The answer is a COSE_Sign1 message too. The SDK verifies it under
57
+ `serverKeys.current` or `serverKeys.next`, and against _this_ request and
58
+ status, before it reads a byte of JSON. An answer that is not sealed at all
59
+ (vpay's coarse `401`, a proxy's error page) is `VpayUnsignedResponseError`;
60
+ one that claims to be and does not verify is `VpayUnverifiedResponseError`.
61
+
62
+ There is no token to cache and no re-authentication. The sealing is not
63
+ reimplemented in TypeScript: `wasm/` is `sdks/rust/wasm` built with
64
+ `wasm-bindgen --target nodejs`, i.e. the same code path `vpay-sdk` (Rust) runs.
65
+ Your private key either goes in as a seed (the module signs) or **stays in
66
+ Node** behind a `crypto.KeyObject` or a `signer` callback, in which case the
67
+ module only ever sees the bytes to sign.
57
68
 
58
69
  ## Usage
59
70
 
@@ -63,8 +74,16 @@ import { VpayClient } from "@vaam-apps/vpay-sdk";
63
74
 
64
75
  const vpay = new VpayClient({
65
76
  baseUrl: "https://api.vpay.example",
66
- clientId: "merchant_a",
67
- privateKey: readFileSync("./merchant_a.key.pem", "utf8"),
77
+ clientId: "merchant_a", // kept for logs; vpay finds you by your key
78
+ // Your Ed25519 seed (32 bytes, unpadded base64url — `cargo xtask
79
+ // gen-envelope-key` writes it), a PKCS#8 PEM or a crypto.KeyObject.
80
+ privateKey: readFileSync("./merchant_a.seed", "utf8"),
81
+ // The two response keys vpay publishes (it logs them at boot): the one it
82
+ // signs with now and the one it will after the next rotation.
83
+ serverKeys: {
84
+ current: readFileSync("./vpay-current.pub", "utf8").trim(),
85
+ next: readFileSync("./vpay-next.pub", "utf8").trim(),
86
+ },
68
87
  });
69
88
 
70
89
  const intent = await vpay.paymentIntents.create(
@@ -108,7 +127,8 @@ await vpay.refunds.create({
108
127
  reason: "requested_by_customer",
109
128
  });
110
129
  await vpay.events.list({ type: "payment_intent.succeeded", limit: 20 });
111
- await vpay.balance.retrieve();
130
+ // vpay.balance.retrieve() is in the surface but no route serves it: it is
131
+ // refused locally (VpayInvalidParamsError) before anything is signed.
112
132
 
113
133
  // Checkout Sessions (Step 9). A session references an intent you already
114
134
  // created; it never creates one, and it carries where the payer goes next.
@@ -155,81 +175,69 @@ get it to the browser at all.
155
175
 
156
176
  ## Configuration
157
177
 
158
- | Option | Default | Notes |
159
- | -------------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
160
- | `baseUrl` | — | Required, e.g. `https://api.vpay.example`. |
161
- | `clientId` | — | Required. Your registered OAuth2 `client_id`. |
162
- | `privateKey` | — | Required. PEM text or a `crypto.KeyObject`. Never logged, never serialized. |
163
- | `kid` | — | Required only if you registered more than one JWK. |
164
- | `issuer` | `${baseUrl}/v1/oauth` | This default is what the server does: `vpay_api::op::issuer_for` builds the issuer as `{public_base_url}/v1/oauth` from the deployment YAML, and `vpay_api::router` mounts the OP there. Override only for a deployment behind a path prefix. |
165
- | `tokenEndpoint` | `${issuer}/token` | The URL this package POSTs the token request to. A **reachability** setting: it must resolve from wherever your server runs. It is also the default `assertionAudience`, but the two are separate settings — see the row below. |
166
- | `assertionAudience` | `tokenEndpoint` | The client assertion's `aud` claim: the OP's own token endpoint (or issuer) **as vpay is configured publicly** — `{deployment.public_base_url}/v1/oauth/token`. Set it when your server reaches vpay by a different URL than payers do. See "Reaching vpay by an internal URL" below. |
167
- | `audience` | `vpay:v1` | The OAuth2 `audience` request parameter. Load-bearing: without it the OP mints a token whose `aud` is the `client_id`, which the resource server rejects. Server-side the same string is `vpay_config::MERCHANT_AUDIENCE`; this package keeps its own copy, so the two must change together. |
168
- | `scope` | — | Omitted from the token request unless set. |
169
- | `assertionLifetimeSeconds` | `60` | Must be an integer in `1..=300`; anything else throws `VpayConfigError` at construction, not at request time. Keep the default — see the note below the table. |
170
- | `timeoutMs` | `30000` | Applies to both the token exchange and every resource call. |
171
- | `fetch` | global `fetch` | Injection point for tests or an outbound proxy. |
172
-
173
- **Do not raise `assertionLifetimeSeconds` to 300.** 300 is not a comfortable
174
- maximum, it is the OP's exact refusal boundary
175
- (`MAX_CLIENT_ASSERTION_LIFETIME_SECS`), and the OP compares it against _its_
176
- clock. A merchant clock running even one second fast mints an `exp` the OP
177
- reads as 301 seconds out, and every assertion is refused — the failure looks
178
- like `invalid_client`, arrives all at once, and clears up on its own when the
179
- clocks drift back. The default of 60 leaves 240 seconds of headroom for a
180
- value that only has to outlive one HTTP round trip.
178
+ | Option | Default | Notes |
179
+ | ------------ | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
180
+ | `baseUrl` | — | Required, e.g. `https://api.vpay.example`. |
181
+ | `clientId` | — | Required. Your registered `client_id`. Not sent: vpay resolves the merchant from the signing key. |
182
+ | `privateKey` | — | Exactly one of this and `signer`. An Ed25519 key as the 32-byte seed (bytes, or unpadded base64url text), PKCS#8 PEM text, or a `crypto.KeyObject`. An RSA or P-256 key is a `VpayConfigError` at construction. Never logged, never serialized. |
183
+ | `signer` | — | `{ publicKey, sign(tbs) }` for a key this process cannot read (a KMS, an HSM). `sign` receives the exact bytes to sign and returns the 64-byte pure-Ed25519 signature (`crypto.sign(null, tbs, key)`). A signature that does not verify under `publicKey` is refused before it is sent, with the cause, instead of becoming the coarse `401`. |
184
+ | `serverKeys` | — | Required. `{ current, next? }`, each 32 bytes (bytes or unpadded base64url). An answer sealed by any other key is refused (`VpayUnverifiedResponseError`). Pin `next` before vpay rotates so a rotation is not a flag day. |
185
+ | `audience` | `baseUrl` | What every signature is addressed to: vpay's `deployment.public_base_url`. Set it when your server reaches vpay by a different URL than payers do — see below. |
186
+ | `timeoutMs` | `30000` | Applies to every resource call. |
187
+ | `agent` | the global agent | An `http.Agent`/`https.Agent` for a proxy or a pool. (There is no `fetch` option: a sealed `GET` has a body.) |
181
188
 
182
189
  ### Reaching vpay by an internal URL
183
190
 
184
191
  Two things look like one and are not:
185
192
 
186
- - **`tokenEndpoint`** — where this process sends the HTTP request. It has to
187
- be reachable from _your_ server: a compose service name, a private DNS
188
- name, a service-mesh address.
189
- - **`assertionAudience`** — what the OP calls _itself_. The OP's
190
- `authenticate_client` compares the assertion's `aud` claim against its own
191
- two names, `{deployment.public_base_url}/v1/oauth/token` and
192
- `{deployment.public_base_url}/v1/oauth`, and against nothing else. The URL
193
- you happened to POST to is never consulted.
194
-
195
- They coincide for a merchant on the public internet, which is why
196
- `assertionAudience` defaults to `tokenEndpoint`. They do not coincide the
197
- moment your server reaches vpay by an internal name, and then every token
198
- request answers `invalid_client` (`InvalidAudience`) with nothing in the
199
- response pointing at the cause — the signature, the `client_id`, the `kid`
200
- and the lifetime are all correct.
193
+ - **`baseUrl`** — where this process sends the HTTP request. It has to be
194
+ reachable from _your_ server: a compose service name, a private DNS name, a
195
+ service-mesh address.
196
+ - **`audience`** — what vpay calls _itself_. The signature binds
197
+ `deployment.public_base_url` as the server was configured with it, and a
198
+ server compares the string byte for byte. The URL you happened to POST to is
199
+ never consulted.
200
+
201
+ They coincide for a merchant on the public internet, which is why `audience`
202
+ defaults to `baseUrl`. They do not coincide the moment your server reaches
203
+ vpay by an internal name, and then every request is vpay's coarse unsigned
204
+ `401` — the key, the signature and the `client_id` are all correct and the
205
+ response says nothing about audiences.
201
206
 
202
207
  ```ts
203
208
  // The demo stack: the shop's container reaches vpay at the compose service
204
209
  // name, but vpay's `deployment.public_base_url` is the published host port.
205
210
  const vpay = new VpayClient({
206
211
  baseUrl: "http://vpay-server:8080",
207
- assertionAudience: "http://localhost:8080/v1/oauth/token",
212
+ audience: "http://localhost:8080",
208
213
  clientId: "shop-merchant",
209
214
  privateKey,
215
+ serverKeys,
210
216
  });
211
217
  ```
212
218
 
213
- The issuer works too — `http://localhost:8080/v1/oauth` — because the OP
214
- accepts either.
215
-
216
219
  ## Error handling
217
220
 
218
221
  Every error extends `VpayError`, so `catch (err) { if (err instanceof VpayError) ... }`
219
222
  works as a catch-all; narrow further with `instanceof` on a specific subclass:
220
223
 
221
- | Class | When | Fields |
222
- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
223
- | `VpayApiError` | A non-2xx response from a `/v1` resource route. | `status`, `type`, `code`, `message`, `param` |
224
- | `VpayAuthError` | A `400`/`401` from the token endpoint (`invalid_client`, etc). Never retried. | `error`, `errorDescription` |
225
- | `VpayUnexpectedResponseError` | A response that isn't the shape this SDK expects — a proxy's HTML 502, an empty body, or a token-endpoint 200 that is not `{ access_token, token_type: "Bearer", expires_in }` (a non-`Bearer` `token_type` lands here, not in `VpayAuthError`: nothing failed to authenticate, the SDK simply cannot present that token). | `status`, `bodyPrefix` (first 500 bytes) |
226
- | `VpayTransportError` | DNS, TLS, connection refused, timeout. | `cause` (the underlying error) |
227
- | `VpayConfigError` | The SDK was misconfigured — caught at construction where possible. | — |
228
- | `VpayInvalidParamsError` | A request parameter this SDK refuses to send, caught before anything is sent: an amount outside `0..=2^53-1`, a value the form encoder cannot put on the wire exactly (a non-safe-integer number, a `Date`, a `Map`), an empty or all-dots path `id`, a URL beside `outOfBand`. Not a `TypeError` (2026-10-21). | `param`, `message` |
229
- | `WebhookSignatureError` | `verifyWebhook` rejected a signature. | — |
224
+ | Class | When | Fields |
225
+ | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
226
+ | `VpayApiError` | A non-2xx response from a `/v1` resource route. | `status`, `type`, `code`, `message`, `param` |
227
+ | `VpayUnsignedResponseError` | vpay refused the call before it was handled: the answer is not sealed (an unregistered or disabled key, a replayed message, the wrong audience — all the same bytes by design — or a proxy's error page). Never retried. | `status` |
228
+ | `VpayUnverifiedResponseError` | The answer claims to be sealed and does not verify under `serverKeys` (a stale pin after a rotation, or the wrong deployment). | — |
229
+ | `VpayUnexpectedResponseError` | A verified answer that isn't the shape this SDK expects — an empty body, or JSON that is not the Stripe-shaped error envelope on a non-2xx status. | `status`, `bodyPrefix` (first 500 bytes) |
230
+ | `VpayTransportError` | DNS, TLS, connection refused, timeout (the cause is a `TimeoutError` when the timeout fired). | `cause` (the underlying error) |
231
+ | `VpayConfigError` | The SDK was misconfigured — caught at construction where possible. | — |
232
+ | `VpayInvalidParamsError` | A request parameter this SDK refuses to send, caught before anything is sent: an amount outside `0..=2^53-1`, a value the form encoder cannot put on the wire exactly (a non-safe-integer number, a `Date`, a `Map`), an empty or all-dots path `id`, a URL beside `outOfBand`. Not a `TypeError` (2026-10-21). | `param`, `message` |
233
+ | `WebhookSignatureError` | `verifyWebhook` rejected a signature. | — |
230
234
 
231
235
  ```ts
232
- import { VpayApiError, VpayAuthError, VpayError } from "@vaam-apps/vpay-sdk";
236
+ import {
237
+ VpayApiError,
238
+ VpayError,
239
+ VpayUnsignedResponseError,
240
+ } from "@vaam-apps/vpay-sdk";
233
241
 
234
242
  try {
235
243
  await vpay.paymentIntents.create({
@@ -240,8 +248,8 @@ try {
240
248
  } catch (err) {
241
249
  if (err instanceof VpayApiError) {
242
250
  console.error(err.status, err.type, err.code, err.message, err.param);
243
- } else if (err instanceof VpayAuthError) {
244
- console.error("authentication failed:", err.error, err.errorDescription);
251
+ } else if (err instanceof VpayUnsignedResponseError) {
252
+ console.error("vpay refused the signature:", err.status);
245
253
  } else if (err instanceof VpayError) {
246
254
  console.error(err.name, err.message);
247
255
  }
@@ -322,28 +330,28 @@ createServer((req, res) => {
322
330
 
323
331
  vpay's `/v1` surface is Stripe-shaped, and the official
324
332
  [`stripe`](https://www.npmjs.com/package/stripe) Node SDK can talk to it —
325
- with an **empty API key** and a `config.authenticator` that performs the
326
- `private_key_jwt` handshake above. `@vaam-apps/vpay-sdk/stripe` is that authenticator:
333
+ with a placeholder API key and a `config.httpClient` that seals each request
334
+ and opens the answer. `@vaam-apps/vpay-sdk/stripe` is that client:
327
335
 
328
336
  ```js
329
337
  import { readFileSync } from "node:fs";
330
338
  import Stripe from "stripe";
331
- import { createStripeAuthenticator } from "@vaam-apps/vpay-sdk/stripe";
332
-
333
- const authenticator = createStripeAuthenticator({
334
- baseUrl: "http://localhost:8080",
335
- clientId: "acme-cameroon",
336
- privateKey: readFileSync("./merchant-key.pem", "utf8"),
337
- kid: "acme-cameroon-2026-08",
338
- });
339
-
340
- const stripe = new Stripe("", {
341
- authenticator,
339
+ import { createStripeHttpClient } from "@vaam-apps/vpay-sdk/stripe";
340
+
341
+ const stripe = new Stripe("unused-placeholder", {
342
+ httpClient: createStripeHttpClient({
343
+ baseUrl: "http://localhost:8080",
344
+ clientId: "acme-cameroon",
345
+ privateKey: readFileSync("./merchant.seed", "utf8"),
346
+ serverKeys: {
347
+ current: readFileSync("./vpay-current.pub", "utf8").trim(),
348
+ next: readFileSync("./vpay-next.pub", "utf8").trim(),
349
+ },
350
+ }),
342
351
  host: "localhost",
343
352
  port: "8080",
344
353
  protocol: "http",
345
- maxNetworkRetries: 2,
346
- timeout: 30_000,
354
+ maxNetworkRetries: 0,
347
355
  telemetry: false,
348
356
  });
349
357
 
@@ -354,46 +362,63 @@ const intent = await stripe.paymentIntents.create({
354
362
  });
355
363
  ```
356
364
 
357
- `host`, `port` and `protocol` are not optional. The authenticator is bound to
365
+ **Why `httpClient` and not `authenticator`.** The signature is the request
366
+ _body_; stripe-node's `authenticator` is a hook that can add headers and
367
+ nothing else. `httpClient` is the seam that is handed the finished request
368
+ (`host`, `port`, `path`, `method`, `headers`, `requestData`, `protocol`,
369
+ `timeout`) and returns a response. The client seals it, sends it, opens the
370
+ answer, and returns the verified JSON as the response body, so everything above
371
+ it — resource methods, typed results, `Stripe.errors.*` — behaves as it does
372
+ against Stripe.
373
+
374
+ `host`, `port` and `protocol` are not optional. The client is bound to
358
375
  `baseUrl`'s origin: a request addressed anywhere else throws `VpayConfigError`
359
- before a token is minted. Omit them and stripe-node addresses
376
+ before anything is signed. Omit them and stripe-node addresses
360
377
  `api.stripe.com:443`, which is exactly the case this refusal exists to stop.
361
- Behind a reverse proxy, or on split-horizon DNS, set `baseUrl` to the origin
362
- this client actually connects to rather than the public one — both the token
363
- exchange and the binding follow `baseUrl`, so a mismatch either mints the
364
- token against an unreachable endpoint or refuses every request as addressed
365
- elsewhere.
366
-
367
- `stripe` is an **optional peer dependency** of this package: install it
368
- yourself if you want this entry point, and `@vaam-apps/vpay-sdk`'s core entry never
369
- imports it. This package itself still has **zero runtime dependencies**.
370
-
371
- The empty first argument is not a trick — stripe-node's `_setAuthenticator`
372
- refuses only _both_ an API key and an authenticator, or _neither_. The token
373
- cache, its single-flight refresh and its `expires_in` safety margin are the
374
- same ones `VpayClient` uses, not a second implementation.
375
378
 
376
- `authenticator.invalidate()` discards the cached token. You need it because an
377
- authenticator runs _before_ a request and its promise settles before any
378
- status code exists — it cannot see a `401` and re-auth the way `VpayClient`
379
- does:
379
+ The first argument is a placeholder stripe-node insists on and that is never
380
+ sent: the client forwards **only** the `Idempotency-Key` of what stripe-node
381
+ set (`Authorization`, `Stripe-Version`, `X-Stripe-Client-User-Agent` and the
382
+ rest are dropped; the signature binds the payload type itself). stripe-node
383
+ only keys POSTs, and vpay requires a key on every write, so a `DELETE` is given
384
+ a fresh one.
380
385
 
381
- ```js
382
- try {
383
- await stripe.paymentIntents.retrieve(id);
384
- } catch (err) {
385
- if (err instanceof Stripe.errors.StripeAuthenticationError) {
386
- authenticator.invalidate();
387
- }
388
- throw err;
389
- }
390
- ```
386
+ `stripe` is an **optional peer dependency** of this package: install it
387
+ yourself if you want this entry point, and `@vaam-apps/vpay-sdk`'s core entry
388
+ never imports it.
389
+
390
+ ### When vpay refuses
391
+
392
+ stripe-node retries every _rejection_ from an `httpClient` (`maxNetworkRetries`
393
+ defaults to **2** on Node) and its public API cannot exempt one, so a refusal is
394
+ not a rejection. A refused call (the unsigned `401`), an answer that does not
395
+ verify and a body over 8 MiB are returned as Stripe-shaped error responses with
396
+ `stripe-should-retry: false` and surface **once**: `StripeAuthenticationError`
397
+ (`code: "unsigned_response"`) for the `401`, `StripeAPIError`
398
+ (`"unverified_response"`, `"response_too_large"`) otherwise, the cause in
399
+ `message`. A gateway's unsigned `5xx` stays retryable.
400
+
401
+ Two more are answered the same way, and neither can resolve as a result or be
402
+ retried. A request the contract has no operation for (a `GET` on a `POST`-only
403
+ path, a path outside `/v1`) is never sent: `StripeInvalidRequestError`, status
404
+ `404`, `code: "unknown_operation"`. A sealed `4xx`/`5xx` that is not in the
405
+ Stripe error envelope (the body bound's `413` is the one you can meet) is an
406
+ error with its status and `code: "unexpected_error_response"`, or
407
+ `"request_too_large"` for the `413` (a `StripeAPIError`, as stripe-node has no
408
+ class for it); the `413` carries vpay's `request-id`.
409
+
410
+ A real transport failure (DNS, TLS, a reset, a timeout) still rejects, is a
411
+ `StripeConnectionError` with the original at `err.detail`, and is retried up to
412
+ `maxNetworkRetries` times, re-sealed each time. A `POST` keeps the
413
+ `Idempotency-Key` stripe-node chose; a `DELETE` has none from stripe-node and
414
+ gets a new one per attempt, so set `maxNetworkRetries: 0` if a repeated `DELETE`
415
+ answering `404` is not acceptable.
391
416
 
392
417
  ### Where vpay diverges from Stripe
393
418
 
394
- - **No API keys, ever.** `sk_live_…` means nothing here; authentication is the
395
- OAuth2 `client_credentials` + `private_key_jwt` handshake above
396
- ([ADR-0010](../../docs/adr/0010-merchant-auth-private-key-jwt.md)). There is
419
+ - **No API keys, ever.** `sk_live_…` means nothing here; authentication is a signed
420
+ message under your Ed25519 key
421
+ ([ADR-0035](../../docs/adr/0035-v1-is-a-signed-message-not-a-token.md)). There is
397
422
  no publishable key and no Connect equivalent.
398
423
  - **`Idempotency-Key` is mandatory on every `/v1` POST**, not optional as at
399
424
  Stripe. This costs you nothing: stripe-node puts a
@@ -452,7 +477,7 @@ try {
452
477
  read as `undefined` at runtime while the type says otherwise, on every
453
478
  route including `create`/`retrieve`.
454
479
  - **`Stripe-Version`, `Stripe-Account`, `Stripe-Context` and the
455
- `X-Stripe-Client-*` headers are accepted and ignored.** vpay advertises no
480
+ `X-Stripe-Client-*` headers are dropped before sealing.** vpay advertises no
456
481
  dated API version, so `obj.lastResponse.apiVersion` is `undefined` and
457
482
  pinning `apiVersion` has no effect.
458
483
 
@@ -497,101 +522,74 @@ const event = stripe.webhooks.constructEvent(
497
522
  it — prefer it in code you write from scratch, and use this package's own
498
523
  `verifyWebhook` if you are not otherwise using stripe-node.
499
524
 
500
- ### A stripe-node defect you will hit if your key is wrong
501
-
502
- **Measured against `stripe@22.6.1`, not inferred.** When the vpay handshake
503
- fails — a bad key, an unregistered `client_id`, vpay unreachable — the
504
- authenticator rejects, as it must. stripe-node builds the right error from it
505
- (`StripeError: Unable to authenticate the request`, with the underlying
506
- `VpayAuthError` at `err.raw.exception`) but **throws it inside a detached
507
- promise chain that never calls its own callback**. The result: the error
508
- arrives as a process-level `unhandledRejection`, and the promise you awaited
509
- **never settles at all** — not even after `timeout`, because no HTTP request
510
- was ever started for a timeout to fire against.
511
-
512
- Two of the ways a key can be wrong no longer reach that path at all. A
513
- `privateKey` that `node:crypto` cannot read, and a `baseUrl` that is not an
514
- absolute URL, are both `VpayConfigError` thrown by `createStripeAuthenticator`
515
- **at construction** — before a `Stripe` instance exists, on the line the
516
- merchant wrote. What is left for the warning below is the set of failures only
517
- the OP can report: an unregistered `client_id`, a key whose public half vpay
518
- does not hold, a clock too far out, vpay unreachable.
519
-
520
- Until stripe-node fixes this, do not rely on `try`/`catch` around a call to
521
- surface a handshake failure. Two things that do work:
522
-
523
- - **Verify the handshake at startup**, where a rejection is yours to catch.
524
- The authenticator is a plain function, so call it once against a throwaway
525
- request object and let it throw before you serve traffic — a `VpayAuthError`
526
- there names the OAuth2 reason (`invalid_client`, …) directly:
527
-
528
- ```js
529
- await authenticator({ headers: {} });
530
- ```
531
-
532
- - **Install a process-level guard** so a mid-flight handshake failure is at
533
- least logged and alerted on rather than silently hanging a request:
534
- `process.on("unhandledRejection", …)`.
535
-
536
- `src/stripe-auth.test.ts` pins this behaviour, so if a future `stripe` release
537
- routes the failure to the caller the test fails and this warning gets deleted.
538
-
539
525
  ### Status
540
526
 
541
- `createStripeAuthenticator` is **built and tested**. Its tests run against a
542
- real `node:http` server and, for the end-to-end case, drive the **real
543
- `stripe` package**: `new Stripe("", { authenticator, host, port, protocol })`
544
- creating a PaymentIntent, with the stub asserting the `Authorization` header
545
- the authenticator minted, the form-encoded body, and stripe-node's
546
- auto-generated `Idempotency-Key`. The type-level assertion that the returned
547
- function is assignable to `Stripe.StripeConfig["authenticator"]` is checked by
527
+ `createStripeHttpClient` is **built and tested**. Its tests run against a real
528
+ `node:http` server that opens the sealed request under the merchant's key and
529
+ seals its answer (cratestack's own server envelope, built from
530
+ `sdks/rust/wasm`'s `responder` feature) and drive the **real `stripe`
531
+ package**: `new Stripe("…", { httpClient, host, port, protocol })` creating,
532
+ listing, retrieving and deleting. The type-level assertion that the returned
533
+ client is assignable to `Stripe.StripeConfig["httpClient"]` is checked by
548
534
  `pnpm --filter @vaam-apps/vpay-sdk typecheck`.
549
535
 
550
536
  What is **not** proven here:
551
537
 
552
- - **Nothing in this package has run against a real `vpay-server`.** The
553
- end-to-end test's server is a stub in this repository. What _has_ run
554
- against a real one is
555
- [`sdks/stripe-compat`](../stripe-compat/) — the official `stripe` package
556
- driven through this authenticator against a live compose stack, 25 cases,
557
- run by CI's `e2e (compose)` job. It is a separate package on purpose: it
558
- needs a stack, and a suite that needs a stack must not be able to report
538
+ - **Nothing in this package has run against a real `vpay-server`** from its
539
+ own tests. What _has_ is [`sdks/stripe-compat`](../stripe-compat/) — the
540
+ official `stripe` package driven through this client against a live compose
541
+ stack, run by CI's `e2e (compose)` job. It is a separate package on purpose:
542
+ it needs a stack, and a suite that needs a stack must not be able to report
559
543
  green in a job that has none.
560
544
  - **Every webhook verified so far was delivered to a WireMock receiver on a
561
- compose network.** The _signature_ is now proven three ways — against this
545
+ compose network.** The _signature_ is proven three ways — against this
562
546
  package's own `verifyWebhook`, against `vpay_sdk::webhooks::verify_at`, and
563
547
  against the official `stripe` package's `constructEvent` — but **no merchant
564
- endpoint has ever been POSTed to**, and there is no SSRF protection on the
565
- destination ([`docs/flows/webhooks.md`](../../docs/flows/webhooks.md)).
548
+ endpoint has ever been POSTed to**.
566
549
  - **The `stripe` peer range (`^22.6.1`) is asserted, not derived.** It is the
567
550
  current major at the time of writing, tested against exactly `22.6.1`.
568
- Nothing pins vpay against a future `stripe` release; a dependency bump is
569
- what will surface a break.
570
551
  - **The server-side compatibility work is not in this package**, though it
571
- has now landed beside it: the `request-id` response header stripe-node
572
- reads, `stripe-should-retry` derived from `Classify::retry`, and refusing
573
- `confirm: true` on create rather than ignoring it are all in `vpay-api`,
574
- with their own unit and integration tests, and are exercised end to end by
575
- `sdks/stripe-compat`. See
552
+ lives beside it: the `request-id` response header stripe-node reads,
553
+ `stripe-should-retry` derived from `Classify::retry`, and refusing
554
+ `confirm: true` on create rather than ignoring it are all in `vpay-api`. See
576
555
  [`docs/flows/stripe-sdk-compat.md`](../../docs/flows/stripe-sdk-compat.md).
577
556
 
578
- ## `scripts/mint-assertion.mjs`
557
+ ## `scripts/vpay-call.mjs`
579
558
 
580
- Mints one assertion and prints it, alongside the public JWK derived from the
581
- same private key, as JSON on stdout — used to feed a real OP verifier (e.g. a
582
- Rust example driving `authkestra_op::client_assertion::verify_client_assertion`
583
- directly) without standing up a server:
559
+ One signed `/v1` call from a shell — what `curl` cannot do, because the request
560
+ is a COSE message and not a header on an ordinary one. The path is under `/v1`;
561
+ the verified JSON goes to stdout, the HTTP status to stderr, and the exit code is
562
+ 0 for a 2xx:
584
563
 
585
564
  ```bash
586
565
  pnpm --filter @vaam-apps/vpay-sdk build
587
- VPAY_CLIENT_ID=merchant_a \
588
- VPAY_PRIVATE_KEY_FILE=./merchant_a.key.pem \
589
- VPAY_AUDIENCE=https://api.vpay.example/v1/oauth/token \
590
- node sdks/nodejs/scripts/mint-assertion.mjs
566
+ export VPAY_BASE_URL=http://localhost:8080
567
+ export VPAY_MERCHANT_SIGNING_SEED_PATH=.e2e/demo-merchant/signing.seed
568
+ export VPAY_SERVER_KEY_CURRENT_PATH=.e2e/envelope/current.pub
569
+ node sdks/nodejs/scripts/vpay-call.mjs GET /payment_intents --query 'limit=3'
570
+ node sdks/nodejs/scripts/vpay-call.mjs POST /payment_intents \
571
+ --data 'amount=5000&currency=xaf&payment_method_types[0]=mtn_momo' --key order-42
591
572
  ```
592
573
 
593
574
  ## Status
594
575
 
576
+ **Breaking, 2026-10-26 (VP-7): `/v1` is signed, and this package signs it.**
577
+ The `private_key_jwt` assertion, the token exchange, the token cache and the
578
+ 401 re-authentication retry are gone, with `mintClientAssertion`,
579
+ `VpayAuthError`, `scripts/mint-assertion.mjs`, the `kid`, `issuer`,
580
+ `tokenEndpoint`, `assertionAudience`, `audience` (now the signature's
581
+ audience, a different thing), `scope`, `assertionLifetimeSeconds` and `fetch`
582
+ options, and `createStripeAuthenticator` (replaced by `createStripeHttpClient`,
583
+ for the reason given above). A client now needs an Ed25519 key and
584
+ `serverKeys`; RSA keys are refused at construction. New errors:
585
+ `VpayUnsignedResponseError`, `VpayUnverifiedResponseError`. The requests go out
586
+ on `node:http(s)` rather than `fetch` (a sealed `GET` has a body), and the
587
+ package needs `sdks/rust/wasm` compiled at build time. Nothing about a
588
+ resource method's signature, a request's form body or a response's shape
589
+ changed. `balance.retrieve()` is now refused locally: no route serves it and
590
+ the operation table has no row to bind (it answered `404 unknown_route`
591
+ before).
592
+
595
593
  **Breaking, 2026-10-21: every local refusal is a `VpayInvalidParamsError`,
596
594
  not a `TypeError`.** An amount outside `0..=2^53-1`, a value the form
597
595
  encoder cannot put on the wire exactly, an empty or all-dots path `id` and a
@@ -666,9 +664,10 @@ package could catch earlier.
666
664
  **No test in _this package_ has ever talked to a vpay** — every server in
667
665
  these tests is a `node:http` stub started by the test. What has talked to a
668
666
  real one is `sdks/stripe-compat`, which drives the official `stripe` package
669
- through this package's own `createStripeAuthenticator` against a live
670
- compose stack (25 cases, CI's `e2e (compose)` job), and the Rust SDK's
671
- `backends/tests/integration/tests/merchant_token_flow.rs`. See
667
+ through this package's own `createStripeHttpClient` against a live compose
668
+ stack (CI's `e2e (compose)` job), and the Rust SDK's
669
+ `backends/tests/integration/tests/customers.rs` and siblings (the real
670
+ `EnvelopeLayer`). See
672
671
  [`docs/status.md`](../../docs/status.md),
673
672
  [`docs/flows/merchant-auth.md`](../../docs/flows/merchant-auth.md) and
674
673
  [`docs/flows/stripe-sdk-compat.md`](../../docs/flows/stripe-sdk-compat.md).
@@ -679,17 +678,23 @@ runs against a real `node:http` server started by the test (never a mocked
679
678
  the webhook verifier and the error-body bounding are pure unit tests, since
680
679
  none of them touches the network:
681
680
 
682
- - The client assertion this SDK mints has every claim and header field the
683
- wire contract specifies, is a fresh `jti` per mint, and its RS256 signature
684
- verifies with `node:crypto` against the matching public key — and fails
685
- against a different one.
686
- - The full `client_credentials` + `private_key_jwt` token exchange: exact
687
- form fields, content type, and the resulting `Authorization: Bearer`
688
- header on the following resource call.
689
- - Token caching (`expires_in` minus the safety margin), single-flight
690
- refresh under concurrent callers, and the single 401-triggered re-auth
691
- retry (including that a second consecutive 401 surfaces as `VpayApiError`
692
- without a third token request).
681
+ - What a signature binds, driven straight at the sealing module with
682
+ cratestack's server envelope on the other end (`src/sealer.test.ts`): an
683
+ untouched message opens; the same bytes a second time are refused (a replay);
684
+ a changed byte, another audience, another route, another path parameter,
685
+ another method, another query (and the same pairs in another order are
686
+ _accepted_: the query is canonical), another `Idempotency-Key` and a key the
687
+ server does not hold are each refused; an operation no table row serves is
688
+ refused before anything is signed; an answer opens only against its own
689
+ request and status, and only once.
690
+ - Signing end to end through `VpayClient` and a real `node:http` server that
691
+ verifies the way vpay does: a seed, a PEM, a `KeyObject` and a callback signer
692
+ all sign (and a callback signature that does not verify is refused with the
693
+ cause); an RSA key, a doubled or missing key, a malformed key (never quoted)
694
+ and a missing `serverKeys` are construction errors; the pinned `next` key
695
+ verifies an answer; a wrong pin is `VpayUnverifiedResponseError`; an
696
+ unregistered key and a wrong audience are `VpayUnsignedResponseError`; a
697
+ sealed request has no `Authorization` header and is the body of even a `GET`.
693
698
  - Every resource method's exact HTTP method, path, headers, and
694
699
  bracket-encoded body — including that a caller-supplied `Idempotency-Key`
695
700
  is honoured and one is generated when omitted.
@@ -713,19 +718,18 @@ none of them touches the network:
713
718
  `Date` in `metadata` — is a `VpayInvalidParamsError` naming its parameter,
714
719
  caught by `instanceof VpayError` and not a `TypeError`, with nothing sent.
715
720
  - That an empty or all-dots `id` throws `VpayInvalidParamsError` on all twenty-one
716
- id-taking methods before any request, the token request included, with one
721
+ id-taking methods before any request, with one
717
722
  fixed message that never quotes it; that an id with dots in it that is not
718
723
  only dots (`a..b`, `.a`, `%2E%2E`) is still sent as exactly one segment;
719
724
  and, as the premise, that WHATWG `URL` resolves `..`, `%2E%2E` and `.%2e`
720
725
  alike.
721
- - Error mapping for a Stripe-shaped `400`, an unexpected `502` HTML body, a
722
- connection failure, and a token-endpoint `401` (which is never retried).
726
+ - Error mapping for a Stripe-shaped `400`, a sealed answer that is not the
727
+ error envelope, a proxy's unsigned `502` HTML page, and a connection failure.
723
728
  - Webhook verification: valid/invalid signatures, timestamp tolerance,
724
729
  multi-signature secret rotation, malformed headers, a one-byte body change,
725
730
  and that a `Buffer` body and its string form verify identically.
726
731
  - That `util.inspect(client)` and `JSON.stringify(client)` never contain the
727
- private key, and that neither the client nor any error this SDK throws
728
- carries an access token into `util.inspect` output.
732
+ signing seed or a PEM.
729
733
  - All thirteen invoice operations (S4b, added 2026-09-08): the exact body of
730
734
  `invoices.create` and of a create that supplies nothing but the two required
731
735
  fields (`customer` and `currency` — the second was optional for one day, and
@@ -759,18 +763,13 @@ none of them touches the network:
759
763
  do **not** claim them, and that an event body's empty `lines` decodes
760
764
  through the same `Invoice` type a `/v1` response's populated `lines` does.
761
765
 
762
- **Separately — and this is _not_ one of the tests above — the assertion has
763
- been checked against the real OP verifier by hand.** An assertion minted by
764
- this SDK was fed directly to
765
- `authkestra_op::client_assertion::verify_client_assertion` at the pinned
766
- `authkestra-op = "=0.7.1"`, against a `ClientRegistration` holding the
767
- corresponding public JWK, and was accepted — and again at `=0.13.1` on
768
- 2026-10-26, when the pin moved. `just sdk-conformance-node`
769
- reproduces it: the recipe mints an assertion via `scripts/mint-assertion.mjs`
770
- and pipes it into `cargo run -p vpay-sdk --example verify_assertion`. It is a
771
- manual check, run on demand — it needs a Rust toolchain, it is not part of
772
- `pnpm test`, and no CI job gates on it. Nothing in the list above depends on
773
- it having been run.
766
+ **There is no separate conformance check, and that is the point.** The old
767
+ `just sdk-conformance-node` fed an assertion this package minted to the real
768
+ OP verifier, because two implementations had to be shown to agree. The signing
769
+ here is the Rust SDK's own code (`sdks/rust/wasm`), and the module's server half
770
+ that these tests open requests with is cratestack's own server envelope, so
771
+ there is one implementation to check, and `sdks/rust/tests/signing.rs` and the
772
+ integration suites check it against the real `EnvelopeLayer`.
774
773
 
775
774
  What this does **not** prove: that any of this works against a real vpay
776
775
  deployment. ~~Nothing in this package has been run against `vpay-server`; the
@@ -784,9 +783,9 @@ _(Struck 2026-09-23. All three clauses had gone stale. **Run against
784
783
  `src/refunds.live.test.ts` on 2026-09-16, drives a real `vpay-server` over a
785
784
  socket, and CI's `e2e` job runs them (`pnpm --filter @vaam-apps/vpay-sdk
786
785
  test:live`). **The defaults:** those suites' preflight
787
- (`src/testing/live-preflight.ts`) builds its client from `baseUrl` alone, so
788
- every live run exercises the default `issuer` and `tokenEndpoint` against the
789
- server's own OP. **The routes:** every method's route is mounted except
786
+ (`src/testing/live-preflight.ts`) builds its client from the live environment's `baseUrl` and keys, so
787
+ every live run exercises the default `audience` against the server's own
788
+ configured name. **The routes:** every method's route is mounted except
790
789
  `balance.retrieve`, which answers `404` by design
791
790
  ([`docs/sdks/parity.md`](../../docs/sdks/parity.md)). What still stands is the
792
791
  sentence this paragraph opens with. That stack is a compose stack with