@onesim.global/sdk 0.0.0-stage → 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/CHANGELOG.md +40 -0
- package/LICENSE +21 -0
- package/README.md +365 -2
- package/dist/cjs/client.d.ts +130 -0
- package/dist/cjs/client.js +314 -0
- package/dist/cjs/errors.d.ts +126 -0
- package/dist/cjs/errors.js +199 -0
- package/dist/cjs/generated/openapi.d.ts +2090 -0
- package/dist/cjs/generated/openapi.js +5 -0
- package/dist/cjs/http.d.ts +40 -0
- package/dist/cjs/http.js +211 -0
- package/dist/cjs/index.d.ts +8 -0
- package/dist/cjs/index.js +27 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/types.d.ts +56 -0
- package/dist/cjs/types.js +4 -0
- package/dist/cjs/webhooks.d.ts +26 -0
- package/dist/cjs/webhooks.js +98 -0
- package/dist/esm/client.d.ts +130 -0
- package/dist/esm/client.js +306 -0
- package/dist/esm/errors.d.ts +126 -0
- package/dist/esm/errors.js +182 -0
- package/dist/esm/generated/openapi.d.ts +2090 -0
- package/dist/esm/generated/openapi.js +4 -0
- package/dist/esm/http.d.ts +40 -0
- package/dist/esm/http.js +205 -0
- package/dist/esm/index.d.ts +8 -0
- package/dist/esm/index.js +5 -0
- package/dist/esm/types.d.ts +56 -0
- package/dist/esm/types.js +3 -0
- package/dist/esm/webhooks.d.ts +26 -0
- package/dist/esm/webhooks.js +95 -0
- package/package.json +64 -4
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** The part of `fetch` the SDK uses. The global `fetch` of every runtime fits. */
|
|
2
|
+
export type FetchLike = (url: string, init: FetchInit) => Promise<FetchResponse>;
|
|
3
|
+
export interface FetchInit {
|
|
4
|
+
method: string;
|
|
5
|
+
headers: Record<string, string>;
|
|
6
|
+
body?: string;
|
|
7
|
+
signal: AbortSignal;
|
|
8
|
+
}
|
|
9
|
+
export interface FetchResponse {
|
|
10
|
+
readonly status: number;
|
|
11
|
+
readonly statusText: string;
|
|
12
|
+
readonly headers: {
|
|
13
|
+
get(name: string): string | null;
|
|
14
|
+
};
|
|
15
|
+
text(): Promise<string>;
|
|
16
|
+
}
|
|
17
|
+
export interface HttpConfig {
|
|
18
|
+
apiKey: string;
|
|
19
|
+
baseURL: string;
|
|
20
|
+
/** Per attempt, in milliseconds. */
|
|
21
|
+
timeout: number;
|
|
22
|
+
maxRetries: number;
|
|
23
|
+
fetch: FetchLike;
|
|
24
|
+
}
|
|
25
|
+
export type Query = Record<string, string | number | Date | null | undefined>;
|
|
26
|
+
export interface HttpRequest {
|
|
27
|
+
method: 'GET' | 'POST';
|
|
28
|
+
path: string;
|
|
29
|
+
query?: Query;
|
|
30
|
+
body?: unknown;
|
|
31
|
+
idempotencyKey?: string;
|
|
32
|
+
signal?: AbortSignal | undefined;
|
|
33
|
+
}
|
|
34
|
+
export declare class Http {
|
|
35
|
+
#private;
|
|
36
|
+
constructor(config: HttpConfig);
|
|
37
|
+
request<T>(request: HttpRequest): Promise<T>;
|
|
38
|
+
}
|
|
39
|
+
export declare function throwIfAborted(signal: AbortSignal | undefined): void;
|
|
40
|
+
export declare function sleep(ms: number, signal: AbortSignal | undefined): Promise<void>;
|
package/dist/esm/http.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// One request to the API, with a timeout per attempt and retries with
|
|
2
|
+
// backoff. Which answers are retried is the guide's (openapi.ts, "Errors" and
|
|
3
|
+
// "Idempotency"): no answer, 429 and 5xx, except the two final ones.
|
|
4
|
+
import { APIConnectionError, APIConnectionTimeoutError, makeAPIError, OnesimError } from './errors.js';
|
|
5
|
+
const BACKOFF_BASE_MS = 500;
|
|
6
|
+
const BACKOFF_CAP_MS = 8_000;
|
|
7
|
+
const RETRY_AFTER_CAP_MS = 60_000;
|
|
8
|
+
const RETRIED_STATUSES = new Set([429, 500, 502, 503, 504]);
|
|
9
|
+
// Final answers: the order failed for good and was refunded, or no eSIM can be
|
|
10
|
+
// issued for a while. Retrying them in seconds changes nothing.
|
|
11
|
+
const FINAL_CODES = new Set(['provisioning_failed', 'esims_unavailable']);
|
|
12
|
+
export class Http {
|
|
13
|
+
#config;
|
|
14
|
+
constructor(config) {
|
|
15
|
+
this.#config = config;
|
|
16
|
+
}
|
|
17
|
+
async request(request) {
|
|
18
|
+
const { maxRetries } = this.#config;
|
|
19
|
+
const { signal, idempotencyKey } = request;
|
|
20
|
+
const url = this.#url(request.path, request.query);
|
|
21
|
+
const headers = {
|
|
22
|
+
authorization: `Bearer ${this.#config.apiKey}`,
|
|
23
|
+
accept: 'application/json'
|
|
24
|
+
};
|
|
25
|
+
let body;
|
|
26
|
+
if (request.body !== undefined) {
|
|
27
|
+
headers['content-type'] = 'application/json';
|
|
28
|
+
body = JSON.stringify(request.body);
|
|
29
|
+
}
|
|
30
|
+
if (idempotencyKey !== undefined)
|
|
31
|
+
headers['idempotency-key'] = idempotencyKey;
|
|
32
|
+
for (let attempt = 0;; attempt++) {
|
|
33
|
+
throwIfAborted(signal);
|
|
34
|
+
let status;
|
|
35
|
+
let text;
|
|
36
|
+
let response;
|
|
37
|
+
try {
|
|
38
|
+
({ response, text } = await this.#attempt(url, { method: request.method, headers, body }, signal));
|
|
39
|
+
status = response.status;
|
|
40
|
+
}
|
|
41
|
+
catch (cause) {
|
|
42
|
+
// The caller's own abort ends the call as it is.
|
|
43
|
+
throwIfAborted(signal);
|
|
44
|
+
if (attempt < maxRetries) {
|
|
45
|
+
await sleep(backoff(attempt), signal);
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
const reason = cause instanceof Error ? cause.message : String(cause);
|
|
49
|
+
const message = `No answer from the onesim API after ${attempt + 1} attempt${attempt ? 's' : ''}: ${reason}`;
|
|
50
|
+
const options = {
|
|
51
|
+
cause,
|
|
52
|
+
...(idempotencyKey !== undefined && { idempotencyKey })
|
|
53
|
+
};
|
|
54
|
+
throw isTimeout(cause)
|
|
55
|
+
? new APIConnectionTimeoutError(message, options)
|
|
56
|
+
: new APIConnectionError(message, options);
|
|
57
|
+
}
|
|
58
|
+
if (status >= 200 && status < 300) {
|
|
59
|
+
try {
|
|
60
|
+
return JSON.parse(text);
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
const error = new OnesimError(`The onesim API answered ${status} with a body that is not JSON.`);
|
|
64
|
+
if (idempotencyKey !== undefined)
|
|
65
|
+
error.idempotencyKey = idempotencyKey;
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const error = apiError(response, text, idempotencyKey);
|
|
70
|
+
if (attempt < maxRetries &&
|
|
71
|
+
RETRIED_STATUSES.has(status) &&
|
|
72
|
+
!FINAL_CODES.has(error.code ?? '')) {
|
|
73
|
+
const wait = error.retryAfter !== undefined
|
|
74
|
+
? Math.min(error.retryAfter * 1000, RETRY_AFTER_CAP_MS)
|
|
75
|
+
: backoff(attempt);
|
|
76
|
+
await sleep(wait, signal);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
throw error;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
#url(path, query = {}) {
|
|
83
|
+
const search = new URLSearchParams();
|
|
84
|
+
for (const [name, value] of Object.entries(query)) {
|
|
85
|
+
if (value === undefined || value === null)
|
|
86
|
+
continue;
|
|
87
|
+
search.set(name, value instanceof Date ? value.toISOString() : String(value));
|
|
88
|
+
}
|
|
89
|
+
const qs = search.toString();
|
|
90
|
+
return `${this.#config.baseURL}${path}${qs ? `?${qs}` : ''}`;
|
|
91
|
+
}
|
|
92
|
+
// One attempt, the body read included, within the timeout. Settles when the
|
|
93
|
+
// timeout or the caller's signal fires even if `fetch` ignores its signal;
|
|
94
|
+
// a timed-out attempt rejects with a TimeoutError.
|
|
95
|
+
async #attempt(url, init, signal) {
|
|
96
|
+
const { timeout } = this.#config;
|
|
97
|
+
const timedOut = new DOMException(`The request timed out after ${timeout} ms.`, 'TimeoutError');
|
|
98
|
+
const controller = new AbortController();
|
|
99
|
+
const aborted = new Promise((_, reject) => {
|
|
100
|
+
controller.signal.addEventListener('abort', () => reject(controller.signal.reason), { once: true });
|
|
101
|
+
});
|
|
102
|
+
const timer = setTimeout(() => controller.abort(timedOut), timeout);
|
|
103
|
+
const onAbort = () => controller.abort(signal?.reason);
|
|
104
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
105
|
+
try {
|
|
106
|
+
const exchange = (async () => {
|
|
107
|
+
const response = await this.#config.fetch(url, {
|
|
108
|
+
...init,
|
|
109
|
+
signal: controller.signal
|
|
110
|
+
});
|
|
111
|
+
return { response, text: await response.text() };
|
|
112
|
+
})();
|
|
113
|
+
return await Promise.race([exchange, aborted]);
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
// However `fetch` reports its abort, a timeout is a TimeoutError.
|
|
117
|
+
if (controller.signal.reason === timedOut)
|
|
118
|
+
throw timedOut;
|
|
119
|
+
throw error;
|
|
120
|
+
}
|
|
121
|
+
finally {
|
|
122
|
+
clearTimeout(timer);
|
|
123
|
+
signal?.removeEventListener('abort', onAbort);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function apiError(response, text, idempotencyKey) {
|
|
128
|
+
let body = text;
|
|
129
|
+
try {
|
|
130
|
+
body = JSON.parse(text);
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
// Not JSON (e.g. an HTML page from a proxy): keep the text.
|
|
134
|
+
}
|
|
135
|
+
const fields = isObject(body) && isObject(body.error) ? body.error : null;
|
|
136
|
+
const code = fields && typeof fields.code === 'string' ? fields.code : null;
|
|
137
|
+
const statusLine = `${response.status}${response.statusText ? ` ${response.statusText}` : ''}`;
|
|
138
|
+
const retryAfter = parseRetryAfter(response.headers.get('retry-after'));
|
|
139
|
+
return makeAPIError({
|
|
140
|
+
status: response.status,
|
|
141
|
+
code,
|
|
142
|
+
message: code && typeof fields?.message === 'string'
|
|
143
|
+
? fields.message
|
|
144
|
+
: `The onesim API answered ${statusLine}.`,
|
|
145
|
+
requestId: (fields && typeof fields.request_id === 'string'
|
|
146
|
+
? fields.request_id
|
|
147
|
+
: null) ?? response.headers.get('request-id'),
|
|
148
|
+
...(typeof fields?.amount === 'number' && { amount: fields.amount }),
|
|
149
|
+
...(typeof fields?.limit === 'string' && { limit: fields.limit }),
|
|
150
|
+
...(isObject(fields?.order) && { order: fields.order }),
|
|
151
|
+
...(retryAfter !== undefined && { retryAfter }),
|
|
152
|
+
...(idempotencyKey !== undefined && { idempotencyKey }),
|
|
153
|
+
body
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
function isTimeout(error) {
|
|
157
|
+
return (typeof error === 'object' &&
|
|
158
|
+
error !== null &&
|
|
159
|
+
error.name === 'TimeoutError');
|
|
160
|
+
}
|
|
161
|
+
function isObject(value) {
|
|
162
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
163
|
+
}
|
|
164
|
+
// Seconds, or an HTTP date.
|
|
165
|
+
function parseRetryAfter(value) {
|
|
166
|
+
if (value === null)
|
|
167
|
+
return undefined;
|
|
168
|
+
const trimmed = value.trim();
|
|
169
|
+
if (/^\d+$/.test(trimmed))
|
|
170
|
+
return Number(trimmed);
|
|
171
|
+
const date = Date.parse(trimmed);
|
|
172
|
+
if (Number.isNaN(date))
|
|
173
|
+
return undefined;
|
|
174
|
+
return Math.max(0, Math.ceil((date - Date.now()) / 1000));
|
|
175
|
+
}
|
|
176
|
+
// Exponential, capped, with jitter: half the step plus a random half.
|
|
177
|
+
function backoff(attempt) {
|
|
178
|
+
const step = Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** attempt);
|
|
179
|
+
return step / 2 + Math.random() * (step / 2);
|
|
180
|
+
}
|
|
181
|
+
export function throwIfAborted(signal) {
|
|
182
|
+
if (signal?.aborted) {
|
|
183
|
+
throw (signal.reason ??
|
|
184
|
+
new DOMException('This operation was aborted.', 'AbortError'));
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
export function sleep(ms, signal) {
|
|
188
|
+
return new Promise((resolve, reject) => {
|
|
189
|
+
if (signal?.aborted) {
|
|
190
|
+
reject(signal.reason ??
|
|
191
|
+
new DOMException('This operation was aborted.', 'AbortError'));
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
const onAbort = () => {
|
|
195
|
+
clearTimeout(timer);
|
|
196
|
+
reject(signal?.reason ??
|
|
197
|
+
new DOMException('This operation was aborted.', 'AbortError'));
|
|
198
|
+
};
|
|
199
|
+
const timer = setTimeout(() => {
|
|
200
|
+
signal?.removeEventListener('abort', onAbort);
|
|
201
|
+
resolve();
|
|
202
|
+
}, ms);
|
|
203
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
204
|
+
});
|
|
205
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { OnesimClient } from './client.js';
|
|
2
|
+
export { BalanceResource, type ClientOptions, type CreateAndPollOptions, type CreateOrderOptions, Esims, OnesimClient, Orders, Packages, type PollOptions, type RequestOptions } from './client.js';
|
|
3
|
+
export default OnesimClient;
|
|
4
|
+
export { APIConnectionError, APIConnectionTimeoutError, APIError, AuthenticationError, BadRequestError, ConflictError, InternalServerError, NotFoundError, OnesimError, PermissionDeniedError, PollTimeoutError, RateLimitError, WebhookVerificationError, type WebhookErrorReason } from './errors.js';
|
|
5
|
+
export type { FetchInit, FetchLike, FetchResponse } from './http.js';
|
|
6
|
+
export { verifyWebhook, type VerifyWebhookOptions } from './webhooks.js';
|
|
7
|
+
export type { Balance, BalanceEvent, Bundle, Catalogue, Country, Currency, ErrorCode, Esim, EsimList, EsimPackage, EsimSummary, Installation, ListEsimsParams, ListOrdersParams, Order, OrderEsim, OrderEvent, OrderList, OrderPackage, OrderRequest, OrderStatus, OrderType, Package, PackageEvent, PingEvent, WebhookEvent, WebhookEventType } from './types.js';
|
|
8
|
+
export type { components, operations, paths, webhooks } from './generated/openapi.js';
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { OnesimClient } from './client.js';
|
|
2
|
+
export { BalanceResource, Esims, OnesimClient, Orders, Packages } from './client.js';
|
|
3
|
+
export default OnesimClient;
|
|
4
|
+
export { APIConnectionError, APIConnectionTimeoutError, APIError, AuthenticationError, BadRequestError, ConflictError, InternalServerError, NotFoundError, OnesimError, PermissionDeniedError, PollTimeoutError, RateLimitError, WebhookVerificationError } from './errors.js';
|
|
5
|
+
export { verifyWebhook } from './webhooks.js';
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { components, operations } from './generated/openapi.js';
|
|
2
|
+
type Schemas = components['schemas'];
|
|
3
|
+
type Simplify<T> = {
|
|
4
|
+
[K in keyof T]: T[K];
|
|
5
|
+
} & {};
|
|
6
|
+
/** A package in your catalogue, with what it costs you each way of buying it. */
|
|
7
|
+
export type Package = Schemas['Package'];
|
|
8
|
+
/** The price of a package with a new eSIM (`type: 'bundle'`). */
|
|
9
|
+
export type Bundle = Schemas['Bundle'];
|
|
10
|
+
/** A country a package covers and the networks it uses there. */
|
|
11
|
+
export type Country = Schemas['Country'];
|
|
12
|
+
/** `GET /v1/packages`: your packages and the price of a blank eSIM. */
|
|
13
|
+
export type Catalogue = Schemas['Catalogue'];
|
|
14
|
+
/** The body of `POST /v1/orders`. */
|
|
15
|
+
export type OrderRequest = Schemas['OrderRequest'];
|
|
16
|
+
export type OrderType = OrderRequest['type'];
|
|
17
|
+
export type Order = Schemas['Order'];
|
|
18
|
+
/** `pending`, `completed`, `failed` or `refunded`. */
|
|
19
|
+
export type OrderStatus = Order['status'];
|
|
20
|
+
export type OrderEsim = Simplify<Schemas['OrderEsim']>;
|
|
21
|
+
export type OrderPackage = Schemas['OrderPackage'];
|
|
22
|
+
/** How to install an eSIM: the activation code and the one-tap links. */
|
|
23
|
+
export type Installation = Schemas['Installation'];
|
|
24
|
+
export type OrderList = Schemas['OrderList'];
|
|
25
|
+
export type EsimSummary = Schemas['EsimSummary'];
|
|
26
|
+
export type EsimList = Schemas['EsimList'];
|
|
27
|
+
/** An eSIM with its packages and usage, read live from the network. */
|
|
28
|
+
export type Esim = Simplify<Schemas['Esim']>;
|
|
29
|
+
export type EsimPackage = Schemas['EsimPackage'];
|
|
30
|
+
export type Balance = Schemas['Balance'];
|
|
31
|
+
/** `EUR` or `USD`: your account's currency. */
|
|
32
|
+
export type Currency = Balance['currency'];
|
|
33
|
+
/** The documented error codes. New ones may be added: handle an unknown one by its HTTP status. */
|
|
34
|
+
export type ErrorCode = Schemas['Error']['error']['code'];
|
|
35
|
+
type ListOrdersQuery = NonNullable<operations['listOrders']['parameters']['query']>;
|
|
36
|
+
/** Filters and paging for `orders.list`. `created_after` takes a `Date` or an ISO string. */
|
|
37
|
+
export type ListOrdersParams = Simplify<Omit<ListOrdersQuery, 'created_after'> & {
|
|
38
|
+
created_after?: string | Date;
|
|
39
|
+
}>;
|
|
40
|
+
/** Filters and paging for `esims.list`. */
|
|
41
|
+
export type ListEsimsParams = NonNullable<operations['listEsims']['parameters']['query']>;
|
|
42
|
+
/** `order.completed` or `order.failed`. */
|
|
43
|
+
export type OrderEvent = Simplify<Schemas['OrderEvent']>;
|
|
44
|
+
/** `package.activated`, `package.usage` or `package.expired`. */
|
|
45
|
+
export type PackageEvent = Simplify<Schemas['PackageEvent']>;
|
|
46
|
+
/** `balance.low`. */
|
|
47
|
+
export type BalanceEvent = Simplify<Schemas['BalanceEvent']>;
|
|
48
|
+
/** `ping`: a test event sent from the partner platform. */
|
|
49
|
+
export type PingEvent = Simplify<Schemas['PingEvent']>;
|
|
50
|
+
/**
|
|
51
|
+
* A webhook event, by `type`. onesim may add event types without notice:
|
|
52
|
+
* ignore a `type` you do not know.
|
|
53
|
+
*/
|
|
54
|
+
export type WebhookEvent = OrderEvent | PackageEvent | BalanceEvent | PingEvent;
|
|
55
|
+
export type WebhookEventType = WebhookEvent['type'];
|
|
56
|
+
export {};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { WebhookEvent } from './types.js';
|
|
2
|
+
export interface VerifyWebhookOptions {
|
|
3
|
+
/**
|
|
4
|
+
* The raw request body, exactly as received: a string or bytes. Not parsed
|
|
5
|
+
* JSON: re-serialising changes the bytes and the signature no longer matches.
|
|
6
|
+
*/
|
|
7
|
+
payload: string | Uint8Array;
|
|
8
|
+
/** The `Onesim-Signature` header. */
|
|
9
|
+
signature: string | null | undefined;
|
|
10
|
+
/** The endpoint's signing secret, `whsec_…`. */
|
|
11
|
+
secret: string;
|
|
12
|
+
/** How old (or how far in the future) `t` may be, in seconds. Default 300. */
|
|
13
|
+
toleranceSeconds?: number;
|
|
14
|
+
/** The time to check `t` against. Default: now. */
|
|
15
|
+
now?: Date;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Checks a webhook delivery's signature and age and returns its event.
|
|
19
|
+
* Throws `WebhookVerificationError` (with a `reason`) when it fails: answer such a
|
|
20
|
+
* request with a 400 and do not act on it.
|
|
21
|
+
*
|
|
22
|
+
* Event types may be added without notice: ignore a `type` you do not know.
|
|
23
|
+
* Delivery is at least once, in no particular order: ignore an event `id` you
|
|
24
|
+
* have seen.
|
|
25
|
+
*/
|
|
26
|
+
export declare function verifyWebhook(options: VerifyWebhookOptions): Promise<WebhookEvent>;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// Verifying a webhook delivery (openapi.ts, "Webhooks"). The Onesim-Signature
|
|
2
|
+
// header is t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>"> with the
|
|
3
|
+
// endpoint's signing secret; a header may carry more than one v1.
|
|
4
|
+
import { WebhookVerificationError } from './errors.js';
|
|
5
|
+
const encoder = new TextEncoder();
|
|
6
|
+
const HEX_SHA256 = /^[0-9a-f]{64}$/i;
|
|
7
|
+
/**
|
|
8
|
+
* Checks a webhook delivery's signature and age and returns its event.
|
|
9
|
+
* Throws `WebhookVerificationError` (with a `reason`) when it fails: answer such a
|
|
10
|
+
* request with a 400 and do not act on it.
|
|
11
|
+
*
|
|
12
|
+
* Event types may be added without notice: ignore a `type` you do not know.
|
|
13
|
+
* Delivery is at least once, in no particular order: ignore an event `id` you
|
|
14
|
+
* have seen.
|
|
15
|
+
*/
|
|
16
|
+
export async function verifyWebhook(options) {
|
|
17
|
+
const { payload, signature, secret, toleranceSeconds = 300, now = new Date() } = options;
|
|
18
|
+
if (typeof secret !== 'string' || secret === '') {
|
|
19
|
+
throw new TypeError("verifyWebhook: secret is required (the endpoint's whsec_… signing secret).");
|
|
20
|
+
}
|
|
21
|
+
if (typeof payload !== 'string' && !ArrayBuffer.isView(payload)) {
|
|
22
|
+
throw new TypeError('verifyWebhook: payload must be the raw body, a string or a Uint8Array, not parsed JSON.');
|
|
23
|
+
}
|
|
24
|
+
if (!signature) {
|
|
25
|
+
throw new WebhookVerificationError('missing_signature', 'The Onesim-Signature header is missing.');
|
|
26
|
+
}
|
|
27
|
+
const header = parseHeader(signature);
|
|
28
|
+
if (!header) {
|
|
29
|
+
throw new WebhookVerificationError('malformed_signature', 'The Onesim-Signature header is not t=<unix seconds>,v1=<hex HMAC-SHA256>.');
|
|
30
|
+
}
|
|
31
|
+
const body = typeof payload === 'string'
|
|
32
|
+
? encoder.encode(payload)
|
|
33
|
+
: new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength);
|
|
34
|
+
const prefix = encoder.encode(`${header.timestamp}.`);
|
|
35
|
+
const signed = new Uint8Array(prefix.length + body.length);
|
|
36
|
+
signed.set(prefix);
|
|
37
|
+
signed.set(body, prefix.length);
|
|
38
|
+
const key = await crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
|
|
39
|
+
let valid = false;
|
|
40
|
+
// crypto.subtle.verify compares in constant time.
|
|
41
|
+
for (const mac of header.signatures) {
|
|
42
|
+
if (await crypto.subtle.verify('HMAC', key, mac, signed))
|
|
43
|
+
valid = true;
|
|
44
|
+
}
|
|
45
|
+
if (!valid) {
|
|
46
|
+
throw new WebhookVerificationError('invalid_signature', 'No v1 signature matches this body and secret.');
|
|
47
|
+
}
|
|
48
|
+
const age = now.getTime() / 1000 - header.timestamp;
|
|
49
|
+
if (!(Math.abs(age) <= toleranceSeconds)) {
|
|
50
|
+
throw new WebhookVerificationError('timestamp_out_of_tolerance', `The signature's timestamp is ${Math.round(Math.abs(age))} s away from now, more than ${toleranceSeconds} s.`);
|
|
51
|
+
}
|
|
52
|
+
let event;
|
|
53
|
+
try {
|
|
54
|
+
event = JSON.parse(typeof payload === 'string' ? payload : new TextDecoder().decode(body));
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
throw new WebhookVerificationError('invalid_payload', 'The body is not JSON.');
|
|
58
|
+
}
|
|
59
|
+
if (typeof event !== 'object' ||
|
|
60
|
+
event === null ||
|
|
61
|
+
Array.isArray(event) ||
|
|
62
|
+
typeof event.type !== 'string') {
|
|
63
|
+
throw new WebhookVerificationError('invalid_payload', 'The body is not an event: no `type`.');
|
|
64
|
+
}
|
|
65
|
+
return event;
|
|
66
|
+
}
|
|
67
|
+
function parseHeader(value) {
|
|
68
|
+
let timestamp = null;
|
|
69
|
+
const signatures = [];
|
|
70
|
+
for (const part of value.split(',')) {
|
|
71
|
+
const separator = part.indexOf('=');
|
|
72
|
+
if (separator < 0)
|
|
73
|
+
continue;
|
|
74
|
+
const name = part.slice(0, separator).trim();
|
|
75
|
+
const item = part.slice(separator + 1).trim();
|
|
76
|
+
if (name === 't') {
|
|
77
|
+
if (timestamp !== null || !/^\d+$/.test(item))
|
|
78
|
+
return null;
|
|
79
|
+
timestamp = Number(item);
|
|
80
|
+
}
|
|
81
|
+
else if (name === 'v1' && HEX_SHA256.test(item)) {
|
|
82
|
+
signatures.push(fromHex(item));
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return timestamp !== null && signatures.length > 0
|
|
86
|
+
? { timestamp, signatures }
|
|
87
|
+
: null;
|
|
88
|
+
}
|
|
89
|
+
function fromHex(hex) {
|
|
90
|
+
const bytes = new Uint8Array(hex.length / 2);
|
|
91
|
+
for (let index = 0; index < bytes.length; index++) {
|
|
92
|
+
bytes[index] = parseInt(hex.slice(index * 2, index * 2 + 2), 16);
|
|
93
|
+
}
|
|
94
|
+
return bytes;
|
|
95
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,66 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@onesim.global/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "TypeScript client for the onesim partner API: buy eSIMs and data packages, follow their usage, verify webhooks.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"onesim",
|
|
7
|
+
"esim",
|
|
8
|
+
"esims",
|
|
9
|
+
"partner api",
|
|
10
|
+
"sdk",
|
|
11
|
+
"api client",
|
|
12
|
+
"telecom",
|
|
13
|
+
"mobile data",
|
|
14
|
+
"roaming",
|
|
15
|
+
"webhooks",
|
|
16
|
+
"typescript"
|
|
17
|
+
],
|
|
18
|
+
"homepage": "https://api.onesim.global/docs",
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"author": "onesim",
|
|
21
|
+
"type": "module",
|
|
22
|
+
"sideEffects": false,
|
|
23
|
+
"main": "./dist/cjs/index.js",
|
|
24
|
+
"module": "./dist/esm/index.js",
|
|
25
|
+
"types": "./dist/cjs/index.d.ts",
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"import": {
|
|
29
|
+
"types": "./dist/esm/index.d.ts",
|
|
30
|
+
"default": "./dist/esm/index.js"
|
|
31
|
+
},
|
|
32
|
+
"require": {
|
|
33
|
+
"types": "./dist/cjs/index.d.ts",
|
|
34
|
+
"default": "./dist/cjs/index.js"
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"./package.json": "./package.json"
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"dist",
|
|
41
|
+
"README.md",
|
|
42
|
+
"LICENSE",
|
|
43
|
+
"CHANGELOG.md"
|
|
44
|
+
],
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=20"
|
|
47
|
+
},
|
|
48
|
+
"publishConfig": {
|
|
49
|
+
"access": "public"
|
|
50
|
+
},
|
|
51
|
+
"scripts": {
|
|
52
|
+
"generate": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON scripts/generate.ts",
|
|
53
|
+
"build": "rm -rf dist && tsc -p tsconfig.esm.json && tsc -p tsconfig.cjs.json && node scripts/cjs-package.js",
|
|
54
|
+
"type-check": "tsc --noEmit",
|
|
55
|
+
"test": "vitest run",
|
|
56
|
+
"check": "yarn type-check && yarn test && yarn build",
|
|
57
|
+
"prepack": "yarn check"
|
|
58
|
+
},
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"@types/node": "^22.10.2",
|
|
61
|
+
"openapi-typescript": "7.13.0",
|
|
62
|
+
"prettier": "^3.6.2",
|
|
63
|
+
"typescript": "^5.9.3",
|
|
64
|
+
"vitest": "^4.0.4"
|
|
65
|
+
}
|
|
66
|
+
}
|