@vaam-apps/vpay-sdk 0.15.0 → 0.17.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/dist/client.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { type MerchantAuthOptions } from "./auth.js";
2
1
  import { AccountHoldersResource } from "./resources/account-holders.js";
3
2
  import { BalanceResource } from "./resources/balance.js";
4
3
  import { CheckoutResource } from "./resources/checkout-sessions.js";
@@ -7,45 +6,42 @@ import { EventsResource } from "./resources/events.js";
7
6
  import { InvoiceItemsResource, InvoicesResource } from "./resources/invoices.js";
8
7
  import { PaymentIntentsResource } from "./resources/payment-intents.js";
9
8
  import { RefundsResource } from "./resources/refunds.js";
9
+ import { type MerchantAuthOptions } from "./sealer.js";
10
10
  /**
11
11
  * Constructor options for {@link VpayClient} — see the package README's
12
12
  * configuration table.
13
13
  *
14
14
  * **This is {@link MerchantAuthOptions}**, which is also what
15
- * `createStripeAuthenticator` takes. The two entry points authenticate the
16
- * same way against the same endpoint with the same defaults
17
- * ({@link resolveMerchantAuth} is the single implementation), so they must
18
- * offer the same knobs — and an interface that merely *listed* the same
19
- * eleven properties would drift the first time one of them gained a twelfth.
20
- * Extending is what makes "the same options" checked rather than intended.
15
+ * `createStripeHttpClient` takes. The two entry points seal the same calls
16
+ * under the same keys with the same defaults ({@link resolveMerchantAuth} is the
17
+ * single implementation), so they must offer the same knobs — and an interface
18
+ * that merely *listed* the same properties would drift the first time one of
19
+ * them gained another. Extending is what makes "the same options" checked
20
+ * rather than intended.
21
21
  *
22
22
  * Every optional property is declared `?: T | undefined`, not `?: T`. Under
23
23
  * `exactOptionalPropertyTypes` (which this repo sets, and which consumers are
24
- * likely to) the shorter form rejects `{ kid: maybeKid }` where `maybeKid` is
25
- * `string | undefined` — forcing every consumer into conditional spreads for
26
- * options that are, semantically, simply optional. `src/types.test.ts` pins
27
- * this at the type level.
24
+ * likely to) the shorter form rejects `{ audience: maybeAudience }` where
25
+ * `maybeAudience` is `string | undefined` — forcing every consumer into
26
+ * conditional spreads for options that are, semantically, simply optional.
27
+ * `src/types.test.ts` pins this at the type level.
28
28
  */
29
29
  export interface VpayClientOptions extends MerchantAuthOptions {
30
- /**
31
- * Default 30000. Applies to **both** the token exchange and every resource
32
- * call — the one place this client's reading of an inherited option is
33
- * narrower than the base's, because `VpayClient` owns its resource
34
- * transport and `createStripeAuthenticator` does not.
35
- */
30
+ /** Default 30000, applied to every resource call. */
36
31
  timeoutMs?: number | undefined;
37
32
  }
38
33
  declare const INSPECT_CUSTOM: unique symbol;
39
34
  /**
40
- * The vpay merchant SDK client. Mints `private_key_jwt` assertions, exchanges
41
- * and caches `/v1` access tokens, and exposes the resource namespaces below.
35
+ * The vpay merchant SDK client. Seals every `/v1` call as a COSE_Sign1 message
36
+ * under the merchant's Ed25519 key, opens the answer under the pinned server
37
+ * keys, and exposes the resource namespaces below.
42
38
  *
43
39
  * The private key never appears in `util.inspect(client)` or
44
- * `JSON.stringify(client)` output — this class never holds it. It is parsed
45
- * once by `resolveMerchantAuth` and kept by the {@link TokenManager} as a
46
- * `crypto.KeyObject`, whose own inspection reveals no key material; the two
47
- * redacted representations below are built by hand from the two fields that
48
- * are safe to print.
40
+ * `JSON.stringify(client)` output — this class never holds it. It is read once
41
+ * by `resolveMerchantAuth` and kept inside the sealer (a seed, in the wasm
42
+ * module's memory) or behind a `crypto.KeyObject`, whose own inspection
43
+ * reveals no key material; the two redacted representations below are built by
44
+ * hand from the two fields that are safe to print.
49
45
  */
50
46
  export declare class VpayClient {
51
47
  #private;
package/dist/client.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import { inspect } from "node:util";
2
- import { resolveMerchantAuth, } from "./auth.js";
3
2
  import { HttpClient } from "./http.js";
4
3
  import { AccountHoldersResource } from "./resources/account-holders.js";
5
4
  import { BalanceResource } from "./resources/balance.js";
@@ -9,22 +8,23 @@ import { EventsResource } from "./resources/events.js";
9
8
  import { InvoiceItemsResource, InvoicesResource, } from "./resources/invoices.js";
10
9
  import { PaymentIntentsResource } from "./resources/payment-intents.js";
11
10
  import { RefundsResource } from "./resources/refunds.js";
11
+ import { resolveMerchantAuth } from "./sealer.js";
12
12
  const INSPECT_CUSTOM = Symbol.for("nodejs.util.inspect.custom");
13
13
  /**
14
- * The vpay merchant SDK client. Mints `private_key_jwt` assertions, exchanges
15
- * and caches `/v1` access tokens, and exposes the resource namespaces below.
14
+ * The vpay merchant SDK client. Seals every `/v1` call as a COSE_Sign1 message
15
+ * under the merchant's Ed25519 key, opens the answer under the pinned server
16
+ * keys, and exposes the resource namespaces below.
16
17
  *
17
18
  * The private key never appears in `util.inspect(client)` or
18
- * `JSON.stringify(client)` output — this class never holds it. It is parsed
19
- * once by `resolveMerchantAuth` and kept by the {@link TokenManager} as a
20
- * `crypto.KeyObject`, whose own inspection reveals no key material; the two
21
- * redacted representations below are built by hand from the two fields that
22
- * are safe to print.
19
+ * `JSON.stringify(client)` output — this class never holds it. It is read once
20
+ * by `resolveMerchantAuth` and kept inside the sealer (a seed, in the wasm
21
+ * module's memory) or behind a `crypto.KeyObject`, whose own inspection
22
+ * reveals no key material; the two redacted representations below are built by
23
+ * hand from the two fields that are safe to print.
23
24
  */
24
25
  export class VpayClient {
25
26
  #clientId;
26
27
  #baseUrl;
27
- #tokenManager;
28
28
  paymentIntents;
29
29
  checkout;
30
30
  /** `/v1/customers` — the merchant-owned record of a payer (S4a). */
@@ -39,21 +39,14 @@ export class VpayClient {
39
39
  /** `/v1/account_holders` — issue #47. */
40
40
  accountHolders;
41
41
  constructor(options) {
42
- // Validation, defaulting and the `TokenManager` itself live in
43
- // `resolveMerchantAuth`, shared with `@vaam-apps/vpay-sdk/stripe`'s authenticator:
44
- // both entry points must mint the same assertion against the same
45
- // endpoint with the same defaults, and one copy is how that stays true.
42
+ // Validation, defaulting and the sealer itself live in
43
+ // `resolveMerchantAuth`, shared with `@vaam-apps/vpay-sdk/stripe`'s HTTP
44
+ // client: both entry points must seal the same bytes under the same keys
45
+ // with the same defaults, and one copy is how that stays true.
46
46
  const auth = resolveMerchantAuth(options);
47
47
  this.#baseUrl = auth.baseUrl;
48
48
  this.#clientId = auth.clientId;
49
- this.#tokenManager = auth.tokenManager;
50
- const httpClient = new HttpClient({
51
- baseUrl: `${this.#baseUrl}/v1`,
52
- tokenManager: this.#tokenManager,
53
- fetchImpl: auth.fetchImpl,
54
- timeoutMs: auth.timeoutMs,
55
- userAgent: auth.userAgent,
56
- });
49
+ const httpClient = new HttpClient(auth);
57
50
  this.paymentIntents = new PaymentIntentsResource(httpClient);
58
51
  this.checkout = new CheckoutResource(httpClient);
59
52
  this.customers = new CustomersResource(httpClient);
package/dist/errors.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Error taxonomy for `@vaam-apps/vpay-sdk`, per docs/flows/merchant-auth.md's
3
- * "Errors" section and the token-endpoint error shape it documents.
3
+ * "Errors" section.
4
4
  *
5
5
  * Every error extends {@link VpayError} so callers can `catch (err) { if
6
6
  * (err instanceof VpayError) ... }` once and still narrow further by
@@ -32,17 +32,35 @@ export declare class VpayApiError extends VpayError {
32
32
  });
33
33
  }
34
34
  /**
35
- * A `400`/`401` from the OAuth2 token endpoint:
36
- * `{ "error": "invalid_client", "error_description": "…" }`
37
- * (`TokenErrorResponse` in `authkestra-op`). Never retried automatically —
38
- * see docs/flows/merchant-auth.md, "Re-authentication".
35
+ * vpay refused the call before any handler saw it: the answer is not sealed.
36
+ *
37
+ * That is the signed transport's one coarse refusal — a `401` whose body is
38
+ * the same for **every** cause (a key nobody registered, a disabled client, a
39
+ * replayed message, the wrong audience, a request that was not signed at all),
40
+ * so that nothing in it helps someone guessing. The cause is in vpay's logs
41
+ * and in the operator's registration of this merchant's key, not here;
42
+ * `docs/flows/merchant-auth.md`, "When the answer is a plain 401", lists what
43
+ * to check, in order. A proxy's own error page lands here too: it is not
44
+ * sealed either.
45
+ *
46
+ * Never retried automatically: the same call would be refused for the same
47
+ * reason, and a replay refusal in particular must not be answered with another
48
+ * replay.
49
+ */
50
+ export declare class VpayUnsignedResponseError extends VpayError {
51
+ /** The HTTP status the unsigned answer came with. */
52
+ readonly status: number;
53
+ constructor(status: number);
54
+ }
55
+ /**
56
+ * The answer claims to be sealed and does not verify under either pinned
57
+ * server key, or does not answer this request. The response is not trusted and
58
+ * nothing in it is read. Almost always a stale `serverKeys` after vpay rotated
59
+ * its response key without a `next` having been pinned first, or a client
60
+ * pointed at the wrong deployment.
39
61
  */
40
- export declare class VpayAuthError extends VpayError {
41
- /** The OAuth2 `error` code, e.g. `invalid_client`. */
42
- readonly error: string;
43
- /** Human-readable detail, when the server sent one. */
44
- readonly errorDescription: string | undefined;
45
- constructor(error: string, errorDescription: string | undefined);
62
+ export declare class VpayUnverifiedResponseError extends VpayError {
63
+ constructor();
46
64
  }
47
65
  /**
48
66
  * A response that is not the Stripe-shaped error envelope this SDK expects —
@@ -87,16 +105,34 @@ export declare class VpayInvalidParamsError extends VpayError {
87
105
  export declare class VpayTransportError extends VpayError {
88
106
  constructor(message: string, options?: ErrorOptions);
89
107
  }
108
+ /**
109
+ * An answer's body exceeded {@link MAX_RESPONSE_BYTES}. Reading stopped at the
110
+ * bound and the connection was destroyed; nothing of the body was kept or
111
+ * opened. The honest server never sends one this large (a page of 100 objects
112
+ * is a few hundred kilobytes), so this is a misbehaving peer or proxy, and an
113
+ * unbounded read would let it make this process hold whatever it liked.
114
+ *
115
+ * A {@link VpayTransportError}, so a caller that handles transport failures
116
+ * already handles this one.
117
+ */
118
+ export declare class VpayResponseTooLargeError extends VpayTransportError {
119
+ /** The bound that was exceeded, in bytes. */
120
+ readonly limit: number;
121
+ constructor(limit: number);
122
+ }
90
123
  /**
91
124
  * The SDK was configured incorrectly — caught before any request is sent.
92
125
  *
93
- * Almost always at construction (a missing `clientId`, an unreadable
94
- * `privateKey`, an `assertionLifetimeSeconds` outside the OP's `1..=300`).
95
- * The one exception is `@vaam-apps/vpay-sdk/stripe`'s host binding: an authenticator
96
- * asked to sign a request addressed somewhere other than its `baseUrl`
97
- * throws this *per request*, because that is when the destination becomes
98
- * knowable. Still before anything is sent — no token is minted and no
99
- * `Authorization` header is written.
126
+ * Almost always at construction (a missing `clientId`, an unreadable or
127
+ * non-Ed25519 `privateKey`, a `serverKeys` entry that is not 32 bytes). The
128
+ * one exception is `@vaam-apps/vpay-sdk/stripe`'s host binding: an HTTP client
129
+ * asked to seal a request addressed somewhere other than its `baseUrl` throws
130
+ * this *per request*, because that is when the destination becomes knowable.
131
+ * Still before anything is sent — nothing is signed.
132
+ *
133
+ * Also thrown when the signing callback fails or returns a signature that does
134
+ * not verify under the registered public key: refused here, with the cause
135
+ * attached, instead of surfacing at vpay as the coarse 401.
100
136
  */
101
137
  export declare class VpayConfigError extends VpayError {
102
138
  }
package/dist/errors.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Error taxonomy for `@vaam-apps/vpay-sdk`, per docs/flows/merchant-auth.md's
3
- * "Errors" section and the token-endpoint error shape it documents.
3
+ * "Errors" section.
4
4
  *
5
5
  * Every error extends {@link VpayError} so callers can `catch (err) { if
6
6
  * (err instanceof VpayError) ... }` once and still narrow further by
@@ -36,20 +36,40 @@ export class VpayApiError extends VpayError {
36
36
  }
37
37
  }
38
38
  /**
39
- * A `400`/`401` from the OAuth2 token endpoint:
40
- * `{ "error": "invalid_client", "error_description": "…" }`
41
- * (`TokenErrorResponse` in `authkestra-op`). Never retried automatically —
42
- * see docs/flows/merchant-auth.md, "Re-authentication".
39
+ * vpay refused the call before any handler saw it: the answer is not sealed.
40
+ *
41
+ * That is the signed transport's one coarse refusal — a `401` whose body is
42
+ * the same for **every** cause (a key nobody registered, a disabled client, a
43
+ * replayed message, the wrong audience, a request that was not signed at all),
44
+ * so that nothing in it helps someone guessing. The cause is in vpay's logs
45
+ * and in the operator's registration of this merchant's key, not here;
46
+ * `docs/flows/merchant-auth.md`, "When the answer is a plain 401", lists what
47
+ * to check, in order. A proxy's own error page lands here too: it is not
48
+ * sealed either.
49
+ *
50
+ * Never retried automatically: the same call would be refused for the same
51
+ * reason, and a replay refusal in particular must not be answered with another
52
+ * replay.
53
+ */
54
+ export class VpayUnsignedResponseError extends VpayError {
55
+ /** The HTTP status the unsigned answer came with. */
56
+ status;
57
+ constructor(status) {
58
+ super(`vpay answered ${status} without a signature: the call was refused before it was handled ` +
59
+ "(unregistered or disabled key, replayed message, wrong audience, or not vpay at all)");
60
+ this.status = status;
61
+ }
62
+ }
63
+ /**
64
+ * The answer claims to be sealed and does not verify under either pinned
65
+ * server key, or does not answer this request. The response is not trusted and
66
+ * nothing in it is read. Almost always a stale `serverKeys` after vpay rotated
67
+ * its response key without a `next` having been pinned first, or a client
68
+ * pointed at the wrong deployment.
43
69
  */
44
- export class VpayAuthError extends VpayError {
45
- /** The OAuth2 `error` code, e.g. `invalid_client`. */
46
- error;
47
- /** Human-readable detail, when the server sent one. */
48
- errorDescription;
49
- constructor(error, errorDescription) {
50
- super(errorDescription ? `${error}: ${errorDescription}` : error);
51
- this.error = error;
52
- this.errorDescription = errorDescription;
70
+ export class VpayUnverifiedResponseError extends VpayError {
71
+ constructor() {
72
+ super("the answer does not verify under the pinned server keys (serverKeys.current / serverKeys.next)");
53
73
  }
54
74
  }
55
75
  /**
@@ -104,16 +124,37 @@ export class VpayTransportError extends VpayError {
104
124
  super(message, options);
105
125
  }
106
126
  }
127
+ /**
128
+ * An answer's body exceeded {@link MAX_RESPONSE_BYTES}. Reading stopped at the
129
+ * bound and the connection was destroyed; nothing of the body was kept or
130
+ * opened. The honest server never sends one this large (a page of 100 objects
131
+ * is a few hundred kilobytes), so this is a misbehaving peer or proxy, and an
132
+ * unbounded read would let it make this process hold whatever it liked.
133
+ *
134
+ * A {@link VpayTransportError}, so a caller that handles transport failures
135
+ * already handles this one.
136
+ */
137
+ export class VpayResponseTooLargeError extends VpayTransportError {
138
+ /** The bound that was exceeded, in bytes. */
139
+ limit;
140
+ constructor(limit) {
141
+ super(`the response body exceeded ${limit} bytes and was not read further`);
142
+ this.limit = limit;
143
+ }
144
+ }
107
145
  /**
108
146
  * The SDK was configured incorrectly — caught before any request is sent.
109
147
  *
110
- * Almost always at construction (a missing `clientId`, an unreadable
111
- * `privateKey`, an `assertionLifetimeSeconds` outside the OP's `1..=300`).
112
- * The one exception is `@vaam-apps/vpay-sdk/stripe`'s host binding: an authenticator
113
- * asked to sign a request addressed somewhere other than its `baseUrl`
114
- * throws this *per request*, because that is when the destination becomes
115
- * knowable. Still before anything is sent — no token is minted and no
116
- * `Authorization` header is written.
148
+ * Almost always at construction (a missing `clientId`, an unreadable or
149
+ * non-Ed25519 `privateKey`, a `serverKeys` entry that is not 32 bytes). The
150
+ * one exception is `@vaam-apps/vpay-sdk/stripe`'s host binding: an HTTP client
151
+ * asked to seal a request addressed somewhere other than its `baseUrl` throws
152
+ * this *per request*, because that is when the destination becomes knowable.
153
+ * Still before anything is sent — nothing is signed.
154
+ *
155
+ * Also thrown when the signing callback fails or returns a signature that does
156
+ * not verify under the registered public key: refused here, with the cause
157
+ * attached, instead of surfacing at vpay as the coarse 401.
117
158
  */
118
159
  export class VpayConfigError extends VpayError {
119
160
  }
package/dist/http.d.ts CHANGED
@@ -1,33 +1,23 @@
1
- import type { TokenManager } from "./auth.js";
2
1
  import { type FormValue } from "./form.js";
2
+ import type { ResolvedMerchantAuth } from "./sealer.js";
3
3
  import type { RequestOptions } from "./types.js";
4
- export interface HttpClientOptions {
5
- baseUrl: string;
6
- tokenManager: TokenManager;
7
- fetchImpl: typeof fetch;
8
- timeoutMs: number;
9
- userAgent: string;
10
- }
11
4
  /**
12
5
  * `DELETE` since 2026-09-06 (S4a) — `DELETE /v1/customers/{id}` is the one
13
6
  * this API has. It is handled as a write below, not as a read: it carries an
14
- * `Idempotency-Key` and, deliberately, **no body**.
15
- *
16
- * The header is the server's contract (`docs/flows/merchant-auth.md`: every
17
- * write under `/v1` carries one) and it is the verb where a replay is most
18
- * confusing without it — the second call would otherwise answer `404` for a
19
- * deletion that succeeded, which a merchant retrying a timed-out request
20
- * cannot tell from "somebody else deleted it".
7
+ * `Idempotency-Key` and, deliberately, **no body** (the sealed message still
8
+ * has an empty payload; the server sees a bodiless `DELETE`).
21
9
  *
22
- * No body, because an empty `application/x-www-form-urlencoded` body and no
23
- * body are different requests to some proxies, and the request hash the
24
- * server stores against the idempotency key is taken over the bytes.
10
+ * The header is the server's contract (every write under `/v1` carries one)
11
+ * and it is the verb where a replay is most confusing without it — the second
12
+ * call would otherwise answer `404` for a deletion that succeeded, which a
13
+ * merchant retrying a timed-out request cannot tell from "somebody else
14
+ * deleted it".
25
15
  */
26
16
  type HttpMethod = "GET" | "POST" | "DELETE";
27
- /** Thin wrapper over `fetch` implementing the merchant-auth wire contract for `/v1`. */
17
+ /** Thin wrapper over the sealed call implementing the `/v1` wire contract. */
28
18
  export declare class HttpClient {
29
19
  #private;
30
- constructor(options: HttpClientOptions);
20
+ constructor(auth: ResolvedMerchantAuth);
31
21
  request<T>(method: HttpMethod, path: string, params?: Record<string, FormValue>, requestOptions?: RequestOptions): Promise<T>;
32
22
  }
33
23
  export {};
package/dist/http.js CHANGED
@@ -1,11 +1,14 @@
1
1
  /**
2
- * The `/v1` resource HTTP layer: request encoding, headers, the single
3
- * 401-triggered re-auth retry, and error-envelope mapping
4
- * (docs/flows/merchant-auth.md, "Headers"/"Errors"/"Re-authentication").
2
+ * The `/v1` resource HTTP layer: request encoding, the `Idempotency-Key`, and
3
+ * error-envelope mapping (docs/flows/merchant-auth.md, "Headers"/"Errors").
4
+ *
5
+ * Every request is sealed (`sealed-call.ts`); there is no token, no
6
+ * `Authorization` header and no re-authentication retry.
5
7
  */
6
8
  import { randomUUID } from "node:crypto";
7
- import { VpayApiError, VpayTransportError, VpayUnexpectedResponseError, boundedBodyPrefix, } from "./errors.js";
9
+ import { VpayApiError, VpayUnexpectedResponseError, boundedBodyPrefix, } from "./errors.js";
8
10
  import { encodeForm } from "./form.js";
11
+ import { performSealedCall } from "./sealed-call.js";
9
12
  function isErrorEnvelope(value) {
10
13
  if (typeof value !== "object" || value === null || !("error" in value)) {
11
14
  return false;
@@ -16,83 +19,42 @@ function isErrorEnvelope(value) {
16
19
  typeof err["type"] === "string" &&
17
20
  typeof err["message"] === "string");
18
21
  }
19
- /** Thin wrapper over `fetch` implementing the merchant-auth wire contract for `/v1`. */
22
+ /** Thin wrapper over the sealed call implementing the `/v1` wire contract. */
20
23
  export class HttpClient {
21
- #options;
22
- constructor(options) {
23
- this.#options = options;
24
+ #auth;
25
+ constructor(auth) {
26
+ this.#auth = auth;
24
27
  }
25
28
  async request(method, path, params, requestOptions) {
26
- let url = `${this.#options.baseUrl}${path}`;
29
+ let query;
27
30
  let body;
28
- const headers = {
29
- Accept: "application/json",
30
- "User-Agent": this.#options.userAgent,
31
- };
31
+ let idempotencyKey;
32
32
  if (method === "GET") {
33
33
  if (params) {
34
- const query = encodeForm(params);
35
- if (query.length > 0) {
36
- url += `?${query}`;
34
+ const encoded = encodeForm(params);
35
+ if (encoded.length > 0) {
36
+ query = encoded;
37
37
  }
38
38
  }
39
39
  }
40
40
  else if (method === "DELETE") {
41
- // Keyed like every other write, and `body` is left `undefined` — see
42
- // the `HttpMethod` comment for why both halves are deliberate.
43
- headers["Idempotency-Key"] =
44
- requestOptions?.idempotencyKey ?? randomUUID();
41
+ idempotencyKey = requestOptions?.idempotencyKey ?? randomUUID();
45
42
  }
46
43
  else {
47
44
  body = params ? encodeForm(params) : "";
48
- headers["Content-Type"] = "application/x-www-form-urlencoded";
49
- headers["Idempotency-Key"] =
50
- requestOptions?.idempotencyKey ?? randomUUID();
51
- }
52
- // `headers` and `body` are built once, above the retry loop, and the
53
- // 401 re-auth below reuses them untouched — only `Authorization` is
54
- // rewritten. The second attempt therefore carries a byte-identical
55
- // `Idempotency-Key` and body, so a re-auth can never double-create
56
- // (docs/flows/merchant-auth.md, "Headers"/"Re-authentication").
57
- let attempt = 0;
58
- for (;;) {
59
- attempt += 1;
60
- const token = await this.#options.tokenManager.getToken();
61
- headers["Authorization"] = `Bearer ${token}`;
62
- let status;
63
- let ok;
64
- let text;
65
- try {
66
- const init = {
67
- method,
68
- headers,
69
- signal: AbortSignal.timeout(this.#options.timeoutMs),
70
- };
71
- if (body !== undefined) {
72
- init.body = body;
73
- }
74
- const response = await this.#options.fetchImpl(url, init);
75
- status = response.status;
76
- ok = response.ok;
77
- // Read the body inside the same `try`. `fetch` resolves as soon as the
78
- // response headers arrive, so a stalled or truncated body — or the
79
- // timeout signal firing mid-stream — rejects *here*, not at the call
80
- // above. Outside this block that rejection escapes as a raw
81
- // `DOMException: TimeoutError` instead of a `VpayTransportError`.
82
- text = await response.text();
83
- }
84
- catch (err) {
85
- throw new VpayTransportError("request failed", { cause: err });
86
- }
87
- if (status === 401 && attempt === 1) {
88
- this.#options.tokenManager.invalidate();
89
- continue;
90
- }
91
- return this.#mapResponse(status, ok, text);
45
+ idempotencyKey = requestOptions?.idempotencyKey ?? randomUUID();
92
46
  }
47
+ const { status, text } = await performSealedCall(this.#auth, {
48
+ method,
49
+ path,
50
+ body,
51
+ query,
52
+ idempotencyKey,
53
+ });
54
+ return this.#mapResponse(status, text);
93
55
  }
94
- #mapResponse(status, ok, text) {
95
- if (ok) {
56
+ #mapResponse(status, text) {
57
+ if (status >= 200 && status < 300) {
96
58
  try {
97
59
  return (text.length > 0 ? JSON.parse(text) : undefined);
98
60
  }
package/dist/index.d.ts CHANGED
@@ -1,15 +1,16 @@
1
1
  /**
2
2
  * `@vaam-apps/vpay-sdk` — the Node.js merchant SDK for vpay.
3
3
  *
4
- * See README.md for the handshake, a usage example, and this package's own
5
- * Status section (the server serves `/v1/oauth` and the `/v1` auth boundary;
6
- * no `/v1` resource route exists yet).
4
+ * Every `/v1` call is sealed as a COSE_Sign1 message under the merchant's
5
+ * Ed25519 key and every answer is opened under the pinned server keys — see
6
+ * README.md for the configuration, a usage example, and the errors a refusal
7
+ * becomes. The sealing is `sdks/rust/wasm`, compiled to WebAssembly.
7
8
  */
8
9
  export { VpayClient, type VpayClientOptions } from "./client.js";
9
- export { mintClientAssertion, type MintClientAssertionOptions, } from "./auth.js";
10
+ export { type ExternalSigner, type KeyBytes, type MerchantAuthOptions, type ServerKeysOption, } from "./sealer.js";
10
11
  export { verifyWebhook, type VerifyWebhookOptions } from "./webhooks.js";
11
12
  /** This package's own version, as sent in the `vpay-sdk-node/<version>` User-Agent. */
12
13
  export { SDK_VERSION } from "./version.js";
13
- export { VpayError, VpayApiError, VpayAuthError, VpayUnexpectedResponseError, VpayTransportError, VpayConfigError, VpayInvalidParamsError, WebhookSignatureError, } from "./errors.js";
14
+ export { VpayError, VpayApiError, VpayUnsignedResponseError, VpayUnverifiedResponseError, VpayUnexpectedResponseError, VpayTransportError, VpayResponseTooLargeError, VpayConfigError, VpayInvalidParamsError, WebhookSignatureError, } from "./errors.js";
14
15
  export type { AccountHolder, RetrieveAccountHolderParams, CheckoutSession, CheckoutSessionStatus, CheckoutSessionUiMode, CheckoutPaymentStatus, CreateCheckoutSessionParams, ListCheckoutSessionsParams, Customer, DeletedCustomer, Address, AddressParams, CreateCustomerParams, UpdateCustomerParams, ListCustomersParams, Invoice, InvoiceLine, InvoiceStatus, InvoiceStatusTransitions, DeletedInvoice, DeletedInvoiceItem, CreateInvoiceParams, UpdateInvoiceParams, ListInvoicesParams, PayInvoiceParams, HostedPayInvoiceParams, OutOfBandPayInvoiceParams, OutOfBandParams, OutOfBandMethod, OutOfBandPayment, CreateInvoiceItemParams, UpdateInvoiceItemParams, PaymentIntent, PaymentIntentStatus, PaymentMethodDetails, PaymentMethodType, NextAction, LastPaymentError, FailureCode, Refund, RefundStatus, Event, KnownEventType, Balance, BalanceAmount, List, ListParams, ListPaymentIntentsParams, ListEventsParams, CreatePaymentIntentParams, ConfirmPaymentIntentParams, MtnMomoPaymentMethodData, OrangeMoneyPaymentMethodData, CreateRefundParams, RefundDestination, UpdateRefundParams, ListRefundsParams, RequestOptions, } from "./types.js";
15
16
  export { isCheckoutSessionEvent, isInvoiceEvent, isPaymentIntentEvent, isRefundEvent, } from "./types.js";
package/dist/index.js CHANGED
@@ -1,14 +1,15 @@
1
1
  /**
2
2
  * `@vaam-apps/vpay-sdk` — the Node.js merchant SDK for vpay.
3
3
  *
4
- * See README.md for the handshake, a usage example, and this package's own
5
- * Status section (the server serves `/v1/oauth` and the `/v1` auth boundary;
6
- * no `/v1` resource route exists yet).
4
+ * Every `/v1` call is sealed as a COSE_Sign1 message under the merchant's
5
+ * Ed25519 key and every answer is opened under the pinned server keys — see
6
+ * README.md for the configuration, a usage example, and the errors a refusal
7
+ * becomes. The sealing is `sdks/rust/wasm`, compiled to WebAssembly.
7
8
  */
8
9
  export { VpayClient } from "./client.js";
9
- export { mintClientAssertion, } from "./auth.js";
10
+ export {} from "./sealer.js";
10
11
  export { verifyWebhook } from "./webhooks.js";
11
12
  /** This package's own version, as sent in the `vpay-sdk-node/<version>` User-Agent. */
12
13
  export { SDK_VERSION } from "./version.js";
13
- export { VpayError, VpayApiError, VpayAuthError, VpayUnexpectedResponseError, VpayTransportError, VpayConfigError, VpayInvalidParamsError, WebhookSignatureError, } from "./errors.js";
14
+ export { VpayError, VpayApiError, VpayUnsignedResponseError, VpayUnverifiedResponseError, VpayUnexpectedResponseError, VpayTransportError, VpayResponseTooLargeError, VpayConfigError, VpayInvalidParamsError, WebhookSignatureError, } from "./errors.js";
14
15
  export { isCheckoutSessionEvent, isInvoiceEvent, isPaymentIntentEvent, isRefundEvent, } from "./types.js";
@@ -0,0 +1,32 @@
1
+ import type { ResolvedMerchantAuth } from "./sealer.js";
2
+ export interface SealedCallSpec {
3
+ method: "GET" | "POST" | "DELETE";
4
+ /** The path **under `/v1`**, parameters in place: `/payment_intents/pi_1/confirm`. */
5
+ path: string;
6
+ /** The form-encoded body of a write. Absent for a read and for a `DELETE`. */
7
+ body?: string | undefined;
8
+ /** The canonical query string of a read, without the `?`. */
9
+ query?: string | undefined;
10
+ /** The `Idempotency-Key` of a write, bound by the signature as sent. */
11
+ idempotencyKey?: string | undefined;
12
+ }
13
+ /** An answer that verified. */
14
+ export interface OpenedAnswer {
15
+ /** The HTTP status, which the signature also binds. */
16
+ status: number;
17
+ /** The verified JSON text. */
18
+ text: string;
19
+ /**
20
+ * The response headers as they arrived, lower-cased, last one winning.
21
+ * **Not authenticated**: the signature covers the payload, the status and the
22
+ * request it answers, not these. Good for a `request-id` in a log line,
23
+ * nothing a decision should rest on.
24
+ */
25
+ headers: Record<string, string>;
26
+ }
27
+ /**
28
+ * Seals `spec`, sends it, and opens the answer. Exactly one attempt: a sealed
29
+ * request is never retried here (a retry is a new message with a new `cti`,
30
+ * which is only safe for a call whose `Idempotency-Key` the caller chose).
31
+ */
32
+ export declare function performSealedCall(auth: ResolvedMerchantAuth, spec: SealedCallSpec, timeoutMs?: number): Promise<OpenedAnswer>;