@rearray/sdk 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 reArray
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,105 @@
1
+ # @rearray/sdk
2
+
3
+ TypeScript SDK for the [reArray Integration API](https://rearray.ai). Universal runtime (Node 18+, Deno, Bun, browsers, edge) with zero runtime dependencies.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @rearray/sdk
9
+ ```
10
+
11
+ ## Quickstart
12
+
13
+ ```typescript
14
+ import { RearrayClient } from '@rearray/sdk';
15
+
16
+ const client = new RearrayClient({
17
+ apiKey: process.env.REARRAY_API_KEY!, // ra_live_...
18
+ });
19
+
20
+ // Queue an execution
21
+ const created = await client.createExecution({
22
+ agent_id: '00000000-0000-4000-8000-000000000001',
23
+ task_id: '00000000-0000-4000-8000-000000000002',
24
+ params: { order_id: 'ORD-123' },
25
+ reference: 'ORD-123',
26
+ callback_url: 'https://your-app.example.com/webhooks/rearray',
27
+ });
28
+
29
+ console.log(created.execution_id, created.status);
30
+
31
+ // Iterate all executions (follows next_cursor)
32
+ for await (const execution of client.iterateExecutions({ status: 'completed' })) {
33
+ console.log(execution.id, execution.status);
34
+ }
35
+ ```
36
+
37
+ ## Webhook verification
38
+
39
+ Webhook callbacks are signed with a **separate webhook secret** (not your API key). Your workspace administrator provides this signing secret for your reArray deployment.
40
+
41
+ ```typescript
42
+ import { verifyWebhookSignature } from '@rearray/sdk';
43
+
44
+ export async function POST(request: Request) {
45
+ const payload = await request.text();
46
+ const timestamp = request.headers.get('x-webhook-timestamp') ?? '';
47
+ const signature = request.headers.get('x-webhook-signature') ?? '';
48
+
49
+ const valid = await verifyWebhookSignature({
50
+ payload,
51
+ timestamp,
52
+ signature,
53
+ secret: process.env.REARRAY_WEBHOOK_SECRET!,
54
+ });
55
+
56
+ if (!valid) {
57
+ return new Response('Invalid signature', { status: 401 });
58
+ }
59
+
60
+ // process JSON.parse(payload)
61
+ return new Response('OK');
62
+ }
63
+ ```
64
+
65
+ Signing scheme: `HMAC-SHA256(body + timestamp, webhook_secret)` as a hex digest in `X-Webhook-Signature`.
66
+
67
+ ## Error handling
68
+
69
+ API errors use a stable `{ error: { code, message, details?, request_id? } }` envelope. Catch `RearrayApiError` and branch on `code`:
70
+
71
+ ```typescript
72
+ import { RearrayApiError, isRearrayApiError } from '@rearray/sdk';
73
+
74
+ try {
75
+ await client.getExecution('not-a-uuid');
76
+ } catch (error) {
77
+ if (isRearrayApiError(error)) {
78
+ console.error(error.code, error.message, error.requestId);
79
+ }
80
+ }
81
+ ```
82
+
83
+ Stable error codes include: `unauthorized`, `forbidden`, `rate_limited`, `invalid_params`, `invalid_request`, `not_found`, `version_not_found`, `concurrency_limit_reached`, `idempotency_conflict`, and `internal_error`.
84
+
85
+ ## Configuration
86
+
87
+ | Option | Default | Description |
88
+ |--------|---------|-------------|
89
+ | `apiKey` | (required) | Bearer token (`ra_live_...`) |
90
+ | `baseUrl` | `https://api.rearray.ai/api/v1/integrations` | API base URL |
91
+ | `fetch` | global `fetch` | Custom fetch implementation |
92
+
93
+ ## Development
94
+
95
+ ```bash
96
+ npm install
97
+ npm run codegen # regenerate types from openapi/integration-api.json
98
+ npm run typecheck
99
+ npm run build
100
+ npm test
101
+ ```
102
+
103
+ ## License
104
+
105
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,240 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ RearrayApiError: () => RearrayApiError,
24
+ RearrayClient: () => RearrayClient,
25
+ isRearrayApiError: () => isRearrayApiError,
26
+ iterateExecutions: () => iterateExecutions,
27
+ parseErrorBody: () => parseErrorBody,
28
+ verifyWebhookSignature: () => verifyWebhookSignature
29
+ });
30
+ module.exports = __toCommonJS(index_exports);
31
+
32
+ // src/errors.ts
33
+ var RearrayApiError = class _RearrayApiError extends Error {
34
+ code;
35
+ status;
36
+ requestId;
37
+ details;
38
+ constructor(code, message, status, requestId, details) {
39
+ super(message);
40
+ this.name = "RearrayApiError";
41
+ this.code = code;
42
+ this.status = status;
43
+ this.requestId = requestId;
44
+ this.details = details;
45
+ }
46
+ static fromBody(body, status) {
47
+ const { code, message, request_id, details } = body.error;
48
+ return new _RearrayApiError(code, message, status, request_id, details);
49
+ }
50
+ };
51
+ function isRearrayApiError(error) {
52
+ return error instanceof RearrayApiError;
53
+ }
54
+ function parseErrorBody(body) {
55
+ if (body && typeof body === "object" && "error" in body && body.error && typeof body.error === "object" && "code" in body.error && "message" in body.error) {
56
+ return body;
57
+ }
58
+ return null;
59
+ }
60
+
61
+ // src/pagination.ts
62
+ async function* iterateExecutions(client, params = {}) {
63
+ let cursor = void 0;
64
+ for (; ; ) {
65
+ const page = await client.listExecutions({
66
+ ...params,
67
+ ...cursor ? { cursor } : {}
68
+ });
69
+ for (const item of page.data ?? []) {
70
+ yield item;
71
+ }
72
+ cursor = page.next_cursor;
73
+ if (!cursor) {
74
+ return;
75
+ }
76
+ }
77
+ }
78
+
79
+ // src/client.ts
80
+ var DEFAULT_BASE_URL = "https://api.rearray.ai/api/v1/integrations";
81
+ var RearrayClient = class {
82
+ apiKey;
83
+ baseUrl;
84
+ fetchFn;
85
+ constructor(options) {
86
+ this.apiKey = options.apiKey;
87
+ this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
88
+ this.fetchFn = options.fetch ?? fetch;
89
+ }
90
+ async createExecution(body, options = {}) {
91
+ const query = options.validateOnly ? "?validate_only=true" : "";
92
+ const headers = {};
93
+ if (options.idempotencyKey) {
94
+ headers["Idempotency-Key"] = options.idempotencyKey;
95
+ }
96
+ return this.request("POST", `/executions${query}`, {
97
+ body,
98
+ headers
99
+ });
100
+ }
101
+ async listExecutions(params = {}) {
102
+ const query = buildQuery(params);
103
+ return this.request("GET", `/executions${query}`);
104
+ }
105
+ async *iterateExecutions(params = {}) {
106
+ yield* iterateExecutions(this, params);
107
+ }
108
+ async getExecution(id) {
109
+ return this.request("GET", `/executions/${id}`);
110
+ }
111
+ async cancelExecution(id) {
112
+ return this.request("POST", `/executions/${id}/cancel`);
113
+ }
114
+ async getExecutionArtifacts(id) {
115
+ return this.request("GET", `/executions/${id}/artifacts`);
116
+ }
117
+ async listTasks() {
118
+ return this.request("GET", "/tasks");
119
+ }
120
+ async getTask(id) {
121
+ return this.request("GET", `/tasks/${id}`);
122
+ }
123
+ async getTaskParamsSchema(id, options = {}) {
124
+ const query = options.version ? `?${new URLSearchParams({ version: options.version }).toString()}` : "";
125
+ return this.request(
126
+ "GET",
127
+ `/tasks/${id}/params-schema${query}`
128
+ );
129
+ }
130
+ async listAgents() {
131
+ return this.request("GET", "/agents");
132
+ }
133
+ async testWebhook(callbackUrl) {
134
+ return this.request("POST", "/webhooks/test", {
135
+ body: { callback_url: callbackUrl }
136
+ });
137
+ }
138
+ async request(method, path, init = {}) {
139
+ const url = `${this.baseUrl.replace(/\/$/, "")}${path}`;
140
+ const headers = {
141
+ Authorization: `Bearer ${this.apiKey}`,
142
+ Accept: "application/json",
143
+ ...init.headers
144
+ };
145
+ const requestInit = {
146
+ method,
147
+ headers
148
+ };
149
+ if (init.body !== void 0) {
150
+ headers["Content-Type"] = "application/json";
151
+ requestInit.body = JSON.stringify(init.body);
152
+ }
153
+ const response = await this.fetchFn(url, requestInit);
154
+ const text = await response.text();
155
+ const json = text.length > 0 ? safeJsonParse(text) : null;
156
+ if (!response.ok) {
157
+ const errorBody = parseErrorBody(json);
158
+ if (errorBody) {
159
+ throw RearrayApiError.fromBody(errorBody, response.status);
160
+ }
161
+ throw new Error(
162
+ `Request failed with status ${response.status}: ${text || response.statusText}`
163
+ );
164
+ }
165
+ return json;
166
+ }
167
+ };
168
+ function buildQuery(params) {
169
+ const search = new URLSearchParams();
170
+ for (const [key, value] of Object.entries(params)) {
171
+ if (value !== void 0 && value !== null) {
172
+ search.set(key, String(value));
173
+ }
174
+ }
175
+ const qs = search.toString();
176
+ return qs ? `?${qs}` : "";
177
+ }
178
+ function safeJsonParse(text) {
179
+ try {
180
+ return JSON.parse(text);
181
+ } catch {
182
+ return text;
183
+ }
184
+ }
185
+
186
+ // src/webhooks.ts
187
+ function buildCanonicalString(payload, timestamp) {
188
+ return `${payload}${timestamp}`;
189
+ }
190
+ async function signPayload(payload, timestamp, secret) {
191
+ const enc = new TextEncoder();
192
+ const key = await crypto.subtle.importKey(
193
+ "raw",
194
+ enc.encode(secret),
195
+ { name: "HMAC", hash: "SHA-256" },
196
+ false,
197
+ ["sign"]
198
+ );
199
+ const sig = await crypto.subtle.sign(
200
+ "HMAC",
201
+ key,
202
+ enc.encode(buildCanonicalString(payload, timestamp))
203
+ );
204
+ return Array.from(new Uint8Array(sig)).map((b) => b.toString(16).padStart(2, "0")).join("");
205
+ }
206
+ function constantTimeEqual(a, b) {
207
+ if (a.length !== b.length) return false;
208
+ let diff = 0;
209
+ for (let i = 0; i < a.length; i++) {
210
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
211
+ }
212
+ return diff === 0;
213
+ }
214
+ async function verifyWebhookSignature(options) {
215
+ const {
216
+ payload,
217
+ timestamp,
218
+ signature,
219
+ secret,
220
+ toleranceSeconds = 300
221
+ } = options;
222
+ if (toleranceSeconds > 0) {
223
+ const ts = Number.parseInt(timestamp, 10);
224
+ if (!Number.isFinite(ts)) return false;
225
+ const age = Math.abs(Math.floor(Date.now() / 1e3) - ts);
226
+ if (age > toleranceSeconds) return false;
227
+ }
228
+ const expected = await signPayload(payload, timestamp, secret);
229
+ return constantTimeEqual(expected, signature);
230
+ }
231
+ // Annotate the CommonJS export names for ESM import in node:
232
+ 0 && (module.exports = {
233
+ RearrayApiError,
234
+ RearrayClient,
235
+ isRearrayApiError,
236
+ iterateExecutions,
237
+ parseErrorBody,
238
+ verifyWebhookSignature
239
+ });
240
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/pagination.ts","../src/client.ts","../src/webhooks.ts"],"sourcesContent":["export { RearrayClient } from './client.js';\nexport type {\n Agent,\n ArtifactsResponse,\n CreateExecutionOptions,\n CreateExecutionRequest,\n CreateExecutionResponse,\n Execution,\n ExecutionDetail,\n GetTaskParamsSchemaOptions,\n ListExecutionsParams,\n ListExecutionsResponse,\n ParamsSchemaResponse,\n RearrayClientOptions,\n Task,\n TaskDetail,\n WebhookEvent,\n} from './client.js';\n\nexport {\n RearrayApiError,\n isRearrayApiError,\n parseErrorBody,\n} from './errors.js';\nexport type { RearrayErrorBody, RearrayErrorCode } from './errors.js';\n\nexport type { ExecutionLister } from './pagination.js';\nexport { iterateExecutions } from './pagination.js';\nexport {\n verifyWebhookSignature,\n type VerifyWebhookSignatureOptions,\n} from './webhooks.js';\n\nexport type { components, paths } from './generated/openapi.js';\n","import type { components } from './generated/openapi.js';\n\nexport type RearrayErrorCode =\n components['schemas']['Error']['error']['code'];\n\nexport type RearrayErrorBody = components['schemas']['Error'];\n\nexport class RearrayApiError extends Error {\n readonly code: RearrayErrorCode;\n readonly status: number;\n readonly requestId?: string;\n readonly details?: unknown;\n\n constructor(\n code: RearrayErrorCode,\n message: string,\n status: number,\n requestId?: string,\n details?: unknown,\n ) {\n super(message);\n this.name = 'RearrayApiError';\n this.code = code;\n this.status = status;\n this.requestId = requestId;\n this.details = details;\n }\n\n static fromBody(body: RearrayErrorBody, status: number): RearrayApiError {\n const { code, message, request_id, details } = body.error;\n return new RearrayApiError(code, message, status, request_id, details);\n }\n}\n\nexport function isRearrayApiError(error: unknown): error is RearrayApiError {\n return error instanceof RearrayApiError;\n}\n\nexport function parseErrorBody(body: unknown): RearrayErrorBody | null {\n if (\n body &&\n typeof body === 'object' &&\n 'error' in body &&\n body.error &&\n typeof body.error === 'object' &&\n 'code' in body.error &&\n 'message' in body.error\n ) {\n return body as RearrayErrorBody;\n }\n return null;\n}\n","import type { components, paths } from './generated/openapi.js';\n\nexport type Execution = components['schemas']['Execution'];\n\nexport type ListExecutionsParams = NonNullable<\n paths['/executions']['get']['parameters']['query']\n>;\n\nexport type ListExecutionsResponse =\n paths['/executions']['get']['responses'][200]['content']['application/json'];\n\nexport type ExecutionLister = {\n listExecutions(params?: ListExecutionsParams): Promise<ListExecutionsResponse>;\n};\n\nexport async function* iterateExecutions(\n client: ExecutionLister,\n params: ListExecutionsParams = {},\n): AsyncGenerator<Execution, void, undefined> {\n let cursor: string | null | undefined = undefined;\n\n for (;;) {\n const page = await client.listExecutions({\n ...params,\n ...(cursor ? { cursor } : {}),\n });\n\n for (const item of page.data ?? []) {\n yield item;\n }\n\n cursor = page.next_cursor;\n if (!cursor) {\n return;\n }\n }\n}\n","import type { components, paths } from './generated/openapi.js';\nimport { parseErrorBody, RearrayApiError } from './errors.js';\nimport { iterateExecutions as iterateExecutionsImpl } from './pagination.js';\n\n/** Webhook callback payload (not yet in OpenAPI). */\nexport type WebhookEvent = {\n event_id: string;\n type: string;\n occurred_at: string;\n request_id?: string;\n reference?: string | null;\n metadata?: Record<string, unknown>;\n execution?: Record<string, unknown> | null;\n message?: string;\n};\n\nexport type CreateExecutionRequest =\n components['schemas']['CreateExecutionRequest'];\nexport type CreateExecutionResponse =\n components['schemas']['CreateExecutionResponse'];\nexport type Execution = components['schemas']['Execution'];\nexport type ExecutionDetail = components['schemas']['ExecutionDetail'];\nexport type ArtifactsResponse = components['schemas']['ArtifactsResponse'];\nexport type Task = components['schemas']['Task'];\nexport type TaskDetail = components['schemas']['TaskDetail'];\nexport type ParamsSchemaResponse =\n components['schemas']['ParamsSchemaResponse'];\nexport type Agent = components['schemas']['Agent'];\n\nexport type ListExecutionsParams = NonNullable<\n paths['/executions']['get']['parameters']['query']\n>;\n\nexport type ListExecutionsResponse =\n paths['/executions']['get']['responses'][200]['content']['application/json'];\n\nexport type CreateExecutionOptions = {\n idempotencyKey?: string;\n validateOnly?: boolean;\n};\n\nexport type GetTaskParamsSchemaOptions = {\n version?: string;\n};\n\nexport type RearrayClientOptions = {\n apiKey: string;\n baseUrl?: string;\n fetch?: typeof fetch;\n};\n\nconst DEFAULT_BASE_URL = 'https://api.rearray.ai/api/v1/integrations';\n\nexport class RearrayClient {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly fetchFn: typeof fetch;\n\n constructor(options: RearrayClientOptions) {\n this.apiKey = options.apiKey;\n this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;\n this.fetchFn = options.fetch ?? fetch;\n }\n\n async createExecution(\n body: CreateExecutionRequest,\n options: CreateExecutionOptions = {},\n ): Promise<CreateExecutionResponse> {\n const query = options.validateOnly ? '?validate_only=true' : '';\n const headers: Record<string, string> = {};\n if (options.idempotencyKey) {\n headers['Idempotency-Key'] = options.idempotencyKey;\n }\n return this.request<CreateExecutionResponse>('POST', `/executions${query}`, {\n body,\n headers,\n });\n }\n\n async listExecutions(\n params: ListExecutionsParams = {},\n ): Promise<ListExecutionsResponse> {\n const query = buildQuery(params);\n return this.request<ListExecutionsResponse>('GET', `/executions${query}`);\n }\n\n async *iterateExecutions(\n params: ListExecutionsParams = {},\n ): AsyncGenerator<Execution, void, undefined> {\n yield* iterateExecutionsImpl(this, params);\n }\n\n async getExecution(id: string): Promise<ExecutionDetail> {\n return this.request<ExecutionDetail>('GET', `/executions/${id}`);\n }\n\n async cancelExecution(id: string): Promise<components['schemas']['CancelExecutionResponse']> {\n return this.request('POST', `/executions/${id}/cancel`);\n }\n\n async getExecutionArtifacts(id: string): Promise<ArtifactsResponse> {\n return this.request<ArtifactsResponse>('GET', `/executions/${id}/artifacts`);\n }\n\n async listTasks(): Promise<{\n data?: Task[];\n request_id?: string;\n }> {\n return this.request('GET', '/tasks');\n }\n\n async getTask(id: string): Promise<TaskDetail> {\n return this.request<TaskDetail>('GET', `/tasks/${id}`);\n }\n\n async getTaskParamsSchema(\n id: string,\n options: GetTaskParamsSchemaOptions = {},\n ): Promise<ParamsSchemaResponse> {\n const query = options.version\n ? `?${new URLSearchParams({ version: options.version }).toString()}`\n : '';\n return this.request<ParamsSchemaResponse>(\n 'GET',\n `/tasks/${id}/params-schema${query}`,\n );\n }\n\n async listAgents(): Promise<{\n data?: Agent[];\n request_id?: string;\n }> {\n return this.request('GET', '/agents');\n }\n\n async testWebhook(callbackUrl: string): Promise<components['schemas']['WebhookTestResponse']> {\n return this.request('POST', '/webhooks/test', {\n body: { callback_url: callbackUrl },\n });\n }\n\n private async request<T>(\n method: string,\n path: string,\n init: {\n body?: unknown;\n headers?: Record<string, string>;\n } = {},\n ): Promise<T> {\n const url = `${this.baseUrl.replace(/\\/$/, '')}${path}`;\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n Accept: 'application/json',\n ...init.headers,\n };\n\n const requestInit: RequestInit = {\n method,\n headers,\n };\n\n if (init.body !== undefined) {\n headers['Content-Type'] = 'application/json';\n requestInit.body = JSON.stringify(init.body);\n }\n\n const response = await this.fetchFn(url, requestInit);\n const text = await response.text();\n const json = text.length > 0 ? safeJsonParse(text) : null;\n\n if (!response.ok) {\n const errorBody = parseErrorBody(json);\n if (errorBody) {\n throw RearrayApiError.fromBody(errorBody, response.status);\n }\n throw new Error(\n `Request failed with status ${response.status}: ${text || response.statusText}`,\n );\n }\n\n return json as T;\n }\n}\n\nfunction buildQuery(params: Record<string, string | number | undefined>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null) {\n search.set(key, String(value));\n }\n }\n const qs = search.toString();\n return qs ? `?${qs}` : '';\n}\n\nfunction safeJsonParse(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n","export type VerifyWebhookSignatureOptions = {\n payload: string;\n timestamp: string;\n signature: string;\n secret: string;\n /** Reject timestamps older than this many seconds (default: 300). Set to 0 to skip. */\n toleranceSeconds?: number;\n};\n\nfunction buildCanonicalString(payload: string, timestamp: string): string {\n return `${payload}${timestamp}`;\n}\n\nasync function signPayload(\n payload: string,\n timestamp: string,\n secret: string,\n): Promise<string> {\n const enc = new TextEncoder();\n const key = await crypto.subtle.importKey(\n 'raw',\n enc.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n const sig = await crypto.subtle.sign(\n 'HMAC',\n key,\n enc.encode(buildCanonicalString(payload, timestamp)),\n );\n return Array.from(new Uint8Array(sig))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\nfunction constantTimeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) {\n diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return diff === 0;\n}\n\nexport async function verifyWebhookSignature(\n options: VerifyWebhookSignatureOptions,\n): Promise<boolean> {\n const {\n payload,\n timestamp,\n signature,\n secret,\n toleranceSeconds = 300,\n } = options;\n\n if (toleranceSeconds > 0) {\n const ts = Number.parseInt(timestamp, 10);\n if (!Number.isFinite(ts)) return false;\n const age = Math.abs(Math.floor(Date.now() / 1000) - ts);\n if (age > toleranceSeconds) return false;\n }\n\n const expected = await signPayload(payload, timestamp, secret);\n return constantTimeEqual(expected, signature);\n}\n\n/** ponytail: test-only helper mirroring server signing for the one runnable check */\nexport async function signWebhookPayloadForTest(\n payload: string,\n timestamp: string,\n secret: string,\n): Promise<string> {\n return signPayload(payload, timestamp, secret);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOO,IAAM,kBAAN,MAAM,yBAAwB,MAAM;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,MACA,SACA,QACA,WACA,SACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,YAAY;AACjB,SAAK,UAAU;AAAA,EACjB;AAAA,EAEA,OAAO,SAAS,MAAwB,QAAiC;AACvE,UAAM,EAAE,MAAM,SAAS,YAAY,QAAQ,IAAI,KAAK;AACpD,WAAO,IAA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