@synqauth/js 0.2.0 → 0.4.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/dist/server.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as SignInFlowStep, M as StartSignInOptions, O as SavedSignIn, c as SynqError, j as SignInStepResult, k as SignInFlow, l as isSynqError, m as IdTokenClaims, r as paths, t as components } from "./management-CWdCiiEv.js";
1
+ import { A as SignInFlowStep, M as StartSignInOptions, O as SavedSignIn, V as LinkedAccount, c as SynqError, j as SignInStepResult, k as SignInFlow, l as isSynqError, m as IdTokenClaims, r as paths, t as components } from "./management-BN4KI1ZH.js";
2
2
  import { JWTPayload, JWTVerifyGetKey } from "jose";
3
3
  //#region src/api.d.ts
4
4
  type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';
@@ -38,7 +38,12 @@ type Success<O> = O extends {
38
38
  };
39
39
  } ? J : never : S extends 204 ? undefined : never; }[keyof R] : never;
40
40
  type Common = {
41
- /** Sent as `Idempotency-Key`: a POST with the same key runs once (the management API keeps the answer 24 hours). */
41
+ /**
42
+ * Sent as `Idempotency-Key`: a POST with the same key runs once (the
43
+ * management API keeps the answer 24 hours). The management client makes
44
+ * one for every POST you don't give one, unless `maxRetries` is 0, and
45
+ * sends the same key on each retry.
46
+ */
42
47
  idempotencyKey?: string;
43
48
  signal?: AbortSignal;
44
49
  };
@@ -60,6 +65,14 @@ type RequestOptions<O> = ([PathParams<O>] extends [never] ? {
60
65
  }) & Common;
61
66
  type Args<O> = object extends RequestOptions<O> ? [options?: RequestOptions<O>] : [options: RequestOptions<O>];
62
67
  type Call<Paths, M extends HttpMethod> = <P extends PathsWith<Paths, M>>(path: P, ...args: Args<Operation<Paths, P, M>>) => Promise<Success<Operation<Paths, P, M>>>;
68
+ /** One item of a list's page: what `paginate` yields. */
69
+ type PageItem<O> = Success<O> extends {
70
+ readonly data: readonly (infer T)[];
71
+ readonly next_cursor: string | null;
72
+ } ? T : never;
73
+ /** The paths of a contract whose GET answers a page (`{ data, next_cursor }`). */
74
+ type PagedPaths<Paths> = { [P in PathsWith<Paths, 'get'>]: [PageItem<Operation<Paths, P, 'get'>>] extends [never] ? never : P; }[PathsWith<Paths, 'get'>] & string;
75
+ type Paginate<Paths> = <P extends PagedPaths<Paths>>(path: P, ...args: Args<Operation<Paths, P, 'get'>>) => AsyncIterable<PageItem<Operation<Paths, P, 'get'>>>;
63
76
  /** A client for one Synq contract: one method per HTTP method, each typed by the contract. */
64
77
  interface ApiClient<Paths> {
65
78
  get: Call<Paths, 'get'>;
@@ -67,6 +80,14 @@ interface ApiClient<Paths> {
67
80
  put: Call<Paths, 'put'>;
68
81
  patch: Call<Paths, 'patch'>;
69
82
  delete: Call<Paths, 'delete'>;
83
+ /**
84
+ * Every item of a list, page by page: `for await (const user of
85
+ * client.paginate('/v1/orgs/{org}/brands/{brand}/users', { path }))`. It
86
+ * asks for the next page (`cursor`, from the last page's `next_cursor`)
87
+ * only when the loop reaches it, so `break` stops asking. `query.limit`
88
+ * is the size of each page.
89
+ */
90
+ paginate: Paginate<Paths>;
70
91
  }
71
92
  //#endregion
72
93
  //#region src/server.d.ts
@@ -112,6 +133,12 @@ export interface AccessTokenClaims {
112
133
  readonly type?: string;
113
134
  readonly client_id?: string;
114
135
  } | undefined;
136
+ /** The person's email, when your API asks for it (`identity_claims`) and they have one. */
137
+ readonly email: string | undefined;
138
+ /** Whether Synq verified it, when your API asks for it. */
139
+ readonly email_verified: boolean | undefined;
140
+ /** Their accounts at upstream providers (GitHub, Google…), when your API asks for them. */
141
+ readonly linked_accounts: readonly LinkedAccount[] | undefined;
115
142
  /** Every claim, as the token carries it. */
116
143
  readonly payload: JWTPayload;
117
144
  }
@@ -169,6 +196,12 @@ export interface ApiKeyClaims {
169
196
  readonly iat: number;
170
197
  /** When it stops working, in seconds; undefined for a key that doesn't expire. */
171
198
  readonly exp: number | undefined;
199
+ /** The person's email, when your API asks for it (`identity_claims`) and they have one. */
200
+ readonly email: string | undefined;
201
+ /** Whether Synq verified it, when your API asks for it. */
202
+ readonly email_verified: boolean | undefined;
203
+ /** Their accounts at upstream providers (GitHub, Google…), when your API asks for them. */
204
+ readonly linked_accounts: readonly LinkedAccount[] | undefined;
172
205
  }
173
206
  /**
174
207
  * Checks one of your users' API keys, as `createApiKeyVerifier` makes it:
@@ -217,13 +250,35 @@ export interface ManagementClientOptions {
217
250
  /** Or a Synq access token, acting as that person: a function so it can be refreshed. */
218
251
  accessToken?: () => string | Promise<string>;
219
252
  fetch?: typeof fetch;
253
+ /**
254
+ * How many times a call is tried again when Synq's answer says it may
255
+ * work later: 2 by default, 0 for never (and then a POST carries only
256
+ * the `idempotencyKey` you give it). Every method retries a 429, a
257
+ * 503 and `idempotency_key_in_flight`; a GET, PUT, PATCH or POST (with
258
+ * its key) also retries a 502, a 504 and a dropped connection; a GET, PUT
259
+ * or PATCH a 500. A DELETE retries only refusals, since a second try
260
+ * could answer 404 for a delete that worked. Each try waits the
261
+ * `Retry-After` Synq names, up to 60 seconds (a longer one is thrown at
262
+ * once, with `retryAfter`), or else backs off from half a second, and an
263
+ * aborted `signal` stops the waiting.
264
+ */
265
+ maxRetries?: number;
220
266
  }
267
+ /** How many times the management client tries a call again by default. */
268
+ export declare const DEFAULT_MAX_RETRIES = 2;
221
269
  /** The management API's typed client: every path, parameter, body and answer from its contract. */
222
270
  export type ManagementClient = ApiClient<paths>;
223
271
  /**
224
272
  * A client for Synq's management API (`/v1`), typed by its contract. Server
225
273
  * only: an API key never reaches a browser. Failures throw a `SynqError`
226
274
  * with the problem's `code`, such as `insufficient_permissions`.
275
+ *
276
+ * Every POST carries an `Idempotency-Key` (yours, or a new one unless
277
+ * `maxRetries` is 0), the same on each try, so a retry never makes two of
278
+ * anything. An answer that holds a secret or a link only its holder may use
279
+ * isn't kept with the key: a retry of it is `conflict`. A call is tried
280
+ * again, up to `maxRetries` times, when Synq's answer says it may work
281
+ * later, and `paginate` walks a list's pages with `for await`.
227
282
  */
228
283
  export declare function createManagementClient(options: ManagementClientOptions): ManagementClient;
229
284
  /** What a server needs to sign people in on its app's own screens (AERO-1411). */
@@ -278,4 +333,4 @@ export interface OwnUiSignIn {
278
333
  */
279
334
  export declare function createOwnUiSignIn(options: OwnUiSignInOptions): OwnUiSignIn;
280
335
  //#endregion
281
- export { type components as ManagementComponents, type paths as ManagementPaths, type SavedSignIn, SignInFlow, type SignInFlowStep, type SignInStepResult, type StartSignInOptions, SynqError, isSynqError };
336
+ export { type LinkedAccount, type components as ManagementComponents, type paths as ManagementPaths, type SavedSignIn, SignInFlow, type SignInFlowStep, type SignInStepResult, type StartSignInOptions, SynqError, isSynqError };
package/dist/server.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as readSavedSignIn, i as newSignIn, n as secureUrl, o as SynqError, r as SignInFlow, s as isSynqError, t as createApiClient } from "./api-CeYAjkvX.js";
1
+ import { a as readSavedSignIn, c as SynqError, i as newSignIn, l as isSynqError, n as secureUrl, o as linkedAccountsOf, r as SignInFlow, t as createApiClient } from "./api-D2jDzTRO.js";
2
2
  import * as oauth from "oauth4webapi";
3
3
  import { createRemoteJWKSet, customFetch, errors, jwtVerify } from "jose";
4
4
  //#region src/server.ts
@@ -105,6 +105,9 @@ function accessTokenClaims(payload) {
105
105
  acr: string(payload.acr),
106
106
  amr,
107
107
  act,
108
+ email: string(payload.email),
109
+ email_verified: typeof payload.email_verified === "boolean" ? payload.email_verified : void 0,
110
+ linked_accounts: linkedAccountsOf(payload.linked_accounts),
108
111
  payload
109
112
  };
110
113
  }
@@ -183,7 +186,10 @@ function createApiKeyVerifier(options) {
183
186
  keyId: string(body.key_id),
184
187
  name: string(body.name),
185
188
  iat: typeof body.iat === "number" ? body.iat : 0,
186
- exp: typeof body.exp === "number" ? body.exp : void 0
189
+ exp: typeof body.exp === "number" ? body.exp : void 0,
190
+ email: typeof body.email === "string" ? body.email : void 0,
191
+ email_verified: typeof body.email_verified === "boolean" ? body.email_verified : void 0,
192
+ linked_accounts: linkedAccountsOf(body.linked_accounts)
187
193
  };
188
194
  if (claims.iss !== issuer) throw new SynqError("invalid_response", "Synq's answer names another issuer", { status: 502 });
189
195
  const missing = (verify.scopes ?? []).filter((scope) => !claims.scopes.includes(scope));
@@ -248,10 +254,19 @@ function fromBase64(value) {
248
254
  return;
249
255
  }
250
256
  }
257
+ /** How many times the management client tries a call again by default. */
258
+ const DEFAULT_MAX_RETRIES = 2;
251
259
  /**
252
260
  * A client for Synq's management API (`/v1`), typed by its contract. Server
253
261
  * only: an API key never reaches a browser. Failures throw a `SynqError`
254
262
  * with the problem's `code`, such as `insufficient_permissions`.
263
+ *
264
+ * Every POST carries an `Idempotency-Key` (yours, or a new one unless
265
+ * `maxRetries` is 0), the same on each try, so a retry never makes two of
266
+ * anything. An answer that holds a secret or a link only its holder may use
267
+ * isn't kept with the key: a retry of it is `conflict`. A call is tried
268
+ * again, up to `maxRetries` times, when Synq's answer says it may work
269
+ * later, and `paginate` walks a list's pages with `for await`.
255
270
  */
256
271
  function createManagementClient(options) {
257
272
  const { apiKey, accessToken } = options;
@@ -259,7 +274,9 @@ function createManagementClient(options) {
259
274
  return createApiClient({
260
275
  baseUrl: options.baseUrl,
261
276
  credential: apiKey ? () => apiKey : accessToken,
262
- fetch: options.fetch
277
+ fetch: options.fetch,
278
+ maxRetries: options.maxRetries ?? 2,
279
+ idempotencyKeys: true
263
280
  });
264
281
  }
265
282
  /**
@@ -314,4 +331,4 @@ function createOwnUiSignIn(options) {
314
331
  };
315
332
  }
316
333
  //#endregion
317
- export { SignInFlow, SynqError, createAccessTokenVerifier, createApiKeyVerifier, createManagementClient, createOwnUiSignIn, isApiKey, isSynqError, verifyWebhook };
334
+ export { DEFAULT_MAX_RETRIES, SignInFlow, SynqError, createAccessTokenVerifier, createApiKeyVerifier, createManagementClient, createOwnUiSignIn, isApiKey, isSynqError, verifyWebhook };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@synqauth/js",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Synq's framework-agnostic client: sign-in and sessions in the browser, the account API, and token and webhook verification on your server.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,467 +0,0 @@
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 };