@smplcty/auth 11.0.0 → 12.0.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.
Files changed (42) hide show
  1. package/README.md +49 -4
  2. package/dist/http/handlers.d.ts.map +1 -1
  3. package/dist/http/handlers.js +69 -23
  4. package/dist/http/handlers.js.map +1 -1
  5. package/dist/http/index.d.ts +1 -1
  6. package/dist/http/index.d.ts.map +1 -1
  7. package/dist/http/types.d.ts +43 -3
  8. package/dist/http/types.d.ts.map +1 -1
  9. package/dist/index.d.ts +2 -2
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +1 -1
  12. package/dist/index.js.map +1 -1
  13. package/dist/methods/email-code/index.d.ts +44 -0
  14. package/dist/methods/email-code/index.d.ts.map +1 -0
  15. package/dist/methods/email-code/index.js +153 -0
  16. package/dist/methods/email-code/index.js.map +1 -0
  17. package/dist/methods/errors.d.ts +12 -0
  18. package/dist/methods/errors.d.ts.map +1 -1
  19. package/dist/methods/errors.js +15 -0
  20. package/dist/methods/errors.js.map +1 -1
  21. package/dist/methods/oidc/credentials.d.ts +76 -0
  22. package/dist/methods/oidc/credentials.d.ts.map +1 -0
  23. package/dist/methods/oidc/credentials.js +164 -0
  24. package/dist/methods/oidc/credentials.js.map +1 -0
  25. package/dist/methods/oidc/index.d.ts +26 -8
  26. package/dist/methods/oidc/index.d.ts.map +1 -1
  27. package/dist/methods/oidc/index.js +45 -2
  28. package/dist/methods/oidc/index.js.map +1 -1
  29. package/dist/methods/router.d.ts +3 -1
  30. package/dist/methods/router.d.ts.map +1 -1
  31. package/dist/methods/router.js +22 -5
  32. package/dist/methods/router.js.map +1 -1
  33. package/dist/methods/twilio/index.d.ts.map +1 -1
  34. package/dist/methods/twilio/index.js +5 -0
  35. package/dist/methods/twilio/index.js.map +1 -1
  36. package/dist/methods/types.d.ts +19 -3
  37. package/dist/methods/types.d.ts.map +1 -1
  38. package/package.json +31 -17
  39. package/schema/tables/auth_domain_credentials.yaml +86 -0
  40. package/schema/tables/auth_domains.yaml +8 -6
  41. package/schema/tables/email_sign_in_codes.yaml +39 -0
  42. package/schema/tables/tenant_email_domains.yaml +9 -5
@@ -0,0 +1,153 @@
1
+ import { createHmac, randomInt, timingSafeEqual } from 'node:crypto';
2
+ import { InvalidInputError } from '../../errors.js';
3
+ import { findUserByCommunicationMethod } from '../../find-user-by-communication-method.js';
4
+ import { isDevOtpEnrolled, verifyDevOtp } from '../../dev-otp.js';
5
+ import { VerificationFailedError } from '../errors.js';
6
+ /** How long an emailed code stays valid. */
7
+ export const EMAIL_CODE_TTL_MINUTES = 10;
8
+ /** Wrong guesses a code survives; the next guess fails even if it is right. */
9
+ export const EMAIL_CODE_MAX_FAILED_ATTEMPTS = 5;
10
+ /** Codes sent to one address per {@link EMAIL_CODE_TTL_MINUTES}; further requests send nothing. */
11
+ export const EMAIL_CODE_MAX_SENDS = 5;
12
+ const MIN_SECRET_BYTES = 32;
13
+ // Issues a code only while the address is under the send limit, retiring the
14
+ // previous live code in the same statement so a refused send keeps it alive.
15
+ const ISSUE_CODE = `
16
+ WITH allowed AS (
17
+ SELECT count(*) < $4 AS ok
18
+ FROM email_sign_in_codes
19
+ WHERE user_communication_method_id = $1
20
+ AND created_at > now() - make_interval(mins => $3)
21
+ ),
22
+ superseded AS (
23
+ UPDATE email_sign_in_codes
24
+ SET superseded_at = now()
25
+ WHERE user_communication_method_id = $1
26
+ AND used_at IS NULL
27
+ AND superseded_at IS NULL
28
+ AND (SELECT ok FROM allowed)
29
+ )
30
+ INSERT INTO email_sign_in_codes (user_communication_method_id, code_hash, expires_at)
31
+ SELECT $1, $2, now() + make_interval(mins => $3)
32
+ WHERE (SELECT ok FROM allowed)
33
+ RETURNING email_sign_in_code_id
34
+ `;
35
+ const LIVE_CODE = `
36
+ WHERE user_communication_method_id = $1
37
+ AND used_at IS NULL
38
+ AND superseded_at IS NULL
39
+ AND expires_at > now()
40
+ AND failed_attempts < $2
41
+ `;
42
+ const SELECT_LIVE_CODE = `
43
+ SELECT email_sign_in_code_id AS "id", code_hash AS "codeHash"
44
+ FROM email_sign_in_codes
45
+ ${LIVE_CODE}
46
+ ORDER BY created_at DESC
47
+ LIMIT 1
48
+ `;
49
+ // Re-checks liveness so two concurrent correct guesses cannot both use the code.
50
+ const USE_CODE = `
51
+ UPDATE email_sign_in_codes
52
+ SET used_at = now()
53
+ ${LIVE_CODE}
54
+ AND email_sign_in_code_id = $3
55
+ RETURNING email_sign_in_code_id
56
+ `;
57
+ const RECORD_FAILED_ATTEMPT = `
58
+ UPDATE email_sign_in_codes
59
+ SET failed_attempts = failed_attempts + 1
60
+ WHERE email_sign_in_code_id = $1
61
+ `;
62
+ function requireIdentifier(identifier) {
63
+ if (typeof identifier !== 'string' || identifier.length === 0) {
64
+ throw new InvalidInputError('the email code handler requires a non-empty identifier');
65
+ }
66
+ return identifier;
67
+ }
68
+ async function findUser(db, identifier) {
69
+ return findUserByCommunicationMethod(db, { channel: 'email', code: identifier });
70
+ }
71
+ /**
72
+ * The user-bound emailed-code method handler (subpath `@smplcty/auth/email-code`).
73
+ * The library issues, stores and checks the code; the app delivers it through
74
+ * `sendCode`, so auth depends on no mail provider.
75
+ *
76
+ * A code is six random digits, valid for {@link EMAIL_CODE_TTL_MINUTES} minutes,
77
+ * single-use, and dead after {@link EMAIL_CODE_MAX_FAILED_ATTEMPTS} wrong guesses.
78
+ * Sending a new code retires the previous one. At most
79
+ * {@link EMAIL_CODE_MAX_SENDS} are sent to an address per
80
+ * {@link EMAIL_CODE_TTL_MINUTES} minutes. Only an HMAC of each code is stored,
81
+ * in `email_sign_in_codes`, and rows are never deleted.
82
+ *
83
+ * Like the Twilio handler it never provisions, reports `otpSent` for an unknown
84
+ * address or a refused send without sending, and accepts a dev-OTP code first.
85
+ *
86
+ * ```ts
87
+ * import { emailCodeHandler } from '@smplcty/auth/email-code';
88
+ *
89
+ * const handler = emailCodeHandler({
90
+ * codeSecret: process.env.EMAIL_CODE_SECRET!,
91
+ * sendCode: ({ to, code }) => sendSignInEmail(to, code),
92
+ * });
93
+ * ```
94
+ */
95
+ export function emailCodeHandler(options) {
96
+ const { codeSecret, sendCode } = options;
97
+ if (Buffer.byteLength(codeSecret) < MIN_SECRET_BYTES) {
98
+ throw new InvalidInputError(`codeSecret must be at least ${MIN_SECRET_BYTES} bytes`);
99
+ }
100
+ const hashCode = (userCommunicationMethodId, code) => createHmac('sha256', codeSecret).update(`${userCommunicationMethodId}:${code}`).digest();
101
+ return {
102
+ async resolveUser(ctx) {
103
+ return findUser(ctx.db, requireIdentifier(ctx.identifier));
104
+ },
105
+ async initiate(ctx) {
106
+ const identifier = requireIdentifier(ctx.identifier);
107
+ const user = await findUser(ctx.db, identifier);
108
+ if (!user || (await isDevOtpEnrolled(ctx.db, user.userCommunicationMethodId))) {
109
+ return { otpSent: true };
110
+ }
111
+ const code = String(randomInt(0, 1_000_000)).padStart(6, '0');
112
+ const { rowCount } = await ctx.db.query(ISSUE_CODE, [
113
+ user.userCommunicationMethodId,
114
+ hashCode(user.userCommunicationMethodId, code).toString('hex'),
115
+ EMAIL_CODE_TTL_MINUTES,
116
+ EMAIL_CODE_MAX_SENDS,
117
+ ]);
118
+ if (rowCount) {
119
+ await sendCode({ to: identifier, code });
120
+ }
121
+ return { otpSent: true };
122
+ },
123
+ async complete(ctx) {
124
+ const identifier = requireIdentifier(ctx.identifier);
125
+ const user = await findUser(ctx.db, identifier);
126
+ if (!user) {
127
+ throw new VerificationFailedError();
128
+ }
129
+ const ucmId = user.userCommunicationMethodId;
130
+ if (await verifyDevOtp(ctx.db, ucmId, ctx.credential)) {
131
+ return user;
132
+ }
133
+ const { rows } = await ctx.db.query(SELECT_LIVE_CODE, [
134
+ ucmId,
135
+ EMAIL_CODE_MAX_FAILED_ATTEMPTS,
136
+ ]);
137
+ const live = rows[0];
138
+ if (!live) {
139
+ throw new VerificationFailedError();
140
+ }
141
+ if (!timingSafeEqual(Buffer.from(live.codeHash, 'hex'), hashCode(ucmId, ctx.credential))) {
142
+ await ctx.db.query(RECORD_FAILED_ATTEMPT, [live.id]);
143
+ throw new VerificationFailedError();
144
+ }
145
+ const { rowCount } = await ctx.db.query(USE_CODE, [ucmId, EMAIL_CODE_MAX_FAILED_ATTEMPTS, live.id]);
146
+ if (!rowCount) {
147
+ throw new VerificationFailedError();
148
+ }
149
+ return user;
150
+ },
151
+ };
152
+ }
153
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/methods/email-code/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACrE,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,6BAA6B,EAAE,MAAM,4CAA4C,CAAC;AAC3F,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAUvD,4CAA4C;AAC5C,MAAM,CAAC,MAAM,sBAAsB,GAAG,EAAE,CAAC;AACzC,+EAA+E;AAC/E,MAAM,CAAC,MAAM,8BAA8B,GAAG,CAAC,CAAC;AAChD,mGAAmG;AACnG,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAEtC,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAe5B,6EAA6E;AAC7E,6EAA6E;AAC7E,MAAM,UAAU,GAAG;;;;;;;;;;;;;;;;;;;CAmBlB,CAAC;AAEF,MAAM,SAAS,GAAG;;;;;;CAMjB,CAAC;AAEF,MAAM,gBAAgB,GAAG;;;IAGrB,SAAS;;;CAGZ,CAAC;AAEF,iFAAiF;AACjF,MAAM,QAAQ,GAAG;;;IAGb,SAAS;;;CAGZ,CAAC;AAEF,MAAM,qBAAqB,GAAG;;;;CAI7B,CAAC;AAEF,SAAS,iBAAiB,CAAC,UAA8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G,CAAC,EAAE,CAAC,KAAK,CAAmC,gBAAgB,EAAE;gBACtF,KAAK;gBACL,8BAA8B;aAC/B,CAAC,CAAC;YACH,MAAM,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;YACrB,IAAI,CAAC,IAAI,EAAE,CAAC;gBACV,MAAM,IAAI,uBAAuB,EAAE,CAAC;YACtC,CAAC;YACD,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,QAAQ,CAAC,KAAK,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC;gBACzF,MAAM,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,qBAAqB,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;gBACrD,MAAM,IAAI,uBAAuB,EAAE,CAAC;YACtC,CAAC;YACD,MAAM,EAAE,QAAQ,EAAE,GAAG,MAAM,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,8BAA8B,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;YACpG,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACd,MAAM,IAAI,uBAAuB,EAAE,CAAC;YACtC,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -42,4 +42,16 @@ export declare class SsoRequiredError extends AuthError {
42
42
  readonly domain: string;
43
43
  constructor(domain: string, message?: string);
44
44
  }
45
+ /**
46
+ * Thrown by an app's sign-in hook to refuse a sign-in, e.g. a verified user
47
+ * with no live role in an active workspace. The message is the app's and is
48
+ * what the person sees. `code` defaults to `SIGN_IN_REFUSED`; on an OIDC
49
+ * sign-in with `signInErrorPath`, only the code reaches the page, so pass your
50
+ * own code when the page needs to tell refusals apart.
51
+ */
52
+ export declare class SignInRefusedError extends AuthError {
53
+ readonly name = "SignInRefusedError";
54
+ readonly code: string;
55
+ constructor(message: string, code?: string);
56
+ }
45
57
  //# sourceMappingURL=errors.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/methods/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,SAAS;IAC/C,SAAkB,IAAI,wBAAwB;IAC9C,SAAkB,IAAI,EAAG,iBAAiB,CAAU;IAEpD,YAAY,OAAO,GAAE,MAAqC,EAEzD;CACF;AAED;;;;GAIG;AACH,qBAAa,uBAAwB,SAAQ,SAAS;IACpD,SAAkB,IAAI,6BAA6B;IACnD,SAAkB,IAAI,EAAG,qBAAqB,CAAU;IAExD,YAAY,OAAO,GAAE,MAA8B,EAElD;CACF;AAED;;;;;GAKG;AACH,qBAAa,2BAA4B,SAAQ,SAAS;IACxD,SAAkB,IAAI,iCAAiC;IACvD,SAAkB,IAAI,EAAG,2BAA2B,CAAU;IAC9D,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAExB,YAAY,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,EAI7D;CACF;AAED;;;;GAIG;AACH,qBAAa,gBAAiB,SAAQ,SAAS;IAC7C,SAAkB,IAAI,sBAAsB;IAC5C,SAAkB,IAAI,EAAG,cAAc,CAAU;IACjD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAExB,YAAY,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,EAG3C;CACF"}
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/methods/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,SAAS;IAC/C,SAAkB,IAAI,wBAAwB;IAC9C,SAAkB,IAAI,EAAG,iBAAiB,CAAU;IAEpD,YAAY,OAAO,GAAE,MAAqC,EAEzD;CACF;AAED;;;;GAIG;AACH,qBAAa,uBAAwB,SAAQ,SAAS;IACpD,SAAkB,IAAI,6BAA6B;IACnD,SAAkB,IAAI,EAAG,qBAAqB,CAAU;IAExD,YAAY,OAAO,GAAE,MAA8B,EAElD;CACF;AAED;;;;;GAKG;AACH,qBAAa,2BAA4B,SAAQ,SAAS;IACxD,SAAkB,IAAI,iCAAiC;IACvD,SAAkB,IAAI,EAAG,2BAA2B,CAAU;IAC9D,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAExB,YAAY,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,EAI7D;CACF;AAED;;;;GAIG;AACH,qBAAa,gBAAiB,SAAQ,SAAS;IAC7C,SAAkB,IAAI,sBAAsB;IAC5C,SAAkB,IAAI,EAAG,cAAc,CAAU;IACjD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAExB,YAAY,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,EAG3C;CACF;AAED;;;;;;GAMG;AACH,qBAAa,kBAAmB,SAAQ,SAAS;IAC/C,SAAkB,IAAI,wBAAwB;IAC9C,SAAkB,IAAI,EAAE,MAAM,CAAC;IAE/B,YAAY,OAAO,EAAE,MAAM,EAAE,IAAI,GAAE,MAA0B,EAG5D;CACF"}
@@ -53,4 +53,19 @@ export class SsoRequiredError extends AuthError {
53
53
  this.domain = domain;
54
54
  }
55
55
  }
56
+ /**
57
+ * Thrown by an app's sign-in hook to refuse a sign-in, e.g. a verified user
58
+ * with no live role in an active workspace. The message is the app's and is
59
+ * what the person sees. `code` defaults to `SIGN_IN_REFUSED`; on an OIDC
60
+ * sign-in with `signInErrorPath`, only the code reaches the page, so pass your
61
+ * own code when the page needs to tell refusals apart.
62
+ */
63
+ export class SignInRefusedError extends AuthError {
64
+ name = 'SignInRefusedError';
65
+ code;
66
+ constructor(message, code = 'SIGN_IN_REFUSED') {
67
+ super(message);
68
+ this.code = code;
69
+ }
70
+ }
56
71
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/methods/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;GAGG;AACH,MAAM,OAAO,kBAAmB,SAAQ,SAAS;IAC7B,IAAI,GAAG,oBAAoB,CAAC;IAC5B,IAAI,GAAG,iBAA0B,CAAC;IAEpD,YAAY,OAAO,GAAW,4BAA4B;QACxD,KAAK,CAAC,OAAO,CAAC,CAAC;IACjB,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,OAAO,uBAAwB,SAAQ,SAAS;IAClC,IAAI,GAAG,yBAAyB,CAAC;IACjC,IAAI,GAAG,qBAA8B,CAAC;IAExD,YAAY,OAAO,GAAW,qBAAqB;QACjD,KAAK,CAAC,OAAO,CAAC,CAAC;IACjB,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,OAAO,2BAA4B,SAAQ,SAAS;IACtC,IAAI,GAAG,6BAA6B,CAAC;IACrC,IAAI,GAAG,2BAAoC,CAAC;IACrD,QAAQ,CAAS;IACjB,MAAM,CAAS;IAExB,YAAY,QAAgB,EAAE,MAAc,EAAE,OAAgB;QAC5D,KAAK,CAAC,OAAO,IAAI,UAAU,QAAQ,sCAAsC,MAAM,EAAE,CAAC,CAAC;QACnF,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,OAAO,gBAAiB,SAAQ,SAAS;IAC3B,IAAI,GAAG,kBAAkB,CAAC;IAC1B,IAAI,GAAG,cAAuB,C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YAAY,MAAc,EAAE,OAAgB;QAC1C,KAAK,CAAC,OAAO,IAAI,eAAe,MAAM,yBAAyB,CAAC,CAAC;QACjE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF;AAED;;;;;;GAMG;AACH,MAAM,OAAO,kBAAmB,SAAQ,SAAS;IAC7B,IAAI,GAAG,oBAAoB,CAAC;IAC5B,IAAI,CAAS;IAE/B,YAAY,OAAe,EAAE,IAAI,GAAW,iBAAiB;QAC3D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;CACF"}
@@ -0,0 +1,76 @@
1
+ import { webcrypto } from 'node:crypto';
2
+ import type { Queryable } from '../../types.js';
3
+ /** What a stored credential is, passed to the cipher with every call. */
4
+ export interface CredentialContext {
5
+ authDomainId: number;
6
+ purpose: 'client_secret' | 'private_key';
7
+ }
8
+ /**
9
+ * Encrypts and decrypts a stored client credential. The app supplies it, for
10
+ * example with an AWS KMS data key, so the library picks no key-management
11
+ * vendor and the database never holds plaintext. Use the context to bind each
12
+ * ciphertext to its row (a KMS encryption context, say), so a ciphertext copied
13
+ * to another auth domain won't decrypt.
14
+ */
15
+ export interface CredentialCipher {
16
+ encrypt(plaintext: string, context: CredentialContext): Promise<string>;
17
+ decrypt(ciphertext: string, context: CredentialContext): Promise<string>;
18
+ }
19
+ /** The public half of an auth domain's generated key, to give its IdP. */
20
+ export interface ClientPublicKey {
21
+ /** A JWKS with the one key, carrying `kid`, `x5c` and `x5t#S256`. */
22
+ jwks: {
23
+ keys: webcrypto.JsonWebKey[];
24
+ };
25
+ /** A self-signed X.509 certificate (PEM), for IdPs that take a certificate, such as Entra. */
26
+ certificatePem: string;
27
+ }
28
+ /** What an admin can see about an auth domain's credential: never the secret or private key. */
29
+ export interface ClientCredentialStatus {
30
+ secretSetAt: Date | null;
31
+ privateKeySetAt: Date | null;
32
+ /** The public key, when one has been generated. */
33
+ publicKey: ClientPublicKey | null;
34
+ }
35
+ /**
36
+ * Set or replace an auth domain's client secret, encrypted through `cipher`.
37
+ * Run it on the admin's session client (e.g. inside `withSession`): only the
38
+ * tenant's security or settings admin may. It takes effect on the next sign-in.
39
+ */
40
+ export declare function setClientSecret(db: Queryable, input: {
41
+ authDomainId: number;
42
+ secret: string;
43
+ cipher: CredentialCipher;
44
+ }): Promise<void>;
45
+ /**
46
+ * Generate (or replace) an auth domain's RSA key pair for `private_key_jwt`.
47
+ * The private key is stored encrypted through `cipher`; the public half comes
48
+ * back, and stays readable through {@link getClientCredentialStatus}, for the
49
+ * admin to upload to their IdP. Run it on the admin's session client.
50
+ *
51
+ * Needs the optional peers `@peculiar/x509` and `reflect-metadata` (for the
52
+ * certificate), loaded only here, so apps that never generate a key needn't
53
+ * install them.
54
+ */
55
+ export declare function generateClientKey(db: Queryable, input: {
56
+ authDomainId: number;
57
+ cipher: CredentialCipher;
58
+ subject?: string;
59
+ validityDays?: number;
60
+ }): Promise<ClientPublicKey>;
61
+ /**
62
+ * Whether an auth domain has a secret and a key, when each was last set, and
63
+ * the public key. Never the secret or private key. Run it on the admin's
64
+ * session client; returns null for an auth domain they can't see or that has
65
+ * no credential.
66
+ */
67
+ export declare function getClientCredentialStatus(db: Queryable, authDomainId: number): Promise<ClientCredentialStatus | null>;
68
+ /** The decrypted client secret, read fresh for this exchange; undefined when none is stored. */
69
+ export declare function loadClientSecret(db: Queryable, authDomainId: number, cipher: CredentialCipher | undefined): Promise<string | undefined>;
70
+ /** The private key and its certificate thumbprints, read fresh for this exchange; undefined when none is stored. */
71
+ export declare function loadClientKey(db: Queryable, authDomainId: number, cipher: CredentialCipher | undefined): Promise<{
72
+ key: CryptoKey;
73
+ x5tS256: string;
74
+ x5t: string;
75
+ } | undefined>;
76
+ //# sourceMappingURL=credentials.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.d.ts","sourceRoot":"","sources":["../../../src/methods/oidc/credentials.ts"],"names":[],"mappings":"AAA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AC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAA;CAAE,GACjG,OAAO,CAAC,eAAe,CAAC,CA0C1B;AAED;;;;;GAKG;AACH,wBAAsB,yBAAyB,CAC7C,EAAE,EAAE,SAAS,EACb,YAAY,EAAE,MAAM,GACnB,OAAO,CAAC,sBAAsB,GAAG,IAAI,CAAC,CAoBxC;AA6CD,gGAAgG;AAChG,wBAAsB,gBAAgB,CACpC,EAAE,EAAE,SAAS,EACb,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,gBAAgB,GAAG,SAAS,GACnC,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAI7B;AAED,oHAAoH;AACpH,wBAAsB,aAAa,CACjC,EAAE,EAAE,SAAS,EACb,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,gBAAgB,GAAG,SAAS,GACnC,OAAO,CAAC;IAAE,GAAG,EAAE,SAAS,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAAC,CAWvE"}
@@ -0,0 +1,164 @@
1
+ import { createHash, webcrypto } from 'node:crypto';
2
+ import { InvalidInputError } from '../../errors.js';
3
+ const RSA = {
4
+ name: 'RSASSA-PKCS1-v1_5',
5
+ hash: 'SHA-256',
6
+ modulusLength: 2048,
7
+ publicExponent: new Uint8Array([1, 0, 1]),
8
+ };
9
+ // Admin writes run on the admin's session client, as app_rls, so RLS admits
10
+ // only the tenant's security or settings admin. app_rls can write these columns
11
+ // but not read the ciphertext back. Update-then-insert, since ON CONFLICT DO
12
+ // UPDATE would need SELECT on the excluded ciphertext columns.
13
+ async function writeCredential(db, authDomainId, set) {
14
+ const cols = Object.keys(set);
15
+ const values = Object.values(set);
16
+ const update = await db.query(`UPDATE auth_domain_credentials SET ${cols.map((c, i) => `${c} = $${i + 2}`).join(', ')}
17
+ WHERE auth_domain_id = $1`, [authDomainId, ...values]);
18
+ if (update.rowCount)
19
+ return;
20
+ try {
21
+ const insert = await db.query(`INSERT INTO auth_domain_credentials (auth_domain_id, ${cols.join(', ')})
22
+ SELECT $1, ${cols.map((_, i) => `$${i + 2}`).join(', ')}
23
+ WHERE NOT EXISTS (SELECT 1 FROM auth_domain_credentials WHERE auth_domain_id = $1)
24
+ ON CONFLICT DO NOTHING`, [authDomainId, ...values]);
25
+ if (insert.rowCount)
26
+ return;
27
+ }
28
+ catch (err) {
29
+ // An RLS refusal: not a live auth domain this admin may configure.
30
+ if (err.code !== '42501')
31
+ throw err;
32
+ }
33
+ throw new InvalidInputError(`auth domain ${authDomainId} is not a live auth domain you may configure`);
34
+ }
35
+ /**
36
+ * Set or replace an auth domain's client secret, encrypted through `cipher`.
37
+ * Run it on the admin's session client (e.g. inside `withSession`): only the
38
+ * tenant's security or settings admin may. It takes effect on the next sign-in.
39
+ */
40
+ export async function setClientSecret(db, input) {
41
+ const { authDomainId, secret, cipher } = input;
42
+ if (typeof secret !== 'string' || secret.length === 0)
43
+ throw new InvalidInputError('secret must be a non-empty string');
44
+ const ciphertext = await cipher.encrypt(secret, { authDomainId, purpose: 'client_secret' });
45
+ await writeCredential(db, authDomainId, { secret_ciphertext: ciphertext, secret_set_at: new Date() });
46
+ }
47
+ /**
48
+ * Generate (or replace) an auth domain's RSA key pair for `private_key_jwt`.
49
+ * The private key is stored encrypted through `cipher`; the public half comes
50
+ * back, and stays readable through {@link getClientCredentialStatus}, for the
51
+ * admin to upload to their IdP. Run it on the admin's session client.
52
+ *
53
+ * Needs the optional peers `@peculiar/x509` and `reflect-metadata` (for the
54
+ * certificate), loaded only here, so apps that never generate a key needn't
55
+ * install them.
56
+ */
57
+ export async function generateClientKey(db, input) {
58
+ const { authDomainId, cipher } = input;
59
+ const validityDays = input.validityDays ?? 730;
60
+ await import('reflect-metadata');
61
+ const x509 = await import('@peculiar/x509');
62
+ x509.cryptoProvider.set(webcrypto);
63
+ const keys = await webcrypto.subtle.generateKey(RSA, true, ['sign', 'verify']);
64
+ const notBefore = new Date();
65
+ const cert = await x509.X509CertificateGenerator.createSelfSigned({
66
+ serialNumber: Buffer.from(webcrypto.getRandomValues(new Uint8Array(16)))
67
+ .toString('hex')
68
+ .replace(/^[89a-f]/, '1'),
69
+ name: `CN=${input.subject ?? `auth-domain-${authDomainId}`}`,
70
+ notBefore,
71
+ notAfter: new Date(notBefore.getTime() + validityDays * 86_400_000),
72
+ keys: keys,
73
+ signingAlgorithm: RSA,
74
+ });
75
+ const der = Buffer.from(cert.rawData);
76
+ const thumbprint = createHash('sha256').update(der).digest('base64url');
77
+ const jwk = {
78
+ ...(await webcrypto.subtle.exportKey('jwk', keys.publicKey)),
79
+ kid: thumbprint,
80
+ alg: 'RS256',
81
+ use: 'sig',
82
+ x5c: [der.toString('base64')],
83
+ 'x5t#S256': thumbprint,
84
+ };
85
+ delete jwk.key_ops;
86
+ delete jwk.ext;
87
+ const pkcs8 = Buffer.from(await webcrypto.subtle.exportKey('pkcs8', keys.privateKey)).toString('base64');
88
+ const ciphertext = await cipher.encrypt(pkcs8, { authDomainId, purpose: 'private_key' });
89
+ const certificatePem = cert.toString('pem');
90
+ await writeCredential(db, authDomainId, {
91
+ private_key_ciphertext: ciphertext,
92
+ private_key_set_at: notBefore,
93
+ public_jwk: JSON.stringify(jwk),
94
+ certificate: certificatePem,
95
+ });
96
+ return { jwks: { keys: [jwk] }, certificatePem };
97
+ }
98
+ /**
99
+ * Whether an auth domain has a secret and a key, when each was last set, and
100
+ * the public key. Never the secret or private key. Run it on the admin's
101
+ * session client; returns null for an auth domain they can't see or that has
102
+ * no credential.
103
+ */
104
+ export async function getClientCredentialStatus(db, authDomainId) {
105
+ const { rows } = await db.query(`SELECT secret_set_at AS "secretSetAt", private_key_set_at AS "privateKeySetAt",
106
+ public_jwk AS "publicJwk", certificate
107
+ FROM auth_domain_credentials WHERE auth_domain_id = $1`, [authDomainId]);
108
+ const row = rows[0];
109
+ if (!row)
110
+ return null;
111
+ return {
112
+ secretSetAt: row.secretSetAt,
113
+ privateKeySetAt: row.privateKeySetAt,
114
+ publicKey: row.publicJwk && row.certificate ? { jwks: { keys: [row.publicJwk] }, certificatePem: row.certificate } : null,
115
+ };
116
+ }
117
+ // ─── Read for the token exchange (privileged, pre-session) ─────────────────
118
+ // Joined to a live auth domain, so a soft-deleted one's credential is never used.
119
+ const SELECT_CREDENTIAL = `
120
+ SELECT c.secret_ciphertext AS "secretCiphertext", c.private_key_ciphertext AS "privateKeyCiphertext",
121
+ c.public_jwk AS "publicJwk"
122
+ FROM auth_domain_credentials c
123
+ JOIN auth_domains ad ON ad.auth_domain_id = c.auth_domain_id AND ad.deleted_at IS NULL
124
+ WHERE c.auth_domain_id = $1
125
+ `;
126
+ async function storedCredential(db, authDomainId) {
127
+ const { rows } = await db.query(SELECT_CREDENTIAL, [authDomainId]);
128
+ return rows[0];
129
+ }
130
+ async function decrypt(cipher, ciphertext, context) {
131
+ if (!cipher) {
132
+ throw new InvalidInputError(`auth domain ${context.authDomainId} has a stored credential but no cipher is configured`);
133
+ }
134
+ try {
135
+ return await cipher.decrypt(ciphertext, context);
136
+ }
137
+ catch {
138
+ // The plaintext never existed here, but keep the hook's error (which may
139
+ // echo its input) out of anything that gets logged or returned.
140
+ throw new Error(`could not decrypt the ${context.purpose.replace('_', ' ')} for auth domain ${context.authDomainId}`);
141
+ }
142
+ }
143
+ /** The decrypted client secret, read fresh for this exchange; undefined when none is stored. */
144
+ export async function loadClientSecret(db, authDomainId, cipher) {
145
+ const stored = await storedCredential(db, authDomainId);
146
+ if (!stored?.secretCiphertext)
147
+ return undefined;
148
+ return decrypt(cipher, stored.secretCiphertext, { authDomainId, purpose: 'client_secret' });
149
+ }
150
+ /** The private key and its certificate thumbprints, read fresh for this exchange; undefined when none is stored. */
151
+ export async function loadClientKey(db, authDomainId, cipher) {
152
+ const stored = await storedCredential(db, authDomainId);
153
+ if (!stored?.privateKeyCiphertext || !stored.publicJwk)
154
+ return undefined;
155
+ const pkcs8 = await decrypt(cipher, stored.privateKeyCiphertext, { authDomainId, purpose: 'private_key' });
156
+ const key = await webcrypto.subtle.importKey('pkcs8', Buffer.from(pkcs8, 'base64'), RSA, false, ['sign']);
157
+ const der = Buffer.from(stored.publicJwk.x5c[0], 'base64');
158
+ return {
159
+ key: key,
160
+ x5tS256: stored.publicJwk['x5t#S256'],
161
+ x5t: createHash('sha1').update(der).digest('base64url'),
162
+ };
163
+ }
164
+ //# sourceMappingURL=credentials.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.js","sourceRoot":"","sources":["../../../src/methods/oidc/credentials.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAqCpD,MAAM,GAAG,GAAoC;IAC3C,IAAI,EAAE,mBAAmB;IACzB,IAAI,EAAE,SAAS;IACf,aAAa,EAAE,IAAI;IACnB,cAAc,EAAE,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;CAC1C,CAAC;AAEF,4EAA4E;AAC5E,gFAAgF;AAChF,6EAA6E;AAC7E,+DAA+D;AAC/D,KAAK,UAAU,eAAe,CAAC,EAAa,EAAE,YAAoB,EAAE,GAA4B;IAC9F,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC9B,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAClC,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC,KAAK,CAC3B,sCAAsC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;+BAC5D,EAC3B,CAAC,YAAY,EAAE,GAAG,MAAM,CAAC,CAC1B,CAAC;IACF,IAAI,MAAM,CAAC,QAAQ;QAA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{ Queryable } from '../../types.js';
3
3
  import type { AuthDomain, ResolvedUser } from '../types.js';
4
+ import { type CredentialCipher } from './credentials.js';
5
+ export { generateClientKey, getClientCredentialStatus, setClientSecret, type ClientCredentialStatus, type ClientPublicKey, type CredentialCipher, type CredentialContext, } from './credentials.js';
6
+ /** How the client authenticates at the token endpoint (OIDC registration's `token_endpoint_auth_method`). */
7
+ export type TokenEndpointAuthMethod = 'none' | 'client_secret_basic' | 'client_secret_post' | 'private_key_jwt';
4
8
  /**
5
9
  * The OIDC provider config read from `auth_domains.integration_params`.
6
- * Public values only — the `client_secret` is supplied out-of-band via
7
- * {@link OidcHandlerOptions.clientSecret} (from the app's secret store), never
8
- * stored here.
10
+ * Public values only. The client's credential never goes here: it is stored
11
+ * encrypted in `auth_domain_credentials` (see {@link setClientSecret} and
12
+ * {@link generateClientKey}), or supplied by the app's
13
+ * {@link OidcHandlerOptions.clientSecret} resolver.
9
14
  */
10
15
  export interface OidcParams {
11
16
  /** Provider issuer URL (discovery is fetched from `${issuer}/.well-known/openid-configuration`). */
@@ -16,6 +21,13 @@ export interface OidcParams {
16
21
  redirectUri: string;
17
22
  /** OAuth scope. Defaults to `openid email profile`. */
18
23
  scope?: string;
24
+ /**
25
+ * How the client authenticates at the token endpoint; only this method is
26
+ * ever sent, and a failure is never retried with another. Leave it out to
27
+ * keep the behavior from before it existed: `client_secret_post` when the
28
+ * {@link OidcHandlerOptions.clientSecret} resolver returns a secret, else none.
29
+ */
30
+ tokenEndpointAuthMethod?: TokenEndpointAuthMethod;
19
31
  }
20
32
  /**
21
33
  * The transient login state produced by {@link OidcHandler.initiate} that the
@@ -36,11 +48,18 @@ export interface OidcAuthorization {
36
48
  }
37
49
  export interface OidcHandlerOptions {
38
50
  /**
39
- * Resolve the confidential client secret for an `auth_domains` row, from the
40
- * app's secret store (Vercel/SSM) — NOT from the database. Return `undefined`
41
- * for a public (PKCE-only) client.
51
+ * Resolve a client secret the app holds itself, from its own secret store.
52
+ * When it returns a secret, that secret is used, ahead of one stored with
53
+ * {@link setClientSecret}; return `undefined` to fall back to the stored one.
42
54
  */
43
55
  clientSecret?: (authDomain: AuthDomain<OidcParams>) => string | undefined | Promise<string | undefined>;
56
+ /**
57
+ * Decrypts credentials stored with {@link setClientSecret} and
58
+ * {@link generateClientKey} (the same cipher that encrypted them). Each is
59
+ * read and decrypted on every sign-in, never cached, so a replaced credential
60
+ * takes effect on the next one.
61
+ */
62
+ cipher?: CredentialCipher;
44
63
  /**
45
64
  * Provision a user when a verified identity has no existing communication
46
65
  * method. The app owns the writes + audit attribution (it knows the tenant
@@ -76,7 +95,7 @@ type ValidatedClaims = NonNullable<ReturnType<typeof oauth.getValidatedIdTokenCl
76
95
  * this is an authentication-authority boundary, not a scope boundary.
77
96
  *
78
97
  * ```ts
79
- * const oidc = oidcHandler({ clientSecret: (ad) => secrets.get(ad.tenantId) });
98
+ * const oidc = oidcHandler({ cipher }); // or clientSecret: (ad) => secrets.get(ad.tenantId)
80
99
  * const { redirectUrl, loginState } = await oidc.initiate(authDomain);
81
100
  * // ...store loginState in a signed cookie keyed by loginState.state, redirect...
82
101
  * const user = await oidc.complete({ db: pool, authDomain, callbackUrl, loginState });
@@ -96,5 +115,4 @@ export interface OidcHandler {
96
115
  }): Promise<ResolvedUser>;
97
116
  }
98
117
  export declare function oidcHandler(options?: OidcHandlerOptions): OidcHandler;
99
- export {};
100
118
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/methods/oidc/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,cAAc,CAAC;AAItC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAEhD,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE5D;;;;;GAKG;AACH,MAAM,WAAW,UAAU;IACzB,oGAAoG;IACpG,MAAM,EAAE,MAAM,CAAC;IACf,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ED,wBAAgB,WAAW,CAAC,OAAO,GAAE,kBAAuB,GAAG,WAAW,CAgGzE"}
@@ -3,6 +3,14 @@ import { InvalidInputError } from '../../errors.js';
3
3
  import { findUserByCommunicationMethod } from '../../find-user-by-communication-method.js';
4
4
  import { emailDomainOf, tenantHasVerifiedDomain } from '../../internal/email-domain.js';
5
5
  import { EmailDomainNotVerifiedError, VerificationFailedError } from '../errors.js';
6
+ import { loadClientKey, loadClientSecret } from './credentials.js';
7
+ export { generateClientKey, getClientCredentialStatus, setClientSecret, } from './credentials.js';
8
+ const TOKEN_ENDPOINT_AUTH_METHODS = [
9
+ 'none',
10
+ 'client_secret_basic',
11
+ 'client_secret_post',
12
+ 'private_key_jwt',
13
+ ];
6
14
  function paramsOf(authDomain) {
7
15
  if (authDomain.integrationType !== 'oidc') {
8
16
  throw new InvalidInputError(`OidcHandler requires integration_type 'oidc', got '${authDomain.integrationType}'`);
@@ -11,8 +19,44 @@ function paramsOf(authDomain) {
11
19
  if (!p.issuer || !p.clientId || !p.redirectUri) {
12
20
  throw new InvalidInputError('OIDC integration_params must include issuer, clientId, and redirectUri');
13
21
  }
22
+ if (p.tokenEndpointAuthMethod !== undefined && !TOKEN_ENDPOINT_AUTH_METHODS.includes(p.tokenEndpointAuthMethod)) {
23
+ throw new InvalidInputError(`OIDC tokenEndpointAuthMethod must be one of ${TOKEN_ENDPOINT_AUTH_METHODS.join(', ')}, got ${JSON.stringify(p.tokenEndpointAuthMethod)}`);
24
+ }
14
25
  return p;
15
26
  }
27
+ /**
28
+ * The client authentication for this exchange: the auth domain's declared
29
+ * method and nothing else, with its credential read and decrypted now.
30
+ */
31
+ async function clientAuthFor(db, authDomain, params, as, options) {
32
+ const method = params.tokenEndpointAuthMethod;
33
+ const id = authDomain.authDomainId;
34
+ if (method === undefined) {
35
+ const secret = options.clientSecret ? await options.clientSecret(authDomain) : undefined;
36
+ return secret ? oauth.ClientSecretPost(secret) : oauth.None();
37
+ }
38
+ if (method === 'none')
39
+ return oauth.None();
40
+ if (method === 'private_key_jwt') {
41
+ const stored = await loadClientKey(db, id, options.cipher);
42
+ if (!stored)
43
+ throw new InvalidInputError(`auth domain ${id} uses private_key_jwt but has no key; generate one`);
44
+ return oauth.PrivateKeyJwt({ key: stored.key, kid: stored.x5tS256 }, {
45
+ // Entra identifies the certificate by thumbprint, not kid, and wants the
46
+ // token endpoint as the audience; oauth4webapi defaults aud to the issuer.
47
+ [oauth.modifyAssertion]: (header, payload) => {
48
+ Object.assign(header, { 'x5t#S256': stored.x5tS256, x5t: stored.x5t });
49
+ if (as.token_endpoint)
50
+ payload.aud = as.token_endpoint;
51
+ },
52
+ });
53
+ }
54
+ const secret = (options.clientSecret ? await options.clientSecret(authDomain) : undefined) ??
55
+ (await loadClientSecret(db, id, options.cipher));
56
+ if (!secret)
57
+ throw new InvalidInputError(`auth domain ${id} uses ${method} but has no client secret; set one`);
58
+ return method === 'client_secret_basic' ? oauth.ClientSecretBasic(secret) : oauth.ClientSecretPost(secret);
59
+ }
16
60
  // Discovery is cached per issuer for the process lifetime (warm-start friendly).
17
61
  // Failures are not cached.
18
62
  const discoveryCache = new Map();
@@ -59,8 +103,7 @@ export function oidcHandler(options = {}) {
59
103
  const params = paramsOf(authDomain);
60
104
  const as = await authorizationServer(params.issuer, options.fetch);
61
105
  const client = { client_id: params.clientId };
62
- const secret = options.clientSecret ? await options.clientSecret(authDomain) : undefined;
63
- const clientAuth = secret ? oauth.ClientSecretPost(secret) : oauth.None();
106
+ const clientAuth = await clientAuthFor(db, authDomain, params, as, options);
64
107
  const currentUrl = typeof callbackUrl === 'string' ? new URL(callbackUrl) : callbackUrl;
65
108
  const fetchOption = options.fetch ? { [oauth.customFetch]: options.fetch } : undefined;
66
109
  let claims;