@easyslip/sdk 1.0.0 → 1.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +8 -6
  3. package/README.th.md +8 -6
  4. package/dist/cjs/index.js +2039 -54
  5. package/dist/cjs/models.d.ts +16 -7
  6. package/dist/cjs/resources/v1.d.ts +2 -0
  7. package/dist/cjs/resources/verify.d.ts +2 -0
  8. package/dist/cjs/version.d.ts +1 -1
  9. package/dist/esm/index.js +1997 -7
  10. package/dist/esm/models.d.ts +16 -7
  11. package/dist/esm/resources/v1.d.ts +2 -0
  12. package/dist/esm/resources/verify.d.ts +2 -0
  13. package/dist/esm/version.d.ts +1 -1
  14. package/package.json +12 -14
  15. package/dist/cjs/client.js +0 -150
  16. package/dist/cjs/core/call.js +0 -60
  17. package/dist/cjs/core/error-codes.js +0 -87
  18. package/dist/cjs/core/errors.js +0 -210
  19. package/dist/cjs/core/files.js +0 -131
  20. package/dist/cjs/core/http.js +0 -242
  21. package/dist/cjs/core/meta.js +0 -52
  22. package/dist/cjs/core/redact.js +0 -208
  23. package/dist/cjs/core/runtime.js +0 -86
  24. package/dist/cjs/core/settings.js +0 -22
  25. package/dist/cjs/core/sha256.js +0 -101
  26. package/dist/cjs/models.js +0 -234
  27. package/dist/cjs/resources/bank-accounts.js +0 -126
  28. package/dist/cjs/resources/banks.js +0 -22
  29. package/dist/cjs/resources/jobs.js +0 -177
  30. package/dist/cjs/resources/v1.js +0 -137
  31. package/dist/cjs/resources/verify.js +0 -105
  32. package/dist/cjs/version.js +0 -5
  33. package/dist/cjs/webhooks.js +0 -92
  34. package/dist/esm/client.js +0 -146
  35. package/dist/esm/core/call.js +0 -52
  36. package/dist/esm/core/error-codes.js +0 -84
  37. package/dist/esm/core/errors.js +0 -184
  38. package/dist/esm/core/files.js +0 -126
  39. package/dist/esm/core/http.js +0 -235
  40. package/dist/esm/core/meta.js +0 -45
  41. package/dist/esm/core/redact.js +0 -198
  42. package/dist/esm/core/runtime.js +0 -47
  43. package/dist/esm/core/settings.js +0 -19
  44. package/dist/esm/core/sha256.js +0 -96
  45. package/dist/esm/models.js +0 -228
  46. package/dist/esm/resources/bank-accounts.js +0 -122
  47. package/dist/esm/resources/banks.js +0 -18
  48. package/dist/esm/resources/jobs.js +0 -173
  49. package/dist/esm/resources/v1.js +0 -133
  50. package/dist/esm/resources/verify.js +0 -100
  51. package/dist/esm/version.js +0 -2
  52. package/dist/esm/webhooks.js +0 -86
@@ -1,122 +0,0 @@
1
- import { call, defined, requestOptions, requireId } from '../core/call.js';
2
- const CREATE_KEYS = [
3
- 'bankCode',
4
- 'bankNumber',
5
- 'nameTh',
6
- 'nameEn',
7
- 'type',
8
- 'extraVerify',
9
- 'matchMode',
10
- ];
11
- function listQuery(params) {
12
- return {
13
- type: params?.type,
14
- bankCode: params?.bankCode,
15
- page: params?.page === undefined ? undefined : String(params.page),
16
- limit: params?.limit === undefined ? undefined : String(params.limit),
17
- };
18
- }
19
- /** Receiving bank accounts used by `matchAccount` (`client.bankAccounts`). */
20
- export class BankAccounts {
21
- #t;
22
- constructor(transport) {
23
- this.#t = transport;
24
- }
25
- /** One page of the accounts linked to this branch. */
26
- async list(params, options) {
27
- return call(this.#t, 'BankAccountPage', {
28
- ...requestOptions(options),
29
- api: 'v2',
30
- method: 'GET',
31
- path: '/bank-accounts',
32
- query: listQuery(params),
33
- retry: 'safe',
34
- });
35
- }
36
- /** One page of every active account of the service, linked to this branch or not. */
37
- async listAll(params, options) {
38
- return call(this.#t, 'BankAccountPage', {
39
- ...requestOptions(options),
40
- api: 'v2',
41
- method: 'GET',
42
- path: '/bank-accounts/all',
43
- query: listQuery(params),
44
- retry: 'safe',
45
- });
46
- }
47
- /** Gets one account linked to this branch. */
48
- async get(id, options) {
49
- requireId(id);
50
- return call(this.#t, 'BankAccount', {
51
- ...requestOptions(options),
52
- api: 'v2',
53
- method: 'GET',
54
- path: `/bank-accounts/${id}`,
55
- retry: 'safe',
56
- });
57
- }
58
- /** Registers an account on the service and links it to this branch. */
59
- async create(params, options) {
60
- return call(this.#t, 'BankAccount', {
61
- ...requestOptions(options),
62
- api: 'v2',
63
- method: 'POST',
64
- path: '/bank-accounts',
65
- json: defined(params, CREATE_KEYS),
66
- retry: 'write',
67
- });
68
- }
69
- /** Changes the fields you pass. Pass `extraVerify: null` to clear it. */
70
- async update(id, params, options) {
71
- requireId(id);
72
- return call(this.#t, 'BankAccount', {
73
- ...requestOptions(options),
74
- api: 'v2',
75
- method: 'PATCH',
76
- path: `/bank-accounts/${id}`,
77
- json: defined(params, CREATE_KEYS),
78
- retry: 'write',
79
- });
80
- }
81
- /** Links an existing service account to this branch. Linking twice is fine. */
82
- async link(id, options) {
83
- requireId(id);
84
- return call(this.#t, 'LinkResult', {
85
- ...requestOptions(options),
86
- api: 'v2',
87
- method: 'POST',
88
- path: `/bank-accounts/${id}/link`,
89
- retry: 'safe',
90
- });
91
- }
92
- /** Unlinks an account from this branch. The account stays on the service. */
93
- async unlink(id, options) {
94
- requireId(id);
95
- return call(this.#t, 'UnlinkResult', {
96
- ...requestOptions(options),
97
- api: 'v2',
98
- method: 'DELETE',
99
- path: `/bank-accounts/${id}/link`,
100
- retry: 'write',
101
- });
102
- }
103
- /** Walks every page of {@link list}, one request per page (100 accounts by default). */
104
- iterate(params, options) {
105
- return this.#walk((p) => this.list(p, options), params);
106
- }
107
- /** Walks every page of {@link listAll}. */
108
- iterateAll(params, options) {
109
- return this.#walk((p) => this.listAll(p, options), params);
110
- }
111
- async *#walk(fetchPage, params) {
112
- let page = params?.page ?? 1;
113
- const limit = params?.limit ?? 100;
114
- while (true) {
115
- const result = await fetchPage({ ...params, page, limit });
116
- yield* result.items;
117
- if (result.items.length === 0 || page * limit >= result.total)
118
- return;
119
- page++;
120
- }
121
- }
122
- }
@@ -1,18 +0,0 @@
1
- import { call, requestOptions } from '../core/call.js';
2
- /** Supported banks and receiving kinds (`client.banks`). */
3
- export class Banks {
4
- #t;
5
- constructor(transport) {
6
- this.#t = transport;
7
- }
8
- /** Lists the bank codes you can register accounts with, and their `extraVerify` options. */
9
- async list(options) {
10
- return call(this.#t, 'BankList', {
11
- ...requestOptions(options),
12
- api: 'v2',
13
- method: 'GET',
14
- path: '/banks',
15
- retry: 'safe',
16
- });
17
- }
18
- }
@@ -1,173 +0,0 @@
1
- import { call, defined, requestOptions, requireString } from '../core/call.js';
2
- import { BatchSubmitError, InputError, JobWaitTimeoutError, RequestTimeoutError, } from '../core/errors.js';
3
- import { verifyFields } from './verify.js';
4
- /** Most slips one batch call accepts. {@link Jobs.submitBankMany} splits larger lists. */
5
- export const BATCH_MAX = 100;
6
- const SLIP_KEYS = ['payload', 'remark', 'matchAccount', 'matchAmount', 'checkDuplicate'];
7
- /**
8
- * Async bank slip verification (`client.jobs`). Submits are billed when the job verifies the
9
- * slip; like the sync calls they are never retried once the request may have arrived.
10
- */
11
- export class Jobs {
12
- #t;
13
- #sleep;
14
- #timeout;
15
- constructor(transport) {
16
- this.#t = transport;
17
- this.#sleep = transport.config.sleep;
18
- this.#timeout = transport.config.timeout;
19
- }
20
- /** Queues one QR payload. The result arrives on the webhook or through {@link get}. */
21
- async submitBank(payload, options) {
22
- requireString(payload, 'payload');
23
- const json = { payload, ...verifyFields(options) };
24
- if (options?.callbackUrl !== undefined)
25
- json.callbackUrl = options.callbackUrl;
26
- return call(this.#t, 'JobSubmission', {
27
- ...requestOptions(options),
28
- api: 'v2',
29
- method: 'POST',
30
- path: '/verify/bank/async',
31
- json,
32
- retry: 'billed',
33
- });
34
- }
35
- /** Queues 1 to 100 payloads in one call. Each slip becomes its own job. */
36
- async submitBankBatch(slips, options) {
37
- if (!Array.isArray(slips) || slips.length === 0) {
38
- throw new InputError('EMPTY_BATCH', 'slips must contain at least one slip');
39
- }
40
- if (slips.length > BATCH_MAX) {
41
- throw new InputError('BATCH_TOO_LARGE', `a batch takes at most ${BATCH_MAX} slips; use submitBankMany for more`);
42
- }
43
- for (const slip of slips)
44
- requireString(slip?.payload, 'slip payload');
45
- const json = {};
46
- if (options?.callbackUrl !== undefined)
47
- json.callbackUrl = options.callbackUrl;
48
- json.slips = slips.map((slip) => defined(slip, SLIP_KEYS));
49
- return call(this.#t, 'BatchSubmission', {
50
- ...requestOptions(options),
51
- api: 'v2',
52
- method: 'POST',
53
- path: '/verify/bank/batch',
54
- json,
55
- retry: 'billed',
56
- });
57
- }
58
- /**
59
- * Queues any number of payloads, 100 per call, one call after another. Quota is the same as
60
- * one big batch: each slip is billed when its job verifies it. If a call fails, the batches
61
- * already accepted keep running and {@link BatchSubmitError} lists them.
62
- */
63
- async submitBankMany(slips, options) {
64
- if (!Array.isArray(slips) || slips.length === 0) {
65
- throw new InputError('EMPTY_BATCH', 'slips must contain at least one slip');
66
- }
67
- const submitted = [];
68
- for (let start = 0, chunk = 0; start < slips.length; start += BATCH_MAX, chunk++) {
69
- try {
70
- submitted.push(await this.submitBankBatch(slips.slice(start, start + BATCH_MAX), options));
71
- }
72
- catch (cause) {
73
- throw new BatchSubmitError(submitted, chunk, cause);
74
- }
75
- }
76
- return submitted;
77
- }
78
- /** Gets a job by id. */
79
- async get(jobId, options) {
80
- requireString(jobId, 'jobId');
81
- return call(this.#t, 'Job', {
82
- ...requestOptions(options),
83
- api: 'v2',
84
- method: 'GET',
85
- path: `/verify/bank/jobs/${encodeURIComponent(jobId)}`,
86
- retry: 'safe',
87
- });
88
- }
89
- /**
90
- * Polls a job until its status is `done` or `failed` and returns it. A failed job is
91
- * returned, not thrown. `timeout` is one deadline for the whole wait: each
92
- * poll and its retries get only the time left, a request still running at the deadline is
93
- * cancelled, and an answer that arrives after the deadline is not returned. Then it throws
94
- * {@link JobWaitTimeoutError} with the last job received in time. Aborting `signal` rejects
95
- * with the signal's reason instead.
96
- */
97
- async waitForJob(jobId, options) {
98
- requireString(jobId, 'jobId');
99
- const interval = Math.max(500, options?.interval ?? 2000);
100
- const timeout = options?.timeout ?? 600_000;
101
- if (!Number.isFinite(timeout) || timeout < 0) {
102
- throw new InputError('INVALID_ARGUMENT', 'timeout must be a number >= 0');
103
- }
104
- const caller = options?.signal;
105
- caller?.throwIfAborted();
106
- const deadline = Date.now() + timeout;
107
- let last = null;
108
- const expired = () => new JobWaitTimeoutError(`job ${jobId} ${last ? `still ${last.status}` : 'not read'} after ${timeout} ms`, last);
109
- // One signal for every request and wait: aborted by the caller or at the deadline.
110
- const budget = new AbortController();
111
- const reason = new Error('waitForJob deadline');
112
- const timer = setTimeout(() => budget.abort(reason), timeout);
113
- const onAbort = () => budget.abort(caller?.reason);
114
- caller?.addEventListener('abort', onAbort, { once: true });
115
- const deadlinePassed = () => budget.signal.reason === reason && !caller?.aborted;
116
- // Settles when the budget is aborted, so a custom fetch or sleep that ignores the signal
117
- // cannot hold the call past the deadline.
118
- const stopped = new Promise((_, reject) => {
119
- budget.signal.addEventListener('abort', () => reject(budget.signal.reason), {
120
- once: true,
121
- });
122
- });
123
- stopped.catch(() => { });
124
- try {
125
- while (true) {
126
- const left = deadline - Date.now();
127
- if (left <= 0)
128
- throw expired();
129
- // The attempt timeout is cut to the time left, so its timeout is the deadline too.
130
- const capped = left < this.#timeout;
131
- let job;
132
- try {
133
- job = await Promise.race([
134
- this.get(jobId, {
135
- signal: budget.signal,
136
- timeout: Math.max(1, Math.min(this.#timeout, left)),
137
- }),
138
- stopped,
139
- ]);
140
- }
141
- catch (error) {
142
- if (deadlinePassed())
143
- throw expired();
144
- if (capped && error instanceof RequestTimeoutError && !caller?.aborted) {
145
- throw expired();
146
- }
147
- throw error;
148
- }
149
- // A request that ignored cancellation can still answer late: do not return it.
150
- if (Date.now() >= deadline)
151
- throw expired();
152
- last = job;
153
- if (job.status === 'done' || job.status === 'failed')
154
- return job;
155
- const wait = Math.min(interval, deadline - Date.now());
156
- if (wait <= 0)
157
- throw expired();
158
- try {
159
- await Promise.race([this.#sleep(wait, budget.signal), stopped]);
160
- }
161
- catch (error) {
162
- if (deadlinePassed())
163
- throw expired();
164
- throw error;
165
- }
166
- }
167
- }
168
- finally {
169
- clearTimeout(timer);
170
- caller?.removeEventListener('abort', onAbort);
171
- }
172
- }
173
- }
@@ -1,133 +0,0 @@
1
- import { call, imageForm, requestOptions, requireString } from '../core/call.js';
2
- import { InputError } from '../core/errors.js';
3
- import { prepareFile } from '../core/files.js';
4
- function decodeBase64(text) {
5
- const binary = atob(text);
6
- const out = new Uint8Array(binary.length);
7
- for (let i = 0; i < binary.length; i++)
8
- out[i] = binary.charCodeAt(i);
9
- return out;
10
- }
11
- function boolString(value) {
12
- return value ? 'true' : 'false';
13
- }
14
- /** The v1 API (`client.v1`). Verify calls are billed; `generateQr` is free. */
15
- export class V1 {
16
- #t;
17
- constructor(transport) {
18
- this.#t = transport;
19
- }
20
- /** Quota and credit of the application. */
21
- async getMe(options) {
22
- return call(this.#t, 'V1Me', {
23
- ...requestOptions(options),
24
- api: 'v1',
25
- method: 'GET',
26
- path: '/me',
27
- retry: 'safe',
28
- });
29
- }
30
- /** Verifies a bank slip from its QR payload (`GET /verify`). */
31
- async verifyBankByPayload(payload, options) {
32
- requireString(payload, 'payload');
33
- return call(this.#t, 'BankSlip', {
34
- ...requestOptions(options),
35
- api: 'v1',
36
- method: 'GET',
37
- path: '/verify',
38
- query: {
39
- payload,
40
- checkDuplicate: options?.checkDuplicate === undefined
41
- ? undefined
42
- : boolString(options.checkDuplicate),
43
- },
44
- retry: 'billed',
45
- duplicateSlip: 'BankSlip',
46
- });
47
- }
48
- /** Verifies a bank slip image (multipart field `file`). */
49
- async verifyBankByImage(file, options) {
50
- const prepared = await prepareFile(file);
51
- const fields = {};
52
- if (options?.checkDuplicate !== undefined) {
53
- fields.checkDuplicate = boolString(options.checkDuplicate);
54
- }
55
- return call(this.#t, 'BankSlip', {
56
- ...requestOptions(options),
57
- api: 'v1',
58
- method: 'POST',
59
- path: '/verify',
60
- form: imageForm('file', prepared, fields),
61
- retry: 'billed',
62
- duplicateSlip: 'BankSlip',
63
- });
64
- }
65
- /** Verifies a base64 bank slip image. Sent as the JSON field `image`. */
66
- async verifyBankByBase64(base64, options) {
67
- requireString(base64, 'base64');
68
- const json = { image: base64 };
69
- if (options?.checkDuplicate !== undefined)
70
- json.checkDuplicate = options.checkDuplicate;
71
- return call(this.#t, 'BankSlip', {
72
- ...requestOptions(options),
73
- api: 'v1',
74
- method: 'POST',
75
- path: '/verify',
76
- json,
77
- retry: 'billed',
78
- duplicateSlip: 'BankSlip',
79
- });
80
- }
81
- /** Verifies a bank slip image the API downloads from a public URL. */
82
- async verifyBankByUrl(url, options) {
83
- requireString(url, 'url');
84
- const json = { url };
85
- if (options?.checkDuplicate !== undefined)
86
- json.checkDuplicate = options.checkDuplicate;
87
- return call(this.#t, 'BankSlip', {
88
- ...requestOptions(options),
89
- api: 'v1',
90
- method: 'POST',
91
- path: '/verify',
92
- json,
93
- retry: 'billed',
94
- duplicateSlip: 'BankSlip',
95
- });
96
- }
97
- /** Verifies a TrueMoney Wallet slip image. */
98
- async verifyTruemoneyByImage(file, options) {
99
- const prepared = await prepareFile(file);
100
- const fields = {};
101
- if (options?.checkDuplicate !== undefined) {
102
- fields.checkDuplicate = boolString(options.checkDuplicate);
103
- }
104
- return call(this.#t, 'TrueWalletSlip', {
105
- ...requestOptions(options),
106
- api: 'v1',
107
- method: 'POST',
108
- path: '/verify/truewallet',
109
- form: imageForm('file', prepared, fields),
110
- retry: 'billed',
111
- duplicateSlip: 'TrueWalletSlip',
112
- });
113
- }
114
- /** Generates a payment QR image. No quota is used. */
115
- async generateQr(request, options) {
116
- if (!request || typeof request !== 'object') {
117
- throw new InputError('INVALID_ARGUMENT', 'request must be an object with a type');
118
- }
119
- const result = await call(this.#t, 'QrCode', {
120
- ...requestOptions(options),
121
- api: 'v1',
122
- method: 'POST',
123
- path: '/qr/generate',
124
- json: request,
125
- retry: 'safe',
126
- });
127
- Object.defineProperty(result, 'imageBytes', {
128
- value: () => decodeBase64(result.image),
129
- enumerable: false,
130
- });
131
- return result;
132
- }
133
- }
@@ -1,100 +0,0 @@
1
- import { call, defined, imageForm, requestOptions, requireString } from '../core/call.js';
2
- import { prepareFile } from '../core/files.js';
3
- const OPTION_KEYS = ['remark', 'matchAccount', 'matchAmount', 'checkDuplicate'];
4
- export function verifyFields(options) {
5
- return defined(options, OPTION_KEYS);
6
- }
7
- /**
8
- * v2 slip verification (`client.verify`). Every call here is billed: it can spend quota, so
9
- * the SDK only retries it when the request never reached the API (or on 429).
10
- */
11
- export class Verify {
12
- #t;
13
- constructor(transport) {
14
- this.#t = transport;
15
- }
16
- /** Verifies a bank slip from its QR payload string. */
17
- async bankByPayload(payload, options) {
18
- requireString(payload, 'payload');
19
- return call(this.#t, 'BankSlipResult', {
20
- ...requestOptions(options),
21
- api: 'v2',
22
- method: 'POST',
23
- path: '/verify/bank',
24
- json: { payload, ...verifyFields(options) },
25
- retry: 'billed',
26
- });
27
- }
28
- /** Verifies a bank slip image (JPEG, PNG, GIF or WebP, up to 4 MB). */
29
- async bankByImage(file, options) {
30
- const prepared = await prepareFile(file);
31
- return call(this.#t, 'BankSlipResult', {
32
- ...requestOptions(options),
33
- api: 'v2',
34
- method: 'POST',
35
- path: '/verify/bank',
36
- form: imageForm('image', prepared, verifyFields(options)),
37
- retry: 'billed',
38
- });
39
- }
40
- /** Verifies a base64 bank slip image. A `data:image/...;base64,` prefix is fine. */
41
- async bankByBase64(base64, options) {
42
- requireString(base64, 'base64');
43
- return call(this.#t, 'BankSlipResult', {
44
- ...requestOptions(options),
45
- api: 'v2',
46
- method: 'POST',
47
- path: '/verify/bank',
48
- json: { base64, ...verifyFields(options) },
49
- retry: 'billed',
50
- });
51
- }
52
- /** Verifies a bank slip image the API downloads from a public http(s) URL. */
53
- async bankByUrl(url, options) {
54
- requireString(url, 'url');
55
- return call(this.#t, 'BankSlipResult', {
56
- ...requestOptions(options),
57
- api: 'v2',
58
- method: 'POST',
59
- path: '/verify/bank',
60
- json: { url, ...verifyFields(options) },
61
- retry: 'billed',
62
- });
63
- }
64
- /** Verifies a TrueMoney Wallet slip image. */
65
- async truewalletByImage(file, options) {
66
- const prepared = await prepareFile(file);
67
- return call(this.#t, 'TrueWalletResult', {
68
- ...requestOptions(options),
69
- api: 'v2',
70
- method: 'POST',
71
- path: '/verify/truewallet',
72
- form: imageForm('image', prepared, verifyFields(options)),
73
- retry: 'billed',
74
- });
75
- }
76
- /** Verifies a base64 TrueMoney Wallet slip image. */
77
- async truewalletByBase64(base64, options) {
78
- requireString(base64, 'base64');
79
- return call(this.#t, 'TrueWalletResult', {
80
- ...requestOptions(options),
81
- api: 'v2',
82
- method: 'POST',
83
- path: '/verify/truewallet',
84
- json: { base64, ...verifyFields(options) },
85
- retry: 'billed',
86
- });
87
- }
88
- /** Verifies a TrueMoney Wallet slip image from a public URL (up to 255 characters). */
89
- async truewalletByUrl(url, options) {
90
- requireString(url, 'url');
91
- return call(this.#t, 'TrueWalletResult', {
92
- ...requestOptions(options),
93
- api: 'v2',
94
- method: 'POST',
95
- path: '/verify/truewallet',
96
- json: { url, ...verifyFields(options) },
97
- retry: 'billed',
98
- });
99
- }
100
- }
@@ -1,2 +0,0 @@
1
- /** SDK version, sent in the User-Agent header. */
2
- export const VERSION = '1.0.0'; // x-release-please-version
@@ -1,86 +0,0 @@
1
- import { InputError, WebhookSignatureError } from './core/errors.js';
2
- import { readEnv } from './core/runtime.js';
3
- import { settings } from './core/settings.js';
4
- import { hmacSha256, toHex } from './core/sha256.js';
5
- import { parseModel } from './models.js';
6
- /** Name of the header that carries the webhook signature. */
7
- export const WEBHOOK_SIGNATURE_HEADER = settings.webhook.signatureHeader;
8
- const PREFIX = settings.webhook.signaturePrefix;
9
- const SIGNATURE = /^[0-9a-f]{64}$/;
10
- function toBytes(body) {
11
- if (typeof body === 'string')
12
- return new TextEncoder().encode(body);
13
- if (body instanceof ArrayBuffer)
14
- return new Uint8Array(body);
15
- if (body instanceof Uint8Array)
16
- return body;
17
- throw new InputError('INVALID_ARGUMENT', 'webhook body must be a string or bytes');
18
- }
19
- function secretOrEnv(secret) {
20
- const value = secret ?? readEnv(settings.env.webhookSecret);
21
- if (!value) {
22
- throw new InputError('INVALID_ARGUMENT', `no webhook secret: pass one or set ${settings.env.webhookSecret}`);
23
- }
24
- return value;
25
- }
26
- function equalConstantTime(a, b) {
27
- if (a.length !== b.length)
28
- return false;
29
- let diff = 0;
30
- for (let i = 0; i < a.length; i++)
31
- diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
32
- return diff === 0;
33
- }
34
- /**
35
- * Checks a webhook signature: `sha256=` plus the lower-case hex HMAC-SHA256 of the raw body
36
- * under your webhook secret, compared in constant time. Pass the body exactly as received,
37
- * before any JSON parsing. A missing header gives false.
38
- *
39
- * @param secret Your branch's webhook secret. Defaults to the webhook secret env variable.
40
- */
41
- export function verifyWebhookSignature(rawBody, signatureHeader, secret) {
42
- const key = secretOrEnv(secret);
43
- const header = Array.isArray(signatureHeader) ? signatureHeader[0] : signatureHeader;
44
- if (typeof header !== 'string' || !header.startsWith(PREFIX))
45
- return false;
46
- const given = header.slice(PREFIX.length);
47
- if (!SIGNATURE.test(given))
48
- return false;
49
- const expected = toHex(hmacSha256(new TextEncoder().encode(key), toBytes(rawBody)));
50
- return equalConstantTime(given, expected);
51
- }
52
- /**
53
- * Parses a webhook body into a {@link WebhookEvent} without checking the signature. Throws
54
- * {@link InputError} when the body is not a JSON object with string `jobId`, `status` and
55
- * `timestamp` fields.
56
- */
57
- export function parseWebhookEvent(rawBody) {
58
- const text = typeof rawBody === 'string' ? rawBody : new TextDecoder().decode(toBytes(rawBody));
59
- let value;
60
- try {
61
- value = JSON.parse(text);
62
- }
63
- catch (cause) {
64
- throw new InputError('INVALID_ARGUMENT', 'webhook body is not JSON', { cause });
65
- }
66
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
67
- throw new InputError('INVALID_ARGUMENT', 'webhook body is not a JSON object');
68
- }
69
- const fields = value;
70
- if (typeof fields.jobId !== 'string' ||
71
- typeof fields.status !== 'string' ||
72
- typeof fields.timestamp !== 'string') {
73
- throw new InputError('INVALID_ARGUMENT', 'webhook body must contain jobId, status and timestamp');
74
- }
75
- return parseModel('WebhookEvent', value);
76
- }
77
- /**
78
- * Verifies the signature, then parses the body. Throws {@link WebhookSignatureError} when the
79
- * signature is missing or wrong, and {@link InputError} when a signed body is not a webhook event.
80
- */
81
- export function constructWebhookEvent(rawBody, signatureHeader, secret) {
82
- if (!verifyWebhookSignature(rawBody, signatureHeader, secret)) {
83
- throw new WebhookSignatureError(`webhook signature in ${WEBHOOK_SIGNATURE_HEADER} is missing or does not match`);
84
- }
85
- return parseWebhookEvent(rawBody);
86
- }