@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 +241 -242
- package/dist/client.d.ts +20 -24
- package/dist/client.js +14 -21
- package/dist/errors.d.ts +54 -18
- package/dist/errors.js +62 -21
- package/dist/http.d.ts +10 -20
- package/dist/http.js +28 -66
- package/dist/index.d.ts +6 -5
- package/dist/index.js +6 -5
- package/dist/sealed-call.d.ts +32 -0
- package/dist/sealed-call.js +65 -0
- package/dist/sealer.d.ts +105 -0
- package/dist/sealer.js +154 -0
- package/dist/stripe-http-client.d.ts +100 -0
- package/dist/stripe-http-client.js +381 -0
- package/dist/transport.d.ts +31 -0
- package/dist/transport.js +109 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/wasm.d.ts +29 -0
- package/dist/wasm.js +41 -0
- package/package.json +10 -5
- package/scripts/build-wasm.sh +79 -0
- package/scripts/vpay-call.mjs +113 -0
- package/wasm/package.json +1 -0
- package/wasm/vpay_sdk_wasm.d.ts +94 -0
- package/wasm/vpay_sdk_wasm.js +718 -0
- package/wasm/vpay_sdk_wasm_bg.wasm +0 -0
- package/wasm/vpay_sdk_wasm_bg.wasm.d.ts +33 -0
- package/dist/auth.d.ts +0 -180
- package/dist/auth.js +0 -297
- package/dist/stripe-auth.d.ts +0 -177
- package/dist/stripe-auth.js +0 -192
- package/scripts/mint-assertion.mjs +0 -73
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@vaam-apps/vpay-sdk/stripe` — an `httpClient` for the **official Stripe
|
|
3
|
+
* Node SDK**, so `stripe-node` can talk to vpay's `/v1` API.
|
|
4
|
+
*
|
|
5
|
+
* vpay never accepts an API key or a token ([ADR-0010](../../../docs/adr/0010-merchant-auth-private-key-jwt.md),
|
|
6
|
+
* superseded by the signed transport): every `/v1` call is a COSE_Sign1 message
|
|
7
|
+
* signed with the merchant's Ed25519 key, and every answer is one signed by
|
|
8
|
+
* vpay (`docs/signed-transport.md`). The request is not a header on an
|
|
9
|
+
* otherwise ordinary call — the **body is the message** — so stripe-node's
|
|
10
|
+
* `authenticator` seam, which can only add headers, cannot carry it. The seam
|
|
11
|
+
* that can is `httpClient`: stripe-node hands it the finished request
|
|
12
|
+
* (`host`, `port`, `path`, `method`, `headers`, `requestData`, `protocol`,
|
|
13
|
+
* `timeout`) and takes back something that looks like a response. This module
|
|
14
|
+
* is that client. It seals the request, sends it, opens the answer, and returns
|
|
15
|
+
* the verified JSON as the response body, so everything above it — resource
|
|
16
|
+
* methods, typed results, `Stripe.errors.*` — behaves as it does against Stripe:
|
|
17
|
+
*
|
|
18
|
+
* ```js
|
|
19
|
+
* import Stripe from "stripe";
|
|
20
|
+
* import { createStripeHttpClient } from "@vaam-apps/vpay-sdk/stripe";
|
|
21
|
+
*
|
|
22
|
+
* const stripe = new Stripe("unused", { // a non-empty string; never sent
|
|
23
|
+
* httpClient: createStripeHttpClient({
|
|
24
|
+
* baseUrl: "http://localhost:8080",
|
|
25
|
+
* clientId: "acme-cameroon",
|
|
26
|
+
* privateKey: readFileSync("./merchant.seed", "utf8"),
|
|
27
|
+
* serverKeys: { current: process.env.VPAY_SERVER_KEY_CURRENT },
|
|
28
|
+
* }),
|
|
29
|
+
* host: "localhost", port: "8080", protocol: "http",
|
|
30
|
+
* });
|
|
31
|
+
* ```
|
|
32
|
+
*
|
|
33
|
+
* The `host`/`port`/`protocol` in that snippet are **not optional garnish** —
|
|
34
|
+
* see {@link createStripeHttpClient}'s "Where a request may be sent".
|
|
35
|
+
*
|
|
36
|
+
* This module deliberately imports **nothing** from `stripe`. `stripe` is an
|
|
37
|
+
* optional peer dependency, and the client is typed structurally, so
|
|
38
|
+
* `@vaam-apps/vpay-sdk` type-checks and builds with `stripe` absent.
|
|
39
|
+
* `src/stripe-http-client.test.ts` pins the structure against the real
|
|
40
|
+
* `Stripe.HttpClientInterface`, so a divergence in a future `stripe` release
|
|
41
|
+
* fails the build rather than the merchant's deployment.
|
|
42
|
+
*
|
|
43
|
+
* See the README's "Using the official Stripe SDK" section for what does and
|
|
44
|
+
* does not carry over from real Stripe.
|
|
45
|
+
*/
|
|
46
|
+
import { randomUUID } from "node:crypto";
|
|
47
|
+
import { VpayConfigError, VpayInvalidParamsError, VpayResponseTooLargeError, VpayUnsignedResponseError, VpayUnverifiedResponseError, } from "./errors.js";
|
|
48
|
+
import { performSealedCall } from "./sealed-call.js";
|
|
49
|
+
import { resolveMerchantAuth, } from "./sealer.js";
|
|
50
|
+
function defaultPortFor(protocol) {
|
|
51
|
+
return protocol === "http" ? "80" : "443";
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* `api.vpay.example`, `API.Vpay.Example.` and `[::1]` all have to compare
|
|
55
|
+
* equal to the same configured host, because a merchant writes `baseUrl` and
|
|
56
|
+
* stripe-node's `host` by hand and nothing makes them agree on case or on
|
|
57
|
+
* bracket notation. Everything else about the value is left alone: this is a
|
|
58
|
+
* comparison, not a validator.
|
|
59
|
+
*/
|
|
60
|
+
function normaliseHost(host) {
|
|
61
|
+
const lowered = host.trim().toLowerCase();
|
|
62
|
+
const unbracketed = lowered.startsWith("[") && lowered.endsWith("]")
|
|
63
|
+
? lowered.slice(1, -1)
|
|
64
|
+
: lowered;
|
|
65
|
+
return unbracketed.endsWith(".") ? unbracketed.slice(0, -1) : unbracketed;
|
|
66
|
+
}
|
|
67
|
+
function normaliseProtocol(protocol) {
|
|
68
|
+
const lowered = protocol.trim().toLowerCase();
|
|
69
|
+
return lowered.endsWith(":") ? lowered.slice(0, -1) : lowered;
|
|
70
|
+
}
|
|
71
|
+
function parseBoundOrigin(baseUrl) {
|
|
72
|
+
let url;
|
|
73
|
+
try {
|
|
74
|
+
url = new URL(baseUrl);
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
throw new VpayConfigError(`baseUrl is not an absolute URL: ${baseUrl}`, {
|
|
78
|
+
cause: err,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
const protocol = normaliseProtocol(url.protocol);
|
|
82
|
+
return {
|
|
83
|
+
host: normaliseHost(url.hostname),
|
|
84
|
+
port: url.port === "" ? defaultPortFor(protocol) : url.port,
|
|
85
|
+
protocol,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function describeOrigin(origin) {
|
|
89
|
+
return `${origin.protocol}://${origin.host}:${origin.port}`;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Refuses to seal a request addressed somewhere other than {@link BoundOrigin}.
|
|
93
|
+
*
|
|
94
|
+
* See {@link createStripeHttpClient}'s "Where a request may be sent" for why
|
|
95
|
+
* this is a refusal and not a warning.
|
|
96
|
+
*/
|
|
97
|
+
function assertRequestIsBound(host, port, protocol, bound) {
|
|
98
|
+
const effectiveProtocol = normaliseProtocol(protocol);
|
|
99
|
+
const effectiveHost = normaliseHost(host);
|
|
100
|
+
const effectivePort = port === undefined || port === ""
|
|
101
|
+
? defaultPortFor(effectiveProtocol)
|
|
102
|
+
: String(port);
|
|
103
|
+
if (effectiveHost === bound.host &&
|
|
104
|
+
effectivePort === bound.port &&
|
|
105
|
+
effectiveProtocol === bound.protocol) {
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
throw new VpayConfigError(`refusing to seal a request to ${describeOrigin({ host: effectiveHost, port: effectivePort, protocol: effectiveProtocol })}: ` +
|
|
109
|
+
`this client signs for ${describeOrigin(bound)} (its baseUrl) and will not send a ` +
|
|
110
|
+
`signed request anywhere else. Set stripe-node's host, port and protocol to match baseUrl — ` +
|
|
111
|
+
`with them omitted stripe-node addresses api.stripe.com:443.`);
|
|
112
|
+
}
|
|
113
|
+
/** The `Idempotency-Key` stripe-node set, if it set one (header names are case-insensitive). */
|
|
114
|
+
function idempotencyKeyOf(headers) {
|
|
115
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
116
|
+
if (name.toLowerCase() === "idempotency-key" && value !== undefined) {
|
|
117
|
+
return Array.isArray(value) ? value[0] : String(value);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return undefined;
|
|
121
|
+
}
|
|
122
|
+
class SealedResponse {
|
|
123
|
+
#status;
|
|
124
|
+
#text;
|
|
125
|
+
#headers;
|
|
126
|
+
/** What stripe-node annotates and exposes as `lastResponse`. */
|
|
127
|
+
#raw;
|
|
128
|
+
constructor(status, text, headers) {
|
|
129
|
+
this.#status = status;
|
|
130
|
+
this.#text = text;
|
|
131
|
+
this.#headers = headers;
|
|
132
|
+
this.#raw = { statusCode: status, headers };
|
|
133
|
+
}
|
|
134
|
+
getStatusCode() {
|
|
135
|
+
return this.#status;
|
|
136
|
+
}
|
|
137
|
+
getHeaders() {
|
|
138
|
+
// The body is the verified JSON payload. The headers are the response's
|
|
139
|
+
// own and **not authenticated**; stripe-node reads `request-id` from them
|
|
140
|
+
// for its error messages and nothing else.
|
|
141
|
+
return { ...this.#headers, "content-type": "application/json" };
|
|
142
|
+
}
|
|
143
|
+
getRawResponse() {
|
|
144
|
+
return this.#raw;
|
|
145
|
+
}
|
|
146
|
+
toStream() {
|
|
147
|
+
throw new VpayConfigError("vpay answers are sealed and read whole; streaming responses are not supported");
|
|
148
|
+
}
|
|
149
|
+
toJSON() {
|
|
150
|
+
return Promise.resolve().then(() => JSON.parse(this.#text));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* A refusal, presented to stripe-node as the response it is.
|
|
155
|
+
*
|
|
156
|
+
* stripe-node retries **every** rejection from an `httpClient` as a connection
|
|
157
|
+
* error: `maxNetworkRetries` defaults to 2 on Node, so a refused call would go
|
|
158
|
+
* out three times, each a fresh signed message, and the public hook that would
|
|
159
|
+
* exempt a rejection (`HttpClientRuntimeError`) is not exported. A response is
|
|
160
|
+
* different: stripe-node honours `stripe-should-retry: false` before it looks
|
|
161
|
+
* at the status. So a refusal that retrying cannot fix (a `4xx` unsigned
|
|
162
|
+
* answer, an answer that does not verify, a body over the bound) is returned
|
|
163
|
+
* as a Stripe-shaped error response carrying that header, and surfaces as the
|
|
164
|
+
* ordinary `StripeAuthenticationError` / `StripeAPIError` with the cause in
|
|
165
|
+
* `message`, once. A gateway's own `5xx` is left retryable: that is what
|
|
166
|
+
* `maxNetworkRetries` is for, and a keyed write is safe to repeat.
|
|
167
|
+
*
|
|
168
|
+
* A request this client cannot seal at all (no such operation) is the same
|
|
169
|
+
* shape: it was never sent, retrying it cannot change that, and it is the
|
|
170
|
+
* caller's request that is wrong, so it is an `invalid_request_error`
|
|
171
|
+
* (`StripeInvalidRequestError`), as Stripe answers an unrecognised URL.
|
|
172
|
+
*/
|
|
173
|
+
function refusal(status, code, message, retryable, type = status ===
|
|
174
|
+
401
|
|
175
|
+
? "authentication_error"
|
|
176
|
+
: "api_error", requestId) {
|
|
177
|
+
const body = JSON.stringify({ error: { type, code, message } });
|
|
178
|
+
return new SealedResponse(status, body, {
|
|
179
|
+
...(retryable ? {} : { "stripe-should-retry": "false" }),
|
|
180
|
+
// The server's own id for the exchange, so the merchant has something to
|
|
181
|
+
// quote to support. Not authenticated, and used for nothing else.
|
|
182
|
+
...(requestId === undefined ? {} : { "request-id": requestId }),
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
/** Whether a verified payload is already a Stripe error envelope (`{ error: { … } }`). */
|
|
186
|
+
function isStripeErrorEnvelope(text) {
|
|
187
|
+
try {
|
|
188
|
+
const parsed = JSON.parse(text);
|
|
189
|
+
return (typeof parsed === "object" &&
|
|
190
|
+
parsed !== null &&
|
|
191
|
+
typeof parsed["error"] === "object" &&
|
|
192
|
+
parsed["error"] !== null);
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
return false;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* A verified `4xx`/`5xx` whose payload is not a Stripe error envelope, put in
|
|
200
|
+
* one.
|
|
201
|
+
*
|
|
202
|
+
* Not every refusal vpay seals comes from its own error renderer: the body
|
|
203
|
+
* bound (`413`) is answered by a layer in front of it, and the signed
|
|
204
|
+
* transport seals that answer as it finds it, in cratestack's own
|
|
205
|
+
* `{ code, message, details }` shape. stripe-node reads an error only from an
|
|
206
|
+
* `error` key, so without this a `413` **resolved**: the merchant's `await
|
|
207
|
+
* paymentIntents.create(…)` returned `{ code: "INTERNAL_ERROR", … }` as though
|
|
208
|
+
* it were a PaymentIntent, and nothing threw. It is now an error that says what
|
|
209
|
+
* happened, never retried when it is a `4xx` (the caller's request) and left
|
|
210
|
+
* retryable when it is a `5xx` (vpay's). stripe-node picks the class from the
|
|
211
|
+
* status alone: `StripeAPIError` for a `413` and a `5xx`, which have no class
|
|
212
|
+
* of their own. The status is the signed
|
|
213
|
+
* one; the sealed body's wording is not repeated (it is `internal error` for a
|
|
214
|
+
* `413`), only its `code`, bounded, when it is a short string.
|
|
215
|
+
*/
|
|
216
|
+
function unenveloped(status, text, headers) {
|
|
217
|
+
const requestId = headers["request-id"] ?? headers["x-request-id"];
|
|
218
|
+
if (status === 413) {
|
|
219
|
+
return refusal(413, "request_too_large", "vpay refused the request: its body is over the limit vpay accepts on /v1 (413)", false, "invalid_request_error", requestId);
|
|
220
|
+
}
|
|
221
|
+
let sealedCode = "";
|
|
222
|
+
try {
|
|
223
|
+
const parsed = JSON.parse(text);
|
|
224
|
+
if (typeof parsed.code === "string" && parsed.code.length <= 64) {
|
|
225
|
+
sealedCode = ` (${parsed.code})`;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
// Not JSON: the status alone is reported.
|
|
230
|
+
}
|
|
231
|
+
return refusal(status, "unexpected_error_response", `vpay answered ${status}${sealedCode} with an error that is not in the Stripe error envelope`, status >= 500, status >= 500
|
|
232
|
+
? "api_error"
|
|
233
|
+
: status === 401
|
|
234
|
+
? "authentication_error"
|
|
235
|
+
: "invalid_request_error", requestId);
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* What a request this client cannot seal is answered with: a resolved,
|
|
239
|
+
* non-retryable `404` `invalid_request_error` / `unknown_operation`. It is
|
|
240
|
+
* never sent, signed or not, so no message leaves the process.
|
|
241
|
+
*/
|
|
242
|
+
function unknownOperation(message) {
|
|
243
|
+
return refusal(404, "unknown_operation", message, false, "invalid_request_error");
|
|
244
|
+
}
|
|
245
|
+
class SealingStripeHttpClient {
|
|
246
|
+
#auth;
|
|
247
|
+
#bound;
|
|
248
|
+
constructor(auth, bound) {
|
|
249
|
+
this.#auth = auth;
|
|
250
|
+
this.#bound = bound;
|
|
251
|
+
}
|
|
252
|
+
getClientName() {
|
|
253
|
+
return "vpay-sealed";
|
|
254
|
+
}
|
|
255
|
+
async makeRequest(host, port, path, method, headers, requestData, protocol, timeout) {
|
|
256
|
+
assertRequestIsBound(host, port, protocol, this.#bound);
|
|
257
|
+
const verb = method.toUpperCase();
|
|
258
|
+
if (verb !== "GET" && verb !== "POST" && verb !== "DELETE") {
|
|
259
|
+
return unknownOperation(`vpay's /v1 has no ${verb} operation`);
|
|
260
|
+
}
|
|
261
|
+
const [pathname = "", query] = path.split("?", 2);
|
|
262
|
+
if (!pathname.startsWith("/v1/")) {
|
|
263
|
+
return unknownOperation(`refusing to seal ${pathname}: vpay serves /v1/… only`);
|
|
264
|
+
}
|
|
265
|
+
const underV1 = pathname.slice("/v1".length);
|
|
266
|
+
try {
|
|
267
|
+
const { status, text, headers: responseHeaders, } = await performSealedCall(this.#auth, {
|
|
268
|
+
method: verb,
|
|
269
|
+
path: underV1,
|
|
270
|
+
body: verb === "POST" ? requestData : undefined,
|
|
271
|
+
query: verb === "GET" ? query : undefined,
|
|
272
|
+
// stripe-node keys POSTs and nothing else; vpay requires a key on
|
|
273
|
+
// every write, `DELETE` included, so a `DELETE` is given one here.
|
|
274
|
+
// **A retry of a `POST` re-seals with the key stripe-node chose,
|
|
275
|
+
// which is what makes it safe. A retry of a `DELETE` does not:**
|
|
276
|
+
// stripe-node sets no key for it, `makeRequest` runs again with no
|
|
277
|
+
// memory of the first attempt, and this draws a new one. That is
|
|
278
|
+
// acceptable because a `DELETE` is naturally idempotent (the
|
|
279
|
+
// repeat of one that landed is a `404`), and it is why the
|
|
280
|
+
// README tells a caller who cannot tolerate that to set
|
|
281
|
+
// `maxNetworkRetries: 0`.
|
|
282
|
+
idempotencyKey: verb === "GET"
|
|
283
|
+
? undefined
|
|
284
|
+
: (idempotencyKeyOf(headers) ?? randomUUID()),
|
|
285
|
+
}, Number.isFinite(timeout) && timeout > 0
|
|
286
|
+
? timeout
|
|
287
|
+
: this.#auth.timeoutMs);
|
|
288
|
+
if (status >= 400 && !isStripeErrorEnvelope(text)) {
|
|
289
|
+
return unenveloped(status, text, responseHeaders);
|
|
290
|
+
}
|
|
291
|
+
return new SealedResponse(status, text, responseHeaders);
|
|
292
|
+
}
|
|
293
|
+
catch (err) {
|
|
294
|
+
// The sealing module found no such operation in the contract table (a
|
|
295
|
+
// GET on a POST-only path, a path with no route): nothing was sent.
|
|
296
|
+
if (err instanceof VpayInvalidParamsError) {
|
|
297
|
+
return unknownOperation(`vpay's /v1 has no ${verb} ${pathname} operation`);
|
|
298
|
+
}
|
|
299
|
+
if (err instanceof VpayUnsignedResponseError) {
|
|
300
|
+
return refusal(err.status, "unsigned_response", err.message, err.status >= 500);
|
|
301
|
+
}
|
|
302
|
+
if (err instanceof VpayUnverifiedResponseError) {
|
|
303
|
+
return refusal(502, "unverified_response", err.message, false);
|
|
304
|
+
}
|
|
305
|
+
if (err instanceof VpayResponseTooLargeError) {
|
|
306
|
+
return refusal(502, "response_too_large", err.message, false);
|
|
307
|
+
}
|
|
308
|
+
throw err;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Builds a stripe-node `httpClient` that seals each request under the
|
|
314
|
+
* merchant's Ed25519 key, sends it, and opens vpay's sealed answer.
|
|
315
|
+
*
|
|
316
|
+
* The signing, the operation table and the verification are the *same* code
|
|
317
|
+
* `VpayClient` and the Rust SDK run (`sdks/rust/wasm`), not a second
|
|
318
|
+
* implementation.
|
|
319
|
+
*
|
|
320
|
+
* # Where a request may be sent
|
|
321
|
+
*
|
|
322
|
+
* **The client is bound to `baseUrl`'s origin and refuses every other one.**
|
|
323
|
+
* stripe-node calls `makeRequest` for *any* request the instance makes;
|
|
324
|
+
* `host`/`port`/`protocol` are configured on the `Stripe` instance, separately
|
|
325
|
+
* from this module, and when they are omitted stripe-node addresses
|
|
326
|
+
* `api.stripe.com:443`. A request signed for vpay and sent to Stripe is not
|
|
327
|
+
* dangerous (the signature binds the audience, and Stripe holds no key that
|
|
328
|
+
* could replay it at vpay), but it is certainly a mistake, and a refusal that
|
|
329
|
+
* names both origins is a better way to learn it than a `401` from a server
|
|
330
|
+
* that was never vpay.
|
|
331
|
+
*
|
|
332
|
+
* So a request whose host, effective port or protocol is not `baseUrl`'s is a
|
|
333
|
+
* {@link VpayConfigError} naming both origins, thrown **before** anything is
|
|
334
|
+
* signed.
|
|
335
|
+
*
|
|
336
|
+
* # What is dropped
|
|
337
|
+
*
|
|
338
|
+
* Everything stripe-node set except the `Idempotency-Key`: `Authorization`
|
|
339
|
+
* (the placeholder API key), `Stripe-Version`, `X-Stripe-Client-User-Agent`,
|
|
340
|
+
* `Content-Type`. The signature binds the payload type itself, and the
|
|
341
|
+
* `Idempotency-Key` as sent.
|
|
342
|
+
*
|
|
343
|
+
* # Failures
|
|
344
|
+
*
|
|
345
|
+
* stripe-node retries any *rejection* from an `httpClient` as a connection
|
|
346
|
+
* error (`maxNetworkRetries` defaults to **2** on Node, not 0), and cannot be
|
|
347
|
+
* told not to, so a refusal is not a rejection. A refused call (the coarse
|
|
348
|
+
* unsigned `401`), an answer that does not verify, or a body over the bound
|
|
349
|
+
* resolves as a Stripe-shaped error response with `stripe-should-retry:
|
|
350
|
+
* false`, and surfaces once: `StripeAuthenticationError` (`code:
|
|
351
|
+
* "unsigned_response"`) for a `401`, `StripeAPIError` (`unverified_response`,
|
|
352
|
+
* `response_too_large`) otherwise, with the cause in `message`. A gateway's
|
|
353
|
+
* unsigned `5xx` stays retryable.
|
|
354
|
+
*
|
|
355
|
+
* A request this client cannot seal, because the contract has no such
|
|
356
|
+
* operation (a `GET` on a `POST`-only path, a path outside `/v1`, a verb `/v1`
|
|
357
|
+
* does not use), is refused the same way, before anything is sent:
|
|
358
|
+
* `StripeInvalidRequestError` with `statusCode: 404` and `code:
|
|
359
|
+
* "unknown_operation"`, once.
|
|
360
|
+
*
|
|
361
|
+
* What does reject is a real transport failure (DNS, TLS, a reset, a timeout)
|
|
362
|
+
* and a {@link VpayConfigError} (a request addressed to another origin, a
|
|
363
|
+
* misconfigured key), reported as `StripeConnectionError` with the
|
|
364
|
+
* original at `err.detail` / `err.raw.exception`, and retried up to
|
|
365
|
+
* `maxNetworkRetries` times. Each retry re-seals the call (a new message). A
|
|
366
|
+
* `POST` keeps the `Idempotency-Key` stripe-node chose, so the retry is the
|
|
367
|
+
* same operation; a `DELETE` has none from stripe-node and gets a new one per
|
|
368
|
+
* attempt (see the comment at the call), so set `maxNetworkRetries: 0` if a
|
|
369
|
+
* repeated `DELETE` answering `404` is not acceptable to you.
|
|
370
|
+
*
|
|
371
|
+
* @throws `VpayConfigError` at construction if `baseUrl` or `clientId` is
|
|
372
|
+
* missing, if `baseUrl` is not an absolute URL, if the key is not an Ed25519
|
|
373
|
+
* key, or if `serverKeys` is missing or malformed.
|
|
374
|
+
*/
|
|
375
|
+
export function createStripeHttpClient(options) {
|
|
376
|
+
const auth = resolveMerchantAuth(options);
|
|
377
|
+
// Parsed once, here: a `baseUrl` that is not a URL is a configuration
|
|
378
|
+
// mistake the merchant should be told about at construction.
|
|
379
|
+
const bound = parseBoundOrigin(auth.baseUrl);
|
|
380
|
+
return new SealingStripeHttpClient(auth, bound);
|
|
381
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Agent as HttpAgent } from "node:http";
|
|
2
|
+
import type { Agent as HttpsAgent } from "node:https";
|
|
3
|
+
import type { HeaderPairs } from "./wasm.js";
|
|
4
|
+
/**
|
|
5
|
+
* The most of an answer's body this client reads, in bytes. A signed answer is
|
|
6
|
+
* a COSE message around JSON, and the largest honest one (a list of 100
|
|
7
|
+
* objects) is a few hundred kilobytes; eight mebibytes is far above that and
|
|
8
|
+
* far below what a hostile peer could otherwise make this process hold. The
|
|
9
|
+
* same number as the Rust SDK's `MAX_RESPONSE_BYTES`.
|
|
10
|
+
*/
|
|
11
|
+
export declare const MAX_RESPONSE_BYTES: number;
|
|
12
|
+
export interface TransportRequest {
|
|
13
|
+
method: string;
|
|
14
|
+
url: string;
|
|
15
|
+
headers: HeaderPairs;
|
|
16
|
+
body: Uint8Array;
|
|
17
|
+
timeoutMs: number;
|
|
18
|
+
}
|
|
19
|
+
export interface TransportResponse {
|
|
20
|
+
status: number;
|
|
21
|
+
/** Every response header, in order, duplicates preserved. */
|
|
22
|
+
headers: HeaderPairs;
|
|
23
|
+
body: Uint8Array;
|
|
24
|
+
}
|
|
25
|
+
/** What {@link sendSealed} needs from the caller's environment. */
|
|
26
|
+
export interface TransportOptions {
|
|
27
|
+
/** A custom agent (a proxy, a pool). Defaults to the global agent. */
|
|
28
|
+
agent?: HttpAgent | HttpsAgent | undefined;
|
|
29
|
+
}
|
|
30
|
+
/** Sends one request and reads the whole answer. Rejects with {@link VpayTransportError}. */
|
|
31
|
+
export declare function sendSealed(request: TransportRequest, options?: TransportOptions): Promise<TransportResponse>;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The HTTP leg of a sealed call, on `node:http` and `node:https`.
|
|
3
|
+
*
|
|
4
|
+
* Not `fetch`: a sealed `GET` carries the signed message as its **body** (the
|
|
5
|
+
* request is a COSE_Sign1 even when the operation has no payload — that is how
|
|
6
|
+
* the signature reaches the server), and `fetch` refuses a body on `GET`. The
|
|
7
|
+
* Rust SDK's `reqwest` and stripe-node's own Node client have no such rule, and
|
|
8
|
+
* neither does `http.request`.
|
|
9
|
+
*
|
|
10
|
+
* One attempt, no retry, no redirect following: a redirect would re-send a
|
|
11
|
+
* signed body to a host the signature was not addressed to.
|
|
12
|
+
*/
|
|
13
|
+
import { request as httpRequest } from "node:http";
|
|
14
|
+
import { request as httpsRequest } from "node:https";
|
|
15
|
+
import { VpayResponseTooLargeError, VpayTransportError } from "./errors.js";
|
|
16
|
+
/**
|
|
17
|
+
* The most of an answer's body this client reads, in bytes. A signed answer is
|
|
18
|
+
* a COSE message around JSON, and the largest honest one (a list of 100
|
|
19
|
+
* objects) is a few hundred kilobytes; eight mebibytes is far above that and
|
|
20
|
+
* far below what a hostile peer could otherwise make this process hold. The
|
|
21
|
+
* same number as the Rust SDK's `MAX_RESPONSE_BYTES`.
|
|
22
|
+
*/
|
|
23
|
+
export const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
24
|
+
/** Sends one request and reads the whole answer. Rejects with {@link VpayTransportError}. */
|
|
25
|
+
export function sendSealed(request, options = {}) {
|
|
26
|
+
return new Promise((resolve, reject) => {
|
|
27
|
+
const signal = AbortSignal.timeout(request.timeoutMs);
|
|
28
|
+
// A request that outlives its timeout is aborted, and `http.request` then
|
|
29
|
+
// reports a generic `AbortError`. The reason on the signal is the
|
|
30
|
+
// `TimeoutError` a caller can tell from a connection failure, so that is
|
|
31
|
+
// what is attached as the cause.
|
|
32
|
+
const fail = (err) => reject(new VpayTransportError("request failed", {
|
|
33
|
+
cause: signal.aborted ? signal.reason : err,
|
|
34
|
+
}));
|
|
35
|
+
let url;
|
|
36
|
+
try {
|
|
37
|
+
url = new URL(request.url);
|
|
38
|
+
}
|
|
39
|
+
catch (err) {
|
|
40
|
+
fail(err);
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const send = url.protocol === "https:" ? httpsRequest : httpRequest;
|
|
44
|
+
const headers = {};
|
|
45
|
+
for (const [name, value] of request.headers) {
|
|
46
|
+
const key = name.toLowerCase();
|
|
47
|
+
const existing = headers[key];
|
|
48
|
+
headers[key] =
|
|
49
|
+
existing === undefined
|
|
50
|
+
? value
|
|
51
|
+
: Array.isArray(existing)
|
|
52
|
+
? [...existing, value]
|
|
53
|
+
: [existing, value];
|
|
54
|
+
}
|
|
55
|
+
// Explicit, because Node omits the length of a `GET` body unless told (it
|
|
56
|
+
// assumes none), and the sealed message would then be read by the server as
|
|
57
|
+
// the start of a second, malformed request.
|
|
58
|
+
headers["content-length"] = String(request.body.byteLength);
|
|
59
|
+
const req = send(url, {
|
|
60
|
+
method: request.method,
|
|
61
|
+
headers,
|
|
62
|
+
agent: options.agent,
|
|
63
|
+
signal,
|
|
64
|
+
}, (res) => {
|
|
65
|
+
const tooLarge = () => {
|
|
66
|
+
// Reject first: destroying the response emits `aborted`
|
|
67
|
+
// synchronously, and that handler would otherwise settle the promise
|
|
68
|
+
// with a generic transport failure before the typed one.
|
|
69
|
+
reject(new VpayResponseTooLargeError(MAX_RESPONSE_BYTES));
|
|
70
|
+
res.destroy();
|
|
71
|
+
};
|
|
72
|
+
// A declared length over the bound is refused before a byte is read;
|
|
73
|
+
// the count below is for a body that declares none (chunked) or lies.
|
|
74
|
+
const declared = Number(res.headers["content-length"]);
|
|
75
|
+
if (Number.isFinite(declared) && declared > MAX_RESPONSE_BYTES) {
|
|
76
|
+
tooLarge();
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const chunks = [];
|
|
80
|
+
let received = 0;
|
|
81
|
+
res.on("data", (chunk) => {
|
|
82
|
+
received += chunk.byteLength;
|
|
83
|
+
if (received > MAX_RESPONSE_BYTES) {
|
|
84
|
+
chunks.length = 0;
|
|
85
|
+
tooLarge();
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
chunks.push(chunk);
|
|
89
|
+
});
|
|
90
|
+
res.on("error", fail);
|
|
91
|
+
// `aborted` fires when the peer severs a response mid-body; `end`
|
|
92
|
+
// would then never come, and the caller would wait for the timeout.
|
|
93
|
+
res.on("aborted", () => fail(new Error("response aborted")));
|
|
94
|
+
res.on("end", () => {
|
|
95
|
+
const pairs = [];
|
|
96
|
+
for (let i = 0; i + 1 < res.rawHeaders.length; i += 2) {
|
|
97
|
+
pairs.push([res.rawHeaders[i], res.rawHeaders[i + 1]]);
|
|
98
|
+
}
|
|
99
|
+
resolve({
|
|
100
|
+
status: res.statusCode ?? 0,
|
|
101
|
+
headers: pairs,
|
|
102
|
+
body: Buffer.concat(chunks),
|
|
103
|
+
});
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
req.on("error", fail);
|
|
107
|
+
req.end(request.body);
|
|
108
|
+
});
|
|
109
|
+
}
|
package/dist/version.d.ts
CHANGED
package/dist/version.js
CHANGED
|
@@ -9,4 +9,4 @@
|
|
|
9
9
|
* releases. A hand-written constant has no such landmine — it just needs to
|
|
10
10
|
* be bumped alongside `package.json`'s own `version` field.
|
|
11
11
|
*/
|
|
12
|
-
export const SDK_VERSION = "0.
|
|
12
|
+
export const SDK_VERSION = "0.16.0"; // x-release-please-version
|
package/dist/wasm.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** `[name, value]` header pairs, as the wasm module takes and returns them. */
|
|
2
|
+
export type HeaderPairs = [string, string][];
|
|
3
|
+
/** A sealed call: the bytes and headers to send, and what the answer is opened with. */
|
|
4
|
+
export interface WasmSealedCall {
|
|
5
|
+
readonly body: Uint8Array;
|
|
6
|
+
readonly headers: HeaderPairs;
|
|
7
|
+
/** Verifies the answer and returns its JSON text. Rejects with a {@link WasmFailure}. */
|
|
8
|
+
openResponse(status: number, headers: HeaderPairs, body: Uint8Array): Promise<string>;
|
|
9
|
+
}
|
|
10
|
+
export interface WasmSealer {
|
|
11
|
+
readonly publicKey: string;
|
|
12
|
+
sealCall(method: string, path: string, body: string | undefined, query: string | undefined, idempotencyKey: string | undefined): Promise<WasmSealedCall>;
|
|
13
|
+
}
|
|
14
|
+
/** What the wasm module rejects with: a plain object, never an `Error`. */
|
|
15
|
+
export interface WasmFailure {
|
|
16
|
+
kind: "unbound" | "seal" | "unsigned" | "unverified" | "invalid";
|
|
17
|
+
message: string;
|
|
18
|
+
status?: number;
|
|
19
|
+
}
|
|
20
|
+
export interface WasmModule {
|
|
21
|
+
Sealer: {
|
|
22
|
+
fromSeed(seedBase64url: string, serverCurrent: string, serverNext: string | undefined, audience: string): WasmSealer;
|
|
23
|
+
fromCallback(publicKeyBase64url: string, sign: (tbs: Uint8Array) => Uint8Array | Promise<Uint8Array>, serverCurrent: string, serverNext: string | undefined, audience: string): WasmSealer;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
/** Loads the sealing module (once). */
|
|
27
|
+
export declare function loadWasm(): WasmModule;
|
|
28
|
+
/** Whether a rejection is one of the wasm module's own failure objects. */
|
|
29
|
+
export declare function isWasmFailure(value: unknown): value is WasmFailure;
|
package/dist/wasm.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The seam to `sdks/rust/wasm`: cratestack's own envelope, compiled to
|
|
3
|
+
* WebAssembly (`just wasm-build`, or `pnpm run build:wasm` in this package).
|
|
4
|
+
*
|
|
5
|
+
* The signature binds a dozen things byte for byte (audience, method, route
|
|
6
|
+
* template, path parameters, canonical query, contract digest, payload type,
|
|
7
|
+
* `Idempotency-Key`), so this SDK does not reimplement the envelope in
|
|
8
|
+
* TypeScript beside the Rust one: `vpay-sdk` seals through the same crate, and
|
|
9
|
+
* this package calls it. The module is CommonJS (what `wasm-bindgen --target
|
|
10
|
+
* nodejs` emits, in a directory whose `package.json` says so), loaded lazily
|
|
11
|
+
* so that `import "@vaam-apps/vpay-sdk"` costs nothing until a client is built.
|
|
12
|
+
*
|
|
13
|
+
* The shapes below are written out by hand rather than read from the generated
|
|
14
|
+
* `.d.ts`: that file does not exist in a checkout until the wasm is built, and
|
|
15
|
+
* `tsc` must not depend on it.
|
|
16
|
+
*/
|
|
17
|
+
import { createRequire } from "node:module";
|
|
18
|
+
import { VpayConfigError } from "./errors.js";
|
|
19
|
+
const require = createRequire(import.meta.url);
|
|
20
|
+
let loaded;
|
|
21
|
+
/** Loads the sealing module (once). */
|
|
22
|
+
export function loadWasm() {
|
|
23
|
+
if (loaded === undefined) {
|
|
24
|
+
try {
|
|
25
|
+
loaded = require("../wasm/vpay_sdk_wasm.js");
|
|
26
|
+
}
|
|
27
|
+
catch (err) {
|
|
28
|
+
throw new VpayConfigError("the sealing module (wasm/vpay_sdk_wasm.js) could not be loaded: " +
|
|
29
|
+
"it is built from sdks/rust/wasm — run `pnpm run build:wasm` in sdks/nodejs, " +
|
|
30
|
+
"or install the published package, which ships it", { cause: err });
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return loaded;
|
|
34
|
+
}
|
|
35
|
+
/** Whether a rejection is one of the wasm module's own failure objects. */
|
|
36
|
+
export function isWasmFailure(value) {
|
|
37
|
+
return (typeof value === "object" &&
|
|
38
|
+
value !== null &&
|
|
39
|
+
typeof value["kind"] === "string" &&
|
|
40
|
+
typeof value["message"] === "string");
|
|
41
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vaam-apps/vpay-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "The Node.js merchant SDK for vpay's /v1 API:
|
|
3
|
+
"version": "0.16.0",
|
|
4
|
+
"description": "The Node.js merchant SDK for vpay's /v1 API: Ed25519-signed requests, payment intents, checkout sessions, refunds, events and webhook verification.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"publishConfig": {
|
|
7
7
|
"access": "public"
|
|
@@ -27,13 +27,14 @@
|
|
|
27
27
|
"default": "./dist/index.js"
|
|
28
28
|
},
|
|
29
29
|
"./stripe": {
|
|
30
|
-
"types": "./dist/stripe-
|
|
31
|
-
"default": "./dist/stripe-
|
|
30
|
+
"types": "./dist/stripe-http-client.d.ts",
|
|
31
|
+
"default": "./dist/stripe-http-client.js"
|
|
32
32
|
}
|
|
33
33
|
},
|
|
34
34
|
"sideEffects": false,
|
|
35
35
|
"files": [
|
|
36
36
|
"dist",
|
|
37
|
+
"wasm",
|
|
37
38
|
"scripts",
|
|
38
39
|
"README.md"
|
|
39
40
|
],
|
|
@@ -54,8 +55,12 @@
|
|
|
54
55
|
"@vpay/config": "0.0.0"
|
|
55
56
|
},
|
|
56
57
|
"scripts": {
|
|
57
|
-
"build": "
|
|
58
|
+
"build:wasm": "bash scripts/build-wasm.sh",
|
|
59
|
+
"build:wasm-test": "bash scripts/build-wasm.sh --responder",
|
|
60
|
+
"build:ts": "tsc -p tsconfig.build.json",
|
|
61
|
+
"build": "pnpm run build:wasm && pnpm run build:ts",
|
|
58
62
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
63
|
+
"pretest": "pnpm run build:wasm && pnpm run build:wasm-test",
|
|
59
64
|
"test": "vitest run",
|
|
60
65
|
"test:live": "vitest run -c vitest.live.config.ts",
|
|
61
66
|
"lint": "eslint . --max-warnings 0"
|