@tungoai/sdk 0.0.0-stage → 0.3.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/CHANGELOG.md +93 -0
- package/LICENSE +21 -0
- package/README.kk.md +327 -0
- package/README.md +346 -2
- package/README.ru.md +327 -0
- package/dist/cjs/chat.d.ts +85 -0
- package/dist/cjs/chat.js +152 -0
- package/dist/cjs/client.d.ts +117 -0
- package/dist/cjs/client.js +225 -0
- package/dist/cjs/core.d.ts +217 -0
- package/dist/cjs/core.js +779 -0
- package/dist/cjs/errors.d.ts +237 -0
- package/dist/cjs/errors.js +446 -0
- package/dist/cjs/generated/resources.d.ts +1149 -0
- package/dist/cjs/generated/resources.js +1145 -0
- package/dist/cjs/generated/types.d.ts +5435 -0
- package/dist/cjs/generated/types.js +11 -0
- package/dist/cjs/index.d.ts +12 -0
- package/dist/cjs/index.js +81 -0
- package/dist/cjs/json.d.ts +16 -0
- package/dist/cjs/json.js +137 -0
- package/dist/cjs/money.d.ts +32 -0
- package/dist/cjs/money.js +141 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pagination.d.ts +47 -0
- package/dist/cjs/pagination.js +114 -0
- package/dist/cjs/streaming.d.ts +76 -0
- package/dist/cjs/streaming.js +291 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +6 -0
- package/dist/cjs/webhooks.d.ts +79 -0
- package/dist/cjs/webhooks.js +262 -0
- package/dist/esm/chat.d.ts +85 -0
- package/dist/esm/chat.js +144 -0
- package/dist/esm/client.d.ts +117 -0
- package/dist/esm/client.js +221 -0
- package/dist/esm/core.d.ts +217 -0
- package/dist/esm/core.js +763 -0
- package/dist/esm/errors.d.ts +237 -0
- package/dist/esm/errors.js +416 -0
- package/dist/esm/generated/resources.d.ts +1149 -0
- package/dist/esm/generated/resources.js +1129 -0
- package/dist/esm/generated/types.d.ts +5435 -0
- package/dist/esm/generated/types.js +10 -0
- package/dist/esm/index.d.ts +12 -0
- package/dist/esm/index.js +11 -0
- package/dist/esm/json.d.ts +16 -0
- package/dist/esm/json.js +132 -0
- package/dist/esm/money.d.ts +32 -0
- package/dist/esm/money.js +137 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/pagination.d.ts +47 -0
- package/dist/esm/pagination.js +108 -0
- package/dist/esm/streaming.d.ts +76 -0
- package/dist/esm/streaming.js +285 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +3 -0
- package/dist/esm/webhooks.d.ts +79 -0
- package/dist/esm/webhooks.js +253 -0
- package/package.json +67 -4
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
// Code generated by tungo-sdkgen. DO NOT EDIT.
|
|
2
|
+
import { MAX_TIMER_MS } from './core.js';
|
|
3
|
+
import { AbortError, ConnectionError, DecodeError, StreamError, TimeoutError, TungoError } from './errors.js';
|
|
4
|
+
import { parseJSON } from './json.js';
|
|
5
|
+
/**
|
|
6
|
+
* Incremental parser of the `text/event-stream` format (WHATWG HTML, "interpreting an event
|
|
7
|
+
* stream"). Feed it the bytes as they arrive; it returns the events completed by each chunk.
|
|
8
|
+
* LF, CRLF and bare CR line endings, a leading BOM, comments, multi-line data and UTF-8
|
|
9
|
+
* sequences split across chunks are handled. An unterminated last event is dropped.
|
|
10
|
+
*/
|
|
11
|
+
export class SSEDecoder {
|
|
12
|
+
#pending = [];
|
|
13
|
+
#pendingLength = 0;
|
|
14
|
+
#skipLineFeed = false;
|
|
15
|
+
#firstLine = true;
|
|
16
|
+
#text = new TextDecoder('utf-8', { ignoreBOM: true });
|
|
17
|
+
#data = [];
|
|
18
|
+
#hasData = false;
|
|
19
|
+
#event = '';
|
|
20
|
+
#lastId = null;
|
|
21
|
+
#retry;
|
|
22
|
+
/** Consumes one chunk and returns the events it completed. */
|
|
23
|
+
feed(chunk) {
|
|
24
|
+
const out = [];
|
|
25
|
+
let start = 0;
|
|
26
|
+
if (this.#skipLineFeed && chunk.length > 0) {
|
|
27
|
+
if (chunk[0] === 10)
|
|
28
|
+
start = 1;
|
|
29
|
+
this.#skipLineFeed = false;
|
|
30
|
+
}
|
|
31
|
+
for (let i = start; i < chunk.length; i++) {
|
|
32
|
+
const byte = chunk[i];
|
|
33
|
+
if (byte !== 10 && byte !== 13)
|
|
34
|
+
continue;
|
|
35
|
+
this.#line(this.#take(chunk.subarray(start, i)), out);
|
|
36
|
+
if (byte === 13) {
|
|
37
|
+
if (i + 1 < chunk.length) {
|
|
38
|
+
if (chunk[i + 1] === 10)
|
|
39
|
+
i++;
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
this.#skipLineFeed = true;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
start = i + 1;
|
|
46
|
+
}
|
|
47
|
+
if (start < chunk.length) {
|
|
48
|
+
const rest = chunk.subarray(start);
|
|
49
|
+
this.#pending.push(rest);
|
|
50
|
+
this.#pendingLength += rest.length;
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
#take(tail) {
|
|
55
|
+
let bytes = tail;
|
|
56
|
+
if (this.#pendingLength > 0) {
|
|
57
|
+
bytes = new Uint8Array(this.#pendingLength + tail.length);
|
|
58
|
+
let offset = 0;
|
|
59
|
+
for (const part of this.#pending) {
|
|
60
|
+
bytes.set(part, offset);
|
|
61
|
+
offset += part.length;
|
|
62
|
+
}
|
|
63
|
+
bytes.set(tail, offset);
|
|
64
|
+
this.#pending = [];
|
|
65
|
+
this.#pendingLength = 0;
|
|
66
|
+
}
|
|
67
|
+
let line = this.#text.decode(bytes);
|
|
68
|
+
if (this.#firstLine) {
|
|
69
|
+
this.#firstLine = false;
|
|
70
|
+
if (line.charCodeAt(0) === 0xfeff)
|
|
71
|
+
line = line.slice(1);
|
|
72
|
+
}
|
|
73
|
+
return line;
|
|
74
|
+
}
|
|
75
|
+
#line(line, out) {
|
|
76
|
+
if (line === '') {
|
|
77
|
+
if (this.#hasData) {
|
|
78
|
+
const event = {
|
|
79
|
+
event: this.#event === '' ? 'message' : this.#event,
|
|
80
|
+
data: this.#data.join('\n'),
|
|
81
|
+
id: this.#lastId,
|
|
82
|
+
};
|
|
83
|
+
if (this.#retry !== undefined)
|
|
84
|
+
event.retry = this.#retry;
|
|
85
|
+
out.push(event);
|
|
86
|
+
}
|
|
87
|
+
this.#data = [];
|
|
88
|
+
this.#hasData = false;
|
|
89
|
+
this.#event = '';
|
|
90
|
+
this.#retry = undefined;
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (line.charCodeAt(0) === 58)
|
|
94
|
+
return;
|
|
95
|
+
const colon = line.indexOf(':');
|
|
96
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
97
|
+
let value = colon === -1 ? '' : line.slice(colon + 1);
|
|
98
|
+
if (value.charCodeAt(0) === 32)
|
|
99
|
+
value = value.slice(1);
|
|
100
|
+
switch (field) {
|
|
101
|
+
case 'event':
|
|
102
|
+
this.#event = value;
|
|
103
|
+
break;
|
|
104
|
+
case 'data':
|
|
105
|
+
this.#data.push(value);
|
|
106
|
+
this.#hasData = true;
|
|
107
|
+
break;
|
|
108
|
+
case 'id':
|
|
109
|
+
if (!value.includes('\u0000'))
|
|
110
|
+
this.#lastId = value;
|
|
111
|
+
break;
|
|
112
|
+
case 'retry':
|
|
113
|
+
if (/^[0-9]+$/.test(value))
|
|
114
|
+
this.#retry = Number(value);
|
|
115
|
+
break;
|
|
116
|
+
default:
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function causeText(cause) {
|
|
122
|
+
return cause instanceof Error ? cause.message : String(cause);
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* A server-sent event stream. Iterate it with `for await` to receive typed events as they arrive.
|
|
126
|
+
* Leaving the loop early, or calling {@link Stream.close}, closes the connection. A stream can be
|
|
127
|
+
* consumed once.
|
|
128
|
+
*/
|
|
129
|
+
export class Stream {
|
|
130
|
+
/** Status and headers of the response that opened the stream. */
|
|
131
|
+
response;
|
|
132
|
+
#init;
|
|
133
|
+
#decode;
|
|
134
|
+
#started = false;
|
|
135
|
+
#closed = false;
|
|
136
|
+
#lastEventId = null;
|
|
137
|
+
constructor(init, decode) {
|
|
138
|
+
this.response = init.response;
|
|
139
|
+
this.#init = init;
|
|
140
|
+
this.#decode = decode;
|
|
141
|
+
}
|
|
142
|
+
/** The id of the last event received so far (send it as `Last-Event-ID` to resume). */
|
|
143
|
+
get lastEventId() {
|
|
144
|
+
return this.#lastEventId;
|
|
145
|
+
}
|
|
146
|
+
/** Closes the connection. Safe to call more than once; a running iteration ends quietly. */
|
|
147
|
+
close() {
|
|
148
|
+
if (this.#closed)
|
|
149
|
+
return;
|
|
150
|
+
this.#closed = true;
|
|
151
|
+
this.#init.detach();
|
|
152
|
+
this.#init.controller.abort();
|
|
153
|
+
if (!this.#started && this.#init.body !== null) {
|
|
154
|
+
this.#init.body.cancel().catch(() => undefined);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/** The raw server-sent events (name, data text, id), including heart-beats. */
|
|
158
|
+
async *events() {
|
|
159
|
+
if (this.#started)
|
|
160
|
+
throw new TungoError('The stream has already been consumed');
|
|
161
|
+
this.#started = true;
|
|
162
|
+
const body = this.#init.body;
|
|
163
|
+
if (body === null || this.#closed)
|
|
164
|
+
return;
|
|
165
|
+
const reader = body.getReader();
|
|
166
|
+
const decoder = new SSEDecoder();
|
|
167
|
+
try {
|
|
168
|
+
for (;;) {
|
|
169
|
+
const chunk = await this.#read(reader);
|
|
170
|
+
if (chunk.done)
|
|
171
|
+
break;
|
|
172
|
+
for (const event of decoder.feed(chunk.value)) {
|
|
173
|
+
if (event.id !== null)
|
|
174
|
+
this.#lastEventId = event.id;
|
|
175
|
+
yield event;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
finally {
|
|
180
|
+
this.#closed = true;
|
|
181
|
+
this.#init.detach();
|
|
182
|
+
try {
|
|
183
|
+
await reader.cancel();
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
// The connection is already gone.
|
|
187
|
+
}
|
|
188
|
+
this.#init.controller.abort();
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
async #read(reader) {
|
|
192
|
+
const idleTimeout = this.#init.idleTimeout;
|
|
193
|
+
let timer;
|
|
194
|
+
try {
|
|
195
|
+
// 0, Infinity and delays no timer can count disable the idle check.
|
|
196
|
+
if (!(idleTimeout > 0) || idleTimeout > MAX_TIMER_MS)
|
|
197
|
+
return await reader.read();
|
|
198
|
+
const idle = new Promise((_resolve, reject) => {
|
|
199
|
+
timer = setTimeout(() => {
|
|
200
|
+
reject(new TimeoutError('No data was received for ' + idleTimeout + ' ms on the stream of ' + this.#init.route, idleTimeout));
|
|
201
|
+
}, idleTimeout);
|
|
202
|
+
});
|
|
203
|
+
return await Promise.race([reader.read(), idle]);
|
|
204
|
+
}
|
|
205
|
+
catch (cause) {
|
|
206
|
+
if (cause instanceof TungoError)
|
|
207
|
+
throw cause;
|
|
208
|
+
const signal = this.#init.signal;
|
|
209
|
+
if (signal !== undefined && signal.aborted) {
|
|
210
|
+
throw new AbortError('The stream of ' + this.#init.route + ' was aborted', { cause: signal.reason });
|
|
211
|
+
}
|
|
212
|
+
if (this.#closed)
|
|
213
|
+
return { done: true, value: undefined };
|
|
214
|
+
throw new ConnectionError('The stream of ' + this.#init.route + ' was interrupted: ' + causeText(cause), { cause });
|
|
215
|
+
}
|
|
216
|
+
finally {
|
|
217
|
+
if (timer !== undefined)
|
|
218
|
+
clearTimeout(timer);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
async *[Symbol.asyncIterator]() {
|
|
222
|
+
for await (const event of this.events()) {
|
|
223
|
+
const value = this.#decode(event, this.response);
|
|
224
|
+
if (value !== undefined)
|
|
225
|
+
yield value;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Decodes the `data` of an event as JSON. Heart-beats (`ping`, or an event with empty data) are
|
|
231
|
+
* skipped; data that is not valid JSON raises a DecodeError. Unless `errorIsEvent` (chat events,
|
|
232
|
+
* where `error` is a variant of the union), an `error` event is a failure of the stream and raises
|
|
233
|
+
* a StreamError, so a broken stream never looks like one that ended normally.
|
|
234
|
+
*/
|
|
235
|
+
export function decodeJSONEvent(event, response, errorIsEvent = false) {
|
|
236
|
+
if (event.event === 'ping' || event.data === '')
|
|
237
|
+
return undefined;
|
|
238
|
+
if (event.event === 'error' && !errorIsEvent)
|
|
239
|
+
throw streamError(event.data, response);
|
|
240
|
+
try {
|
|
241
|
+
return parseJSON(event.data);
|
|
242
|
+
}
|
|
243
|
+
catch (cause) {
|
|
244
|
+
throw new DecodeError('The data of the "' + event.event + '" stream event is not valid JSON', {
|
|
245
|
+
status: response.status,
|
|
246
|
+
requestId: response.requestId,
|
|
247
|
+
body: event.data,
|
|
248
|
+
cause,
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Reads the data of an `error` event: `{"error": "code", "message": ...}` as the contract sends it,
|
|
254
|
+
* or the API error envelope `{"error": {"code", "message", ...}}`. Other data still gives a StreamError.
|
|
255
|
+
*/
|
|
256
|
+
function streamError(data, response) {
|
|
257
|
+
let root;
|
|
258
|
+
try {
|
|
259
|
+
root = parseJSON(data);
|
|
260
|
+
}
|
|
261
|
+
catch {
|
|
262
|
+
root = undefined;
|
|
263
|
+
}
|
|
264
|
+
const text = (value) => (typeof value === 'string' && value !== '' ? value : null);
|
|
265
|
+
const props = isRecord(root) ? root : {};
|
|
266
|
+
const inner = isRecord(props['error']) ? props['error'] : {};
|
|
267
|
+
const extra = {};
|
|
268
|
+
for (const [key, value] of Object.entries(inner))
|
|
269
|
+
if (key !== 'code' && key !== 'message')
|
|
270
|
+
extra[key] = value;
|
|
271
|
+
for (const [key, value] of Object.entries(props)) {
|
|
272
|
+
if (key !== 'error' && key !== 'code' && key !== 'message' && key !== 'request_id')
|
|
273
|
+
extra[key] = value;
|
|
274
|
+
}
|
|
275
|
+
return new StreamError({
|
|
276
|
+
code: text(props['code']) ?? text(props['error']) ?? text(inner['code']),
|
|
277
|
+
detail: text(props['message']) ?? text(inner['message']) ?? 'The stream reported an error',
|
|
278
|
+
requestId: text(props['request_id']) ?? response.requestId,
|
|
279
|
+
extra,
|
|
280
|
+
body: data,
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
function isRecord(value) {
|
|
284
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
285
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { APIPromise, type APIClient, type RequestOptions } from './core.js';
|
|
2
|
+
import type { WebhookEvent } from './generated/types.js';
|
|
3
|
+
/** Default tolerance for the webhook timestamp, in seconds (both directions). */
|
|
4
|
+
export declare const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
|
|
5
|
+
/**
|
|
6
|
+
* Header containers accepted by the webhook helpers: a fetch `Headers` object, a plain object
|
|
7
|
+
* (Node.js `req.headers`, with string or string[] values), a Map, or an array of pairs.
|
|
8
|
+
* Names are matched case-insensitively.
|
|
9
|
+
*/
|
|
10
|
+
export type HeadersLike = Headers | Iterable<readonly [string, string]> | Record<string, string | readonly string[] | undefined>;
|
|
11
|
+
/** Options of `verifyWebhook`. */
|
|
12
|
+
export interface VerifyWebhookOptions {
|
|
13
|
+
/** Maximum distance between the timestamp and the clock, in seconds. Default 300; must be positive. */
|
|
14
|
+
toleranceSeconds?: number | undefined;
|
|
15
|
+
/** The clock: unix seconds, a Date, or a function returning unix seconds. Default: the system clock. */
|
|
16
|
+
now?: number | Date | (() => number) | undefined;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Verifies an outgoing Tungo webhook (Standard Webhooks / Svix) and returns the typed event.
|
|
20
|
+
*
|
|
21
|
+
* Pass the RAW request body (the exact bytes, before any JSON parsing), the request headers
|
|
22
|
+
* (`webhook-*` or `svix-*`) and the endpoint's signing secret (`whsec_...`). The signature is
|
|
23
|
+
* checked in constant time and the timestamp must be within the tolerance of the clock.
|
|
24
|
+
* Every problem is reported as a {@link WebhookVerificationError}.
|
|
25
|
+
*/
|
|
26
|
+
export declare function verifyWebhook(body: string | Uint8Array | ArrayBuffer, headers: HeadersLike, secret: string, options?: VerifyWebhookOptions): Promise<WebhookEvent>;
|
|
27
|
+
/**
|
|
28
|
+
* Computes the signature of an incoming-hook body: lower-case hex of HMAC-SHA256(secret, body).
|
|
29
|
+
* Send it as `X-Signature: sha256=<hex>`. An empty secret is rejected.
|
|
30
|
+
*/
|
|
31
|
+
export declare function signHookPayload(body: string | Uint8Array | ArrayBuffer, secret: string): Promise<string>;
|
|
32
|
+
/**
|
|
33
|
+
* Checks a hook signature (hex in any case, with or without the `sha256=` prefix) in constant
|
|
34
|
+
* time. Returns false for an empty secret or a malformed signature; it never throws for those.
|
|
35
|
+
*/
|
|
36
|
+
export declare function verifyHookSignature(body: string | Uint8Array | ArrayBuffer, signature: string, secret: string): Promise<boolean>;
|
|
37
|
+
/** Encodes bytes as base64 without relying on Node.js APIs. */
|
|
38
|
+
export declare function bytesToBase64(bytes: Uint8Array): string;
|
|
39
|
+
/** Helpers for incoming automation hooks (`/hooks/{token}`). */
|
|
40
|
+
export declare const TungoHooks: {
|
|
41
|
+
readonly sign: typeof signHookPayload;
|
|
42
|
+
readonly verify: typeof verifyHookSignature;
|
|
43
|
+
};
|
|
44
|
+
/** Helpers for outgoing webhooks. */
|
|
45
|
+
export declare const TungoWebhooks: {
|
|
46
|
+
readonly verify: typeof verifyWebhook;
|
|
47
|
+
};
|
|
48
|
+
/** What `sendHook` accepts as a payload: text or bytes are sent as they are, anything else as JSON. */
|
|
49
|
+
export type HookPayload = string | Uint8Array | ArrayBuffer | Record<string, unknown> | readonly unknown[] | number | boolean | null;
|
|
50
|
+
/** Turns a hook payload into the exact bytes to send and their default content type. */
|
|
51
|
+
export declare function encodeHookPayload(payload: HookPayload): {
|
|
52
|
+
bytes: Uint8Array;
|
|
53
|
+
contentType: string;
|
|
54
|
+
};
|
|
55
|
+
/** The contract details of the incoming-hook operation; supplied by the generated resource. */
|
|
56
|
+
export interface HookOperation {
|
|
57
|
+
method: string;
|
|
58
|
+
path: string;
|
|
59
|
+
tokenParam: string;
|
|
60
|
+
signatureHeader: string;
|
|
61
|
+
eventIdHeader: string | undefined;
|
|
62
|
+
idempotencyHeader: string | undefined;
|
|
63
|
+
}
|
|
64
|
+
/** Options of `sendHook` / `automations.postHook`. */
|
|
65
|
+
export interface SendHookOptions extends RequestOptions {
|
|
66
|
+
/** The hook's signing secret. When given, the exact bytes sent are signed in the signature header. */
|
|
67
|
+
secret?: string | undefined;
|
|
68
|
+
/**
|
|
69
|
+
* The header the hook reads its signature from: the `signature_header` it was created with.
|
|
70
|
+
* Default `X-Signature`.
|
|
71
|
+
*/
|
|
72
|
+
signatureHeader?: string | undefined;
|
|
73
|
+
/** Your id of the event, for de-duplication on the server. */
|
|
74
|
+
eventId?: string | undefined;
|
|
75
|
+
/** Content type of the body. Default: `application/json` for text and JSON values, `application/octet-stream` for bytes. */
|
|
76
|
+
contentType?: string | undefined;
|
|
77
|
+
}
|
|
78
|
+
/** Posts an event to an incoming hook. No API key is sent: the token in the path authenticates. */
|
|
79
|
+
export declare function sendHook<R>(client: APIClient, operation: HookOperation, token: string, payload: HookPayload, options?: SendHookOptions): APIPromise<R>;
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
// Code generated by tungo-sdkgen. DO NOT EDIT.
|
|
2
|
+
import { ValidationError, WebhookVerificationError } from './errors.js';
|
|
3
|
+
import { APIPromise } from './core.js';
|
|
4
|
+
import { parseJSON, stringifyJSON } from './json.js';
|
|
5
|
+
/** Default tolerance for the webhook timestamp, in seconds (both directions). */
|
|
6
|
+
export const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
|
|
7
|
+
const encoder = new TextEncoder();
|
|
8
|
+
function toBytes(body) {
|
|
9
|
+
if (typeof body === 'string')
|
|
10
|
+
return encoder.encode(body);
|
|
11
|
+
if (body instanceof ArrayBuffer)
|
|
12
|
+
return new Uint8Array(body);
|
|
13
|
+
if (ArrayBuffer.isView(body)) {
|
|
14
|
+
const copy = new Uint8Array(body.byteLength);
|
|
15
|
+
copy.set(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));
|
|
16
|
+
return copy;
|
|
17
|
+
}
|
|
18
|
+
throw new ValidationError('The body must be a string, a Uint8Array or an ArrayBuffer (the raw bytes as received)');
|
|
19
|
+
}
|
|
20
|
+
function concat(a, b) {
|
|
21
|
+
const out = new Uint8Array(a.length + b.length);
|
|
22
|
+
out.set(a, 0);
|
|
23
|
+
out.set(b, a.length);
|
|
24
|
+
return out;
|
|
25
|
+
}
|
|
26
|
+
function decodeBase64(text) {
|
|
27
|
+
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(text))
|
|
28
|
+
return null;
|
|
29
|
+
let binary;
|
|
30
|
+
try {
|
|
31
|
+
binary = atob(text);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
const out = new Uint8Array(binary.length);
|
|
37
|
+
for (let i = 0; i < binary.length; i++)
|
|
38
|
+
out[i] = binary.charCodeAt(i);
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
function decodeHex(text) {
|
|
42
|
+
if (text.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(text))
|
|
43
|
+
return null;
|
|
44
|
+
const out = new Uint8Array(text.length / 2);
|
|
45
|
+
for (let i = 0; i < out.length; i++)
|
|
46
|
+
out[i] = Number.parseInt(text.slice(i * 2, i * 2 + 2), 16);
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
function encodeHex(bytes) {
|
|
50
|
+
let out = '';
|
|
51
|
+
for (const b of bytes)
|
|
52
|
+
out += b.toString(16).padStart(2, '0');
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
function hmacKey(key, usage) {
|
|
56
|
+
return crypto.subtle.importKey('raw', key, { name: 'HMAC', hash: 'SHA-256' }, false, [usage]);
|
|
57
|
+
}
|
|
58
|
+
function findHeader(headers, name) {
|
|
59
|
+
const wanted = name.toLowerCase();
|
|
60
|
+
const iterable = headers;
|
|
61
|
+
if (typeof iterable[Symbol.iterator] === 'function') {
|
|
62
|
+
for (const pair of headers) {
|
|
63
|
+
if (Array.isArray(pair) && typeof pair[0] === 'string' && pair[0].toLowerCase() === wanted && typeof pair[1] === 'string') {
|
|
64
|
+
return pair[1];
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
70
|
+
if (key.toLowerCase() !== wanted)
|
|
71
|
+
continue;
|
|
72
|
+
if (typeof value === 'string')
|
|
73
|
+
return value;
|
|
74
|
+
if (Array.isArray(value) && typeof value[0] === 'string')
|
|
75
|
+
return value[0];
|
|
76
|
+
}
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
function clock(now) {
|
|
80
|
+
if (now === undefined)
|
|
81
|
+
return Math.floor(Date.now() / 1000);
|
|
82
|
+
if (typeof now === 'number')
|
|
83
|
+
return now;
|
|
84
|
+
if (now instanceof Date)
|
|
85
|
+
return Math.floor(now.getTime() / 1000);
|
|
86
|
+
return now();
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Verifies an outgoing Tungo webhook (Standard Webhooks / Svix) and returns the typed event.
|
|
90
|
+
*
|
|
91
|
+
* Pass the RAW request body (the exact bytes, before any JSON parsing), the request headers
|
|
92
|
+
* (`webhook-*` or `svix-*`) and the endpoint's signing secret (`whsec_...`). The signature is
|
|
93
|
+
* checked in constant time and the timestamp must be within the tolerance of the clock.
|
|
94
|
+
* Every problem is reported as a {@link WebhookVerificationError}.
|
|
95
|
+
*/
|
|
96
|
+
export async function verifyWebhook(body, headers, secret, options = {}) {
|
|
97
|
+
const tolerance = options.toleranceSeconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS;
|
|
98
|
+
if (typeof tolerance !== 'number' || !(tolerance > 0) || !Number.isFinite(tolerance)) {
|
|
99
|
+
throw new WebhookVerificationError('invalid_tolerance', 'The webhook tolerance must be a positive number of seconds');
|
|
100
|
+
}
|
|
101
|
+
if (typeof secret !== 'string') {
|
|
102
|
+
throw new WebhookVerificationError('invalid_secret', 'The webhook secret must be a string');
|
|
103
|
+
}
|
|
104
|
+
const encoded = secret.startsWith('whsec_') ? secret.slice(6) : secret;
|
|
105
|
+
const key = encoded === '' ? null : decodeBase64(encoded);
|
|
106
|
+
if (key === null || key.length === 0) {
|
|
107
|
+
throw new WebhookVerificationError('invalid_secret', 'The webhook secret is empty or is not base64 (expected "whsec_" followed by base64)');
|
|
108
|
+
}
|
|
109
|
+
if (headers === null || typeof headers !== 'object') {
|
|
110
|
+
throw new WebhookVerificationError('missing_header', 'The webhook headers are missing');
|
|
111
|
+
}
|
|
112
|
+
const get = (suffix) => findHeader(headers, 'svix-' + suffix) ?? findHeader(headers, 'webhook-' + suffix);
|
|
113
|
+
const id = get('id');
|
|
114
|
+
const timestamp = get('timestamp');
|
|
115
|
+
const signature = get('signature');
|
|
116
|
+
if (id === undefined || timestamp === undefined || signature === undefined) {
|
|
117
|
+
throw new WebhookVerificationError('missing_header', 'A webhook header is missing (webhook-id, webhook-timestamp and webhook-signature are required)');
|
|
118
|
+
}
|
|
119
|
+
if (!/^[0-9]+$/.test(timestamp) || !Number.isSafeInteger(Number(timestamp))) {
|
|
120
|
+
throw new WebhookVerificationError('malformed_timestamp', 'The webhook timestamp is not a whole number of seconds');
|
|
121
|
+
}
|
|
122
|
+
const sent = Number(timestamp);
|
|
123
|
+
const now = clock(options.now);
|
|
124
|
+
if (now - sent > tolerance) {
|
|
125
|
+
throw new WebhookVerificationError('timestamp_too_old', 'The webhook timestamp is older than the tolerance of ' + tolerance + ' s');
|
|
126
|
+
}
|
|
127
|
+
if (sent - now > tolerance) {
|
|
128
|
+
throw new WebhookVerificationError('timestamp_too_new', 'The webhook timestamp is further in the future than the tolerance of ' + tolerance + ' s');
|
|
129
|
+
}
|
|
130
|
+
let bytes;
|
|
131
|
+
try {
|
|
132
|
+
bytes = toBytes(body);
|
|
133
|
+
}
|
|
134
|
+
catch (cause) {
|
|
135
|
+
throw new WebhookVerificationError('invalid_payload', 'The webhook body must be the raw request body (string or bytes)', { cause });
|
|
136
|
+
}
|
|
137
|
+
const signed = concat(encoder.encode(id + '.' + timestamp + '.'), bytes);
|
|
138
|
+
let matched = false;
|
|
139
|
+
try {
|
|
140
|
+
const cryptoKey = await hmacKey(key, 'verify');
|
|
141
|
+
for (const part of signature.split(/[ \t\r\n\f\v]+/)) {
|
|
142
|
+
const comma = part.indexOf(',');
|
|
143
|
+
if (comma === -1 || part.slice(0, comma) !== 'v1')
|
|
144
|
+
continue;
|
|
145
|
+
const candidate = decodeBase64(part.slice(comma + 1));
|
|
146
|
+
if (candidate === null)
|
|
147
|
+
continue;
|
|
148
|
+
// SubtleCrypto.verify compares the MAC in constant time.
|
|
149
|
+
if (await crypto.subtle.verify('HMAC', cryptoKey, candidate, signed))
|
|
150
|
+
matched = true;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
catch (cause) {
|
|
154
|
+
throw new WebhookVerificationError('signature_mismatch', 'The webhook signature could not be checked', { cause });
|
|
155
|
+
}
|
|
156
|
+
if (!matched) {
|
|
157
|
+
throw new WebhookVerificationError('signature_mismatch', 'No webhook signature matches the body: check the secret and pass the raw body');
|
|
158
|
+
}
|
|
159
|
+
let event;
|
|
160
|
+
try {
|
|
161
|
+
event = parseJSON(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
|
|
162
|
+
}
|
|
163
|
+
catch (cause) {
|
|
164
|
+
throw new WebhookVerificationError('invalid_payload', 'The webhook signature is valid but the body is not JSON', { cause });
|
|
165
|
+
}
|
|
166
|
+
if (typeof event !== 'object' || event === null || typeof event.type !== 'string') {
|
|
167
|
+
throw new WebhookVerificationError('invalid_payload', 'The webhook signature is valid but the body is not an event object');
|
|
168
|
+
}
|
|
169
|
+
return event;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Computes the signature of an incoming-hook body: lower-case hex of HMAC-SHA256(secret, body).
|
|
173
|
+
* Send it as `X-Signature: sha256=<hex>`. An empty secret is rejected.
|
|
174
|
+
*/
|
|
175
|
+
export async function signHookPayload(body, secret) {
|
|
176
|
+
if (typeof secret !== 'string' || secret === '')
|
|
177
|
+
throw new ValidationError('The hook secret must not be empty');
|
|
178
|
+
const key = await hmacKey(encoder.encode(secret), 'sign');
|
|
179
|
+
return encodeHex(new Uint8Array(await crypto.subtle.sign('HMAC', key, toBytes(body))));
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Checks a hook signature (hex in any case, with or without the `sha256=` prefix) in constant
|
|
183
|
+
* time. Returns false for an empty secret or a malformed signature; it never throws for those.
|
|
184
|
+
*/
|
|
185
|
+
export async function verifyHookSignature(body, signature, secret) {
|
|
186
|
+
if (typeof secret !== 'string' || secret === '' || typeof signature !== 'string')
|
|
187
|
+
return false;
|
|
188
|
+
const hex = signature.slice(0, 7).toLowerCase() === 'sha256=' ? signature.slice(7) : signature;
|
|
189
|
+
const given = decodeHex(hex);
|
|
190
|
+
if (given === null || given.length !== 32)
|
|
191
|
+
return false;
|
|
192
|
+
const key = await hmacKey(encoder.encode(secret), 'verify');
|
|
193
|
+
return crypto.subtle.verify('HMAC', key, given, toBytes(body));
|
|
194
|
+
}
|
|
195
|
+
/** Encodes bytes as base64 without relying on Node.js APIs. */
|
|
196
|
+
export function bytesToBase64(bytes) {
|
|
197
|
+
let binary = '';
|
|
198
|
+
for (let i = 0; i < bytes.length; i += 0x8000) {
|
|
199
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
200
|
+
}
|
|
201
|
+
return btoa(binary);
|
|
202
|
+
}
|
|
203
|
+
/** Helpers for incoming automation hooks (`/hooks/{token}`). */
|
|
204
|
+
export const TungoHooks = { sign: signHookPayload, verify: verifyHookSignature };
|
|
205
|
+
/** Helpers for outgoing webhooks. */
|
|
206
|
+
export const TungoWebhooks = { verify: verifyWebhook };
|
|
207
|
+
/** Turns a hook payload into the exact bytes to send and their default content type. */
|
|
208
|
+
export function encodeHookPayload(payload) {
|
|
209
|
+
if (typeof payload === 'string')
|
|
210
|
+
return { bytes: encoder.encode(payload), contentType: 'application/json' };
|
|
211
|
+
if (payload instanceof ArrayBuffer || ArrayBuffer.isView(payload)) {
|
|
212
|
+
return { bytes: toBytes(payload), contentType: 'application/octet-stream' };
|
|
213
|
+
}
|
|
214
|
+
return { bytes: encoder.encode(stringifyJSON(payload)), contentType: 'application/json' };
|
|
215
|
+
}
|
|
216
|
+
const HOOK_SIGNATURE_HEADER = /^[A-Za-z0-9-]{1,64}$/;
|
|
217
|
+
/** Posts an event to an incoming hook. No API key is sent: the token in the path authenticates. */
|
|
218
|
+
export function sendHook(client, operation, token, payload, options = {}) {
|
|
219
|
+
const run = async () => {
|
|
220
|
+
const { secret, eventId, contentType, signatureHeader, ...requestOptions } = options;
|
|
221
|
+
const target = signatureHeader ?? operation.signatureHeader;
|
|
222
|
+
if (typeof target !== 'string' || !HOOK_SIGNATURE_HEADER.test(target)) {
|
|
223
|
+
throw new ValidationError("signatureHeader must be 1 to 64 Latin letters, digits or hyphens, like the hook's signature_header.");
|
|
224
|
+
}
|
|
225
|
+
const encoded = encodeHookPayload(payload);
|
|
226
|
+
const headers = {};
|
|
227
|
+
if (secret !== undefined) {
|
|
228
|
+
const lower = target.toLowerCase();
|
|
229
|
+
if (Object.entries(requestOptions.headers ?? {}).some(([name, value]) => name.toLowerCase() === lower && value != null)) {
|
|
230
|
+
throw new ValidationError(`Pass either secret or the ${target} header, not both.`);
|
|
231
|
+
}
|
|
232
|
+
headers[target] = 'sha256=' + (await signHookPayload(encoded.bytes, secret));
|
|
233
|
+
}
|
|
234
|
+
if (eventId !== undefined && operation.eventIdHeader !== undefined)
|
|
235
|
+
headers[operation.eventIdHeader] = eventId;
|
|
236
|
+
return {
|
|
237
|
+
method: operation.method,
|
|
238
|
+
path: operation.path,
|
|
239
|
+
pathParams: { [operation.tokenParam]: token },
|
|
240
|
+
rawBody: encoded.bytes,
|
|
241
|
+
contentType: contentType ?? encoded.contentType,
|
|
242
|
+
headers,
|
|
243
|
+
auth: 'hook',
|
|
244
|
+
idempotencyHeader: operation.idempotencyHeader,
|
|
245
|
+
// The backend takes the id of a hook event from Idempotency-Key before X-Event-Id, so a random
|
|
246
|
+
// key would override the caller's event id: the event id is the default key. A key the caller
|
|
247
|
+
// gives (`idempotencyKey`, or the header per request or in the client's default headers) wins.
|
|
248
|
+
defaultIdempotencyKey: eventId,
|
|
249
|
+
options: requestOptions,
|
|
250
|
+
};
|
|
251
|
+
};
|
|
252
|
+
return new APIPromise(run().then((spec) => client.request(spec).withResponse()));
|
|
253
|
+
}
|