@onesim.global/sdk 0.0.0-stage → 0.1.1
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 +47 -0
- package/LICENSE +21 -0
- package/README.md +376 -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 +76 -4
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Generated by scripts/generate.ts from openapi.ts
|
|
3
|
+
// (server/supabase/functions/partner-api/openapi.ts). Do not edit: change the
|
|
4
|
+
// contract, then run yarn workspace @onesim.global/sdk generate.
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
@@ -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/cjs/http.js
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// One request to the API, with a timeout per attempt and retries with
|
|
3
|
+
// backoff. Which answers are retried is the guide's (openapi.ts, "Errors" and
|
|
4
|
+
// "Idempotency"): no answer, 429 and 5xx, except the two final ones.
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.Http = void 0;
|
|
7
|
+
exports.throwIfAborted = throwIfAborted;
|
|
8
|
+
exports.sleep = sleep;
|
|
9
|
+
const errors_js_1 = require("./errors.js");
|
|
10
|
+
const BACKOFF_BASE_MS = 500;
|
|
11
|
+
const BACKOFF_CAP_MS = 8_000;
|
|
12
|
+
const RETRY_AFTER_CAP_MS = 60_000;
|
|
13
|
+
const RETRIED_STATUSES = new Set([429, 500, 502, 503, 504]);
|
|
14
|
+
// Final answers: the order failed for good and was refunded, or no eSIM can be
|
|
15
|
+
// issued for a while. Retrying them in seconds changes nothing.
|
|
16
|
+
const FINAL_CODES = new Set(['provisioning_failed', 'esims_unavailable']);
|
|
17
|
+
class Http {
|
|
18
|
+
#config;
|
|
19
|
+
constructor(config) {
|
|
20
|
+
this.#config = config;
|
|
21
|
+
}
|
|
22
|
+
async request(request) {
|
|
23
|
+
const { maxRetries } = this.#config;
|
|
24
|
+
const { signal, idempotencyKey } = request;
|
|
25
|
+
const url = this.#url(request.path, request.query);
|
|
26
|
+
const headers = {
|
|
27
|
+
authorization: `Bearer ${this.#config.apiKey}`,
|
|
28
|
+
accept: 'application/json'
|
|
29
|
+
};
|
|
30
|
+
let body;
|
|
31
|
+
if (request.body !== undefined) {
|
|
32
|
+
headers['content-type'] = 'application/json';
|
|
33
|
+
body = JSON.stringify(request.body);
|
|
34
|
+
}
|
|
35
|
+
if (idempotencyKey !== undefined)
|
|
36
|
+
headers['idempotency-key'] = idempotencyKey;
|
|
37
|
+
for (let attempt = 0;; attempt++) {
|
|
38
|
+
throwIfAborted(signal);
|
|
39
|
+
let status;
|
|
40
|
+
let text;
|
|
41
|
+
let response;
|
|
42
|
+
try {
|
|
43
|
+
({ response, text } = await this.#attempt(url, { method: request.method, headers, body }, signal));
|
|
44
|
+
status = response.status;
|
|
45
|
+
}
|
|
46
|
+
catch (cause) {
|
|
47
|
+
// The caller's own abort ends the call as it is.
|
|
48
|
+
throwIfAborted(signal);
|
|
49
|
+
if (attempt < maxRetries) {
|
|
50
|
+
await sleep(backoff(attempt), signal);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
const reason = cause instanceof Error ? cause.message : String(cause);
|
|
54
|
+
const message = `No answer from the onesim API after ${attempt + 1} attempt${attempt ? 's' : ''}: ${reason}`;
|
|
55
|
+
const options = {
|
|
56
|
+
cause,
|
|
57
|
+
...(idempotencyKey !== undefined && { idempotencyKey })
|
|
58
|
+
};
|
|
59
|
+
throw isTimeout(cause)
|
|
60
|
+
? new errors_js_1.APIConnectionTimeoutError(message, options)
|
|
61
|
+
: new errors_js_1.APIConnectionError(message, options);
|
|
62
|
+
}
|
|
63
|
+
if (status >= 200 && status < 300) {
|
|
64
|
+
try {
|
|
65
|
+
return JSON.parse(text);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
const error = new errors_js_1.OnesimError(`The onesim API answered ${status} with a body that is not JSON.`);
|
|
69
|
+
if (idempotencyKey !== undefined)
|
|
70
|
+
error.idempotencyKey = idempotencyKey;
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const error = apiError(response, text, idempotencyKey);
|
|
75
|
+
if (attempt < maxRetries &&
|
|
76
|
+
RETRIED_STATUSES.has(status) &&
|
|
77
|
+
!FINAL_CODES.has(error.code ?? '')) {
|
|
78
|
+
const wait = error.retryAfter !== undefined
|
|
79
|
+
? Math.min(error.retryAfter * 1000, RETRY_AFTER_CAP_MS)
|
|
80
|
+
: backoff(attempt);
|
|
81
|
+
await sleep(wait, signal);
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
#url(path, query = {}) {
|
|
88
|
+
const search = new URLSearchParams();
|
|
89
|
+
for (const [name, value] of Object.entries(query)) {
|
|
90
|
+
if (value === undefined || value === null)
|
|
91
|
+
continue;
|
|
92
|
+
search.set(name, value instanceof Date ? value.toISOString() : String(value));
|
|
93
|
+
}
|
|
94
|
+
const qs = search.toString();
|
|
95
|
+
return `${this.#config.baseURL}${path}${qs ? `?${qs}` : ''}`;
|
|
96
|
+
}
|
|
97
|
+
// One attempt, the body read included, within the timeout. Settles when the
|
|
98
|
+
// timeout or the caller's signal fires even if `fetch` ignores its signal;
|
|
99
|
+
// a timed-out attempt rejects with a TimeoutError.
|
|
100
|
+
async #attempt(url, init, signal) {
|
|
101
|
+
const { timeout } = this.#config;
|
|
102
|
+
const timedOut = new DOMException(`The request timed out after ${timeout} ms.`, 'TimeoutError');
|
|
103
|
+
const controller = new AbortController();
|
|
104
|
+
const aborted = new Promise((_, reject) => {
|
|
105
|
+
controller.signal.addEventListener('abort', () => reject(controller.signal.reason), { once: true });
|
|
106
|
+
});
|
|
107
|
+
const timer = setTimeout(() => controller.abort(timedOut), timeout);
|
|
108
|
+
const onAbort = () => controller.abort(signal?.reason);
|
|
109
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
110
|
+
try {
|
|
111
|
+
const exchange = (async () => {
|
|
112
|
+
const response = await this.#config.fetch(url, {
|
|
113
|
+
...init,
|
|
114
|
+
signal: controller.signal
|
|
115
|
+
});
|
|
116
|
+
return { response, text: await response.text() };
|
|
117
|
+
})();
|
|
118
|
+
return await Promise.race([exchange, aborted]);
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
// However `fetch` reports its abort, a timeout is a TimeoutError.
|
|
122
|
+
if (controller.signal.reason === timedOut)
|
|
123
|
+
throw timedOut;
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
finally {
|
|
127
|
+
clearTimeout(timer);
|
|
128
|
+
signal?.removeEventListener('abort', onAbort);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
exports.Http = Http;
|
|
133
|
+
function apiError(response, text, idempotencyKey) {
|
|
134
|
+
let body = text;
|
|
135
|
+
try {
|
|
136
|
+
body = JSON.parse(text);
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
// Not JSON (e.g. an HTML page from a proxy): keep the text.
|
|
140
|
+
}
|
|
141
|
+
const fields = isObject(body) && isObject(body.error) ? body.error : null;
|
|
142
|
+
const code = fields && typeof fields.code === 'string' ? fields.code : null;
|
|
143
|
+
const statusLine = `${response.status}${response.statusText ? ` ${response.statusText}` : ''}`;
|
|
144
|
+
const retryAfter = parseRetryAfter(response.headers.get('retry-after'));
|
|
145
|
+
return (0, errors_js_1.makeAPIError)({
|
|
146
|
+
status: response.status,
|
|
147
|
+
code,
|
|
148
|
+
message: code && typeof fields?.message === 'string'
|
|
149
|
+
? fields.message
|
|
150
|
+
: `The onesim API answered ${statusLine}.`,
|
|
151
|
+
requestId: (fields && typeof fields.request_id === 'string'
|
|
152
|
+
? fields.request_id
|
|
153
|
+
: null) ?? response.headers.get('request-id'),
|
|
154
|
+
...(typeof fields?.amount === 'number' && { amount: fields.amount }),
|
|
155
|
+
...(typeof fields?.limit === 'string' && { limit: fields.limit }),
|
|
156
|
+
...(isObject(fields?.order) && { order: fields.order }),
|
|
157
|
+
...(retryAfter !== undefined && { retryAfter }),
|
|
158
|
+
...(idempotencyKey !== undefined && { idempotencyKey }),
|
|
159
|
+
body
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
function isTimeout(error) {
|
|
163
|
+
return (typeof error === 'object' &&
|
|
164
|
+
error !== null &&
|
|
165
|
+
error.name === 'TimeoutError');
|
|
166
|
+
}
|
|
167
|
+
function isObject(value) {
|
|
168
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
169
|
+
}
|
|
170
|
+
// Seconds, or an HTTP date.
|
|
171
|
+
function parseRetryAfter(value) {
|
|
172
|
+
if (value === null)
|
|
173
|
+
return undefined;
|
|
174
|
+
const trimmed = value.trim();
|
|
175
|
+
if (/^\d+$/.test(trimmed))
|
|
176
|
+
return Number(trimmed);
|
|
177
|
+
const date = Date.parse(trimmed);
|
|
178
|
+
if (Number.isNaN(date))
|
|
179
|
+
return undefined;
|
|
180
|
+
return Math.max(0, Math.ceil((date - Date.now()) / 1000));
|
|
181
|
+
}
|
|
182
|
+
// Exponential, capped, with jitter: half the step plus a random half.
|
|
183
|
+
function backoff(attempt) {
|
|
184
|
+
const step = Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** attempt);
|
|
185
|
+
return step / 2 + Math.random() * (step / 2);
|
|
186
|
+
}
|
|
187
|
+
function throwIfAborted(signal) {
|
|
188
|
+
if (signal?.aborted) {
|
|
189
|
+
throw (signal.reason ??
|
|
190
|
+
new DOMException('This operation was aborted.', 'AbortError'));
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
function sleep(ms, signal) {
|
|
194
|
+
return new Promise((resolve, reject) => {
|
|
195
|
+
if (signal?.aborted) {
|
|
196
|
+
reject(signal.reason ??
|
|
197
|
+
new DOMException('This operation was aborted.', 'AbortError'));
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
const onAbort = () => {
|
|
201
|
+
clearTimeout(timer);
|
|
202
|
+
reject(signal?.reason ??
|
|
203
|
+
new DOMException('This operation was aborted.', 'AbortError'));
|
|
204
|
+
};
|
|
205
|
+
const timer = setTimeout(() => {
|
|
206
|
+
signal?.removeEventListener('abort', onAbort);
|
|
207
|
+
resolve();
|
|
208
|
+
}, ms);
|
|
209
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
210
|
+
});
|
|
211
|
+
}
|
|
@@ -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,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.verifyWebhook = exports.WebhookVerificationError = exports.RateLimitError = exports.PollTimeoutError = exports.PermissionDeniedError = exports.OnesimError = exports.NotFoundError = exports.InternalServerError = exports.ConflictError = exports.BadRequestError = exports.AuthenticationError = exports.APIError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.Packages = exports.Orders = exports.OnesimClient = exports.Esims = exports.BalanceResource = void 0;
|
|
4
|
+
const client_js_1 = require("./client.js");
|
|
5
|
+
var client_js_2 = require("./client.js");
|
|
6
|
+
Object.defineProperty(exports, "BalanceResource", { enumerable: true, get: function () { return client_js_2.BalanceResource; } });
|
|
7
|
+
Object.defineProperty(exports, "Esims", { enumerable: true, get: function () { return client_js_2.Esims; } });
|
|
8
|
+
Object.defineProperty(exports, "OnesimClient", { enumerable: true, get: function () { return client_js_2.OnesimClient; } });
|
|
9
|
+
Object.defineProperty(exports, "Orders", { enumerable: true, get: function () { return client_js_2.Orders; } });
|
|
10
|
+
Object.defineProperty(exports, "Packages", { enumerable: true, get: function () { return client_js_2.Packages; } });
|
|
11
|
+
exports.default = client_js_1.OnesimClient;
|
|
12
|
+
var errors_js_1 = require("./errors.js");
|
|
13
|
+
Object.defineProperty(exports, "APIConnectionError", { enumerable: true, get: function () { return errors_js_1.APIConnectionError; } });
|
|
14
|
+
Object.defineProperty(exports, "APIConnectionTimeoutError", { enumerable: true, get: function () { return errors_js_1.APIConnectionTimeoutError; } });
|
|
15
|
+
Object.defineProperty(exports, "APIError", { enumerable: true, get: function () { return errors_js_1.APIError; } });
|
|
16
|
+
Object.defineProperty(exports, "AuthenticationError", { enumerable: true, get: function () { return errors_js_1.AuthenticationError; } });
|
|
17
|
+
Object.defineProperty(exports, "BadRequestError", { enumerable: true, get: function () { return errors_js_1.BadRequestError; } });
|
|
18
|
+
Object.defineProperty(exports, "ConflictError", { enumerable: true, get: function () { return errors_js_1.ConflictError; } });
|
|
19
|
+
Object.defineProperty(exports, "InternalServerError", { enumerable: true, get: function () { return errors_js_1.InternalServerError; } });
|
|
20
|
+
Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return errors_js_1.NotFoundError; } });
|
|
21
|
+
Object.defineProperty(exports, "OnesimError", { enumerable: true, get: function () { return errors_js_1.OnesimError; } });
|
|
22
|
+
Object.defineProperty(exports, "PermissionDeniedError", { enumerable: true, get: function () { return errors_js_1.PermissionDeniedError; } });
|
|
23
|
+
Object.defineProperty(exports, "PollTimeoutError", { enumerable: true, get: function () { return errors_js_1.PollTimeoutError; } });
|
|
24
|
+
Object.defineProperty(exports, "RateLimitError", { enumerable: true, get: function () { return errors_js_1.RateLimitError; } });
|
|
25
|
+
Object.defineProperty(exports, "WebhookVerificationError", { enumerable: true, get: function () { return errors_js_1.WebhookVerificationError; } });
|
|
26
|
+
var webhooks_js_1 = require("./webhooks.js");
|
|
27
|
+
Object.defineProperty(exports, "verifyWebhook", { enumerable: true, get: function () { return webhooks_js_1.verifyWebhook; } });
|
|
@@ -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,98 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Verifying a webhook delivery (openapi.ts, "Webhooks"). The Onesim-Signature
|
|
3
|
+
// header is t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>"> with the
|
|
4
|
+
// endpoint's signing secret; a header may carry more than one v1.
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.verifyWebhook = verifyWebhook;
|
|
7
|
+
const errors_js_1 = require("./errors.js");
|
|
8
|
+
const encoder = new TextEncoder();
|
|
9
|
+
const HEX_SHA256 = /^[0-9a-f]{64}$/i;
|
|
10
|
+
/**
|
|
11
|
+
* Checks a webhook delivery's signature and age and returns its event.
|
|
12
|
+
* Throws `WebhookVerificationError` (with a `reason`) when it fails: answer such a
|
|
13
|
+
* request with a 400 and do not act on it.
|
|
14
|
+
*
|
|
15
|
+
* Event types may be added without notice: ignore a `type` you do not know.
|
|
16
|
+
* Delivery is at least once, in no particular order: ignore an event `id` you
|
|
17
|
+
* have seen.
|
|
18
|
+
*/
|
|
19
|
+
async function verifyWebhook(options) {
|
|
20
|
+
const { payload, signature, secret, toleranceSeconds = 300, now = new Date() } = options;
|
|
21
|
+
if (typeof secret !== 'string' || secret === '') {
|
|
22
|
+
throw new TypeError("verifyWebhook: secret is required (the endpoint's whsec_… signing secret).");
|
|
23
|
+
}
|
|
24
|
+
if (typeof payload !== 'string' && !ArrayBuffer.isView(payload)) {
|
|
25
|
+
throw new TypeError('verifyWebhook: payload must be the raw body, a string or a Uint8Array, not parsed JSON.');
|
|
26
|
+
}
|
|
27
|
+
if (!signature) {
|
|
28
|
+
throw new errors_js_1.WebhookVerificationError('missing_signature', 'The Onesim-Signature header is missing.');
|
|
29
|
+
}
|
|
30
|
+
const header = parseHeader(signature);
|
|
31
|
+
if (!header) {
|
|
32
|
+
throw new errors_js_1.WebhookVerificationError('malformed_signature', 'The Onesim-Signature header is not t=<unix seconds>,v1=<hex HMAC-SHA256>.');
|
|
33
|
+
}
|
|
34
|
+
const body = typeof payload === 'string'
|
|
35
|
+
? encoder.encode(payload)
|
|
36
|
+
: new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength);
|
|
37
|
+
const prefix = encoder.encode(`${header.timestamp}.`);
|
|
38
|
+
const signed = new Uint8Array(prefix.length + body.length);
|
|
39
|
+
signed.set(prefix);
|
|
40
|
+
signed.set(body, prefix.length);
|
|
41
|
+
const key = await crypto.subtle.importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
|
|
42
|
+
let valid = false;
|
|
43
|
+
// crypto.subtle.verify compares in constant time.
|
|
44
|
+
for (const mac of header.signatures) {
|
|
45
|
+
if (await crypto.subtle.verify('HMAC', key, mac, signed))
|
|
46
|
+
valid = true;
|
|
47
|
+
}
|
|
48
|
+
if (!valid) {
|
|
49
|
+
throw new errors_js_1.WebhookVerificationError('invalid_signature', 'No v1 signature matches this body and secret.');
|
|
50
|
+
}
|
|
51
|
+
const age = now.getTime() / 1000 - header.timestamp;
|
|
52
|
+
if (!(Math.abs(age) <= toleranceSeconds)) {
|
|
53
|
+
throw new errors_js_1.WebhookVerificationError('timestamp_out_of_tolerance', `The signature's timestamp is ${Math.round(Math.abs(age))} s away from now, more than ${toleranceSeconds} s.`);
|
|
54
|
+
}
|
|
55
|
+
let event;
|
|
56
|
+
try {
|
|
57
|
+
event = JSON.parse(typeof payload === 'string' ? payload : new TextDecoder().decode(body));
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
throw new errors_js_1.WebhookVerificationError('invalid_payload', 'The body is not JSON.');
|
|
61
|
+
}
|
|
62
|
+
if (typeof event !== 'object' ||
|
|
63
|
+
event === null ||
|
|
64
|
+
Array.isArray(event) ||
|
|
65
|
+
typeof event.type !== 'string') {
|
|
66
|
+
throw new errors_js_1.WebhookVerificationError('invalid_payload', 'The body is not an event: no `type`.');
|
|
67
|
+
}
|
|
68
|
+
return event;
|
|
69
|
+
}
|
|
70
|
+
function parseHeader(value) {
|
|
71
|
+
let timestamp = null;
|
|
72
|
+
const signatures = [];
|
|
73
|
+
for (const part of value.split(',')) {
|
|
74
|
+
const separator = part.indexOf('=');
|
|
75
|
+
if (separator < 0)
|
|
76
|
+
continue;
|
|
77
|
+
const name = part.slice(0, separator).trim();
|
|
78
|
+
const item = part.slice(separator + 1).trim();
|
|
79
|
+
if (name === 't') {
|
|
80
|
+
if (timestamp !== null || !/^\d+$/.test(item))
|
|
81
|
+
return null;
|
|
82
|
+
timestamp = Number(item);
|
|
83
|
+
}
|
|
84
|
+
else if (name === 'v1' && HEX_SHA256.test(item)) {
|
|
85
|
+
signatures.push(fromHex(item));
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return timestamp !== null && signatures.length > 0
|
|
89
|
+
? { timestamp, signatures }
|
|
90
|
+
: null;
|
|
91
|
+
}
|
|
92
|
+
function fromHex(hex) {
|
|
93
|
+
const bytes = new Uint8Array(hex.length / 2);
|
|
94
|
+
for (let index = 0; index < bytes.length; index++) {
|
|
95
|
+
bytes[index] = parseInt(hex.slice(index * 2, index * 2 + 2), 16);
|
|
96
|
+
}
|
|
97
|
+
return bytes;
|
|
98
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { type FetchLike, Http } from './http.js';
|
|
2
|
+
import type { Balance, Catalogue, Esim, EsimList, EsimSummary, ListEsimsParams, ListOrdersParams, Order, OrderList, OrderRequest, Package } from './types.js';
|
|
3
|
+
export interface ClientOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Your API key, `osk_live_…`. A secret for your servers only. Default: the
|
|
6
|
+
* `ONESIM_API_KEY` environment variable.
|
|
7
|
+
*/
|
|
8
|
+
apiKey?: string;
|
|
9
|
+
/** Default `https://api.onesim.global`. */
|
|
10
|
+
baseURL?: string;
|
|
11
|
+
/**
|
|
12
|
+
* How long one attempt may take, in milliseconds. Default 60 000: placing an
|
|
13
|
+
* order can make two calls to the network provider of up to 20 seconds each.
|
|
14
|
+
*/
|
|
15
|
+
timeout?: number;
|
|
16
|
+
/** How many times a failed request is retried. Default 2. */
|
|
17
|
+
maxRetries?: number;
|
|
18
|
+
/** A `fetch` to use instead of the global one (e.g. in tests). */
|
|
19
|
+
fetch?: FetchLike;
|
|
20
|
+
}
|
|
21
|
+
export interface RequestOptions {
|
|
22
|
+
/** Aborting it stops the call, retries included, and rejects with its reason. */
|
|
23
|
+
signal?: AbortSignal;
|
|
24
|
+
}
|
|
25
|
+
export interface CreateOrderOptions extends RequestOptions {
|
|
26
|
+
/**
|
|
27
|
+
* A UUID, new for each purchase and the same on every retry of it. Store it
|
|
28
|
+
* with your booking before you call, so a retry after a crash never buys
|
|
29
|
+
* twice. Default: a new UUID for this call, used on all its retries.
|
|
30
|
+
*/
|
|
31
|
+
idempotencyKey?: string;
|
|
32
|
+
}
|
|
33
|
+
export interface PollOptions extends RequestOptions {
|
|
34
|
+
/**
|
|
35
|
+
* How long to poll before giving up, in milliseconds, reads and their
|
|
36
|
+
* retries included. Default 660 000 (11 minutes).
|
|
37
|
+
*/
|
|
38
|
+
timeout?: number;
|
|
39
|
+
/** How long to wait between reads, in milliseconds. Default 3 000. */
|
|
40
|
+
pollInterval?: number;
|
|
41
|
+
}
|
|
42
|
+
export type CreateAndPollOptions = CreateOrderOptions & PollOptions;
|
|
43
|
+
/**
|
|
44
|
+
* The onesim partner API.
|
|
45
|
+
*
|
|
46
|
+
* ```ts
|
|
47
|
+
* import OnesimClient from '@onesim.global/sdk';
|
|
48
|
+
*
|
|
49
|
+
* const onesim = new OnesimClient(); // reads ONESIM_API_KEY
|
|
50
|
+
* const catalogue = await onesim.packages.list();
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
export declare class OnesimClient {
|
|
54
|
+
/** Your catalogue: what you can buy and what it costs you. */
|
|
55
|
+
readonly packages: Packages;
|
|
56
|
+
/** Buying blank eSIMs, packages and bundles. */
|
|
57
|
+
readonly orders: Orders;
|
|
58
|
+
/** The eSIMs you own, with their packages and usage. */
|
|
59
|
+
readonly esims: Esims;
|
|
60
|
+
/** Your partner balance. */
|
|
61
|
+
readonly balance: BalanceResource;
|
|
62
|
+
constructor(options?: ClientOptions);
|
|
63
|
+
}
|
|
64
|
+
export declare class Packages {
|
|
65
|
+
#private;
|
|
66
|
+
constructor(http: Http);
|
|
67
|
+
/** `GET /v1/packages`: your packages and the price of a blank eSIM. A `null` price means "not offered that way". */
|
|
68
|
+
list(options?: RequestOptions): Promise<Catalogue>;
|
|
69
|
+
/** `GET /v1/packages/{id}`. */
|
|
70
|
+
retrieve(packageId: string, options?: RequestOptions): Promise<Package>;
|
|
71
|
+
}
|
|
72
|
+
export declare class Orders {
|
|
73
|
+
#private;
|
|
74
|
+
constructor(http: Http);
|
|
75
|
+
/**
|
|
76
|
+
* `POST /v1/orders`: buy a blank eSIM (`type: 'esim'`), a package on an eSIM
|
|
77
|
+
* you own (`type: 'package'`) or a new eSIM with a package (`type: 'bundle'`).
|
|
78
|
+
* Resolves with the order as the API answers it: `completed`, or `pending`
|
|
79
|
+
* (follow it with `orders.poll`, or use `orders.createAndPoll`).
|
|
80
|
+
*
|
|
81
|
+
* Every attempt of this call sends the same Idempotency-Key, so a retry
|
|
82
|
+
* never buys twice. Pass your own `idempotencyKey`, stored with your
|
|
83
|
+
* booking, to make retries across restarts safe too. Any `OnesimError`
|
|
84
|
+
* thrown carries the key it used as `error.idempotencyKey`.
|
|
85
|
+
*/
|
|
86
|
+
create(body: OrderRequest, options?: CreateOrderOptions): Promise<Order>;
|
|
87
|
+
/**
|
|
88
|
+
* `orders.create`, then `orders.poll` while the order is pending. Resolves
|
|
89
|
+
* with the final order whatever its status (`completed`, `failed` or
|
|
90
|
+
* `refunded`): a `502 provisioning_failed` is not thrown but resolves with
|
|
91
|
+
* its failed order, so check `order.status`. Other errors are thrown, with
|
|
92
|
+
* the Idempotency-Key as `error.idempotencyKey`; `PollTimeoutError` when
|
|
93
|
+
* `timeout` runs out first.
|
|
94
|
+
*/
|
|
95
|
+
createAndPoll(body: OrderRequest, options?: CreateAndPollOptions): Promise<Order>;
|
|
96
|
+
/** `GET /v1/orders/{id}`. Reading a pending order also moves it forward. */
|
|
97
|
+
retrieve(orderId: string, options?: RequestOptions): Promise<Order>;
|
|
98
|
+
/** `GET /v1/orders`: one page of your orders, newest first. */
|
|
99
|
+
list(params?: ListOrdersParams, options?: RequestOptions): Promise<OrderList>;
|
|
100
|
+
/** Every order matching `params`, newest first, following `next_cursor` page after page. */
|
|
101
|
+
listAll(params?: ListOrdersParams, options?: RequestOptions): AsyncGenerator<Order, void, undefined>;
|
|
102
|
+
/**
|
|
103
|
+
* Reads the order until it is no longer `pending`, and resolves with it:
|
|
104
|
+
* `completed`, `failed` or `refunded`. A pending order completes or fails
|
|
105
|
+
* within about ten minutes. `timeout` bounds the whole poll, reads and
|
|
106
|
+
* their retries included: when it runs out, throws `PollTimeoutError` with
|
|
107
|
+
* the order as last read.
|
|
108
|
+
*/
|
|
109
|
+
poll(orderId: string, options?: PollOptions): Promise<Order>;
|
|
110
|
+
}
|
|
111
|
+
export declare class Esims {
|
|
112
|
+
#private;
|
|
113
|
+
constructor(http: Http);
|
|
114
|
+
/**
|
|
115
|
+
* `GET /v1/esims/{id}`: the eSIM with its packages and usage, read live from
|
|
116
|
+
* the network. When the network does not answer, the last known values with
|
|
117
|
+
* `refreshed_at: null`.
|
|
118
|
+
*/
|
|
119
|
+
retrieve(esimId: string, options?: RequestOptions): Promise<Esim>;
|
|
120
|
+
/** `GET /v1/esims`: one page of your eSIMs, newest first. */
|
|
121
|
+
list(params?: ListEsimsParams, options?: RequestOptions): Promise<EsimList>;
|
|
122
|
+
/** Every eSIM matching `params`, newest first, following `next_cursor` page after page. */
|
|
123
|
+
listAll(params?: ListEsimsParams, options?: RequestOptions): AsyncGenerator<EsimSummary, void, undefined>;
|
|
124
|
+
}
|
|
125
|
+
export declare class BalanceResource {
|
|
126
|
+
#private;
|
|
127
|
+
constructor(http: Http);
|
|
128
|
+
/** `GET /v1/balance`: your balance, overdraft and what you can spend now, in cents. */
|
|
129
|
+
retrieve(options?: RequestOptions): Promise<Balance>;
|
|
130
|
+
}
|