@onflay/node 0.2.1 → 1.0.0-staging-20261206080029
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/CHANGELOG.md +74 -0
- package/README.md +211 -48
- package/dist/chunk-4RUPPDC2.mjs +121 -0
- package/dist/chunk-4RUPPDC2.mjs.map +1 -0
- package/dist/chunk-63KSRMJG.mjs +47 -0
- package/dist/chunk-63KSRMJG.mjs.map +1 -0
- package/dist/chunk-7LYAEZCT.mjs +197 -0
- package/dist/chunk-7LYAEZCT.mjs.map +1 -0
- package/dist/chunk-A3TRCKHK.mjs +60 -0
- package/dist/chunk-A3TRCKHK.mjs.map +1 -0
- package/dist/chunk-AFAU2FH2.js +47 -0
- package/dist/chunk-AFAU2FH2.js.map +1 -0
- package/dist/chunk-DBE2YZWE.mjs +38 -0
- package/dist/chunk-DBE2YZWE.mjs.map +1 -0
- package/dist/chunk-EOHFYWFQ.mjs +154 -0
- package/dist/chunk-EOHFYWFQ.mjs.map +1 -0
- package/dist/chunk-I2IVHBFA.js +197 -0
- package/dist/chunk-I2IVHBFA.js.map +1 -0
- package/dist/chunk-J4MYKTPN.mjs +37 -0
- package/dist/chunk-J4MYKTPN.mjs.map +1 -0
- package/dist/chunk-JQPANXLV.mjs +37 -0
- package/dist/chunk-JQPANXLV.mjs.map +1 -0
- package/dist/chunk-JXP6V2P2.mjs +1057 -0
- package/dist/chunk-JXP6V2P2.mjs.map +1 -0
- package/dist/chunk-M52GW7GQ.js +1057 -0
- package/dist/chunk-M52GW7GQ.js.map +1 -0
- package/dist/chunk-MMMUKAI6.js +37 -0
- package/dist/chunk-MMMUKAI6.js.map +1 -0
- package/dist/chunk-NSR4UQLV.js +87 -0
- package/dist/chunk-NSR4UQLV.js.map +1 -0
- package/dist/chunk-SUONZUVK.js +154 -0
- package/dist/chunk-SUONZUVK.js.map +1 -0
- package/dist/chunk-T26CPULH.js +121 -0
- package/dist/chunk-T26CPULH.js.map +1 -0
- package/dist/chunk-V2XJ4GZU.js +38 -0
- package/dist/chunk-V2XJ4GZU.js.map +1 -0
- package/dist/chunk-W6AEPYUG.js +37 -0
- package/dist/chunk-W6AEPYUG.js.map +1 -0
- package/dist/chunk-YHQ7XIC6.js +60 -0
- package/dist/chunk-YHQ7XIC6.js.map +1 -0
- package/dist/chunk-YSXUZYUY.mjs +87 -0
- package/dist/chunk-YSXUZYUY.mjs.map +1 -0
- package/dist/index-C1KFW_9r.d.mts +3989 -0
- package/dist/index-C1KFW_9r.d.ts +3989 -0
- package/dist/index.d.mts +918 -0
- package/dist/index.d.ts +918 -26
- package/dist/index.js +2990 -40
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2991 -0
- package/dist/index.mjs.map +1 -0
- package/dist/lib/config.d.mts +59 -0
- package/dist/lib/config.d.ts +59 -0
- package/dist/lib/config.js +15 -0
- package/dist/lib/config.js.map +1 -0
- package/dist/lib/config.mjs +15 -0
- package/dist/lib/config.mjs.map +1 -0
- package/dist/lib/http.d.mts +51 -0
- package/dist/lib/http.d.ts +51 -0
- package/dist/lib/http.js +13 -0
- package/dist/lib/http.js.map +1 -0
- package/dist/lib/http.mjs +13 -0
- package/dist/lib/http.mjs.map +1 -0
- package/dist/lib/retries.d.mts +41 -0
- package/dist/lib/retries.d.ts +41 -0
- package/dist/lib/retries.js +16 -0
- package/dist/lib/retries.js.map +1 -0
- package/dist/lib/retries.mjs +16 -0
- package/dist/lib/retries.mjs.map +1 -0
- package/dist/lib/sdks.d.mts +61 -0
- package/dist/lib/sdks.d.ts +61 -0
- package/dist/lib/sdks.js +12 -0
- package/dist/lib/sdks.js.map +1 -0
- package/dist/lib/sdks.mjs +12 -0
- package/dist/lib/sdks.mjs.map +1 -0
- package/dist/models/components/index.d.mts +1 -0
- package/dist/models/components/index.d.ts +1 -0
- package/dist/models/components/index.js +1 -0
- package/dist/models/components/index.js.map +1 -0
- package/dist/models/components/index.mjs +1 -0
- package/dist/models/components/index.mjs.map +1 -0
- package/dist/models/errors/index.d.mts +161 -0
- package/dist/models/errors/index.d.ts +161 -0
- package/dist/models/errors/index.js +29 -0
- package/dist/models/errors/index.js.map +1 -0
- package/dist/models/errors/index.mjs +29 -0
- package/dist/models/errors/index.mjs.map +1 -0
- package/dist/models/operations/index.d.mts +769 -0
- package/dist/models/operations/index.d.ts +769 -0
- package/dist/models/operations/index.js +1 -0
- package/dist/models/operations/index.js.map +1 -0
- package/dist/models/operations/index.mjs +1 -0
- package/dist/models/operations/index.mjs.map +1 -0
- package/dist/types/index.d.mts +26 -0
- package/dist/types/index.d.ts +26 -0
- package/dist/types/index.js +1 -0
- package/dist/types/index.js.map +1 -0
- package/dist/types/index.mjs +1 -0
- package/dist/types/index.mjs.map +1 -0
- package/dist/verify-tF2BsJK6.d.mts +325 -0
- package/dist/verify-tF2BsJK6.d.ts +325 -0
- package/dist/webhooks/express.d.mts +39 -0
- package/dist/webhooks/express.d.ts +39 -0
- package/dist/webhooks/express.js +10 -0
- package/dist/webhooks/express.js.map +1 -0
- package/dist/webhooks/express.mjs +10 -0
- package/dist/webhooks/express.mjs.map +1 -0
- package/dist/webhooks/hono.d.mts +33 -0
- package/dist/webhooks/hono.d.ts +33 -0
- package/dist/webhooks/hono.js +10 -0
- package/dist/webhooks/hono.js.map +1 -0
- package/dist/webhooks/hono.mjs +10 -0
- package/dist/webhooks/hono.mjs.map +1 -0
- package/dist/webhooks/index.d.mts +34 -0
- package/dist/webhooks/index.d.ts +34 -0
- package/dist/webhooks/index.js +75 -0
- package/dist/webhooks/index.js.map +1 -0
- package/dist/webhooks/index.mjs +75 -0
- package/dist/webhooks/index.mjs.map +1 -0
- package/dist/webhooks/next.d.mts +38 -0
- package/dist/webhooks/next.d.ts +38 -0
- package/dist/webhooks/next.js +10 -0
- package/dist/webhooks/next.js.map +1 -0
- package/dist/webhooks/next.mjs +10 -0
- package/dist/webhooks/next.mjs.map +1 -0
- package/package.json +273 -14
- package/dist/client.d.ts +0 -65
- package/dist/client.d.ts.map +0 -1
- package/dist/client.js +0 -216
- package/dist/client.js.map +0 -1
- package/dist/errors.d.ts +0 -61
- package/dist/errors.d.ts.map +0 -1
- package/dist/errors.js +0 -134
- package/dist/errors.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/onflay.d.ts +0 -42
- package/dist/onflay.d.ts.map +0 -1
- package/dist/onflay.js +0 -60
- package/dist/onflay.js.map +0 -1
- package/dist/pagination.d.ts +0 -19
- package/dist/pagination.d.ts.map +0 -1
- package/dist/pagination.js +0 -61
- package/dist/pagination.js.map +0 -1
- package/dist/resources/checkout-sessions.d.ts +0 -11
- package/dist/resources/checkout-sessions.d.ts.map +0 -1
- package/dist/resources/checkout-sessions.js +0 -20
- package/dist/resources/checkout-sessions.js.map +0 -1
- package/dist/resources/customers.d.ts +0 -17
- package/dist/resources/customers.d.ts.map +0 -1
- package/dist/resources/customers.js +0 -39
- package/dist/resources/customers.js.map +0 -1
- package/dist/resources/payments.d.ts +0 -11
- package/dist/resources/payments.d.ts.map +0 -1
- package/dist/resources/payments.js +0 -27
- package/dist/resources/payments.js.map +0 -1
- package/dist/resources/prices.d.ts +0 -24
- package/dist/resources/prices.d.ts.map +0 -1
- package/dist/resources/prices.js +0 -46
- package/dist/resources/prices.js.map +0 -1
- package/dist/resources/products.d.ts +0 -18
- package/dist/resources/products.d.ts.map +0 -1
- package/dist/resources/products.js +0 -40
- package/dist/resources/products.js.map +0 -1
- package/dist/resources/subscriptions.d.ts +0 -39
- package/dist/resources/subscriptions.d.ts.map +0 -1
- package/dist/resources/subscriptions.js +0 -62
- package/dist/resources/subscriptions.js.map +0 -1
- package/dist/resources/usage.d.ts +0 -26
- package/dist/resources/usage.d.ts.map +0 -1
- package/dist/resources/usage.js +0 -43
- package/dist/resources/usage.js.map +0 -1
- package/dist/resources/webhook-endpoints.d.ts +0 -20
- package/dist/resources/webhook-endpoints.d.ts.map +0 -1
- package/dist/resources/webhook-endpoints.js +0 -47
- package/dist/resources/webhook-endpoints.js.map +0 -1
- package/dist/types/checkout-sessions.d.ts +0 -67
- package/dist/types/checkout-sessions.d.ts.map +0 -1
- package/dist/types/checkout-sessions.js +0 -3
- package/dist/types/checkout-sessions.js.map +0 -1
- package/dist/types/customers.d.ts +0 -28
- package/dist/types/customers.d.ts.map +0 -1
- package/dist/types/customers.js +0 -3
- package/dist/types/customers.js.map +0 -1
- package/dist/types/events.d.ts +0 -95
- package/dist/types/events.d.ts.map +0 -1
- package/dist/types/events.js +0 -24
- package/dist/types/events.js.map +0 -1
- package/dist/types/payments.d.ts +0 -25
- package/dist/types/payments.d.ts.map +0 -1
- package/dist/types/payments.js +0 -3
- package/dist/types/payments.js.map +0 -1
- package/dist/types/prices.d.ts +0 -57
- package/dist/types/prices.d.ts.map +0 -1
- package/dist/types/prices.js +0 -3
- package/dist/types/prices.js.map +0 -1
- package/dist/types/products.d.ts +0 -29
- package/dist/types/products.d.ts.map +0 -1
- package/dist/types/products.js +0 -3
- package/dist/types/products.js.map +0 -1
- package/dist/types/shared.d.ts +0 -34
- package/dist/types/shared.d.ts.map +0 -1
- package/dist/types/shared.js +0 -4
- package/dist/types/shared.js.map +0 -1
- package/dist/types/subscriptions.d.ts +0 -85
- package/dist/types/subscriptions.d.ts.map +0 -1
- package/dist/types/subscriptions.js +0 -3
- package/dist/types/subscriptions.js.map +0 -1
- package/dist/types/usage.d.ts +0 -35
- package/dist/types/usage.d.ts.map +0 -1
- package/dist/types/usage.js +0 -3
- package/dist/types/usage.js.map +0 -1
- package/dist/types/webhook-endpoints.d.ts +0 -48
- package/dist/types/webhook-endpoints.d.ts.map +0 -1
- package/dist/types/webhook-endpoints.js +0 -3
- package/dist/types/webhook-endpoints.js.map +0 -1
- package/dist/version.d.ts +0 -4
- package/dist/version.d.ts.map +0 -1
- package/dist/version.js +0 -7
- package/dist/version.js.map +0 -1
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// src/webhooks/verify.ts
|
|
2
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
3
|
+
var ONFLAY_SIGNATURE_HEADER = "x-onflay-signature";
|
|
4
|
+
var STANDARD_WEBHOOK_ID_HEADER = "webhook-id";
|
|
5
|
+
var STANDARD_WEBHOOK_TIMESTAMP_HEADER = "webhook-timestamp";
|
|
6
|
+
var STANDARD_WEBHOOK_SIGNATURE_HEADER = "webhook-signature";
|
|
7
|
+
var DEFAULT_REPLAY_TOLERANCE_SECONDS = 300;
|
|
8
|
+
var OnflaySignatureError = class extends Error {
|
|
9
|
+
code;
|
|
10
|
+
constructor(code, message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = "OnflaySignatureError";
|
|
13
|
+
this.code = code;
|
|
14
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
function verifyWebhookSignature(rawBody, signatureHeaderOrHeaders, options) {
|
|
18
|
+
assertInputs(rawBody, options, "verifyWebhookSignature");
|
|
19
|
+
if (signatureHeaderOrHeaders === null || signatureHeaderOrHeaders === void 0 || typeof signatureHeaderOrHeaders === "string" || Array.isArray(signatureHeaderOrHeaders)) {
|
|
20
|
+
return verifyLegacy(rawBody, signatureHeaderOrHeaders, options);
|
|
21
|
+
}
|
|
22
|
+
const headers = signatureHeaderOrHeaders;
|
|
23
|
+
const legacyHeader = readHeader(headers, ONFLAY_SIGNATURE_HEADER);
|
|
24
|
+
if (readHeader(headers, STANDARD_WEBHOOK_SIGNATURE_HEADER) === void 0) {
|
|
25
|
+
return verifyLegacy(rawBody, legacyHeader, options);
|
|
26
|
+
}
|
|
27
|
+
try {
|
|
28
|
+
return verifyStandardWebhook(rawBody, headers, options);
|
|
29
|
+
} catch (standardError) {
|
|
30
|
+
if (legacyHeader === void 0) throw standardError;
|
|
31
|
+
try {
|
|
32
|
+
return verifyLegacy(rawBody, legacyHeader, options);
|
|
33
|
+
} catch {
|
|
34
|
+
throw standardError;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function verifyStandardWebhook(rawBody, headers, options) {
|
|
39
|
+
assertInputs(rawBody, options, "verifyStandardWebhook");
|
|
40
|
+
const id = readHeader(headers, STANDARD_WEBHOOK_ID_HEADER);
|
|
41
|
+
const timestampHeader = readHeader(headers, STANDARD_WEBHOOK_TIMESTAMP_HEADER);
|
|
42
|
+
const signatureHeader = readHeader(headers, STANDARD_WEBHOOK_SIGNATURE_HEADER);
|
|
43
|
+
if (!id || !timestampHeader || !signatureHeader) {
|
|
44
|
+
throw new OnflaySignatureError(
|
|
45
|
+
"missing_signature",
|
|
46
|
+
"Missing webhook-id, webhook-timestamp or webhook-signature header."
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
const timestamp = Number(timestampHeader);
|
|
50
|
+
if (!/^\d+$/.test(timestampHeader.trim()) || !Number.isSafeInteger(timestamp) || timestamp <= 0) {
|
|
51
|
+
throw new OnflaySignatureError(
|
|
52
|
+
"malformed_signature",
|
|
53
|
+
"Could not parse webhook-timestamp header (expected unix seconds)."
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
const signatures = signatureHeader.split(" ").map((entry) => entry.trim()).filter(Boolean).flatMap((entry) => {
|
|
57
|
+
const comma = entry.indexOf(",");
|
|
58
|
+
if (comma <= 0) return [];
|
|
59
|
+
return entry.slice(0, comma) === "v1" ? [entry.slice(comma + 1)] : [];
|
|
60
|
+
});
|
|
61
|
+
if (signatures.length === 0) {
|
|
62
|
+
throw new OnflaySignatureError(
|
|
63
|
+
"malformed_signature",
|
|
64
|
+
"Could not parse webhook-signature header (expected `v1,<base64>`)."
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
assertWithinTolerance(timestamp, options);
|
|
68
|
+
const expected = Buffer.from(
|
|
69
|
+
createHmac("sha256", standardWebhookKey(options.secret)).update(`${id}.${timestamp}.${rawBody}`, "utf8").digest("base64"),
|
|
70
|
+
"utf8"
|
|
71
|
+
);
|
|
72
|
+
if (!signatures.some((sig) => safeEqual(sig, expected))) {
|
|
73
|
+
throw new OnflaySignatureError(
|
|
74
|
+
"invalid_signature",
|
|
75
|
+
"Webhook signature did not match. Check that you are using the raw body and the correct endpoint secret."
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
return { event: parseBody(rawBody), rawBody, timestamp, scheme: "standard", webhookId: id };
|
|
79
|
+
}
|
|
80
|
+
function verifyLegacy(rawBody, signatureHeader, options) {
|
|
81
|
+
const headerValue = Array.isArray(signatureHeader) ? signatureHeader[0] : signatureHeader;
|
|
82
|
+
if (!headerValue) {
|
|
83
|
+
throw new OnflaySignatureError(
|
|
84
|
+
"missing_signature",
|
|
85
|
+
"Missing X-Onflay-Signature header."
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
const parsed = parseSignatureHeader(headerValue);
|
|
89
|
+
if (!parsed) {
|
|
90
|
+
throw new OnflaySignatureError(
|
|
91
|
+
"malformed_signature",
|
|
92
|
+
"Could not parse signature header (expected `t=<unix>,v1=<hex>`)."
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
const { timestamp, signatures } = parsed;
|
|
96
|
+
assertWithinTolerance(timestamp, options);
|
|
97
|
+
const expected = createHmac("sha256", options.secret).update(`${timestamp}.${rawBody}`, "utf8").digest("hex");
|
|
98
|
+
const expectedBuf = Buffer.from(expected, "utf8");
|
|
99
|
+
const ok = signatures.some((sig) => safeEqual(sig, expectedBuf));
|
|
100
|
+
if (!ok) {
|
|
101
|
+
throw new OnflaySignatureError(
|
|
102
|
+
"invalid_signature",
|
|
103
|
+
"Webhook signature did not match. Check that you are using the raw body and the correct endpoint secret."
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
return { event: parseBody(rawBody), rawBody, timestamp, scheme: "legacy" };
|
|
107
|
+
}
|
|
108
|
+
function assertInputs(rawBody, options, fn) {
|
|
109
|
+
if (!options?.secret || typeof options.secret !== "string") {
|
|
110
|
+
throw new OnflaySignatureError(
|
|
111
|
+
"missing_signature",
|
|
112
|
+
"A signing secret is required to verify Onflay webhooks."
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
if (typeof rawBody !== "string" || rawBody.length === 0) {
|
|
116
|
+
throw new OnflaySignatureError(
|
|
117
|
+
"missing_payload",
|
|
118
|
+
`${fn}: rawBody must be the raw request bytes as a string.`
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
function assertWithinTolerance(timestamp, options) {
|
|
123
|
+
const tolerance = options.toleranceSeconds ?? DEFAULT_REPLAY_TOLERANCE_SECONDS;
|
|
124
|
+
if (tolerance <= 0) return;
|
|
125
|
+
const now = (options.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
126
|
+
const ageSeconds = Math.abs(Math.floor(now.getTime() / 1e3) - timestamp);
|
|
127
|
+
if (ageSeconds > tolerance) {
|
|
128
|
+
throw new OnflaySignatureError(
|
|
129
|
+
"expired_signature",
|
|
130
|
+
`Webhook is outside the replay tolerance (${ageSeconds}s > ${tolerance}s).`
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function parseBody(rawBody) {
|
|
135
|
+
try {
|
|
136
|
+
return JSON.parse(rawBody);
|
|
137
|
+
} catch {
|
|
138
|
+
throw new OnflaySignatureError(
|
|
139
|
+
"missing_payload",
|
|
140
|
+
"Webhook signature was valid but body is not parseable JSON."
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function standardWebhookKey(secret) {
|
|
145
|
+
const encoded = secret.startsWith("whsec_") ? secret.slice("whsec_".length) : secret;
|
|
146
|
+
return Buffer.from(encoded, "base64");
|
|
147
|
+
}
|
|
148
|
+
function readHeader(headers, name) {
|
|
149
|
+
if (typeof headers.get === "function") {
|
|
150
|
+
const value2 = headers.get(name);
|
|
151
|
+
return value2 ?? void 0;
|
|
152
|
+
}
|
|
153
|
+
const record = headers;
|
|
154
|
+
const lower = name.toLowerCase();
|
|
155
|
+
const key = Object.keys(record).find((k) => k.toLowerCase() === lower);
|
|
156
|
+
if (key === void 0) return void 0;
|
|
157
|
+
const value = record[key];
|
|
158
|
+
const first = Array.isArray(value) ? value[0] : value;
|
|
159
|
+
return first ?? void 0;
|
|
160
|
+
}
|
|
161
|
+
function parseSignatureHeader(value) {
|
|
162
|
+
const parts = value.split(",").map((part) => part.trim()).filter(Boolean);
|
|
163
|
+
let timestamp = null;
|
|
164
|
+
const signatures = [];
|
|
165
|
+
for (const part of parts) {
|
|
166
|
+
const idx = part.indexOf("=");
|
|
167
|
+
if (idx <= 0) continue;
|
|
168
|
+
const key = part.slice(0, idx);
|
|
169
|
+
const val = part.slice(idx + 1);
|
|
170
|
+
if (key === "t") {
|
|
171
|
+
const ts = Number(val);
|
|
172
|
+
if (Number.isInteger(ts) && ts > 0) timestamp = ts;
|
|
173
|
+
} else if (key === "v1") {
|
|
174
|
+
signatures.push(val);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (timestamp === null || signatures.length === 0) return null;
|
|
178
|
+
return { timestamp, signatures };
|
|
179
|
+
}
|
|
180
|
+
function safeEqual(actual, expected) {
|
|
181
|
+
if (actual.length !== expected.length) return false;
|
|
182
|
+
const actualBuf = Buffer.from(actual, "utf8");
|
|
183
|
+
if (actualBuf.length !== expected.length) return false;
|
|
184
|
+
return timingSafeEqual(actualBuf, expected);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export {
|
|
188
|
+
ONFLAY_SIGNATURE_HEADER,
|
|
189
|
+
STANDARD_WEBHOOK_ID_HEADER,
|
|
190
|
+
STANDARD_WEBHOOK_TIMESTAMP_HEADER,
|
|
191
|
+
STANDARD_WEBHOOK_SIGNATURE_HEADER,
|
|
192
|
+
DEFAULT_REPLAY_TOLERANCE_SECONDS,
|
|
193
|
+
OnflaySignatureError,
|
|
194
|
+
verifyWebhookSignature,
|
|
195
|
+
verifyStandardWebhook
|
|
196
|
+
};
|
|
197
|
+
//# sourceMappingURL=chunk-7LYAEZCT.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/webhooks/verify.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from 'node:crypto';\n\nexport const ONFLAY_SIGNATURE_HEADER = 'x-onflay-signature';\nexport const STANDARD_WEBHOOK_ID_HEADER = 'webhook-id';\nexport const STANDARD_WEBHOOK_TIMESTAMP_HEADER = 'webhook-timestamp';\nexport const STANDARD_WEBHOOK_SIGNATURE_HEADER = 'webhook-signature';\nexport const DEFAULT_REPLAY_TOLERANCE_SECONDS = 300;\n\n/**\n * Request headers in any common shape: a Fetch `Headers` instance (Next.js,\n * Hono, Workers) or a plain object such as Node/Express `req.headers`.\n * Plain-object lookups are case-insensitive.\n */\nexport type WebhookHeaders =\n | { get(name: string): string | null }\n | Record<string, string | string[] | null | undefined>;\n\nexport class OnflaySignatureError extends Error {\n public readonly code:\n | 'missing_signature'\n | 'malformed_signature'\n | 'invalid_signature'\n | 'expired_signature'\n | 'missing_payload';\n\n constructor(\n code: OnflaySignatureError['code'],\n message: string,\n ) {\n super(message);\n this.name = 'OnflaySignatureError';\n this.code = code;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport interface VerifyWebhookOptions {\n /** Per-endpoint signing secret (`whsec_…`). */\n secret: string;\n /**\n * Replay window in seconds. Reject events older than this. Defaults to\n * 300 (5 minutes); set to 0 to disable.\n */\n toleranceSeconds?: number;\n /** Inject a clock for tests. Defaults to `Date.now`. */\n now?: () => Date;\n}\n\nexport interface VerifiedWebhook<TEvent = unknown> {\n /** The parsed JSON envelope. */\n event: TEvent;\n /** Raw bytes that were verified (the body field passed in). */\n rawBody: string;\n /** Signature timestamp (unix seconds). */\n timestamp: number;\n /** Which signature scheme verified the request. */\n scheme: 'standard' | 'legacy';\n /** Standard Webhooks message id (`webhook-id`); set when `scheme` is `standard`. */\n webhookId?: string;\n}\n\n/**\n * Verify an inbound Onflay webhook against the raw request body and a\n * per-endpoint secret. Returns the parsed event envelope on success;\n * throws `OnflaySignatureError` for any verification failure.\n *\n * The second argument is either:\n * - the request headers (`Headers` or a plain object): Standard Webhooks\n * (`webhook-id` / `webhook-timestamp` / `webhook-signature`) is tried\n * first, then the legacy `X-Onflay-Signature` header; or\n * - the `X-Onflay-Signature` header value alone (legacy scheme only, the\n * original signature of this function).\n *\n * IMPORTANT: pass the raw body bytes (string), NOT a re-serialized JSON\n * object. Re-serializing changes whitespace/property order and breaks the\n * HMAC.\n */\nexport function verifyWebhookSignature<TEvent = unknown>(\n rawBody: string,\n signatureHeaderOrHeaders: string | string[] | null | undefined | WebhookHeaders,\n options: VerifyWebhookOptions,\n): VerifiedWebhook<TEvent> {\n assertInputs(rawBody, options, 'verifyWebhookSignature');\n if (\n signatureHeaderOrHeaders === null ||\n signatureHeaderOrHeaders === undefined ||\n typeof signatureHeaderOrHeaders === 'string' ||\n Array.isArray(signatureHeaderOrHeaders)\n ) {\n return verifyLegacy<TEvent>(rawBody, signatureHeaderOrHeaders, options);\n }\n const headers = signatureHeaderOrHeaders;\n const legacyHeader = readHeader(headers, ONFLAY_SIGNATURE_HEADER);\n if (readHeader(headers, STANDARD_WEBHOOK_SIGNATURE_HEADER) === undefined) {\n return verifyLegacy<TEvent>(rawBody, legacyHeader, options);\n }\n try {\n return verifyStandardWebhook<TEvent>(rawBody, headers, options);\n } catch (standardError) {\n if (legacyHeader === undefined) throw standardError;\n try {\n return verifyLegacy<TEvent>(rawBody, legacyHeader, options);\n } catch {\n // Both schemes failed: report the recommended scheme's error.\n throw standardError;\n }\n }\n}\n\n/**\n * Verify a Standard Webhooks signature (https://www.standardwebhooks.com):\n * `webhook-signature` holds one or more space-separated `v1,<base64>`\n * entries, each an HMAC-SHA256 over `{webhook-id}.{webhook-timestamp}.{body}`\n * keyed with the base64 decode of the secret after its `whsec_` prefix.\n * Rejects timestamps more than `toleranceSeconds` (default 300) away from\n * now in either direction.\n */\nexport function verifyStandardWebhook<TEvent = unknown>(\n rawBody: string,\n headers: WebhookHeaders,\n options: VerifyWebhookOptions,\n): VerifiedWebhook<TEvent> {\n assertInputs(rawBody, options, 'verifyStandardWebhook');\n const id = readHeader(headers, STANDARD_WEBHOOK_ID_HEADER);\n const timestampHeader = readHeader(headers, STANDARD_WEBHOOK_TIMESTAMP_HEADER);\n const signatureHeader = readHeader(headers, STANDARD_WEBHOOK_SIGNATURE_HEADER);\n if (!id || !timestampHeader || !signatureHeader) {\n throw new OnflaySignatureError(\n 'missing_signature',\n 'Missing webhook-id, webhook-timestamp or webhook-signature header.',\n );\n }\n const timestamp = Number(timestampHeader);\n if (!/^\\d+$/.test(timestampHeader.trim()) || !Number.isSafeInteger(timestamp) || timestamp <= 0) {\n throw new OnflaySignatureError(\n 'malformed_signature',\n 'Could not parse webhook-timestamp header (expected unix seconds).',\n );\n }\n const signatures = signatureHeader\n .split(' ')\n .map((entry) => entry.trim())\n .filter(Boolean)\n .flatMap((entry) => {\n const comma = entry.indexOf(',');\n if (comma <= 0) return [];\n return entry.slice(0, comma) === 'v1' ? [entry.slice(comma + 1)] : [];\n });\n if (signatures.length === 0) {\n throw new OnflaySignatureError(\n 'malformed_signature',\n 'Could not parse webhook-signature header (expected `v1,<base64>`).',\n );\n }\n assertWithinTolerance(timestamp, options);\n const expected = Buffer.from(\n createHmac('sha256', standardWebhookKey(options.secret))\n .update(`${id}.${timestamp}.${rawBody}`, 'utf8')\n .digest('base64'),\n 'utf8',\n );\n if (!signatures.some((sig) => safeEqual(sig, expected))) {\n throw new OnflaySignatureError(\n 'invalid_signature',\n 'Webhook signature did not match. Check that you are using the raw body and the correct endpoint secret.',\n );\n }\n return { event: parseBody<TEvent>(rawBody), rawBody, timestamp, scheme: 'standard', webhookId: id };\n}\n\nfunction verifyLegacy<TEvent>(\n rawBody: string,\n signatureHeader: string | string[] | null | undefined,\n options: VerifyWebhookOptions,\n): VerifiedWebhook<TEvent> {\n const headerValue = Array.isArray(signatureHeader)\n ? signatureHeader[0]\n : signatureHeader;\n if (!headerValue) {\n throw new OnflaySignatureError(\n 'missing_signature',\n 'Missing X-Onflay-Signature header.',\n );\n }\n const parsed = parseSignatureHeader(headerValue);\n if (!parsed) {\n throw new OnflaySignatureError(\n 'malformed_signature',\n 'Could not parse signature header (expected `t=<unix>,v1=<hex>`).',\n );\n }\n const { timestamp, signatures } = parsed;\n assertWithinTolerance(timestamp, options);\n const expected = createHmac('sha256', options.secret)\n .update(`${timestamp}.${rawBody}`, 'utf8')\n .digest('hex');\n const expectedBuf = Buffer.from(expected, 'utf8');\n const ok = signatures.some((sig) => safeEqual(sig, expectedBuf));\n if (!ok) {\n throw new OnflaySignatureError(\n 'invalid_signature',\n 'Webhook signature did not match. Check that you are using the raw body and the correct endpoint secret.',\n );\n }\n return { event: parseBody<TEvent>(rawBody), rawBody, timestamp, scheme: 'legacy' };\n}\n\nfunction assertInputs(rawBody: string, options: VerifyWebhookOptions, fn: string): void {\n if (!options?.secret || typeof options.secret !== 'string') {\n throw new OnflaySignatureError(\n 'missing_signature',\n 'A signing secret is required to verify Onflay webhooks.',\n );\n }\n if (typeof rawBody !== 'string' || rawBody.length === 0) {\n throw new OnflaySignatureError(\n 'missing_payload',\n `${fn}: rawBody must be the raw request bytes as a string.`,\n );\n }\n}\n\nfunction assertWithinTolerance(timestamp: number, options: VerifyWebhookOptions): void {\n const tolerance = options.toleranceSeconds ?? DEFAULT_REPLAY_TOLERANCE_SECONDS;\n if (tolerance <= 0) return;\n const now = (options.now ?? (() => new Date()))();\n const ageSeconds = Math.abs(Math.floor(now.getTime() / 1000) - timestamp);\n if (ageSeconds > tolerance) {\n throw new OnflaySignatureError(\n 'expired_signature',\n `Webhook is outside the replay tolerance (${ageSeconds}s > ${tolerance}s).`,\n );\n }\n}\n\nfunction parseBody<TEvent>(rawBody: string): TEvent {\n try {\n return JSON.parse(rawBody) as TEvent;\n } catch {\n throw new OnflaySignatureError(\n 'missing_payload',\n 'Webhook signature was valid but body is not parseable JSON.',\n );\n }\n}\n\nfunction standardWebhookKey(secret: string): Buffer {\n const encoded = secret.startsWith('whsec_') ? secret.slice('whsec_'.length) : secret;\n return Buffer.from(encoded, 'base64');\n}\n\nfunction readHeader(headers: WebhookHeaders, name: string): string | undefined {\n if (typeof (headers as { get?: unknown }).get === 'function') {\n const value = (headers as { get(name: string): string | null }).get(name);\n return value ?? undefined;\n }\n const record = headers as Record<string, string | string[] | null | undefined>;\n const lower = name.toLowerCase();\n const key = Object.keys(record).find((k) => k.toLowerCase() === lower);\n if (key === undefined) return undefined;\n const value = record[key];\n const first = Array.isArray(value) ? value[0] : value;\n return first ?? undefined;\n}\n\nfunction parseSignatureHeader(\n value: string,\n): { timestamp: number; signatures: string[] } | null {\n const parts = value.split(',').map((part) => part.trim()).filter(Boolean);\n let timestamp: number | null = null;\n const signatures: string[] = [];\n for (const part of parts) {\n const idx = part.indexOf('=');\n if (idx <= 0) continue;\n const key = part.slice(0, idx);\n const val = part.slice(idx + 1);\n if (key === 't') {\n const ts = Number(val);\n if (Number.isInteger(ts) && ts > 0) timestamp = ts;\n } else if (key === 'v1') {\n signatures.push(val);\n }\n }\n if (timestamp === null || signatures.length === 0) return null;\n return { timestamp, signatures };\n}\n\nfunction safeEqual(actual: string, expected: Buffer): boolean {\n if (actual.length !== expected.length) return false;\n const actualBuf = Buffer.from(actual, 'utf8');\n if (actualBuf.length !== expected.length) return false;\n return timingSafeEqual(actualBuf, expected);\n}\n"],"mappings":";AAAA,SAAS,YAAY,uBAAuB;AAErC,IAAM,0BAA0B;AAChC,IAAM,6BAA6B;AACnC,IAAM,oCAAoC;AAC1C,IAAM,oCAAoC;AAC1C,IAAM,mCAAmC;AAWzC,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9B;AAAA,EAOhB,YACE,MACA,SACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;AA2CO,SAAS,uBACd,SACA,0BACA,SACyB;AACzB,eAAa,SAAS,SAAS,wBAAwB;AACvD,MACE,6BAA6B,QAC7B,6BAA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+
sandbox: "https://sandbox-api.onflay.com"
|
|
7
|
+
};
|
|
8
|
+
var DEFAULT_RETRY_CONFIG = {
|
|
9
|
+
strategy: "backoff",
|
|
10
|
+
backoff: {
|
|
11
|
+
initialInterval: 500,
|
|
12
|
+
maxInterval: 6e4,
|
|
13
|
+
exponent: 1.5,
|
|
14
|
+
maxElapsedTime: 3e5
|
|
15
|
+
},
|
|
16
|
+
retryConnectionErrors: true
|
|
17
|
+
};
|
|
18
|
+
var DEFAULT_RETRY_CODES = ["429", "5XX"];
|
|
19
|
+
|
|
20
|
+
// src/generated/version.ts
|
|
21
|
+
var PACKAGE_VERSION = "1.0.0-staging-20261206080029";
|
|
22
|
+
|
|
23
|
+
// src/lib/config.ts
|
|
24
|
+
var ServerProduction = "production";
|
|
25
|
+
var ServerSandbox = "sandbox";
|
|
26
|
+
var ServerList = SERVER_LIST;
|
|
27
|
+
function serverURLFromOptions(options, bearerHint) {
|
|
28
|
+
let serverURL = options.serverURL;
|
|
29
|
+
if (!serverURL) {
|
|
30
|
+
const server = options.server ?? inferServerFromKey(bearerHint);
|
|
31
|
+
if (!(server in ServerList)) {
|
|
32
|
+
throw new Error(`Invalid server: ${String(server)}`);
|
|
33
|
+
}
|
|
34
|
+
serverURL = ServerList[server] || "";
|
|
35
|
+
}
|
|
36
|
+
const u = new URL(serverURL);
|
|
37
|
+
return u;
|
|
38
|
+
}
|
|
39
|
+
function inferServerFromKey(key) {
|
|
40
|
+
if (key && (key.startsWith("sk_test_") || key.startsWith("pk_test_"))) return ServerSandbox;
|
|
41
|
+
return ServerProduction;
|
|
42
|
+
}
|
|
43
|
+
var SDK_METADATA = {
|
|
44
|
+
language: "typescript",
|
|
45
|
+
openapiDocVersion: SPEC_VERSION,
|
|
46
|
+
sdkVersion: PACKAGE_VERSION,
|
|
47
|
+
genVersion: GENERATOR,
|
|
48
|
+
userAgent: `onflay-node/${PACKAGE_VERSION} (typescript; api ${SPEC_VERSION})`
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export {
|
|
52
|
+
DEFAULT_RETRY_CONFIG,
|
|
53
|
+
DEFAULT_RETRY_CODES,
|
|
54
|
+
ServerProduction,
|
|
55
|
+
ServerSandbox,
|
|
56
|
+
ServerList,
|
|
57
|
+
serverURLFromOptions,
|
|
58
|
+
SDK_METADATA
|
|
59
|
+
};
|
|
60
|
+
//# sourceMappingURL=chunk-A3TRCKHK.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/generated/spec.ts","../src/generated/version.ts","../src/lib/config.ts"],"sourcesContent":["// This file is generated by scripts/generate.mjs from apps/docs/api-reference/openapi.json. Do not edit.\nimport type { RetryConfig } from '../lib/retries';\n\n/** `info.version` of the spec: the API version this SDK targets (`X-Onflay-Api-Version`). */\nexport const SPEC_VERSION = '2026-01-01';\n\n/** Generator of the low-level layer. */\nexport const GENERATOR = '@hey-api/openapi-ts@0.99.0';\n\n/** `servers`, by `x-speakeasy-server-id`. */\nexport const SERVER_LIST = {\n production: 'https://api.onflay.com',\n sandbox: 'https://sandbox-api.onflay.com',\n} as const;\n\n/** Default retry strategy (`x-speakeasy-retries`). */\nexport const DEFAULT_RETRY_CONFIG: RetryConfig = {\n strategy: 'backoff',\n backoff: {\n initialInterval: 500,\n maxInterval: 60000,\n exponent: 1.5,\n maxElapsedTime: 300000,\n },\n retryConnectionErrors: true,\n};\n\n/** Status codes retried by default (`x-speakeasy-retries.statusCodes`). */\nexport const DEFAULT_RETRY_CODES: string[] = ['429', '5XX'];\n","// Generated by scripts/gen-version.mjs from package.json. Do not edit.\nexport const PACKAGE_VERSION = '1.0.0-staging-20261206080029';\n","import { GENERATOR, SPEC_VERSION, SERVER_LIST } from '../generated/spec';\nimport { PACKAGE_VERSION } from '../generated/version';\nimport type { HTTPClient } from './http';\nimport type { Logger } from './logger';\nimport type { RetryConfig } from './retries';\n\n/** Server id of the live API (`sk_live_*` keys). */\nexport const ServerProduction = 'production';\n/** Server id of the sandbox API (`sk_test_*` keys). */\nexport const ServerSandbox = 'sandbox';\n\n/** Contains the list of servers available to the SDK, by server id (`x-speakeasy-server-id`). */\nexport const ServerList = SERVER_LIST;\n\nexport type SDKOptions = {\n /**\n * Secret API key (`sk_live_*` / `sk_test_*`), sent as a Bearer token. A function is\n * called before every request. Defaults to the `ONFLAY_BEARER` environment variable,\n * then `ONFLAY_SECRET_KEY`.\n */\n bearer?: string | (() => Promise<string>) | undefined;\n\n httpClient?: HTTPClient;\n /**\n * Allows overriding the default server used by the SDK. When neither `server` nor\n * `serverURL` is set, `sk_test_*` / `pk_test_*` keys use `sandbox` and every other\n * key uses `production`.\n */\n server?: keyof typeof ServerList | undefined;\n /** Allows overriding the default server URL used by the SDK. */\n serverURL?: string | undefined;\n /**\n * Value of the `X-Onflay-Api-Version` header. Defaults to the API version this SDK\n * was generated from (the spec's `info.version`). Set to `null` to omit the header\n * and get the account's default version.\n */\n apiVersion?: string | null | undefined;\n /** Allows overriding the default user agent used by the SDK. */\n userAgent?: string | undefined;\n /** Allows overriding the default retry config used by the SDK. */\n retryConfig?: RetryConfig;\n /** Per-attempt timeout in milliseconds. `-1` (default) disables it. */\n timeoutMs?: number;\n debugLogger?: Logger;\n};\n\nexport function serverURLFromOptions(options: SDKOptions, bearerHint?: string): URL | null {\n let serverURL = options.serverURL;\n if (!serverURL) {\n const server = options.server ?? inferServerFromKey(bearerHint);\n if (!(server in ServerList)) {\n throw new Error(`Invalid server: ${String(server)}`);\n }\n serverURL = ServerList[server as keyof typeof ServerList] || '';\n }\n const u = new URL(serverURL);\n return u;\n}\n\nfunction inferServerFromKey(key: string | undefined): keyof typeof ServerList {\n if (key && (key.startsWith('sk_test_') || key.startsWith('pk_test_'))) return ServerSandbox;\n return ServerProduction;\n}\n\nexport const SDK_METADATA = {\n language: 'typescript',\n openapiDocVersion: SPEC_VERSION,\n sdkVersion: PACKAGE_VERSION,\n genVersion: GENERATOR,\n userAgent: `onflay-node/${PACKAGE_VERSION} (typescript; api ${SPEC_VERSION})`,\n} as const;\n"],"mappings":";AAIO,IAAM,eAAe;AAGrB,IAAM,YAAY;AAGlB,IAAM,cAAc;AAAA,EACzB,YAAY;AAAA,EACZ,SAAS;AACX;AAGO,IAAM,uBAAoC;AAAA,EAC/C,UAAU;AAAA,EACV,SAAS;AAAA,IACP,iBAAiB;AAAA,IACjB,aAAa;AAAA,IACb,UAAU;AAAA,IACV,gBAAgB;AAAA,EAClB;AAAA,EACA,uBAAuB;AACzB;AAGO,IAAM,sBAAgC,CAAC,OAAO,KAAK;;;AC3BnD,IAAM,kBAAkB;;;ACMxB,IAAM,mBAAmB;AAEzB,IAAM,gBAAgB;AAGtB,IAAM,aAAa;AAkCnB,SAAS,qBAAqB,SAAqB,YAAiC;AACzF,MAAI,YAAY,QAAQ;AACxB,MAAI,CAAC,WAAW;AACd,UAAM,SAAS,QAAQ,UAAU,mBAAmB,UAAU;AAC9D,QAAI,EAAE,UAAU,aAAa;AAC3B,YAAM,IAAI,MAAM,mBAAmB,OAAO,MAAM,CAAC,EAAE;AAAA,IACrD;AACA,gBAAY,WAAW,MAAiC,KAAK;AAAA,EAC/D;AACA,QAAM,IAAI,IAAI,IAAI,SAAS;AAC3B,SAAO;AACT;AAEA,SAAS,mBAAmB,KAAkD;AAC5E,MAAI,QAAQ,IAAI,WAAW,UAAU,KAAK,IAAI,WAAW,UAAU,GAAI,QAAO;AAC9E,SAAO;AACT;AAEO,IAAM,eAAe;AAAA,EAC1B,UAAU;AAAA,EACV,mBAAmB;AAAA,EACnB,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,WAAW,eAAe,eAAe,qBAAqB,YAAY;AAC5E;","names":[]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
var _chunkI2IVHBFAjs = require('./chunk-I2IVHBFA.js');
|
|
5
|
+
|
|
6
|
+
// src/webhooks/adapters/express.ts
|
|
7
|
+
function verifyExpressWebhook(req, options) {
|
|
8
|
+
const raw = readRawBody(req);
|
|
9
|
+
return _chunkI2IVHBFAjs.verifyWebhookSignature.call(void 0, raw, req.headers, options);
|
|
10
|
+
}
|
|
11
|
+
function createExpressWebhookHandler(opts) {
|
|
12
|
+
return async function onflayWebhookHandler(req, res, next) {
|
|
13
|
+
try {
|
|
14
|
+
const verified = verifyExpressWebhook(req, opts);
|
|
15
|
+
await opts.onEvent(verified.event, verified);
|
|
16
|
+
res.status(200).send("ok");
|
|
17
|
+
} catch (err) {
|
|
18
|
+
_optionalChain([opts, 'access', _ => _.onError, 'optionalCall', _2 => _2(err)]);
|
|
19
|
+
if (err instanceof _chunkI2IVHBFAjs.OnflaySignatureError) {
|
|
20
|
+
res.status(400).json({ error: { type: "invalid_request", code: err.code, message: err.message } });
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
if (next) {
|
|
24
|
+
next(err);
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
res.status(500).json({ error: { type: "api_error", code: "handler_failed" } });
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function readRawBody(req) {
|
|
32
|
+
if (req.rawBody) {
|
|
33
|
+
return typeof req.rawBody === "string" ? req.rawBody : req.rawBody.toString("utf8");
|
|
34
|
+
}
|
|
35
|
+
if (Buffer.isBuffer(req.body)) return req.body.toString("utf8");
|
|
36
|
+
if (typeof req.body === "string") return req.body;
|
|
37
|
+
throw new (0, _chunkI2IVHBFAjs.OnflaySignatureError)(
|
|
38
|
+
"missing_payload",
|
|
39
|
+
'Express adapter requires the raw request body. Mount with `express.raw({ type: "*" })` ahead of the handler.'
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
exports.verifyExpressWebhook = verifyExpressWebhook; exports.createExpressWebhookHandler = createExpressWebhookHandler;
|
|
47
|
+
//# sourceMappingURL=chunk-AFAU2FH2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/onflay/onflay/sdks/node/dist/chunk-AFAU2FH2.js","../src/webhooks/adapters/express.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,sDAA4B;AAC5B;AACA;ACuBO,SAAS,oBAAA,CACd,GAAA,EACA,OAAA,EACyB;AACzB,EAAA,MAAM,IAAA,EAAM,WAAA,CAAY,GAAG,CAAA;AAG3B,EAAA,OAAO,qDAAA,GAA+B,EAAK,GAAA,CAAI,OAAA,EAAS,OAAO,CAAA;AACjE;AAmBO,SAAS,2BAAA,CAA4B,IAAA,EAA6B;AACvE,EAAA,OAAO,MAAA,SAAe,oBAAA,CACpB,GAAA,EACA,GAAA,EACA,IAAA,EACe;AACf,IAAA,IAAI;AACF,MAAA,MAAM,SAAA,EAAW,oBAAA,CAAkC,GAAA,EAAK,IAAI,CAAA;AAC5D,MAAA,MAAM,IAAA,CAAK,OAAA,CAAQ,QAAA,CAAS,KAAA,EAAO,QAAQ,CAAA;AAC3C,MAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK,IAAI,CAAA;AAAA,IAC3B,EAAA,MAAA,CAAS,GAAA,EAAK;AACZ,sBAAA,IAAA,mBAAK,OAAA,0BAAA,CAAU,GAAY,GAAA;AAC3B,MAAA,GAAA,CAAI,IAAA,WAAe,qCAAA,EAAsB;AACvC,QAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK,EAAE,KAAA,EAAO,EAAE,IAAA,EAAM,iBAAA,EAAmB,IAAA,EAAM,GAAA,CAAI,IAAA,EAAM,OAAA,EAAS,GAAA,CAAI,QAAQ,EAAE,CAAC,CAAA;AACjG,QAAA,MAAA;AAAA,MACF;AACA,MAAA,GAAA,CAAI,IAAA,EAAM;AACR,QAAA,IAAA,CAAK,GAAG,CAAA;AACR,QAAA,MAAA;AAAA,MACF;AACA,MAAA,GAAA,CAAI,MAAA,CAAO,GAAG,CAAA,CAAE,IAAA,CAAK,EAAE,KAAA,EAAO,EAAE,IAAA,EAAM,WAAA,EAAa,IAAA,EAAM,iBAAiB,EAAE,CAAC,CAAA;AAAA,IAC/E;AAAA,EACF,CAAA;AACF;AAEA,SAAS,WAAA,CAAY,GAAA,EAAiC;AACpD,EAAA,GAAA,CAAI,GAAA,CAAI,OAAA,EAAS;AACf,IAAA,OAAO,OAAO,GAAA,CAAI,QAAA,IAAY,SAAA,EAAW,GAAA,CAAI,QAAA,EAAU,GAAA,CAAI,OAAA,CAAQ,QAAA,CAAS,MAAM,CAAA;AAAA,EACpF;AACA,EAAA,GAAA,CAAI,MAAA,CAAO,QAAA,CAAS,GAAA,CAAI,IAAI,CAAA,EAAG,OAAO,GAAA,CAAI,IAAA,CAAK,QAAA,CAAS,MAAM,CAAA;AAC9D,EAAA,GAAA,CAAI,OAAO,GAAA,CAAI,KAAA,IAAS,QAAA,EAAU,OAAO,GAAA,CAAI,IAAA;AAC7C,EAAA,MAAM,IAAI,0CAAA;AAAA,IACR,iBAAA;AAAA,IACA;AAAA,EACF,CAAA;AACF;ADjDA;AACA;AACE;AACA;AACF,uHAAC","file":"/home/runner/work/onflay/onflay/sdks/node/dist/chunk-AFAU2FH2.js","sourcesContent":[null,"import type { OnflayEvent } from '../events';\nimport {\n OnflaySignatureError,\n verifyWebhookSignature,\n type VerifiedWebhook,\n type VerifyWebhookOptions,\n} from '../verify';\n\ninterface ExpressLikeRequest {\n headers: Record<string, string | string[] | undefined>;\n body: unknown;\n rawBody?: Buffer | string;\n}\n\ninterface ExpressLikeResponse {\n status(code: number): ExpressLikeResponse;\n send(body?: unknown): unknown;\n json(body: unknown): unknown;\n}\n\ntype NextFn = (err?: unknown) => void;\n\n/**\n * Verify the signature of an inbound Express request whose body has been\n * captured raw. Configure your route with `express.raw({ type: '*' })`\n * (or equivalent) so the request body remains a `Buffer`. Re-parsing\n * after `express.json()` will break the HMAC.\n */\nexport function verifyExpressWebhook<TEvent = OnflayEvent>(\n req: ExpressLikeRequest,\n options: VerifyWebhookOptions,\n): VerifiedWebhook<TEvent> {\n const raw = readRawBody(req);\n // Header lookup is case-insensitive; Standard Webhooks is tried first,\n // then the legacy X-Onflay-Signature header.\n return verifyWebhookSignature<TEvent>(raw, req.headers, options);\n}\n\ninterface ExpressHandlerOptions extends VerifyWebhookOptions {\n /** Called after successful verification with the parsed event. */\n onEvent: (event: OnflayEvent, raw: VerifiedWebhook<OnflayEvent>) => unknown | Promise<unknown>;\n /** Optional logger override; defaults to no-op. */\n onError?: (error: OnflaySignatureError | Error) => void;\n}\n\n/**\n * Higher-level helper that returns a ready-to-mount Express middleware:\n *\n * ```ts\n * app.post('/webhooks/onflay',\n * express.raw({ type: 'application/json' }),\n * createExpressWebhookHandler({ secret, onEvent: async (e) => {} }),\n * );\n * ```\n */\nexport function createExpressWebhookHandler(opts: ExpressHandlerOptions) {\n return async function onflayWebhookHandler(\n req: ExpressLikeRequest,\n res: ExpressLikeResponse,\n next?: NextFn,\n ): Promise<void> {\n try {\n const verified = verifyExpressWebhook<OnflayEvent>(req, opts);\n await opts.onEvent(verified.event, verified);\n res.status(200).send('ok');\n } catch (err) {\n opts.onError?.(err as Error);\n if (err instanceof OnflaySignatureError) {\n res.status(400).json({ error: { type: 'invalid_request', code: err.code, message: err.message } });\n return;\n }\n if (next) {\n next(err);\n return;\n }\n res.status(500).json({ error: { type: 'api_error', code: 'handler_failed' } });\n }\n };\n}\n\nfunction readRawBody(req: ExpressLikeRequest): string {\n if (req.rawBody) {\n return typeof req.rawBody === 'string' ? req.rawBody : req.rawBody.toString('utf8');\n }\n if (Buffer.isBuffer(req.body)) return req.body.toString('utf8');\n if (typeof req.body === 'string') return req.body;\n throw new OnflaySignatureError(\n 'missing_payload',\n 'Express adapter requires the raw request body. Mount with `express.raw({ type: \"*\" })` ahead of the handler.',\n );\n}\n"]}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// src/models/errors/httpclienterrors.ts
|
|
2
|
+
var HTTPClientError = class extends Error {
|
|
3
|
+
/** The underlying cause of the error. */
|
|
4
|
+
cause;
|
|
5
|
+
name = "HTTPClientError";
|
|
6
|
+
constructor(message, opts) {
|
|
7
|
+
let msg = message;
|
|
8
|
+
if (opts?.cause) msg += `: ${String(opts.cause)}`;
|
|
9
|
+
super(msg, opts);
|
|
10
|
+
this.cause = opts?.cause;
|
|
11
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
var UnexpectedClientError = class extends HTTPClientError {
|
|
15
|
+
name = "UnexpectedClientError";
|
|
16
|
+
};
|
|
17
|
+
var InvalidRequestError = class extends HTTPClientError {
|
|
18
|
+
name = "InvalidRequestError";
|
|
19
|
+
};
|
|
20
|
+
var RequestAbortedError = class extends HTTPClientError {
|
|
21
|
+
name = "RequestAbortedError";
|
|
22
|
+
};
|
|
23
|
+
var RequestTimeoutError = class extends HTTPClientError {
|
|
24
|
+
name = "RequestTimeoutError";
|
|
25
|
+
};
|
|
26
|
+
var ConnectionError = class extends HTTPClientError {
|
|
27
|
+
name = "ConnectionError";
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export {
|
|
31
|
+
HTTPClientError,
|
|
32
|
+
UnexpectedClientError,
|
|
33
|
+
InvalidRequestError,
|
|
34
|
+
RequestAbortedError,
|
|
35
|
+
RequestTimeoutError,
|
|
36
|
+
ConnectionError
|
|
37
|
+
};
|
|
38
|
+
//# sourceMappingURL=chunk-DBE2YZWE.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/models/errors/httpclienterrors.ts"],"sourcesContent":["/** Base class for failures to get a response at all (network, timeout, abort, invalid request). */\nexport class HTTPClientError extends Error {\n /** The underlying cause of the error. */\n override readonly cause: unknown;\n override name = 'HTTPClientError';\n constructor(message: string, opts?: { cause?: unknown }) {\n let msg = message;\n if (opts?.cause) msg += `: ${String(opts.cause)}`;\n super(msg, opts);\n this.cause = opts?.cause;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** An unrecognised or unexpected error occurred while sending the request. */\nexport class UnexpectedClientError extends HTTPClientError {\n override name = 'UnexpectedClientError';\n}\n\n/** The request could not be built (for example, an invalid server URL). */\nexport class InvalidRequestError extends HTTPClientError {\n override name = 'InvalidRequestError';\n}\n\n/** The request was aborted by the caller (`signal`). */\nexport class RequestAbortedError extends HTTPClientError {\n override readonly name = 'RequestAbortedError';\n}\n\n/** The request took longer than `timeoutMs`. Retried when `retryConnectionErrors` is on. */\nexport class RequestTimeoutError extends HTTPClientError {\n override readonly name = 'RequestTimeoutError';\n}\n\n/** The server could not be reached (DNS, refused or reset connection, TLS). Retried when `retryConnectionErrors` is on. */\nexport class ConnectionError extends HTTPClientError {\n override readonly name = 'ConnectionError';\n}\n"],"mappings":";AACO,IAAM,kBAAN,cAA8B,MAAM;AAAA;AAAA,EAEvB;AAAA,EACT,OAAO;AAAA,EAChB,YAAY,SAAiB,MAA4B;AACvD,QAAI,MAAM;AACV,QAAI,MAAM,MAAO,QAAO,KAAK,OAAO,KAAK,KAAK,CAAC;AAC/C,UAAM,KAAK,IAAI;AACf,SAAK,QAAQ,MAAM;AACnB,WAAO,eAAe,MAAM,WAAW,SAAS;AAAA,EAClD;AACF;AAGO,IAAM,wBAAN,cAAoC,gBAAgB;AAAA,EAChD,OAAO;AAClB;AAGO,IAAM,sBAAN,cAAkC,gBAAgB;AAAA,EAC9C,OAAO;AAClB;AAGO,IAAM,sBAAN,cAAkC,gBAAgB;AAAA,EACrC,OAAO;AAC3B;AAGO,IAAM,sBAAN,cAAkC,gBAAgB;AAAA,EACrC,OAAO;AAC3B;AAGO,IAAM,kBAAN,cAA8B,gBAAgB;AAAA,EACjC,OAAO;AAC3B;","names":[]}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// src/models/errors/onflayerror.ts
|
|
2
|
+
var OnflayError = class extends Error {
|
|
3
|
+
/** HTTP status code. */
|
|
4
|
+
statusCode;
|
|
5
|
+
/** Raw response body (may be an empty string). */
|
|
6
|
+
body;
|
|
7
|
+
/** Response headers. */
|
|
8
|
+
headers;
|
|
9
|
+
/** Response `Content-Type`. */
|
|
10
|
+
contentType;
|
|
11
|
+
/** The raw `Response`. */
|
|
12
|
+
rawResponse;
|
|
13
|
+
constructor(message, httpMeta) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.statusCode = httpMeta.response.status;
|
|
16
|
+
this.body = httpMeta.body;
|
|
17
|
+
this.headers = httpMeta.response.headers;
|
|
18
|
+
this.contentType = httpMeta.response.headers.get("content-type") || "";
|
|
19
|
+
this.rawResponse = httpMeta.response;
|
|
20
|
+
this.name = "OnflayError";
|
|
21
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
// src/models/errors/onflaydefaulterror.ts
|
|
26
|
+
var OnflayDefaultError = class extends OnflayError {
|
|
27
|
+
constructor(message, httpMeta) {
|
|
28
|
+
if (message) message += ": ";
|
|
29
|
+
message += `Status ${httpMeta.response.status}`;
|
|
30
|
+
const contentType = httpMeta.response.headers.get("content-type") || '""';
|
|
31
|
+
if (contentType !== '""') message += ` Content-Type ${contentType.includes(" ") ? `"${contentType}"` : contentType}`;
|
|
32
|
+
const body = httpMeta.body || '""';
|
|
33
|
+
message += body.length > 100 ? "\n" : " ";
|
|
34
|
+
message += `Body ${body}`;
|
|
35
|
+
message = message.trim();
|
|
36
|
+
super(message, httpMeta);
|
|
37
|
+
this.name = "OnflayDefaultError";
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
// src/models/errors/apierror.ts
|
|
42
|
+
var ApiError = class extends OnflayError {
|
|
43
|
+
/** The envelope's `error` object (camelCase). */
|
|
44
|
+
error;
|
|
45
|
+
/** The original data that was passed to this error instance. */
|
|
46
|
+
data$;
|
|
47
|
+
constructor(err, httpMeta) {
|
|
48
|
+
const message = err.error?.message || `API error occurred: ${JSON.stringify(err)}`;
|
|
49
|
+
super(message, httpMeta);
|
|
50
|
+
this.data$ = err;
|
|
51
|
+
this.error = err.error;
|
|
52
|
+
this.name = "ApiError";
|
|
53
|
+
}
|
|
54
|
+
/** `error.type`. */
|
|
55
|
+
get type() {
|
|
56
|
+
return this.error.type;
|
|
57
|
+
}
|
|
58
|
+
/** `error.code`, e.g. `not_found`. */
|
|
59
|
+
get code() {
|
|
60
|
+
return this.error.code;
|
|
61
|
+
}
|
|
62
|
+
/** `error.hint`: how to fix the request. */
|
|
63
|
+
get hint() {
|
|
64
|
+
return this.error.hint;
|
|
65
|
+
}
|
|
66
|
+
/** `error.docUrl`: the code's reference page. */
|
|
67
|
+
get docUrl() {
|
|
68
|
+
return this.error.docUrl;
|
|
69
|
+
}
|
|
70
|
+
/** `error.param`. */
|
|
71
|
+
get param() {
|
|
72
|
+
return this.error.param;
|
|
73
|
+
}
|
|
74
|
+
/** `error.requestId` (quote it to support). */
|
|
75
|
+
get requestId() {
|
|
76
|
+
return this.error.requestId;
|
|
77
|
+
}
|
|
78
|
+
/** `error.errors`: validation errors, one per failed rule. */
|
|
79
|
+
get errors() {
|
|
80
|
+
return this.error.errors;
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
function parseApiError(raw) {
|
|
84
|
+
if (!raw || typeof raw !== "object") return null;
|
|
85
|
+
const inner = raw.error;
|
|
86
|
+
if (!inner || typeof inner !== "object") return null;
|
|
87
|
+
const e = inner;
|
|
88
|
+
if (typeof e.code !== "string" || typeof e.message !== "string") return null;
|
|
89
|
+
const requestId = e.requestId ?? e.request_id;
|
|
90
|
+
const body = {
|
|
91
|
+
type: e.type,
|
|
92
|
+
code: e.code,
|
|
93
|
+
message: e.message,
|
|
94
|
+
requestId: typeof requestId === "string" ? requestId : ""
|
|
95
|
+
};
|
|
96
|
+
if (typeof e.hint === "string") body.hint = e.hint;
|
|
97
|
+
if (typeof e.doc_url === "string") body.docUrl = e.doc_url;
|
|
98
|
+
if (typeof e.param === "string") body.param = e.param;
|
|
99
|
+
if (typeof e.field === "string") body.field = e.field;
|
|
100
|
+
if (Array.isArray(e.errors)) body.errors = e.errors;
|
|
101
|
+
return { error: body };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// src/models/errors/responsevalidationerror.ts
|
|
105
|
+
var ResponseValidationError = class extends OnflayError {
|
|
106
|
+
/** The raw value that failed validation. */
|
|
107
|
+
rawValue;
|
|
108
|
+
/** The raw message that failed validation. */
|
|
109
|
+
rawMessage;
|
|
110
|
+
constructor(message, extra) {
|
|
111
|
+
super(message, extra);
|
|
112
|
+
this.name = "ResponseValidationError";
|
|
113
|
+
this.rawValue = extra.rawValue;
|
|
114
|
+
this.rawMessage = extra.rawMessage;
|
|
115
|
+
if (extra.cause !== void 0) {
|
|
116
|
+
Object.defineProperty(this, "cause", { value: extra.cause, enumerable: false, writable: true, configurable: true });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** A human-readable version of the error. */
|
|
120
|
+
pretty() {
|
|
121
|
+
return `${this.message}
|
|
122
|
+
${String(this.rawMessage)}`;
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
// src/models/errors/sdkvalidationerror.ts
|
|
127
|
+
var SDKValidationError = class extends Error {
|
|
128
|
+
/** The raw value that failed validation. */
|
|
129
|
+
rawValue;
|
|
130
|
+
/** The raw message that failed validation. */
|
|
131
|
+
rawMessage;
|
|
132
|
+
constructor(message, cause, rawValue) {
|
|
133
|
+
super(`${message}: ${String(cause)}`);
|
|
134
|
+
this.name = "SDKValidationError";
|
|
135
|
+
this.cause = cause;
|
|
136
|
+
this.rawValue = rawValue;
|
|
137
|
+
this.rawMessage = message;
|
|
138
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
139
|
+
}
|
|
140
|
+
/** A human-readable version of the error. */
|
|
141
|
+
pretty() {
|
|
142
|
+
return `${this.message}`;
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
export {
|
|
147
|
+
OnflayError,
|
|
148
|
+
OnflayDefaultError,
|
|
149
|
+
ApiError,
|
|
150
|
+
parseApiError,
|
|
151
|
+
ResponseValidationError,
|
|
152
|
+
SDKValidationError
|
|
153
|
+
};
|
|
154
|
+
//# sourceMappingURL=chunk-EOHFYWFQ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/models/errors/onflayerror.ts","../src/models/errors/onflaydefaulterror.ts","../src/models/errors/apierror.ts","../src/models/errors/responsevalidationerror.ts","../src/models/errors/sdkvalidationerror.ts"],"sourcesContent":["/** HTTP metadata attached to every error built from an API response. */\nexport type HTTPMeta = {\n response: Response;\n request: Request;\n /** Raw response body (may be an empty string). */\n body: string;\n};\n\n/**\n * Base class of every error built from an HTTP response (Speakeasy's `{Sdk}Error`).\n * Catch it to handle any non-2xx answer from the API.\n */\nexport class OnflayError extends Error {\n /** HTTP status code. */\n public readonly statusCode: number;\n /** Raw response body (may be an empty string). */\n public readonly body: string;\n /** Response headers. */\n public readonly headers: Headers;\n /** Response `Content-Type`. */\n public readonly contentType: string;\n /** The raw `Response`. */\n public readonly rawResponse: Response;\n\n constructor(message: string, httpMeta: HTTPMeta) {\n super(message);\n this.statusCode = httpMeta.response.status;\n this.body = httpMeta.body;\n this.headers = httpMeta.response.headers;\n this.contentType = httpMeta.response.headers.get('content-type') || '';\n this.rawResponse = httpMeta.response;\n this.name = 'OnflayError';\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { OnflayError, type HTTPMeta } from './onflayerror';\n\n/**\n * Fallback for an error response that does not match a documented error shape (a status\n * code the operation does not list, or a body that is not the Onflay error envelope,\n * e.g. an HTML 502 from a proxy). Speakeasy's default error class.\n */\nexport class OnflayDefaultError extends OnflayError {\n constructor(message: string, httpMeta: HTTPMeta) {\n if (message) message += ': ';\n message += `Status ${httpMeta.response.status}`;\n const contentType = httpMeta.response.headers.get('content-type') || '\"\"';\n if (contentType !== '\"\"') message += ` Content-Type ${contentType.includes(' ') ? `\"${contentType}\"` : contentType}`;\n const body = httpMeta.body || '\"\"';\n message += body.length > 100 ? '\\n' : ' ';\n message += `Body ${body}`;\n message = message.trim();\n super(message, httpMeta);\n this.name = 'OnflayDefaultError';\n }\n}\n","import type { ApiErrorDetail as RawErrorDetail, ApiFieldError as RawFieldError } from '../../generated/hey-api/types.gen';\nimport { OnflayError, type HTTPMeta } from './onflayerror';\n\n/** One failed validation rule (`error.errors[]`). */\nexport type ApiFieldError = RawFieldError;\n\n/**\n * The `error` object of the Onflay error envelope, with camelCase names\n * (`doc_url` → `docUrl`, `request_id` folded into `requestId`), as a Speakeasy model.\n */\nexport type ApiErrorDetail = {\n /** Error class: `authentication_error`, `invalid_request`, `api_error`, `rate_limit_error`, `idempotency_error`. */\n type: RawErrorDetail['type'];\n /** Stable machine-readable code, documented at https://docs.onflay.com/errors. */\n code: string;\n message: string;\n /** One sentence saying how to fix the request. */\n hint?: string | undefined;\n /** Reference page for `code`. */\n docUrl?: string | undefined;\n /** Request field the error refers to (first invalid field for validation errors). */\n param?: string | undefined;\n /** Alias of `param`. */\n field?: string | undefined;\n /** Validation errors only: one entry per failed rule. */\n errors?: ApiFieldError[] | undefined;\n requestId: string;\n};\n\n/** The error envelope as sent by the API: `{ error: { type, code, message, … } }`. */\nexport type ApiErrorData = {\n error: ApiErrorDetail;\n};\n\n/**\n * An error response in the Onflay error envelope (every documented 4XX/5XX). The class is\n * named after the spec's `ApiError` schema, as Speakeasy names error classes.\n *\n * ```ts\n * import { ApiError } from '@onflay/node/models/errors';\n *\n * try {\n * await onflay.customers.retrieve({ id: 'cus_missing' });\n * } catch (err) {\n * if (err instanceof ApiError) {\n * console.log(err.statusCode, err.error.code, err.error.hint, err.error.requestId);\n * }\n * }\n * ```\n *\n * The envelope members are also available directly on the error (`err.code`, `err.hint`, …).\n */\nexport class ApiError extends OnflayError {\n /** The envelope's `error` object (camelCase). */\n public readonly error: ApiErrorDetail;\n /** The original data that was passed to this error instance. */\n public readonly data$: ApiErrorData;\n\n constructor(err: ApiErrorData, httpMeta: HTTPMeta) {\n const message = err.error?.message || `API error occurred: ${JSON.stringify(err)}`;\n super(message, httpMeta);\n this.data$ = err;\n this.error = err.error;\n this.name = 'ApiError';\n }\n\n /** `error.type`. */\n get type(): ApiErrorDetail['type'] {\n return this.error.type;\n }\n /** `error.code`, e.g. `not_found`. */\n get code(): string {\n return this.error.code;\n }\n /** `error.hint`: how to fix the request. */\n get hint(): string | undefined {\n return this.error.hint;\n }\n /** `error.docUrl`: the code's reference page. */\n get docUrl(): string | undefined {\n return this.error.docUrl;\n }\n /** `error.param`. */\n get param(): string | undefined {\n return this.error.param;\n }\n /** `error.requestId` (quote it to support). */\n get requestId(): string {\n return this.error.requestId;\n }\n /** `error.errors`: validation errors, one per failed rule. */\n get errors(): ApiFieldError[] | undefined {\n return this.error.errors;\n }\n}\n\n/** Parses an error body; returns `null` unless it is the Onflay error envelope. */\nexport function parseApiError(raw: unknown): ApiErrorData | null {\n if (!raw || typeof raw !== 'object') return null;\n const inner = (raw as { error?: unknown }).error;\n if (!inner || typeof inner !== 'object') return null;\n const e = inner as Partial<RawErrorDetail> & Record<string, unknown>;\n if (typeof e.code !== 'string' || typeof e.message !== 'string') return null;\n const requestId = e.requestId ?? e.request_id;\n const body: ApiErrorDetail = {\n type: e.type as RawErrorDetail['type'],\n code: e.code,\n message: e.message,\n requestId: typeof requestId === 'string' ? requestId : '',\n };\n if (typeof e.hint === 'string') body.hint = e.hint;\n if (typeof e.doc_url === 'string') body.docUrl = e.doc_url;\n if (typeof e.param === 'string') body.param = e.param;\n if (typeof e.field === 'string') body.field = e.field;\n if (Array.isArray(e.errors)) body.errors = e.errors as ApiFieldError[];\n return { error: body };\n}\n","import { OnflayError, type HTTPMeta } from './onflayerror';\n\n/** A 2XX response whose body could not be read as the documented type (e.g. not JSON). */\nexport class ResponseValidationError extends OnflayError {\n /** The raw value that failed validation. */\n public readonly rawValue: unknown;\n /** The raw message that failed validation. */\n public readonly rawMessage: unknown;\n\n constructor(message: string, extra: HTTPMeta & { rawValue: unknown; rawMessage: unknown; cause?: unknown }) {\n super(message, extra);\n this.name = 'ResponseValidationError';\n this.rawValue = extra.rawValue;\n this.rawMessage = extra.rawMessage;\n if (extra.cause !== undefined) {\n Object.defineProperty(this, 'cause', { value: extra.cause, enumerable: false, writable: true, configurable: true });\n }\n }\n\n /** A human-readable version of the error. */\n pretty(): string {\n return `${this.message}\\n${String(this.rawMessage)}`;\n }\n}\n","/** Input that the SDK rejects before sending (e.g. a missing required argument). */\nexport class SDKValidationError extends Error {\n /** The raw value that failed validation. */\n public readonly rawValue: unknown;\n /** The raw message that failed validation. */\n public readonly rawMessage: unknown;\n\n constructor(message: string, cause: unknown, rawValue: unknown) {\n super(`${message}: ${String(cause)}`);\n this.name = 'SDKValidationError';\n this.cause = cause;\n this.rawValue = rawValue;\n this.rawMessage = message;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n /** A human-readable version of the error. */\n pretty(): string {\n return `${this.message}`;\n }\n}\n"],"mappings":";AAYO,IAAM,cAAN,cAA0B,MAAM;AAAA;AAAA,EAErB;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EAEhB,YAAY,SAAiB,UAAoB;AAC/C,UAAM,OAAO;AACb,SAAK,aAAa,SAAS,SAAS;AACpC,SAAK,OAAO,SAAS;AACrB,SAAK,UAAU,SAAS,SAAS;AACjC,SAAK,cAAc,SAAS,SAAS,QAAQ,IAAI,cA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