@synqauth/js 0.2.0 → 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/README.md +7 -1
- package/dist/api-BGeXhXo6.js +913 -0
- package/dist/index.d.ts +3198 -1536
- package/dist/index.js +458 -10
- package/dist/management-C4LYIC3S.d.ts +20745 -0
- package/dist/server.d.ts +58 -3
- package/dist/server.js +21 -4
- package/package.json +1 -1
- package/dist/api-CeYAjkvX.js +0 -467
- package/dist/management-CWdCiiEv.d.ts +0 -11856
|
@@ -0,0 +1,913 @@
|
|
|
1
|
+
import * as oauth from "oauth4webapi";
|
|
2
|
+
import { AuthorizationResponseError, OperationProcessingError, ResponseBodyError, WWWAuthenticateChallengeError } from "oauth4webapi";
|
|
3
|
+
//#region src/errors.ts
|
|
4
|
+
/**
|
|
5
|
+
* Every error the SDK throws. Branch on `code`, which is stable: the API's
|
|
6
|
+
* problem `code`, OAuth's `error`, or one of the SDK's own; never on the
|
|
7
|
+
* message.
|
|
8
|
+
*/
|
|
9
|
+
var SynqError = class extends Error {
|
|
10
|
+
name = "SynqError";
|
|
11
|
+
code;
|
|
12
|
+
/** The HTTP status Synq answered with, when it answered. */
|
|
13
|
+
status;
|
|
14
|
+
/** What Synq said about it: OAuth's `error_description` or a problem's `detail`. */
|
|
15
|
+
description;
|
|
16
|
+
/**
|
|
17
|
+
* Known seconds to wait from Retry-After, or a validated 429 problem's
|
|
18
|
+
* retry_after when the header is unavailable. Undefined when no wait is known.
|
|
19
|
+
*/
|
|
20
|
+
retryAfter;
|
|
21
|
+
/** The API-origin execution ID to quote to support, when the server supplied one. */
|
|
22
|
+
requestId;
|
|
23
|
+
constructor(code, message, options = {}) {
|
|
24
|
+
super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
|
|
25
|
+
this.code = code;
|
|
26
|
+
this.status = options.status;
|
|
27
|
+
this.description = options.description;
|
|
28
|
+
this.retryAfter = options.retryAfter;
|
|
29
|
+
this.requestId = options.requestId;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
/** Whether `error` is a `SynqError`, with `code` when given. */
|
|
33
|
+
function isSynqError(error, code) {
|
|
34
|
+
return error instanceof SynqError && (code === void 0 || error.code === code);
|
|
35
|
+
}
|
|
36
|
+
/** A `SynqError` for a problem document a Synq API answered with. */
|
|
37
|
+
function problemError(status, problem, retryAfter, requestId) {
|
|
38
|
+
const code = typeof problem.code === "string" ? problem.code : `http_${status}`;
|
|
39
|
+
const description = typeof problem.detail === "string" ? problem.detail : void 0;
|
|
40
|
+
return new SynqError(code, description ?? problem.title ?? `Synq answered ${status}`, {
|
|
41
|
+
status,
|
|
42
|
+
description,
|
|
43
|
+
retryAfter: retryAfter ?? (status === 429 && typeof problem.retry_after === "number" && Number.isSafeInteger(problem.retry_after) && problem.retry_after >= 0 ? problem.retry_after : void 0),
|
|
44
|
+
requestId: validRequestId(requestId) ?? validRequestId(problem.request_id),
|
|
45
|
+
cause: problem
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
function validRequestId(value) {
|
|
49
|
+
return typeof value === "string" && /^req_[0-9a-f]{32}$/.test(value) ? value : void 0;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The seconds a `Retry-After` header asks for: a number of seconds, or an
|
|
53
|
+
* HTTP date, counted from `now`. Undefined when there is none, or it can't
|
|
54
|
+
* be read.
|
|
55
|
+
*/
|
|
56
|
+
function retryAfterSeconds(header, now = Date.now()) {
|
|
57
|
+
const value = header?.trim();
|
|
58
|
+
if (!value) return void 0;
|
|
59
|
+
if (/^[0-9]+$/.test(value)) {
|
|
60
|
+
const seconds = Number(value);
|
|
61
|
+
return Number.isSafeInteger(seconds) ? seconds : void 0;
|
|
62
|
+
}
|
|
63
|
+
if (!/[A-Za-z]/.test(value)) return void 0;
|
|
64
|
+
const at = Date.parse(value);
|
|
65
|
+
return Number.isNaN(at) ? void 0 : Math.max(0, Math.ceil((at - now) / 1e3));
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* A `SynqError` for whatever went wrong talking to Synq's issuer: OAuth's
|
|
69
|
+
* error responses keep their `error`, a failed check of Synq's answer is
|
|
70
|
+
* `invalid_response`, and a request that never got an answer is
|
|
71
|
+
* `network_error`.
|
|
72
|
+
*/
|
|
73
|
+
function toSynqError(error) {
|
|
74
|
+
if (error instanceof SynqError) return error;
|
|
75
|
+
if (error instanceof ResponseBodyError) return new SynqError(error.error, error.error_description ?? error.error, {
|
|
76
|
+
status: error.status,
|
|
77
|
+
description: error.error_description,
|
|
78
|
+
cause: error
|
|
79
|
+
});
|
|
80
|
+
if (error instanceof AuthorizationResponseError) return new SynqError(error.error, error.error_description ?? error.error, {
|
|
81
|
+
description: error.error_description,
|
|
82
|
+
cause: error
|
|
83
|
+
});
|
|
84
|
+
if (error instanceof WWWAuthenticateChallengeError) {
|
|
85
|
+
const challenge = error.cause[0];
|
|
86
|
+
const code = challenge?.parameters.error ?? "invalid_token";
|
|
87
|
+
const description = challenge?.parameters.error_description;
|
|
88
|
+
return new SynqError(code, description ?? code, {
|
|
89
|
+
status: error.status,
|
|
90
|
+
description,
|
|
91
|
+
cause: error
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
if (error instanceof OperationProcessingError) return new SynqError("invalid_response", error.message, { cause: error });
|
|
95
|
+
if (error instanceof TypeError) return new SynqError("network_error", `Synq couldn't be reached: ${error.message}`, { cause: error });
|
|
96
|
+
return new SynqError("invalid_response", error instanceof Error ? error.message : "Synq answered with something unexpected", { cause: error });
|
|
97
|
+
}
|
|
98
|
+
//#endregion
|
|
99
|
+
//#region src/email-work.js
|
|
100
|
+
/** @typedef {{ticket:string, algorithm:'sha256-leading-zero-bits-v1', bits:number, expiresAt:number}} EmailWorkChallenge */
|
|
101
|
+
const K = new Int32Array([
|
|
102
|
+
1116352408,
|
|
103
|
+
1899447441,
|
|
104
|
+
3049323471,
|
|
105
|
+
3921009573,
|
|
106
|
+
961987163,
|
|
107
|
+
1508970993,
|
|
108
|
+
2453635748,
|
|
109
|
+
2870763221,
|
|
110
|
+
3624381080,
|
|
111
|
+
310598401,
|
|
112
|
+
607225278,
|
|
113
|
+
1426881987,
|
|
114
|
+
1925078388,
|
|
115
|
+
2162078206,
|
|
116
|
+
2614888103,
|
|
117
|
+
3248222580,
|
|
118
|
+
3835390401,
|
|
119
|
+
4022224774,
|
|
120
|
+
264347078,
|
|
121
|
+
604807628,
|
|
122
|
+
770255983,
|
|
123
|
+
1249150122,
|
|
124
|
+
1555081692,
|
|
125
|
+
1996064986,
|
|
126
|
+
2554220882,
|
|
127
|
+
2821834349,
|
|
128
|
+
2952996808,
|
|
129
|
+
3210313671,
|
|
130
|
+
3336571891,
|
|
131
|
+
3584528711,
|
|
132
|
+
113926993,
|
|
133
|
+
338241895,
|
|
134
|
+
666307205,
|
|
135
|
+
773529912,
|
|
136
|
+
1294757372,
|
|
137
|
+
1396182291,
|
|
138
|
+
1695183700,
|
|
139
|
+
1986661051,
|
|
140
|
+
2177026350,
|
|
141
|
+
2456956037,
|
|
142
|
+
2730485921,
|
|
143
|
+
2820302411,
|
|
144
|
+
3259730800,
|
|
145
|
+
3345764771,
|
|
146
|
+
3516065817,
|
|
147
|
+
3600352804,
|
|
148
|
+
4094571909,
|
|
149
|
+
275423344,
|
|
150
|
+
430227734,
|
|
151
|
+
506948616,
|
|
152
|
+
659060556,
|
|
153
|
+
883997877,
|
|
154
|
+
958139571,
|
|
155
|
+
1322822218,
|
|
156
|
+
1537002063,
|
|
157
|
+
1747873779,
|
|
158
|
+
1955562222,
|
|
159
|
+
2024104815,
|
|
160
|
+
2227730452,
|
|
161
|
+
2361852424,
|
|
162
|
+
2428436474,
|
|
163
|
+
2756734187,
|
|
164
|
+
3204031479,
|
|
165
|
+
3329325298
|
|
166
|
+
]);
|
|
167
|
+
const IV = [
|
|
168
|
+
1779033703,
|
|
169
|
+
3144134277,
|
|
170
|
+
1013904242,
|
|
171
|
+
2773480762,
|
|
172
|
+
1359893119,
|
|
173
|
+
2600822924,
|
|
174
|
+
528734635,
|
|
175
|
+
1541459225
|
|
176
|
+
];
|
|
177
|
+
/**
|
|
178
|
+
* One SHA-256 compression of the 64 bytes of `block` at `at` into `state`.
|
|
179
|
+
* @param {Int32Array} state eight words, updated in place
|
|
180
|
+
* @param {Uint8Array} block
|
|
181
|
+
* @param {number} at
|
|
182
|
+
* @param {Int32Array} w a 64-word schedule to reuse
|
|
183
|
+
*/
|
|
184
|
+
function compress(state, block, at, w) {
|
|
185
|
+
for (let i = 0; i < 16; i++, at += 4) w[i] = (block[at] ?? 0) << 24 | (block[at + 1] ?? 0) << 16 | (block[at + 2] ?? 0) << 8 | (block[at + 3] ?? 0);
|
|
186
|
+
for (let i = 16; i < 64; i++) {
|
|
187
|
+
const x = w[i - 15] ?? 0, y = w[i - 2] ?? 0;
|
|
188
|
+
const s0 = (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ x >>> 3;
|
|
189
|
+
const s1 = (y >>> 17 | y << 15) ^ (y >>> 19 | y << 13) ^ y >>> 10;
|
|
190
|
+
w[i] = (w[i - 16] ?? 0) + s0 + (w[i - 7] ?? 0) + s1 | 0;
|
|
191
|
+
}
|
|
192
|
+
let a = state[0] ?? 0, b = state[1] ?? 0, c = state[2] ?? 0, d = state[3] ?? 0, e = state[4] ?? 0, f = state[5] ?? 0, g = state[6] ?? 0, h = state[7] ?? 0;
|
|
193
|
+
for (let i = 0; i < 64; i++) {
|
|
194
|
+
const t1 = h + ((e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7)) + (e & f ^ ~e & g) + (K[i] ?? 0) + (w[i] ?? 0) | 0;
|
|
195
|
+
const t2 = ((a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10)) + (a & b ^ a & c ^ b & c) | 0;
|
|
196
|
+
h = g;
|
|
197
|
+
g = f;
|
|
198
|
+
f = e;
|
|
199
|
+
e = d + t1 | 0;
|
|
200
|
+
d = c;
|
|
201
|
+
c = b;
|
|
202
|
+
b = a;
|
|
203
|
+
a = t1 + t2 | 0;
|
|
204
|
+
}
|
|
205
|
+
state[0] = (state[0] ?? 0) + a | 0;
|
|
206
|
+
state[1] = (state[1] ?? 0) + b | 0;
|
|
207
|
+
state[2] = (state[2] ?? 0) + c | 0;
|
|
208
|
+
state[3] = (state[3] ?? 0) + d | 0;
|
|
209
|
+
state[4] = (state[4] ?? 0) + e | 0;
|
|
210
|
+
state[5] = (state[5] ?? 0) + f | 0;
|
|
211
|
+
state[6] = (state[6] ?? 0) + g | 0;
|
|
212
|
+
state[7] = (state[7] ?? 0) + h | 0;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* The first 32 bits of SHA-256(`synq/signup-email-work/v1\0<ticket>\0<nonce>`),
|
|
216
|
+
* for one ticket and any nonce from 0 to 9,999,999. Only the nonce changes
|
|
217
|
+
* between attempts, so every whole 64-byte block before it is hashed once,
|
|
218
|
+
* and each attempt hashes only the last one or two blocks: a ticket of up to
|
|
219
|
+
* 2 KiB costs an attempt no more than a short one does. Exported for the
|
|
220
|
+
* tests, which hold it to node:crypto; not part of the SDK's API.
|
|
221
|
+
* @param {string} ticket
|
|
222
|
+
* @returns {(nonce: number) => number} the digest's first word, unsigned
|
|
223
|
+
*/
|
|
224
|
+
function emailWorkHasher(ticket) {
|
|
225
|
+
const prefix = `synq/signup-email-work/v1\0${ticket}\0`;
|
|
226
|
+
for (let i = 0; i < prefix.length; i++) if (prefix.charCodeAt(i) > 127) throw new TypeError("An email work ticket is ASCII");
|
|
227
|
+
const whole = prefix.length - prefix.length % 64;
|
|
228
|
+
const bytes = new Uint8Array(whole);
|
|
229
|
+
for (let i = 0; i < whole; i++) bytes[i] = prefix.charCodeAt(i);
|
|
230
|
+
const w = /* @__PURE__ */ new Int32Array(64), midstate = Int32Array.from(IV), state = /* @__PURE__ */ new Int32Array(8);
|
|
231
|
+
for (let at = 0; at < whole; at += 64) compress(midstate, bytes, at, w);
|
|
232
|
+
const tail = /* @__PURE__ */ new Uint8Array(128), rest = prefix.length - whole;
|
|
233
|
+
for (let i = 0; i < rest; i++) tail[i] = prefix.charCodeAt(whole + i);
|
|
234
|
+
return (nonce) => {
|
|
235
|
+
const digits = String(nonce);
|
|
236
|
+
let at = rest;
|
|
237
|
+
for (let i = 0; i < digits.length; i++) tail[at++] = digits.charCodeAt(i);
|
|
238
|
+
tail[at++] = 128;
|
|
239
|
+
const end = at + 8 <= 64 ? 64 : 128;
|
|
240
|
+
tail.fill(0, at, end - 4);
|
|
241
|
+
const bits = (prefix.length + digits.length) * 8;
|
|
242
|
+
tail[end - 4] = bits >>> 24;
|
|
243
|
+
tail[end - 3] = bits >>> 16;
|
|
244
|
+
tail[end - 2] = bits >>> 8;
|
|
245
|
+
tail[end - 1] = bits;
|
|
246
|
+
state.set(midstate);
|
|
247
|
+
compress(state, tail, 0, w);
|
|
248
|
+
if (end === 128) compress(state, tail, 64, w);
|
|
249
|
+
return (state[0] ?? 0) >>> 0;
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* How the solver gives the event loop a turn between slices of work, so
|
|
254
|
+
* input, rendering and an abort run while it works, with no timer's clamped
|
|
255
|
+
* delay where the runtime has something better: `scheduler.yield()`; in a
|
|
256
|
+
* browser without it, a MessageChannel, whose every message is a task of its
|
|
257
|
+
* own; in Node, setImmediate (Node drains a port's messages without turning
|
|
258
|
+
* its loop); elsewhere (React Native, whose chained setImmediate never hands
|
|
259
|
+
* native a turn), a timer.
|
|
260
|
+
* @returns {{pause: () => Promise<unknown>, close: () => void}}
|
|
261
|
+
*/
|
|
262
|
+
function turns() {
|
|
263
|
+
const scope = globalThis;
|
|
264
|
+
const scheduler = scope.scheduler, yieldTurn = scheduler?.yield, immediate = scope.setImmediate;
|
|
265
|
+
if (typeof yieldTurn === "function") return {
|
|
266
|
+
pause: () => yieldTurn.call(scheduler),
|
|
267
|
+
close: () => {}
|
|
268
|
+
};
|
|
269
|
+
if (typeof scope.document === "object" && typeof MessageChannel === "function") {
|
|
270
|
+
const channel = new MessageChannel();
|
|
271
|
+
/** @type {(value?: unknown) => void} */
|
|
272
|
+
let wake = () => {};
|
|
273
|
+
channel.port1.onmessage = () => wake();
|
|
274
|
+
return {
|
|
275
|
+
pause: () => new Promise((resolve) => {
|
|
276
|
+
wake = resolve;
|
|
277
|
+
channel.port2.postMessage(0);
|
|
278
|
+
}),
|
|
279
|
+
close: () => channel.port1.close()
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
if (typeof scope.process?.versions?.node === "string" && typeof immediate === "function") return {
|
|
283
|
+
pause: () => new Promise((resolve) => immediate(() => resolve(void 0))),
|
|
284
|
+
close: () => {}
|
|
285
|
+
};
|
|
286
|
+
return {
|
|
287
|
+
pause: () => new Promise((resolve) => setTimeout(resolve, 0)),
|
|
288
|
+
close: () => {}
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
/** How long one slice of attempts may hold the thread before the solver yields. */
|
|
292
|
+
const SLICE_MS = 8;
|
|
293
|
+
/**
|
|
294
|
+
* Public, bounded proof solver in plain JavaScript (the hash above): no key,
|
|
295
|
+
* account lookup, platform crypto or third-party code, so it runs the same in
|
|
296
|
+
* every browser, Node and React Native.
|
|
297
|
+
* @param {EmailWorkChallenge} work
|
|
298
|
+
* @param {{signal?:AbortSignal, maxIterations?:number, timeoutMs?:number}} [options]
|
|
299
|
+
* @returns {Promise<string>} Canonical decimal nonce; send with the unchanged ticket.
|
|
300
|
+
*/
|
|
301
|
+
async function solveEmailWork$1(work, options = {}) {
|
|
302
|
+
const cap = Math.min(options.maxIterations ?? 1048576, 1048576);
|
|
303
|
+
const timeout = Math.min(options.timeoutMs ?? 2e3, 2e3);
|
|
304
|
+
if (!work || typeof work.ticket !== "string" || work.ticket.length > 2048 || !/^synq_work_[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}$/.test(work.ticket) || work.algorithm !== "sha256-leading-zero-bits-v1" || ![12, 14].includes(work.bits) || !Number.isSafeInteger(work.expiresAt) || work.expiresAt <= Date.now() || !Number.isSafeInteger(cap) || cap < 1 || !Number.isFinite(timeout) || timeout < 1) throw new Error("Invalid email work challenge: request another");
|
|
305
|
+
const started = performance.now(), hash = emailWorkHasher(work.ticket), shift = 32 - work.bits, turn = turns();
|
|
306
|
+
try {
|
|
307
|
+
for (let nonce = 0; nonce < cap;) {
|
|
308
|
+
options.signal?.throwIfAborted();
|
|
309
|
+
if (Date.now() >= work.expiresAt) throw new Error("Email work expired: request another");
|
|
310
|
+
const now = performance.now();
|
|
311
|
+
if (now - started >= timeout) throw new Error("Email work took too long: retry or use another sign-in method");
|
|
312
|
+
const until = now + SLICE_MS;
|
|
313
|
+
do
|
|
314
|
+
for (const stop = Math.min(cap, nonce + 256); nonce < stop; nonce++) if (hash(nonce) >>> shift === 0) {
|
|
315
|
+
if (Date.now() >= work.expiresAt) throw new Error("Email work expired: request another");
|
|
316
|
+
return String(nonce);
|
|
317
|
+
}
|
|
318
|
+
while (nonce < cap && performance.now() < until);
|
|
319
|
+
if (nonce < cap) await turn.pause();
|
|
320
|
+
}
|
|
321
|
+
} finally {
|
|
322
|
+
turn.close();
|
|
323
|
+
}
|
|
324
|
+
throw new Error("Email work limit reached: request another challenge");
|
|
325
|
+
}
|
|
326
|
+
//#endregion
|
|
327
|
+
//#region src/email-work-api.ts
|
|
328
|
+
/** Solve with bounded work in plain JavaScript and return the decimal nonce for the unchanged ticket. */
|
|
329
|
+
function solveEmailWork(work, options = {}) {
|
|
330
|
+
return solveEmailWork$1(work, options);
|
|
331
|
+
}
|
|
332
|
+
//#endregion
|
|
333
|
+
//#region src/linked-accounts.ts
|
|
334
|
+
/** A test account as `/authorize-challenge` takes it: `synq_test_*` fields. */
|
|
335
|
+
function testAccountFields(account) {
|
|
336
|
+
const fields = {
|
|
337
|
+
provider: account.provider,
|
|
338
|
+
account: account.account,
|
|
339
|
+
username: account.username,
|
|
340
|
+
email: account.email,
|
|
341
|
+
name: account.name,
|
|
342
|
+
account_type: account.accountType,
|
|
343
|
+
account_age_days: account.accountAgeDays,
|
|
344
|
+
created_at: account.createdAt,
|
|
345
|
+
public_repos: account.publicRepos,
|
|
346
|
+
followers: account.followers,
|
|
347
|
+
email_verified: account.emailVerified,
|
|
348
|
+
workspace_domain: account.workspaceDomain
|
|
349
|
+
};
|
|
350
|
+
return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== void 0).map(([name, value]) => [`synq_test_${name}`, String(value)]));
|
|
351
|
+
}
|
|
352
|
+
/** The `linked_accounts` claim, read safely: the entries that are objects, else undefined. */
|
|
353
|
+
function linkedAccountsOf(value) {
|
|
354
|
+
if (!Array.isArray(value)) return void 0;
|
|
355
|
+
return value.filter((entry) => typeof entry === "object" && entry !== null && typeof entry.provider === "string" && typeof entry.subject === "string");
|
|
356
|
+
}
|
|
357
|
+
//#endregion
|
|
358
|
+
//#region src/sign-in-flow.ts
|
|
359
|
+
/** A new flow's state: a PKCE verifier and nonce of its own. */
|
|
360
|
+
function newSignIn(scope, options) {
|
|
361
|
+
return {
|
|
362
|
+
v: 1,
|
|
363
|
+
verifier: oauth.generateRandomCodeVerifier(),
|
|
364
|
+
nonce: oauth.generateRandomNonce(),
|
|
365
|
+
scope,
|
|
366
|
+
...options.resource ? { resource: options.resource } : {},
|
|
367
|
+
...options.additionalResources?.length ? { additionalResources: [...options.additionalResources] } : {},
|
|
368
|
+
...options.acr ? { acr: options.acr } : {},
|
|
369
|
+
step: "start"
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
/** A saved flow, checked: one this SDK wrote. */
|
|
373
|
+
function readSavedSignIn(saved) {
|
|
374
|
+
const value = typeof saved === "string" ? JSON.parse(saved) : saved;
|
|
375
|
+
if (value?.v !== 1 || typeof value.verifier !== "string" || typeof value.nonce !== "string" || typeof value.scope !== "string" || typeof value.step !== "string") throw new SynqError("invalid_options", "That is not a sign-in this SDK saved");
|
|
376
|
+
return value;
|
|
377
|
+
}
|
|
378
|
+
/** One sign-in on an app's own screens. */
|
|
379
|
+
var SignInFlow = class {
|
|
380
|
+
#port;
|
|
381
|
+
#state;
|
|
382
|
+
#workEpoch = 0;
|
|
383
|
+
#workJob;
|
|
384
|
+
constructor(port, state) {
|
|
385
|
+
this.#port = port;
|
|
386
|
+
this.#state = state;
|
|
387
|
+
}
|
|
388
|
+
/** What the app's screen asks for now. */
|
|
389
|
+
get step() {
|
|
390
|
+
return this.#state.step;
|
|
391
|
+
}
|
|
392
|
+
/** The address the sign-in is for, once one was typed. */
|
|
393
|
+
get address() {
|
|
394
|
+
return this.#state.email;
|
|
395
|
+
}
|
|
396
|
+
/** Email and password. */
|
|
397
|
+
password = {
|
|
398
|
+
signIn: (input) => this.#ask(this.#method("password", {
|
|
399
|
+
username: input.email,
|
|
400
|
+
password: input.password
|
|
401
|
+
}), { email: input.email }),
|
|
402
|
+
/** Makes an account where the brand lets people sign up; its address is verified next. */
|
|
403
|
+
signUp: (input) => this.#ask(this.#method("password", {
|
|
404
|
+
username: input.email,
|
|
405
|
+
password: input.password,
|
|
406
|
+
synq_screen: "sign-up"
|
|
407
|
+
}), { email: input.email })
|
|
408
|
+
};
|
|
409
|
+
/** A code by email. */
|
|
410
|
+
email = {
|
|
411
|
+
send: (email) => this.#ask(this.#method("email", { username: email }), { email }),
|
|
412
|
+
verify: (code) => this.#ask({ otp: code }),
|
|
413
|
+
resend: () => this.#ask({ synq_action: "resend" })
|
|
414
|
+
};
|
|
415
|
+
/**
|
|
416
|
+
* A test sign-in (AERO-2343): a made-up GitHub or Google account, signed
|
|
417
|
+
* in at once, for an app with `test_sign_ins` on, on Synq's stages other
|
|
418
|
+
* than production. For end-to-end tests that want tokens without a real
|
|
419
|
+
* account or a browser.
|
|
420
|
+
*/
|
|
421
|
+
test = { signIn: (account) => this.#ask(this.#method("test", testAccountFields(account))) };
|
|
422
|
+
/** A passkey: `options()`, then the browser's assertion to `signIn`. */
|
|
423
|
+
passkey = {
|
|
424
|
+
options: () => this.#ask(this.#method("passkey", {})),
|
|
425
|
+
signIn: (credential, options = {}) => this.#ask({
|
|
426
|
+
synq_passkey: JSON.stringify(credential),
|
|
427
|
+
...options.related ? { synq_passkey_rp: "related" } : {}
|
|
428
|
+
})
|
|
429
|
+
};
|
|
430
|
+
/**
|
|
431
|
+
* A Solana wallet (AERO-2681): `siws` is the wallet's signature over a
|
|
432
|
+
* sign-in request this app's page asked the issuer for, as
|
|
433
|
+
* `@synqauth/solana`'s `requestSignIn`, `signWithWallet` and `encodeSiws`
|
|
434
|
+
* make it. One request, with no page: signed in, or `retry` with
|
|
435
|
+
* `wallet_failed` (not the wallet's signature) or `wallet_expired` (ask
|
|
436
|
+
* for another request), the flow going on for the next try.
|
|
437
|
+
*
|
|
438
|
+
* `reauthenticate` signs the person signed in now in again, for a change
|
|
439
|
+
* that wants a recent sign-in: it is the ID token this app holds for
|
|
440
|
+
* them, and only they can sign in. Another account's wallet, or one
|
|
441
|
+
* nobody signs in with, is `refused` with `other_account`, and nothing
|
|
442
|
+
* changes at Synq.
|
|
443
|
+
*/
|
|
444
|
+
wallet = { signIn: (siws, options = {}) => this.#ask(this.#method("wallet", {
|
|
445
|
+
synq_siws: siws,
|
|
446
|
+
...options.reauthenticate ? { synq_reauthenticate: options.reauthenticate } : {}
|
|
447
|
+
})) };
|
|
448
|
+
/** Verifying an address after a sign-in that didn't prove it. */
|
|
449
|
+
verifyEmail = {
|
|
450
|
+
verify: (code) => this.#ask({ otp: code }),
|
|
451
|
+
resend: () => this.#ask({ synq_action: "resend" }),
|
|
452
|
+
skip: () => this.#ask({ synq_action: "skip" })
|
|
453
|
+
};
|
|
454
|
+
/** The flow, to keep between requests (a server's sealed cookie, a phone's secure storage). */
|
|
455
|
+
toJSON() {
|
|
456
|
+
return this.#state;
|
|
457
|
+
}
|
|
458
|
+
/** Cancel only local email-work computation; the server sign-in may be retried. */
|
|
459
|
+
cancelEmailWork() {
|
|
460
|
+
this.#workEpoch++;
|
|
461
|
+
this.#workJob?.abort();
|
|
462
|
+
this.#workJob = void 0;
|
|
463
|
+
}
|
|
464
|
+
/** Fields that name `method`, which a session already under way switches to. */
|
|
465
|
+
#method(method, fields) {
|
|
466
|
+
return {
|
|
467
|
+
synq_method: method,
|
|
468
|
+
...fields
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
async #ask(fields, changes = {}) {
|
|
472
|
+
if (this.#state.step === "done") throw new SynqError("invalid_session", "This sign-in has finished: start another");
|
|
473
|
+
this.cancelEmailWork();
|
|
474
|
+
const epoch = this.#workEpoch;
|
|
475
|
+
if (changes.email !== void 0) this.#state = {
|
|
476
|
+
...this.#state,
|
|
477
|
+
email: changes.email
|
|
478
|
+
};
|
|
479
|
+
const recipient = this.#state.email ?? "";
|
|
480
|
+
const superseded = () => ({
|
|
481
|
+
status: "retry",
|
|
482
|
+
problem: "work_required",
|
|
483
|
+
message: "This computation was cancelled or replaced. Continue with your latest sign-in request."
|
|
484
|
+
});
|
|
485
|
+
const initial = { ...this.#state };
|
|
486
|
+
let answer = await this.#send(fields, initial);
|
|
487
|
+
if (epoch !== this.#workEpoch) return superseded();
|
|
488
|
+
const work = answer.body.synq_work;
|
|
489
|
+
if ((fields.synq_method === "email" || fields.synq_action === "resend" && this.#state.step === "code") && answer.body.synq_problem === "work_required" && work && typeof work === "object" && typeof answer.body.auth_session === "string") {
|
|
490
|
+
if (epoch !== this.#workEpoch) return superseded();
|
|
491
|
+
const captured = {
|
|
492
|
+
...this.#state,
|
|
493
|
+
email: recipient,
|
|
494
|
+
authSession: answer.body.auth_session
|
|
495
|
+
};
|
|
496
|
+
this.#state = captured;
|
|
497
|
+
const job = new AbortController();
|
|
498
|
+
this.#workJob = job;
|
|
499
|
+
const current = () => epoch === this.#workEpoch && this.#workJob === job && !job.signal.aborted;
|
|
500
|
+
try {
|
|
501
|
+
let solution;
|
|
502
|
+
try {
|
|
503
|
+
solution = await solveEmailWork(work, { signal: job.signal });
|
|
504
|
+
} catch {
|
|
505
|
+
return current() ? this.#read(answer) : superseded();
|
|
506
|
+
}
|
|
507
|
+
if (!current()) return superseded();
|
|
508
|
+
try {
|
|
509
|
+
answer = await this.#send({
|
|
510
|
+
...fields,
|
|
511
|
+
username: recipient,
|
|
512
|
+
synq_work: work.ticket,
|
|
513
|
+
synq_work_nonce: solution
|
|
514
|
+
}, captured, job.signal);
|
|
515
|
+
} catch (error) {
|
|
516
|
+
if (!current()) return superseded();
|
|
517
|
+
throw error;
|
|
518
|
+
}
|
|
519
|
+
if (!current()) return superseded();
|
|
520
|
+
return this.#read(answer);
|
|
521
|
+
} finally {
|
|
522
|
+
if (this.#workJob === job) this.#workJob = void 0;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
return this.#read(answer);
|
|
526
|
+
}
|
|
527
|
+
async #send(fields, captured, signal) {
|
|
528
|
+
const port = this.#port;
|
|
529
|
+
const server = await port.server();
|
|
530
|
+
signal?.throwIfAborted();
|
|
531
|
+
const endpoint = server.authorization_challenge_endpoint;
|
|
532
|
+
if (typeof endpoint !== "string") throw new SynqError("discovery_failed", "The issuer doesn't sign people in on apps' own screens");
|
|
533
|
+
const body = new URLSearchParams(fields);
|
|
534
|
+
const state = captured ?? this.#state;
|
|
535
|
+
if (state.authSession) body.set("auth_session", state.authSession);
|
|
536
|
+
else {
|
|
537
|
+
body.set("response_type", "code");
|
|
538
|
+
body.set("scope", state.scope);
|
|
539
|
+
body.set("nonce", state.nonce);
|
|
540
|
+
body.set("code_challenge", await oauth.calculatePKCECodeChallenge(state.verifier));
|
|
541
|
+
body.set("code_challenge_method", "S256");
|
|
542
|
+
if (state.resource) body.set("resource", state.resource);
|
|
543
|
+
for (const extra of state.additionalResources ?? []) if (extra !== state.resource) body.append("resource", extra);
|
|
544
|
+
if (state.acr) {
|
|
545
|
+
if (state.acr.essential) body.set("claims", JSON.stringify({ id_token: { acr: {
|
|
546
|
+
essential: true,
|
|
547
|
+
values: [...state.acr.values]
|
|
548
|
+
} } }));
|
|
549
|
+
else body.set("acr_values", state.acr.values.join(" "));
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
const headers = new Headers({
|
|
553
|
+
accept: "application/json",
|
|
554
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
555
|
+
...port.headers
|
|
556
|
+
});
|
|
557
|
+
await port.auth(server, port.client, body, headers);
|
|
558
|
+
signal?.throwIfAborted();
|
|
559
|
+
let response;
|
|
560
|
+
try {
|
|
561
|
+
response = await port.fetch(endpoint, {
|
|
562
|
+
method: "POST",
|
|
563
|
+
headers,
|
|
564
|
+
body: body.toString(),
|
|
565
|
+
redirect: "manual",
|
|
566
|
+
...signal ? { signal } : {}
|
|
567
|
+
});
|
|
568
|
+
} catch (error) {
|
|
569
|
+
throw toSynqError(error);
|
|
570
|
+
}
|
|
571
|
+
let parsed;
|
|
572
|
+
try {
|
|
573
|
+
parsed = await response.json();
|
|
574
|
+
} catch {
|
|
575
|
+
parsed = void 0;
|
|
576
|
+
}
|
|
577
|
+
if (!parsed || typeof parsed !== "object") throw new SynqError("invalid_response", `Synq answered ${response.status} with no JSON`, { status: response.status });
|
|
578
|
+
return {
|
|
579
|
+
status: response.status,
|
|
580
|
+
body: parsed,
|
|
581
|
+
retryAfter: retryAfterSeconds(response.headers.get("retry-after"))
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
async #read(answer) {
|
|
585
|
+
const { body } = answer;
|
|
586
|
+
const text = (name) => typeof body[name] === "string" ? body[name] : void 0;
|
|
587
|
+
const message = text("error_description") ?? "";
|
|
588
|
+
const problem = text("synq_problem");
|
|
589
|
+
const session = text("auth_session");
|
|
590
|
+
if (session) this.#state = {
|
|
591
|
+
...this.#state,
|
|
592
|
+
authSession: session
|
|
593
|
+
};
|
|
594
|
+
if (answer.status === 200 && typeof body.authorization_code === "string") {
|
|
595
|
+
this.#state = {
|
|
596
|
+
...this.#state,
|
|
597
|
+
step: "done"
|
|
598
|
+
};
|
|
599
|
+
return {
|
|
600
|
+
status: "signed-in",
|
|
601
|
+
session: await this.#redeem(body.authorization_code)
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
const error = text("error");
|
|
605
|
+
switch (error) {
|
|
606
|
+
case "insufficient_authorization": return this.#next(body, problem, message);
|
|
607
|
+
case "redirect_to_web": {
|
|
608
|
+
this.#state = {
|
|
609
|
+
...this.#state,
|
|
610
|
+
step: "done"
|
|
611
|
+
};
|
|
612
|
+
const method = text("synq_method");
|
|
613
|
+
const loginHint = text("login_hint") ?? this.#state.email;
|
|
614
|
+
return {
|
|
615
|
+
status: "hosted",
|
|
616
|
+
reason: text("synq_reason"),
|
|
617
|
+
...method ? { method } : {},
|
|
618
|
+
...loginHint ? { loginHint } : {},
|
|
619
|
+
continue: () => this.#port.hosted({
|
|
620
|
+
...method ? { method } : {},
|
|
621
|
+
...loginHint ? { loginHint } : {}
|
|
622
|
+
})
|
|
623
|
+
};
|
|
624
|
+
}
|
|
625
|
+
case "access_denied":
|
|
626
|
+
this.#state = {
|
|
627
|
+
...this.#state,
|
|
628
|
+
step: "done"
|
|
629
|
+
};
|
|
630
|
+
return {
|
|
631
|
+
status: "refused",
|
|
632
|
+
reason: text("synq_reason"),
|
|
633
|
+
message
|
|
634
|
+
};
|
|
635
|
+
case "too_many_requests":
|
|
636
|
+
if (session && problem) return {
|
|
637
|
+
status: "retry",
|
|
638
|
+
problem,
|
|
639
|
+
message,
|
|
640
|
+
...answer.retryAfter === void 0 ? {} : { retryAfter: answer.retryAfter }
|
|
641
|
+
};
|
|
642
|
+
throw new SynqError("too_many_requests", message || "Too many requests", {
|
|
643
|
+
status: answer.status,
|
|
644
|
+
description: message,
|
|
645
|
+
...answer.retryAfter === void 0 ? {} : { retryAfter: answer.retryAfter }
|
|
646
|
+
});
|
|
647
|
+
default:
|
|
648
|
+
if (error === "invalid_session") this.#state = {
|
|
649
|
+
...this.#state,
|
|
650
|
+
step: "done"
|
|
651
|
+
};
|
|
652
|
+
throw new SynqError(error ?? `http_${answer.status}`, message || `Synq answered ${answer.status}`, {
|
|
653
|
+
status: answer.status,
|
|
654
|
+
description: message || void 0
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
/** What Synq asks for next, or the same step again with what went wrong. */
|
|
659
|
+
#next(body, problem, message) {
|
|
660
|
+
const next = body.synq_next;
|
|
661
|
+
const step = next === "otp" ? "code" : next === "verify_email" ? "verify-email" : next === "method" ? "start" : next;
|
|
662
|
+
this.#state = {
|
|
663
|
+
...this.#state,
|
|
664
|
+
step
|
|
665
|
+
};
|
|
666
|
+
if (next === "passkey") {
|
|
667
|
+
const related = body.synq_passkey_related_options;
|
|
668
|
+
return {
|
|
669
|
+
status: "passkey",
|
|
670
|
+
options: body.synq_passkey_options,
|
|
671
|
+
...related ? { related: {
|
|
672
|
+
rpId: related.rp_id,
|
|
673
|
+
options: related.options
|
|
674
|
+
} } : {},
|
|
675
|
+
...problem ? {
|
|
676
|
+
problem,
|
|
677
|
+
message
|
|
678
|
+
} : {}
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
if (problem) return {
|
|
682
|
+
status: "retry",
|
|
683
|
+
problem,
|
|
684
|
+
message
|
|
685
|
+
};
|
|
686
|
+
const email = this.#state.email ?? "";
|
|
687
|
+
if (next === "otp") {
|
|
688
|
+
const seconds = typeof body.synq_code_expires_in === "number" ? body.synq_code_expires_in : 0;
|
|
689
|
+
return {
|
|
690
|
+
status: "code-sent",
|
|
691
|
+
email,
|
|
692
|
+
expiresAt: new Date(Date.now() + seconds * 1e3)
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
if (next === "verify_email") return {
|
|
696
|
+
status: "verify-email",
|
|
697
|
+
email,
|
|
698
|
+
canSkip: body.synq_can_skip === true
|
|
699
|
+
};
|
|
700
|
+
return {
|
|
701
|
+
status: "retry",
|
|
702
|
+
problem: "missing",
|
|
703
|
+
message
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
/** Redeems the code at the token endpoint, with the verifier and no redirect URI. */
|
|
707
|
+
async #redeem(code) {
|
|
708
|
+
const port = this.#port;
|
|
709
|
+
const server = await port.server();
|
|
710
|
+
if (!server.token_endpoint) throw new SynqError("discovery_failed", "The issuer has no token endpoint");
|
|
711
|
+
const body = new URLSearchParams({
|
|
712
|
+
grant_type: "authorization_code",
|
|
713
|
+
code,
|
|
714
|
+
code_verifier: this.#state.verifier
|
|
715
|
+
});
|
|
716
|
+
if (this.#state.resource) body.set("resource", this.#state.resource);
|
|
717
|
+
const headers = new Headers({
|
|
718
|
+
accept: "application/json",
|
|
719
|
+
"content-type": "application/x-www-form-urlencoded"
|
|
720
|
+
});
|
|
721
|
+
await port.auth(server, port.client, body, headers);
|
|
722
|
+
try {
|
|
723
|
+
const response = await port.fetch(server.token_endpoint, {
|
|
724
|
+
method: "POST",
|
|
725
|
+
headers,
|
|
726
|
+
body: body.toString(),
|
|
727
|
+
redirect: "manual"
|
|
728
|
+
});
|
|
729
|
+
const result = await oauth.processAuthorizationCodeResponse(server, port.client, response, {
|
|
730
|
+
expectedNonce: this.#state.nonce,
|
|
731
|
+
maxAge: oauth.skipAuthTimeCheck,
|
|
732
|
+
requireIdToken: true
|
|
733
|
+
});
|
|
734
|
+
const claims = oauth.getValidatedIdTokenClaims(result);
|
|
735
|
+
const acr = this.#state.acr;
|
|
736
|
+
if (acr?.essential && !(typeof claims?.acr === "string" && acr.values.includes(claims.acr))) throw new SynqError("unmet_authentication_requirements", "The sign-in did not reach the level this app requires");
|
|
737
|
+
return await port.finish(result, claims);
|
|
738
|
+
} catch (error) {
|
|
739
|
+
throw toSynqError(error);
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
};
|
|
743
|
+
//#endregion
|
|
744
|
+
//#region src/urls.ts
|
|
745
|
+
/** Whether a host is this machine: a Synq stack under `localhost`, or a loopback address. */
|
|
746
|
+
function isLoopback(hostname) {
|
|
747
|
+
return hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "127.0.0.1" || hostname === "[::1]";
|
|
748
|
+
}
|
|
749
|
+
/**
|
|
750
|
+
* `value` as a URL, which must be https: Synq's hosts always are. Plain http
|
|
751
|
+
* only on this machine, for a local Synq stack. `what` names it in the error.
|
|
752
|
+
*/
|
|
753
|
+
function secureUrl(value, what) {
|
|
754
|
+
let url;
|
|
755
|
+
try {
|
|
756
|
+
url = new URL(value);
|
|
757
|
+
} catch {
|
|
758
|
+
throw new SynqError("invalid_options", `${what} isn't a URL: ${String(value)}`);
|
|
759
|
+
}
|
|
760
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && isLoopback(url.hostname))) throw new SynqError("invalid_options", `${what} must be https: (http: only for a Synq stack on this machine, under 'localhost')`);
|
|
761
|
+
return url;
|
|
762
|
+
}
|
|
763
|
+
/** The longest wait between tries when Synq names none. */
|
|
764
|
+
const RETRY_MAX_DELAY_MS = 8e3;
|
|
765
|
+
/**
|
|
766
|
+
* Whether a call that failed this way may be tried again, and nothing
|
|
767
|
+
* happens twice when it is:
|
|
768
|
+
*
|
|
769
|
+
* - 429 and 503 are refusals: Synq did nothing, so any method retries. A
|
|
770
|
+
* 503 problem `service_unavailable` without `Retry-After` is a part not
|
|
771
|
+
* set up on this server, which waiting doesn't change, so it doesn't.
|
|
772
|
+
* - 409 `idempotency_key_in_flight`: the first try with this key is still
|
|
773
|
+
* running; the retry gets its answer once it finishes.
|
|
774
|
+
* - 502, 504 and a dropped connection may come after Synq acted. A GET,
|
|
775
|
+
* PUT or PATCH sets the same thing again, and a POST carries its
|
|
776
|
+
* `Idempotency-Key`, whose answer Synq keeps once it succeeds, so the
|
|
777
|
+
* retry is answered with it. A DELETE isn't retried: a second try could
|
|
778
|
+
* answer 404 for a delete that worked.
|
|
779
|
+
* - 500 is Synq's own error, which isn't kept with the key: a POST could
|
|
780
|
+
* run twice, so only a GET, PUT or PATCH retries.
|
|
781
|
+
*
|
|
782
|
+
* Anything else, a 4xx above all, fails the same way however often it is
|
|
783
|
+
* sent.
|
|
784
|
+
*/
|
|
785
|
+
function retryable(method, failure, hasIdempotencyKey) {
|
|
786
|
+
const { status, code } = failure;
|
|
787
|
+
const sets = method === "get" || method === "put" || method === "patch";
|
|
788
|
+
const ambiguousOk = sets || method === "post" && hasIdempotencyKey;
|
|
789
|
+
if (status === void 0) return ambiguousOk;
|
|
790
|
+
if (status === 429) return true;
|
|
791
|
+
if (status === 503) return !(code === "service_unavailable" && failure.retryAfter === void 0);
|
|
792
|
+
if (status === 409) return code === "idempotency_key_in_flight";
|
|
793
|
+
if (status === 502 || status === 504) return ambiguousOk;
|
|
794
|
+
if (status === 500) return sets;
|
|
795
|
+
return false;
|
|
796
|
+
}
|
|
797
|
+
/** How long to wait before try `retry` (1 for the first retry): Synq's `Retry-After`, else jittered backoff. */
|
|
798
|
+
function retryDelayMs(retry, retryAfter, random = Math.random) {
|
|
799
|
+
if (retryAfter !== void 0) return retryAfter * 1e3;
|
|
800
|
+
const ceiling = Math.min(RETRY_MAX_DELAY_MS, 500 * 2 ** (retry - 1));
|
|
801
|
+
return Math.round(ceiling / 2 + random() * (ceiling / 2));
|
|
802
|
+
}
|
|
803
|
+
function createApiClient(options) {
|
|
804
|
+
const base = secureUrl(options.baseUrl, "The API base URL").href.replace(/\/+$/, "");
|
|
805
|
+
const maxRetries = options.maxRetries ?? 0;
|
|
806
|
+
if (!Number.isSafeInteger(maxRetries) || maxRetries < 0) throw new SynqError("invalid_options", "maxRetries must be a whole number, 0 or more");
|
|
807
|
+
const call = (method) => ((path, request = {}) => send(method, path, request));
|
|
808
|
+
async function send(method, path, request) {
|
|
809
|
+
const url = new URL(base + fill(path, request.path));
|
|
810
|
+
for (const [name, value] of Object.entries(request.query ?? {})) {
|
|
811
|
+
if (value === void 0) continue;
|
|
812
|
+
for (const item of Array.isArray(value) ? value : [value]) url.searchParams.append(name, String(item));
|
|
813
|
+
}
|
|
814
|
+
const body = request.body === void 0 ? void 0 : JSON.stringify(request.body);
|
|
815
|
+
const idempotencyKey = request.idempotencyKey || (options.idempotencyKeys && maxRetries > 0 && method === "post" ? crypto.randomUUID() : void 0);
|
|
816
|
+
for (let retry = 0;; retry++) try {
|
|
817
|
+
return await attempt(method, url, body, idempotencyKey, request.signal);
|
|
818
|
+
} catch (error) {
|
|
819
|
+
if (!(error instanceof SynqError) || retry >= maxRetries || request.signal?.aborted) throw error;
|
|
820
|
+
if (!retryable(method, {
|
|
821
|
+
status: error.status,
|
|
822
|
+
code: error.code,
|
|
823
|
+
retryAfter: error.retryAfter
|
|
824
|
+
}, idempotencyKey !== void 0)) throw error;
|
|
825
|
+
if (error.retryAfter !== void 0 && error.retryAfter > 60) throw error;
|
|
826
|
+
await sleep(retryDelayMs(retry + 1, error.retryAfter), request.signal, error);
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
async function attempt(method, url, body, idempotencyKey, signal) {
|
|
830
|
+
const headers = new Headers({
|
|
831
|
+
accept: "application/json, application/problem+json",
|
|
832
|
+
authorization: `Bearer ${await options.credential()}`
|
|
833
|
+
});
|
|
834
|
+
if (body !== void 0) headers.set("content-type", "application/json");
|
|
835
|
+
if (idempotencyKey) headers.set("idempotency-key", idempotencyKey);
|
|
836
|
+
let response;
|
|
837
|
+
try {
|
|
838
|
+
response = await (options.fetch ?? fetch)(url, {
|
|
839
|
+
method: method.toUpperCase(),
|
|
840
|
+
headers,
|
|
841
|
+
body,
|
|
842
|
+
signal
|
|
843
|
+
});
|
|
844
|
+
} catch (error) {
|
|
845
|
+
throw new SynqError("network_error", `Synq couldn't be reached: ${String(error)}`, { cause: error });
|
|
846
|
+
}
|
|
847
|
+
const text = await response.text();
|
|
848
|
+
let json;
|
|
849
|
+
try {
|
|
850
|
+
json = text ? JSON.parse(text) : void 0;
|
|
851
|
+
} catch {
|
|
852
|
+
json = void 0;
|
|
853
|
+
}
|
|
854
|
+
if (!response.ok) throw problemError(response.status, json !== null && typeof json === "object" ? json : {}, retryAfterSeconds(response.headers.get("retry-after")), response.headers.get("request-id"));
|
|
855
|
+
return json;
|
|
856
|
+
}
|
|
857
|
+
async function* paginate(path, request = {}) {
|
|
858
|
+
let cursor = request.query?.cursor;
|
|
859
|
+
for (;;) {
|
|
860
|
+
const page = await send("get", path, {
|
|
861
|
+
...request,
|
|
862
|
+
query: {
|
|
863
|
+
...request.query,
|
|
864
|
+
cursor
|
|
865
|
+
}
|
|
866
|
+
});
|
|
867
|
+
if (!page || !Array.isArray(page.data)) throw new SynqError("invalid_response", `${path} didn't answer a page of data`);
|
|
868
|
+
yield* page.data;
|
|
869
|
+
const next = page.next_cursor;
|
|
870
|
+
if (next === null || next === void 0) return;
|
|
871
|
+
if (typeof next !== "string" || next === "" || next === cursor) throw new SynqError("invalid_response", `${path} answered a next_cursor that can't be followed`);
|
|
872
|
+
cursor = next;
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
return {
|
|
876
|
+
get: call("get"),
|
|
877
|
+
post: call("post"),
|
|
878
|
+
put: call("put"),
|
|
879
|
+
patch: call("patch"),
|
|
880
|
+
delete: call("delete"),
|
|
881
|
+
paginate
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
/** Waits `ms`, or rejects with the abort's reason (or `failure`) as soon as `signal` fires. */
|
|
885
|
+
function sleep(ms, signal, failure) {
|
|
886
|
+
return new Promise((resolve, reject) => {
|
|
887
|
+
if (signal?.aborted) {
|
|
888
|
+
reject(failure);
|
|
889
|
+
return;
|
|
890
|
+
}
|
|
891
|
+
const done = () => {
|
|
892
|
+
signal?.removeEventListener("abort", aborted);
|
|
893
|
+
resolve();
|
|
894
|
+
};
|
|
895
|
+
const timer = setTimeout(done, ms);
|
|
896
|
+
const aborted = () => {
|
|
897
|
+
clearTimeout(timer);
|
|
898
|
+
reject(failure);
|
|
899
|
+
};
|
|
900
|
+
signal?.addEventListener("abort", aborted, { once: true });
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
/** The path with each `{name}` replaced by its parameter, encoded. */
|
|
904
|
+
function fill(path, params = {}) {
|
|
905
|
+
return path.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
906
|
+
const value = params[name];
|
|
907
|
+
if (value === void 0 || value === "") throw new SynqError("invalid_options", `The path ${path} needs ${name}`);
|
|
908
|
+
if (/^\.+$/.test(String(value))) throw new SynqError("invalid_options", `${name} can't be ${String(value)}`);
|
|
909
|
+
return encodeURIComponent(String(value));
|
|
910
|
+
});
|
|
911
|
+
}
|
|
912
|
+
//#endregion
|
|
913
|
+
export { readSavedSignIn as a, SynqError as c, toSynqError as d, newSignIn as i, isSynqError as l, secureUrl as n, linkedAccountsOf as o, SignInFlow as r, solveEmailWork as s, createApiClient as t, problemError as u };
|