@synqauth/js 0.0.0 → 0.2.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.
@@ -0,0 +1,467 @@
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
+ * How many seconds to wait before trying again, from Synq's `Retry-After`:
18
+ * set on `rate_limited` (429), and wherever else Synq sends one.
19
+ */
20
+ retryAfter;
21
+ constructor(code, message, options = {}) {
22
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
23
+ this.code = code;
24
+ this.status = options.status;
25
+ this.description = options.description;
26
+ this.retryAfter = options.retryAfter;
27
+ }
28
+ };
29
+ /** Whether `error` is a `SynqError`, with `code` when given. */
30
+ function isSynqError(error, code) {
31
+ return error instanceof SynqError && (code === void 0 || error.code === code);
32
+ }
33
+ /** A `SynqError` for a problem document a Synq API answered with. */
34
+ function problemError(status, problem, retryAfter) {
35
+ const code = typeof problem.code === "string" ? problem.code : `http_${status}`;
36
+ const description = typeof problem.detail === "string" ? problem.detail : void 0;
37
+ return new SynqError(code, description ?? problem.title ?? `Synq answered ${status}`, {
38
+ status,
39
+ description,
40
+ retryAfter,
41
+ cause: problem
42
+ });
43
+ }
44
+ /**
45
+ * The seconds a `Retry-After` header asks for: a number of seconds, or an
46
+ * HTTP date, counted from `now`. Undefined when there is none, or it can't
47
+ * be read.
48
+ */
49
+ function retryAfterSeconds(header, now = Date.now()) {
50
+ const value = header?.trim();
51
+ if (!value) return void 0;
52
+ if (/^[0-9]+$/.test(value)) return Number(value);
53
+ if (!/[A-Za-z]/.test(value)) return void 0;
54
+ const at = Date.parse(value);
55
+ return Number.isNaN(at) ? void 0 : Math.max(0, Math.ceil((at - now) / 1e3));
56
+ }
57
+ /**
58
+ * A `SynqError` for whatever went wrong talking to Synq's issuer: OAuth's
59
+ * error responses keep their `error`, a failed check of Synq's answer is
60
+ * `invalid_response`, and a request that never got an answer is
61
+ * `network_error`.
62
+ */
63
+ function toSynqError(error) {
64
+ if (error instanceof SynqError) return error;
65
+ if (error instanceof ResponseBodyError) return new SynqError(error.error, error.error_description ?? error.error, {
66
+ status: error.status,
67
+ description: error.error_description,
68
+ cause: error
69
+ });
70
+ if (error instanceof AuthorizationResponseError) return new SynqError(error.error, error.error_description ?? error.error, {
71
+ description: error.error_description,
72
+ cause: error
73
+ });
74
+ if (error instanceof WWWAuthenticateChallengeError) {
75
+ const challenge = error.cause[0];
76
+ const code = challenge?.parameters.error ?? "invalid_token";
77
+ const description = challenge?.parameters.error_description;
78
+ return new SynqError(code, description ?? code, {
79
+ status: error.status,
80
+ description,
81
+ cause: error
82
+ });
83
+ }
84
+ if (error instanceof OperationProcessingError) return new SynqError("invalid_response", error.message, { cause: error });
85
+ if (error instanceof TypeError) return new SynqError("network_error", `Synq couldn't be reached: ${error.message}`, { cause: error });
86
+ return new SynqError("invalid_response", error instanceof Error ? error.message : "Synq answered with something unexpected", { cause: error });
87
+ }
88
+ //#endregion
89
+ //#region src/sign-in-flow.ts
90
+ /** A new flow's state: a PKCE verifier and nonce of its own. */
91
+ function newSignIn(scope, options) {
92
+ return {
93
+ v: 1,
94
+ verifier: oauth.generateRandomCodeVerifier(),
95
+ nonce: oauth.generateRandomNonce(),
96
+ scope,
97
+ ...options.resource ? { resource: options.resource } : {},
98
+ ...options.additionalResources?.length ? { additionalResources: [...options.additionalResources] } : {},
99
+ ...options.acr ? { acr: options.acr } : {},
100
+ step: "start"
101
+ };
102
+ }
103
+ /** A saved flow, checked: one this SDK wrote. */
104
+ function readSavedSignIn(saved) {
105
+ const value = typeof saved === "string" ? JSON.parse(saved) : saved;
106
+ 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");
107
+ return value;
108
+ }
109
+ /** One sign-in on an app's own screens. */
110
+ var SignInFlow = class {
111
+ #port;
112
+ #state;
113
+ constructor(port, state) {
114
+ this.#port = port;
115
+ this.#state = state;
116
+ }
117
+ /** What the app's screen asks for now. */
118
+ get step() {
119
+ return this.#state.step;
120
+ }
121
+ /** The address the sign-in is for, once one was typed. */
122
+ get address() {
123
+ return this.#state.email;
124
+ }
125
+ /** Email and password. */
126
+ password = {
127
+ signIn: (input) => this.#ask(this.#method("password", {
128
+ username: input.email,
129
+ password: input.password
130
+ }), { email: input.email }),
131
+ /** Makes an account where the brand lets people sign up; its address is verified next. */
132
+ signUp: (input) => this.#ask(this.#method("password", {
133
+ username: input.email,
134
+ password: input.password,
135
+ synq_screen: "sign-up"
136
+ }), { email: input.email })
137
+ };
138
+ /** A code by email. */
139
+ email = {
140
+ send: (email) => this.#ask(this.#method("email", { username: email }), { email }),
141
+ verify: (code) => this.#ask({ otp: code }),
142
+ resend: () => this.#ask({ synq_action: "resend" })
143
+ };
144
+ /** A passkey: `options()`, then the browser's assertion to `signIn`. */
145
+ passkey = {
146
+ options: () => this.#ask(this.#method("passkey", {})),
147
+ signIn: (credential, options = {}) => this.#ask({
148
+ synq_passkey: JSON.stringify(credential),
149
+ ...options.related ? { synq_passkey_rp: "related" } : {}
150
+ })
151
+ };
152
+ /** Verifying an address after a sign-in that didn't prove it. */
153
+ verifyEmail = {
154
+ verify: (code) => this.#ask({ otp: code }),
155
+ resend: () => this.#ask({ synq_action: "resend" }),
156
+ skip: () => this.#ask({ synq_action: "skip" })
157
+ };
158
+ /** The flow, to keep between requests (a server's sealed cookie, a phone's secure storage). */
159
+ toJSON() {
160
+ return this.#state;
161
+ }
162
+ /** Fields that name `method`, which a session already under way switches to. */
163
+ #method(method, fields) {
164
+ return {
165
+ synq_method: method,
166
+ ...fields
167
+ };
168
+ }
169
+ async #ask(fields, changes = {}) {
170
+ if (this.#state.step === "done") throw new SynqError("invalid_session", "This sign-in has finished: start another");
171
+ if (changes.email !== void 0) this.#state = {
172
+ ...this.#state,
173
+ email: changes.email
174
+ };
175
+ const answer = await this.#send(fields);
176
+ return this.#read(answer);
177
+ }
178
+ async #send(fields) {
179
+ const port = this.#port;
180
+ const server = await port.server();
181
+ const endpoint = server.authorization_challenge_endpoint;
182
+ if (typeof endpoint !== "string") throw new SynqError("discovery_failed", "The issuer doesn't sign people in on apps' own screens");
183
+ const body = new URLSearchParams(fields);
184
+ const state = this.#state;
185
+ if (state.authSession) body.set("auth_session", state.authSession);
186
+ else {
187
+ body.set("response_type", "code");
188
+ body.set("scope", state.scope);
189
+ body.set("nonce", state.nonce);
190
+ body.set("code_challenge", await oauth.calculatePKCECodeChallenge(state.verifier));
191
+ body.set("code_challenge_method", "S256");
192
+ if (state.resource) body.set("resource", state.resource);
193
+ for (const extra of state.additionalResources ?? []) if (extra !== state.resource) body.append("resource", extra);
194
+ if (state.acr) {
195
+ if (state.acr.essential) body.set("claims", JSON.stringify({ id_token: { acr: {
196
+ essential: true,
197
+ values: [...state.acr.values]
198
+ } } }));
199
+ else body.set("acr_values", state.acr.values.join(" "));
200
+ }
201
+ }
202
+ const headers = new Headers({
203
+ accept: "application/json",
204
+ "content-type": "application/x-www-form-urlencoded",
205
+ ...port.headers
206
+ });
207
+ await port.auth(server, port.client, body, headers);
208
+ let response;
209
+ try {
210
+ response = await port.fetch(endpoint, {
211
+ method: "POST",
212
+ headers,
213
+ body: body.toString(),
214
+ redirect: "manual"
215
+ });
216
+ } catch (error) {
217
+ throw toSynqError(error);
218
+ }
219
+ let parsed;
220
+ try {
221
+ parsed = await response.json();
222
+ } catch {
223
+ parsed = void 0;
224
+ }
225
+ if (!parsed || typeof parsed !== "object") throw new SynqError("invalid_response", `Synq answered ${response.status} with no JSON`, { status: response.status });
226
+ return {
227
+ status: response.status,
228
+ body: parsed,
229
+ retryAfter: retryAfterSeconds(response.headers.get("retry-after"))
230
+ };
231
+ }
232
+ async #read(answer) {
233
+ const { body } = answer;
234
+ const text = (name) => typeof body[name] === "string" ? body[name] : void 0;
235
+ const message = text("error_description") ?? "";
236
+ const problem = text("synq_problem");
237
+ const session = text("auth_session");
238
+ if (session) this.#state = {
239
+ ...this.#state,
240
+ authSession: session
241
+ };
242
+ if (answer.status === 200 && typeof body.authorization_code === "string") {
243
+ this.#state = {
244
+ ...this.#state,
245
+ step: "done"
246
+ };
247
+ return {
248
+ status: "signed-in",
249
+ session: await this.#redeem(body.authorization_code)
250
+ };
251
+ }
252
+ const error = text("error");
253
+ switch (error) {
254
+ case "insufficient_authorization": return this.#next(body, problem, message);
255
+ case "redirect_to_web": {
256
+ this.#state = {
257
+ ...this.#state,
258
+ step: "done"
259
+ };
260
+ const method = text("synq_method");
261
+ const loginHint = text("login_hint") ?? this.#state.email;
262
+ return {
263
+ status: "hosted",
264
+ reason: text("synq_reason"),
265
+ ...method ? { method } : {},
266
+ ...loginHint ? { loginHint } : {},
267
+ continue: () => this.#port.hosted({
268
+ ...method ? { method } : {},
269
+ ...loginHint ? { loginHint } : {}
270
+ })
271
+ };
272
+ }
273
+ case "access_denied":
274
+ this.#state = {
275
+ ...this.#state,
276
+ step: "done"
277
+ };
278
+ return {
279
+ status: "refused",
280
+ reason: text("synq_reason"),
281
+ message
282
+ };
283
+ case "too_many_requests":
284
+ if (session && problem) return {
285
+ status: "retry",
286
+ problem,
287
+ message,
288
+ ...answer.retryAfter === void 0 ? {} : { retryAfter: answer.retryAfter }
289
+ };
290
+ throw new SynqError("too_many_requests", message || "Too many requests", {
291
+ status: answer.status,
292
+ description: message,
293
+ ...answer.retryAfter === void 0 ? {} : { retryAfter: answer.retryAfter }
294
+ });
295
+ default:
296
+ if (error === "invalid_session") this.#state = {
297
+ ...this.#state,
298
+ step: "done"
299
+ };
300
+ throw new SynqError(error ?? `http_${answer.status}`, message || `Synq answered ${answer.status}`, {
301
+ status: answer.status,
302
+ description: message || void 0
303
+ });
304
+ }
305
+ }
306
+ /** What Synq asks for next, or the same step again with what went wrong. */
307
+ #next(body, problem, message) {
308
+ const next = body.synq_next;
309
+ const step = next === "otp" ? "code" : next === "verify_email" ? "verify-email" : next === "method" ? "start" : next;
310
+ this.#state = {
311
+ ...this.#state,
312
+ step
313
+ };
314
+ if (next === "passkey") {
315
+ const related = body.synq_passkey_related_options;
316
+ return {
317
+ status: "passkey",
318
+ options: body.synq_passkey_options,
319
+ ...related ? { related: {
320
+ rpId: related.rp_id,
321
+ options: related.options
322
+ } } : {},
323
+ ...problem ? {
324
+ problem,
325
+ message
326
+ } : {}
327
+ };
328
+ }
329
+ if (problem) return {
330
+ status: "retry",
331
+ problem,
332
+ message
333
+ };
334
+ const email = this.#state.email ?? "";
335
+ if (next === "otp") {
336
+ const seconds = typeof body.synq_code_expires_in === "number" ? body.synq_code_expires_in : 0;
337
+ return {
338
+ status: "code-sent",
339
+ email,
340
+ expiresAt: new Date(Date.now() + seconds * 1e3)
341
+ };
342
+ }
343
+ if (next === "verify_email") return {
344
+ status: "verify-email",
345
+ email,
346
+ canSkip: body.synq_can_skip === true
347
+ };
348
+ return {
349
+ status: "retry",
350
+ problem: "missing",
351
+ message
352
+ };
353
+ }
354
+ /** Redeems the code at the token endpoint, with the verifier and no redirect URI. */
355
+ async #redeem(code) {
356
+ const port = this.#port;
357
+ const server = await port.server();
358
+ if (!server.token_endpoint) throw new SynqError("discovery_failed", "The issuer has no token endpoint");
359
+ const body = new URLSearchParams({
360
+ grant_type: "authorization_code",
361
+ code,
362
+ code_verifier: this.#state.verifier
363
+ });
364
+ if (this.#state.resource) body.set("resource", this.#state.resource);
365
+ const headers = new Headers({
366
+ accept: "application/json",
367
+ "content-type": "application/x-www-form-urlencoded"
368
+ });
369
+ await port.auth(server, port.client, body, headers);
370
+ try {
371
+ const response = await port.fetch(server.token_endpoint, {
372
+ method: "POST",
373
+ headers,
374
+ body: body.toString(),
375
+ redirect: "manual"
376
+ });
377
+ const result = await oauth.processAuthorizationCodeResponse(server, port.client, response, {
378
+ expectedNonce: this.#state.nonce,
379
+ maxAge: oauth.skipAuthTimeCheck,
380
+ requireIdToken: true
381
+ });
382
+ const claims = oauth.getValidatedIdTokenClaims(result);
383
+ const acr = this.#state.acr;
384
+ 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");
385
+ return await port.finish(result, claims);
386
+ } catch (error) {
387
+ throw toSynqError(error);
388
+ }
389
+ }
390
+ };
391
+ //#endregion
392
+ //#region src/urls.ts
393
+ /** Whether a host is this machine: a Synq stack under `localhost`, or a loopback address. */
394
+ function isLoopback(hostname) {
395
+ return hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "127.0.0.1" || hostname === "[::1]";
396
+ }
397
+ /**
398
+ * `value` as a URL, which must be https: Synq's hosts always are. Plain http
399
+ * only on this machine, for a local Synq stack. `what` names it in the error.
400
+ */
401
+ function secureUrl(value, what) {
402
+ let url;
403
+ try {
404
+ url = new URL(value);
405
+ } catch {
406
+ throw new SynqError("invalid_options", `${what} isn't a URL: ${String(value)}`);
407
+ }
408
+ 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')`);
409
+ return url;
410
+ }
411
+ //#endregion
412
+ //#region src/api.ts
413
+ function createApiClient(options) {
414
+ const base = secureUrl(options.baseUrl, "The API base URL").href.replace(/\/+$/, "");
415
+ const call = (method) => ((path, request = {}) => send(method, path, request));
416
+ async function send(method, path, request) {
417
+ const url = new URL(base + fill(path, request.path));
418
+ for (const [name, value] of Object.entries(request.query ?? {})) {
419
+ if (value === void 0) continue;
420
+ for (const item of Array.isArray(value) ? value : [value]) url.searchParams.append(name, String(item));
421
+ }
422
+ const headers = new Headers({
423
+ accept: "application/json, application/problem+json",
424
+ authorization: `Bearer ${await options.credential()}`
425
+ });
426
+ if (request.body !== void 0) headers.set("content-type", "application/json");
427
+ if (request.idempotencyKey) headers.set("idempotency-key", request.idempotencyKey);
428
+ let response;
429
+ try {
430
+ response = await (options.fetch ?? fetch)(url, {
431
+ method: method.toUpperCase(),
432
+ headers,
433
+ body: request.body === void 0 ? void 0 : JSON.stringify(request.body),
434
+ signal: request.signal
435
+ });
436
+ } catch (error) {
437
+ throw new SynqError("network_error", `Synq couldn't be reached: ${String(error)}`, { cause: error });
438
+ }
439
+ const text = await response.text();
440
+ let json;
441
+ try {
442
+ json = text ? JSON.parse(text) : void 0;
443
+ } catch {
444
+ json = void 0;
445
+ }
446
+ if (!response.ok) throw problemError(response.status, json !== null && typeof json === "object" ? json : {}, retryAfterSeconds(response.headers.get("retry-after")));
447
+ return json;
448
+ }
449
+ return {
450
+ get: call("get"),
451
+ post: call("post"),
452
+ put: call("put"),
453
+ patch: call("patch"),
454
+ delete: call("delete")
455
+ };
456
+ }
457
+ /** The path with each `{name}` replaced by its parameter, encoded. */
458
+ function fill(path, params = {}) {
459
+ return path.replace(/\{([^}]+)\}/g, (_, name) => {
460
+ const value = params[name];
461
+ if (value === void 0 || value === "") throw new SynqError("invalid_options", `The path ${path} needs ${name}`);
462
+ if (/^\.+$/.test(String(value))) throw new SynqError("invalid_options", `${name} can't be ${String(value)}`);
463
+ return encodeURIComponent(String(value));
464
+ });
465
+ }
466
+ //#endregion
467
+ export { readSavedSignIn as a, problemError as c, newSignIn as i, toSynqError as l, secureUrl as n, SynqError as o, SignInFlow as r, isSynqError as s, createApiClient as t };