@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.
@@ -0,0 +1,65 @@
1
+ /**
2
+ * One sealed call, start to finish: seal, send, open.
3
+ *
4
+ * The single place the two entry points (`VpayClient`'s resources and
5
+ * `@vaam-apps/vpay-sdk/stripe`'s HTTP client) go through, so that both bind the
6
+ * same bytes and map the same failures to the same errors.
7
+ */
8
+ import { VpayConfigError, VpayInvalidParamsError, VpayTransportError, VpayUnexpectedResponseError, VpayUnsignedResponseError, VpayUnverifiedResponseError, } from "./errors.js";
9
+ import { sendSealed } from "./transport.js";
10
+ import { isWasmFailure } from "./wasm.js";
11
+ function mapFailure(err) {
12
+ if (!isWasmFailure(err)) {
13
+ return new VpayConfigError("sealing the call failed", { cause: err });
14
+ }
15
+ switch (err.kind) {
16
+ case "unbound":
17
+ return new VpayInvalidParamsError("path", err.message);
18
+ case "unsigned":
19
+ return new VpayUnsignedResponseError(err.status ?? 0);
20
+ case "unverified":
21
+ return new VpayUnverifiedResponseError();
22
+ default:
23
+ return new VpayConfigError(err.message);
24
+ }
25
+ }
26
+ /**
27
+ * Seals `spec`, sends it, and opens the answer. Exactly one attempt: a sealed
28
+ * request is never retried here (a retry is a new message with a new `cti`,
29
+ * which is only safe for a call whose `Idempotency-Key` the caller chose).
30
+ */
31
+ export async function performSealedCall(auth, spec, timeoutMs = auth.timeoutMs) {
32
+ let sealed;
33
+ try {
34
+ sealed = await auth.sealer.sealCall(spec.method, spec.path, spec.body, spec.query, spec.idempotencyKey);
35
+ }
36
+ catch (err) {
37
+ throw mapFailure(err);
38
+ }
39
+ const query = spec.query !== undefined && spec.query.length > 0 ? `?${spec.query}` : "";
40
+ const response = await sendSealed({
41
+ method: spec.method,
42
+ url: `${auth.baseUrl}/v1${spec.path}${query}`,
43
+ headers: [...sealed.headers, ["user-agent", auth.userAgent]],
44
+ body: sealed.body,
45
+ timeoutMs,
46
+ }, { agent: auth.agent });
47
+ try {
48
+ const text = await sealed.openResponse(response.status, response.headers, response.body);
49
+ const headers = {};
50
+ for (const [name, value] of response.headers) {
51
+ headers[name.toLowerCase()] = value;
52
+ }
53
+ return { status: response.status, text, headers };
54
+ }
55
+ catch (err) {
56
+ if (isWasmFailure(err) && err.kind === "seal") {
57
+ // The module could not read the answer at all (an unreadable header, a
58
+ // payload type vpay did not advertise): the response, not the request.
59
+ throw new VpayUnexpectedResponseError(response.status, err.message);
60
+ }
61
+ if (err instanceof VpayTransportError)
62
+ throw err;
63
+ throw mapFailure(err);
64
+ }
65
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The merchant's signing identity and the keys it trusts, resolved once.
3
+ *
4
+ * vpay does not issue tokens. Every `/v1` call is a COSE_Sign1 message signed
5
+ * with an **Ed25519** key the operator registered for this merchant
6
+ * (`merchant_clients[].cose_keys`), and every answer is one signed by vpay's
7
+ * response key, which this client pins (`serverKeys`). There is no
8
+ * `client_credentials` grant, no assertion, no access-token cache and no
9
+ * re-authentication retry: `docs/signed-transport.md`, and
10
+ * `docs/flows/merchant-auth.md` for the flow.
11
+ */
12
+ import { type KeyObject } from "node:crypto";
13
+ import type { Agent as HttpAgent } from "node:http";
14
+ import type { Agent as HttpsAgent } from "node:https";
15
+ import { type WasmSealer } from "./wasm.js";
16
+ /** Default timeout for every resource call, in milliseconds. */
17
+ export declare const DEFAULT_TIMEOUT_MS = 30000;
18
+ /** A key given as bytes or as the unpadded base64url text a key file holds. */
19
+ export type KeyBytes = string | Uint8Array;
20
+ /**
21
+ * A signer whose key this process cannot read: a KMS, an HSM, a Node
22
+ * `KeyObject` held elsewhere. `sign` receives the exact bytes to sign and must
23
+ * return the 64-byte pure Ed25519 signature over them — `crypto.sign(null, tbs,
24
+ * key)`, never a pre-hash. A signature that does not verify under `publicKey`
25
+ * is refused before it is sent, rather than failing at vpay as the coarse 401.
26
+ */
27
+ export interface ExternalSigner {
28
+ /** The registered public key: 32 bytes, or unpadded base64url. */
29
+ publicKey: KeyBytes;
30
+ sign(tbs: Uint8Array): Uint8Array | Promise<Uint8Array>;
31
+ }
32
+ /** The response keys this client trusts. */
33
+ export interface ServerKeysOption {
34
+ /** The key vpay seals answers with now: 32 bytes, or unpadded base64url. */
35
+ current: KeyBytes;
36
+ /**
37
+ * The key it will use after the next rotation, so a rotation is not a flag
38
+ * day. Omit it for a first deployment that has not prepared one.
39
+ */
40
+ next?: KeyBytes | undefined;
41
+ }
42
+ /**
43
+ * The options that decide how this package signs: everything the sealer needs,
44
+ * plus the `baseUrl` the defaults are derived from.
45
+ *
46
+ * Shared by {@link VpayClient} and `createStripeHttpClient` on purpose. The two
47
+ * entry points seal the same calls under the same keys with the same defaults;
48
+ * resolving them in one place is what stops them drifting.
49
+ *
50
+ * Every optional property is `?: T | undefined` for the
51
+ * `exactOptionalPropertyTypes` reason spelled out on `VpayClientOptions`.
52
+ */
53
+ export interface MerchantAuthOptions {
54
+ /** vpay's base URL, e.g. `https://api.vpay.example`. */
55
+ baseUrl: string;
56
+ /** This merchant's registered `client_id`. Kept for logs; it is not sent. */
57
+ clientId: string;
58
+ /**
59
+ * The merchant's Ed25519 private key, in any of the forms an operator has
60
+ * it in: a PKCS#8 PEM text or a `crypto.KeyObject` (the key then stays in
61
+ * Node and signs through `crypto.sign`), or the 32-byte RFC 8032 seed as
62
+ * bytes or unpadded base64url (the format `cargo xtask gen-envelope-key`
63
+ * writes). Exactly one of this and {@link signer}.
64
+ */
65
+ privateKey?: string | KeyObject | Uint8Array | undefined;
66
+ /** A signer for a key this process cannot read. Exactly one of this and {@link privateKey}. */
67
+ signer?: ExternalSigner | undefined;
68
+ /** The response keys to trust (`vpay-server` logs them at boot). */
69
+ serverKeys: ServerKeysOption;
70
+ /**
71
+ * What the signature is addressed to: vpay's configured audience, which is
72
+ * its `deployment.public_base_url`. Default {@link baseUrl}. **Set it when
73
+ * your server reaches vpay by a different URL than payers do** (a compose
74
+ * service name, a private DNS name): the signature binds this value, and a
75
+ * mismatch is the coarse 401 with nothing in it to say why.
76
+ */
77
+ audience?: string | undefined;
78
+ /** Default {@link DEFAULT_TIMEOUT_MS}. */
79
+ timeoutMs?: number | undefined;
80
+ /** An `http.Agent`/`https.Agent` for a proxy or a pool. Defaults to the global agent. */
81
+ agent?: HttpAgent | HttpsAgent | undefined;
82
+ }
83
+ /** What {@link resolveMerchantAuth} hands back. */
84
+ export interface ResolvedMerchantAuth {
85
+ /** `baseUrl` with any trailing slash removed. */
86
+ baseUrl: string;
87
+ clientId: string;
88
+ timeoutMs: number;
89
+ userAgent: string;
90
+ agent: HttpAgent | HttpsAgent | undefined;
91
+ sealer: WasmSealer;
92
+ }
93
+ /**
94
+ * 32 bytes as unpadded base64url. Anything else is a {@link VpayConfigError}
95
+ * naming the field and never quoting the value — it may be a private seed.
96
+ */
97
+ export declare function toKeyBase64url(value: KeyBytes | undefined, field: string): string;
98
+ /**
99
+ * Validates {@link MerchantAuthOptions}, applies this package's defaults, and
100
+ * builds the sealer both entry points share.
101
+ *
102
+ * Every failure it can detect is detected here — at construction — rather than
103
+ * on the first request.
104
+ */
105
+ export declare function resolveMerchantAuth(options: MerchantAuthOptions): ResolvedMerchantAuth;
package/dist/sealer.js ADDED
@@ -0,0 +1,154 @@
1
+ /**
2
+ * The merchant's signing identity and the keys it trusts, resolved once.
3
+ *
4
+ * vpay does not issue tokens. Every `/v1` call is a COSE_Sign1 message signed
5
+ * with an **Ed25519** key the operator registered for this merchant
6
+ * (`merchant_clients[].cose_keys`), and every answer is one signed by vpay's
7
+ * response key, which this client pins (`serverKeys`). There is no
8
+ * `client_credentials` grant, no assertion, no access-token cache and no
9
+ * re-authentication retry: `docs/signed-transport.md`, and
10
+ * `docs/flows/merchant-auth.md` for the flow.
11
+ */
12
+ import { createPrivateKey, createPublicKey, sign, } from "node:crypto";
13
+ import { VpayConfigError } from "./errors.js";
14
+ import { SDK_VERSION } from "./version.js";
15
+ import { isWasmFailure, loadWasm } from "./wasm.js";
16
+ /** Default timeout for every resource call, in milliseconds. */
17
+ export const DEFAULT_TIMEOUT_MS = 30_000;
18
+ function requireNonEmptyString(value, field) {
19
+ if (typeof value !== "string" || value.length === 0) {
20
+ throw new VpayConfigError(`${field} is required`);
21
+ }
22
+ return value;
23
+ }
24
+ function stripTrailingSlash(url) {
25
+ return url.endsWith("/") ? url.slice(0, -1) : url;
26
+ }
27
+ /**
28
+ * 32 bytes as unpadded base64url. Anything else is a {@link VpayConfigError}
29
+ * naming the field and never quoting the value — it may be a private seed.
30
+ */
31
+ export function toKeyBase64url(value, field) {
32
+ if (value === undefined) {
33
+ throw new VpayConfigError(`${field} is required`);
34
+ }
35
+ if (typeof value === "string") {
36
+ const text = value.trim();
37
+ const bytes = Buffer.from(text, "base64url");
38
+ if (bytes.length !== 32 ||
39
+ bytes.toString("base64url") !== text // rejects padding and other alphabets
40
+ ) {
41
+ throw new VpayConfigError(`${field} must be 32 bytes, as unpadded base64url text`);
42
+ }
43
+ return text;
44
+ }
45
+ if (value.length !== 32) {
46
+ throw new VpayConfigError(`${field} must be exactly 32 bytes`);
47
+ }
48
+ return Buffer.from(value).toString("base64url");
49
+ }
50
+ function ed25519PublicBase64url(key) {
51
+ const jwk = createPublicKey(key).export({ format: "jwk" });
52
+ if (typeof jwk.x !== "string") {
53
+ throw new VpayConfigError("privateKey has no Ed25519 public half");
54
+ }
55
+ return jwk.x;
56
+ }
57
+ /**
58
+ * Turns a configured PEM or `KeyObject` into a signer, once. A bad key is a
59
+ * startup failure (a {@link VpayConfigError} from the constructor the merchant
60
+ * wrote), not an exception out of the first request; the message never quotes
61
+ * the key, and `cause` carries OpenSSL's own reason.
62
+ */
63
+ function signerFromKeyObject(privateKey) {
64
+ let key;
65
+ if (typeof privateKey === "string") {
66
+ try {
67
+ key = createPrivateKey(privateKey);
68
+ }
69
+ catch (err) {
70
+ throw new VpayConfigError("privateKey could not be read as a private key: expected PKCS#8 PEM text, a crypto.KeyObject, or a 32-byte Ed25519 seed", { cause: err });
71
+ }
72
+ }
73
+ else {
74
+ key = privateKey;
75
+ }
76
+ if (key.type !== "private" || key.asymmetricKeyType !== "ed25519") {
77
+ throw new VpayConfigError(`privateKey must be an Ed25519 private key (got ${key.asymmetricKeyType ?? key.type}); ` +
78
+ "vpay's signed transport has no RSA or P-256 path for merchants");
79
+ }
80
+ return {
81
+ publicKey: ed25519PublicBase64url(key),
82
+ sign: (tbs) => sign(null, tbs, key),
83
+ };
84
+ }
85
+ function looksLikePem(text) {
86
+ return text.includes("-----BEGIN");
87
+ }
88
+ /**
89
+ * Validates {@link MerchantAuthOptions}, applies this package's defaults, and
90
+ * builds the sealer both entry points share.
91
+ *
92
+ * Every failure it can detect is detected here — at construction — rather than
93
+ * on the first request.
94
+ */
95
+ export function resolveMerchantAuth(options) {
96
+ const baseUrl = stripTrailingSlash(requireNonEmptyString(options.baseUrl, "baseUrl"));
97
+ const clientId = requireNonEmptyString(options.clientId, "clientId");
98
+ const hasKey = options.privateKey !== undefined && options.privateKey !== null;
99
+ const hasSigner = options.signer !== undefined && options.signer !== null;
100
+ if (hasKey === hasSigner) {
101
+ throw new VpayConfigError(hasKey
102
+ ? "give privateKey or signer, not both"
103
+ : "privateKey (or signer) is required");
104
+ }
105
+ if (options.serverKeys === undefined || options.serverKeys === null) {
106
+ throw new VpayConfigError("serverKeys is required: the client refuses to trust an answer it has no key for");
107
+ }
108
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
109
+ if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) {
110
+ throw new VpayConfigError(`timeoutMs must be a positive integer, got ${timeoutMs}`);
111
+ }
112
+ const audience = stripTrailingSlash(options.audience ?? baseUrl);
113
+ const current = toKeyBase64url(options.serverKeys.current, "serverKeys.current");
114
+ const next = options.serverKeys.next === undefined
115
+ ? undefined
116
+ : toKeyBase64url(options.serverKeys.next, "serverKeys.next");
117
+ const wasm = loadWasm();
118
+ let sealer;
119
+ try {
120
+ const external = options.signer;
121
+ const privateKey = options.privateKey;
122
+ if (external !== undefined && external !== null) {
123
+ sealer = wasm.Sealer.fromCallback(toKeyBase64url(external.publicKey, "signer.publicKey"), (tbs) => external.sign(tbs), current, next, audience);
124
+ }
125
+ else if (privateKey instanceof Uint8Array ||
126
+ (typeof privateKey === "string" && !looksLikePem(privateKey))) {
127
+ sealer = wasm.Sealer.fromSeed(toKeyBase64url(privateKey, "privateKey"), current, next, audience);
128
+ }
129
+ else if (privateKey !== undefined && privateKey !== null) {
130
+ const signer = signerFromKeyObject(privateKey);
131
+ sealer = wasm.Sealer.fromCallback(signer.publicKey, (tbs) => signer.sign(tbs), current, next, audience);
132
+ }
133
+ else {
134
+ throw new VpayConfigError("privateKey (or signer) is required");
135
+ }
136
+ }
137
+ catch (err) {
138
+ if (err instanceof VpayConfigError)
139
+ throw err;
140
+ // The wasm module rejects with a plain `{ kind, message }`; its messages
141
+ // describe the key's shape, never its bytes.
142
+ throw new VpayConfigError(isWasmFailure(err)
143
+ ? err.message
144
+ : "the signing identity could not be built", { cause: err });
145
+ }
146
+ return {
147
+ baseUrl,
148
+ clientId,
149
+ timeoutMs,
150
+ userAgent: `vpay-sdk-node/${SDK_VERSION}`,
151
+ agent: options.agent,
152
+ sealer,
153
+ };
154
+ }
@@ -0,0 +1,100 @@
1
+ import { type MerchantAuthOptions } from "./sealer.js";
2
+ /**
3
+ * Configuration for {@link createStripeHttpClient}.
4
+ *
5
+ * **The same options `VpayClient` takes** ({@link MerchantAuthOptions}): both
6
+ * entry points seal through the same {@link resolveMerchantAuth}, so a knob one
7
+ * of them offers and the other does not would be a bug rather than a feature.
8
+ * `timeoutMs` is the one that narrows: stripe-node passes its own `timeout` to
9
+ * every request, and that is what governs the call; `timeoutMs` here is the
10
+ * fallback for a request that arrives without one.
11
+ */
12
+ export interface StripeHttpClientOptions extends MerchantAuthOptions {
13
+ /** Default 30000. Used only when stripe-node passes no `timeout` of its own. */
14
+ timeoutMs?: number | undefined;
15
+ }
16
+ /** The request headers stripe-node passes (`RequestHeaders`). */
17
+ export type StripeRequestHeaders = Record<string, string | number | string[] | undefined>;
18
+ /**
19
+ * What stripe-node reads off the object `makeRequest` resolves with
20
+ * (`HttpClientResponseInterface`).
21
+ */
22
+ export interface VpayStripeHttpResponse {
23
+ getStatusCode(): number;
24
+ getHeaders(): Record<string, string | string[]>;
25
+ getRawResponse(): unknown;
26
+ toStream(streamCompleteCallback: () => void): never;
27
+ toJSON(): Promise<unknown>;
28
+ }
29
+ /**
30
+ * What {@link createStripeHttpClient} returns: assignable to
31
+ * `Stripe.StripeConfig["httpClient"]` (`HttpClientInterface`).
32
+ */
33
+ export interface VpayStripeHttpClient {
34
+ getClientName(): string;
35
+ makeRequest(host: string, port: string, path: string, method: string, headers: StripeRequestHeaders, requestData: string, protocol: string, timeout: number): Promise<VpayStripeHttpResponse>;
36
+ }
37
+ /**
38
+ * Builds a stripe-node `httpClient` that seals each request under the
39
+ * merchant's Ed25519 key, sends it, and opens vpay's sealed answer.
40
+ *
41
+ * The signing, the operation table and the verification are the *same* code
42
+ * `VpayClient` and the Rust SDK run (`sdks/rust/wasm`), not a second
43
+ * implementation.
44
+ *
45
+ * # Where a request may be sent
46
+ *
47
+ * **The client is bound to `baseUrl`'s origin and refuses every other one.**
48
+ * stripe-node calls `makeRequest` for *any* request the instance makes;
49
+ * `host`/`port`/`protocol` are configured on the `Stripe` instance, separately
50
+ * from this module, and when they are omitted stripe-node addresses
51
+ * `api.stripe.com:443`. A request signed for vpay and sent to Stripe is not
52
+ * dangerous (the signature binds the audience, and Stripe holds no key that
53
+ * could replay it at vpay), but it is certainly a mistake, and a refusal that
54
+ * names both origins is a better way to learn it than a `401` from a server
55
+ * that was never vpay.
56
+ *
57
+ * So a request whose host, effective port or protocol is not `baseUrl`'s is a
58
+ * {@link VpayConfigError} naming both origins, thrown **before** anything is
59
+ * signed.
60
+ *
61
+ * # What is dropped
62
+ *
63
+ * Everything stripe-node set except the `Idempotency-Key`: `Authorization`
64
+ * (the placeholder API key), `Stripe-Version`, `X-Stripe-Client-User-Agent`,
65
+ * `Content-Type`. The signature binds the payload type itself, and the
66
+ * `Idempotency-Key` as sent.
67
+ *
68
+ * # Failures
69
+ *
70
+ * stripe-node retries any *rejection* from an `httpClient` as a connection
71
+ * error (`maxNetworkRetries` defaults to **2** on Node, not 0), and cannot be
72
+ * told not to, so a refusal is not a rejection. A refused call (the coarse
73
+ * unsigned `401`), an answer that does not verify, or a body over the bound
74
+ * resolves as a Stripe-shaped error response with `stripe-should-retry:
75
+ * false`, and surfaces once: `StripeAuthenticationError` (`code:
76
+ * "unsigned_response"`) for a `401`, `StripeAPIError` (`unverified_response`,
77
+ * `response_too_large`) otherwise, with the cause in `message`. A gateway's
78
+ * unsigned `5xx` stays retryable.
79
+ *
80
+ * A request this client cannot seal, because the contract has no such
81
+ * operation (a `GET` on a `POST`-only path, a path outside `/v1`, a verb `/v1`
82
+ * does not use), is refused the same way, before anything is sent:
83
+ * `StripeInvalidRequestError` with `statusCode: 404` and `code:
84
+ * "unknown_operation"`, once.
85
+ *
86
+ * What does reject is a real transport failure (DNS, TLS, a reset, a timeout)
87
+ * and a {@link VpayConfigError} (a request addressed to another origin, a
88
+ * misconfigured key), reported as `StripeConnectionError` with the
89
+ * original at `err.detail` / `err.raw.exception`, and retried up to
90
+ * `maxNetworkRetries` times. Each retry re-seals the call (a new message). A
91
+ * `POST` keeps the `Idempotency-Key` stripe-node chose, so the retry is the
92
+ * same operation; a `DELETE` has none from stripe-node and gets a new one per
93
+ * attempt (see the comment at the call), so set `maxNetworkRetries: 0` if a
94
+ * repeated `DELETE` answering `404` is not acceptable to you.
95
+ *
96
+ * @throws `VpayConfigError` at construction if `baseUrl` or `clientId` is
97
+ * missing, if `baseUrl` is not an absolute URL, if the key is not an Ed25519
98
+ * key, or if `serverKeys` is missing or malformed.
99
+ */
100
+ export declare function createStripeHttpClient(options: StripeHttpClientOptions): VpayStripeHttpClient;