@warlock.js/auth 5.14.0 → 5.16.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 (51) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/esm/contracts/index.d.mts +1 -1
  3. package/esm/contracts/providers.d.mts +59 -1
  4. package/esm/contracts/providers.d.mts.map +1 -1
  5. package/esm/index.d.mts +8 -2
  6. package/esm/index.mjs +7 -1
  7. package/esm/providers/apple-provider.d.mts +74 -0
  8. package/esm/providers/apple-provider.d.mts.map +1 -0
  9. package/esm/providers/apple-provider.mjs +157 -0
  10. package/esm/providers/apple-provider.mjs.map +1 -0
  11. package/esm/providers/discord-provider.d.mts +25 -0
  12. package/esm/providers/discord-provider.d.mts.map +1 -0
  13. package/esm/providers/discord-provider.mjs +84 -0
  14. package/esm/providers/discord-provider.mjs.map +1 -0
  15. package/esm/providers/facebook-provider.d.mts +36 -0
  16. package/esm/providers/facebook-provider.d.mts.map +1 -0
  17. package/esm/providers/facebook-provider.mjs +94 -0
  18. package/esm/providers/facebook-provider.mjs.map +1 -0
  19. package/esm/providers/github-provider.d.mts +31 -0
  20. package/esm/providers/github-provider.d.mts.map +1 -0
  21. package/esm/providers/github-provider.mjs +115 -0
  22. package/esm/providers/github-provider.mjs.map +1 -0
  23. package/esm/providers/index.d.mts +7 -1
  24. package/esm/providers/index.mjs +6 -0
  25. package/esm/providers/linkedin-provider.d.mts +35 -0
  26. package/esm/providers/linkedin-provider.d.mts.map +1 -0
  27. package/esm/providers/linkedin-provider.mjs +108 -0
  28. package/esm/providers/linkedin-provider.mjs.map +1 -0
  29. package/esm/providers/provider-login.d.mts +2 -1
  30. package/esm/providers/provider-login.d.mts.map +1 -1
  31. package/esm/providers/provider-login.mjs +47 -7
  32. package/esm/providers/provider-login.mjs.map +1 -1
  33. package/esm/providers/provider-state-cookie.mjs +35 -16
  34. package/esm/providers/provider-state-cookie.mjs.map +1 -1
  35. package/esm/providers/x-provider.d.mts +35 -0
  36. package/esm/providers/x-provider.d.mts.map +1 -0
  37. package/esm/providers/x-provider.mjs +101 -0
  38. package/esm/providers/x-provider.mjs.map +1 -0
  39. package/esm/services/auth-config.mjs +16 -1
  40. package/esm/services/auth-config.mjs.map +1 -1
  41. package/llms-full.txt +1075 -765
  42. package/llms.txt +5 -5
  43. package/package.json +8 -8
  44. package/skills/auth-basics/SKILL.md +16 -1
  45. package/skills/customize-token-storage/SKILL.md +160 -122
  46. package/skills/customize-user-type/SKILL.md +168 -142
  47. package/skills/handle-login-and-logout/SKILL.md +179 -165
  48. package/skills/login-with-providers/SKILL.md +131 -2
  49. package/skills/protect-routes/SKILL.md +308 -249
  50. package/skills/register-user/SKILL.md +15 -1
  51. package/skills/run-auth-commands/SKILL.md +16 -1
@@ -19,41 +19,60 @@ function sign(payload) {
19
19
  return createHmac("sha256", createHmac("sha256", authConfig.accessToken.secret()).update("@warlock.js/auth:provider-state").digest()).update(payload).digest("base64url");
20
20
  }
21
21
  /**
22
- * Write the signed, 10-minute state cookie for a provider login. Attribute
23
- * flags (`HttpOnly`, `SameSite=Lax`, `Secure` outside dev) come from the
24
- * `response.cookie()` secure defaults; `Lax` still rides the provider's
25
- * top-level GET redirect back to the app.
22
+ * Write the signed, 10-minute state cookie for a provider login. `HttpOnly`
23
+ * comes from the `response.cookie()` secure defaults. `callbackMode` picks
24
+ * the `SameSite`/`Secure` pair: `"query"` (default) keeps the framework's
25
+ * `SameSite=Lax`, which still rides a top-level GET redirect back to the app;
26
+ * `"form_post"` (Apple) overrides to `SameSite=None; Secure`, since a browser
27
+ * drops a `Lax` cookie on the provider's cross-site POST callback. Either
28
+ * way, the signed `state`/`nonce`/PKCE values — not the cookie's SameSite
29
+ * attribute — are what actually defend against CSRF here.
26
30
  */
27
- function writeProviderState(response, provider, state) {
31
+ function writeProviderState(response, provider, state, callbackMode = "query") {
28
32
  const stored = {
29
33
  ...state,
30
34
  provider,
31
- expiresAt: Date.now() + PROVIDER_STATE_TTL_SECONDS * 1e3
35
+ expiresAt: Date.now() + PROVIDER_STATE_TTL_SECONDS * 1e3,
36
+ callbackMode
32
37
  };
33
38
  const payload = Buffer.from(JSON.stringify(stored)).toString("base64url");
34
39
  response.cookie(PROVIDER_STATE_COOKIE, `${payload}.${sign(payload)}`, {
35
40
  raw: true,
36
41
  path: "/",
37
- maxAge: PROVIDER_STATE_TTL_SECONDS
42
+ maxAge: PROVIDER_STATE_TTL_SECONDS,
43
+ ...callbackMode === "form_post" ? {
44
+ sameSite: "none",
45
+ secure: true
46
+ } : {}
38
47
  });
39
48
  }
40
49
  /**
41
50
  * Read AND clear the state cookie, so a started login completes at most once.
42
51
  * Resolves `undefined` for an absent, forged (bad MAC), malformed or expired
43
- * cookie.
52
+ * cookie. The clearing `Set-Cookie` repeats whatever `SameSite`/`Secure` pair
53
+ * the cookie was WRITTEN with (recovered from the decoded payload itself, so
54
+ * this needs no mode passed in) — a browser only honours a clearing cookie
55
+ * when it matches the original's attributes, and for a `form_post` (Apple)
56
+ * cookie that means `SameSite=None; Secure` too, or the original survives.
44
57
  */
45
58
  function takeProviderState(request, response) {
46
59
  const raw = request.cookie(PROVIDER_STATE_COOKIE);
47
- response.clearCookie(PROVIDER_STATE_COOKIE, { path: "/" });
48
- if (typeof raw !== "string") return void 0;
49
- const [payload, signature, ...rest] = raw.split(".");
50
- if (!payload || !signature || rest.length > 0 || !safeEqual(signature, sign(payload))) return;
51
60
  let stored;
52
- try {
53
- stored = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
54
- } catch {
55
- return;
61
+ if (typeof raw === "string") {
62
+ const [payload, signature, ...rest] = raw.split(".");
63
+ if (payload && signature && rest.length === 0 && safeEqual(signature, sign(payload))) try {
64
+ stored = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
65
+ } catch {
66
+ stored = void 0;
67
+ }
56
68
  }
69
+ response.clearCookie(PROVIDER_STATE_COOKIE, {
70
+ path: "/",
71
+ ...stored?.callbackMode === "form_post" ? {
72
+ sameSite: "none",
73
+ secure: true
74
+ } : {}
75
+ });
57
76
  if (typeof stored?.state !== "string" || typeof stored.nonce !== "string" || typeof stored.codeVerifier !== "string" || typeof stored.provider !== "string" || typeof stored.expiresAt !== "number" || stored.expiresAt <= Date.now()) return;
58
77
  return stored;
59
78
  }
@@ -1 +1 @@
1
- {"version":3,"file":"provider-state-cookie.mjs","names":[],"sources":["../../../../../../../auth/src/providers/provider-state-cookie.ts"],"sourcesContent":["import type { Request, Response } from \"@warlock.js/core\";\nimport { createHmac, randomBytes } from \"node:crypto\";\nimport type { ProviderAuthorizationState } from \"../contracts/providers\";\nimport { authConfig } from \"../services/auth-config\";\nimport { safeEqual } from \"../utils/safe-equal\";\n\n/** Cookie carrying a redirect login's state from the start to the callback. */\nexport const PROVIDER_STATE_COOKIE = \"auth_provider_state\";\n\n/** How long a started provider login stays completable. */\nconst PROVIDER_STATE_TTL_SECONDS = 600;\n\n/** What the signed cookie holds. */\nexport type StoredProviderState = ProviderAuthorizationState & {\n provider: string;\n expiresAt: number;\n};\n\n/** 32 random bytes, base64url — used for `state`, `nonce` and the PKCE verifier. */\nexport function randomUrlSafe(): string {\n return randomBytes(32).toString(\"base64url\");\n}\n\n/**\n * HMAC over the payload with a key DERIVED from the access-token secret, so\n * the state cookie never shares a MAC key with the JWTs themselves.\n */\nfunction sign(payload: string): string {\n const key = createHmac(\"sha256\", authConfig.accessToken.secret())\n .update(\"@warlock.js/auth:provider-state\")\n .digest();\n\n return createHmac(\"sha256\", key).update(payload).digest(\"base64url\");\n}\n\n/**\n * Write the signed, 10-minute state cookie for a provider login. Attribute\n * flags (`HttpOnly`, `SameSite=Lax`, `Secure` outside dev) come from the\n * `response.cookie()` secure defaults; `Lax` still rides the provider's\n * top-level GET redirect back to the app.\n */\nexport function writeProviderState(\n response: Response,\n provider: string,\n state: ProviderAuthorizationState,\n): void {\n const stored: StoredProviderState = {\n ...state,\n provider,\n expiresAt: Date.now() + PROVIDER_STATE_TTL_SECONDS * 1000,\n };\n const payload = Buffer.from(JSON.stringify(stored)).toString(\"base64url\");\n\n response.cookie(PROVIDER_STATE_COOKIE, `${payload}.${sign(payload)}`, {\n raw: true,\n path: \"/\",\n maxAge: PROVIDER_STATE_TTL_SECONDS,\n });\n}\n\n/**\n * Read AND clear the state cookie, so a started login completes at most once.\n * Resolves `undefined` for an absent, forged (bad MAC), malformed or expired\n * cookie.\n */\nexport function takeProviderState(\n request: Request,\n response: Response,\n): StoredProviderState | undefined {\n const raw: unknown = request.cookie(PROVIDER_STATE_COOKIE);\n\n response.clearCookie(PROVIDER_STATE_COOKIE, { path: \"/\" });\n\n if (typeof raw !== \"string\") return undefined;\n\n const [payload, signature, ...rest] = raw.split(\".\");\n\n if (!payload || !signature || rest.length > 0 || !safeEqual(signature, sign(payload))) {\n return undefined;\n }\n\n let stored: Partial<StoredProviderState> | undefined;\n\n try {\n stored = JSON.parse(Buffer.from(payload, \"base64url\").toString(\"utf8\"));\n } catch {\n return undefined;\n }\n\n if (\n typeof stored?.state !== \"string\" ||\n typeof stored.nonce !== \"string\" ||\n typeof stored.codeVerifier !== \"string\" ||\n typeof stored.provider !== \"string\" ||\n typeof stored.expiresAt !== \"number\" ||\n stored.expiresAt <= Date.now()\n ) {\n return undefined;\n }\n\n return stored as StoredProviderState;\n}\n"],"mappings":";;;;;;AAOA,MAAa,wBAAwB;;AAGrC,MAAM,6BAA6B;;AASnC,SAAgB,gBAAwB;CACtC,OAAO,YAAY,EAAE,CAAC,CAAC,SAAS,WAAW;AAC7C;;;;;AAMA,SAAS,KAAK,SAAyB;CAKrC,OAAO,WAAW,UAJN,WAAW,UAAU,WAAW,YAAY,OAAO,CAAC,CAAC,CAC9D,OAAO,iCAAiC,CAAC,CACzC,OAE2B,CAAC,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,OAAO,WAAW;AACrE;;;;;;;AAQA,SAAgB,mBACd,UACA,UACA,OACM;CACN,MAAM,SAA8B;EAClC,GAAG;EACH;EACA,WAAW,KAAK,IAAI,IAAI,6BAA6B;CACvD;CACA,MAAM,UAAU,OAAO,KAAK,KAAK,UAAU,MAAM,CAAC,CAAC,CAAC,SAAS,WAAW;CAExE,SAAS,OAAO,uBAAuB,GAAG,QAAQ,GAAG,KAAK,OAAO,KAAK;EACpE,KAAK;EACL,MAAM;EACN,QAAQ;CACV,CAAC;AACH;;;;;;AAOA,SAAgB,kBACd,SACA,UACiC;CACjC,MAAM,MAAe,QAAQ,OAAO,qBAAqB;CAEzD,SAAS,YAAY,uBAAuB,EAAE,MAAM,IAAI,CAAC;CAEzD,IAAI,OAAO,QAAQ,UAAU,OAAO;CAEpC,MAAM,CAAC,SAAS,WAAW,GAAG,QAAQ,IAAI,MAAM,GAAG;CAEnD,IAAI,CAAC,WAAW,CAAC,aAAa,KAAK,SAAS,KAAK,CAAC,UAAU,WAAW,KAAK,OAAO,CAAC,GAClF;CAGF,IAAI;CAEJ,IAAI;EACF,SAAS,KAAK,MAAM,OAAO,KAAK,SAAS,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC;CACxE,QAAQ;EACN;CACF;CAEA,IACE,OAAO,QAAQ,UAAU,YACzB,OAAO,OAAO,UAAU,YACxB,OAAO,OAAO,iBAAiB,YAC/B,OAAO,OAAO,aAAa,YAC3B,OAAO,OAAO,cAAc,YAC5B,OAAO,aAAa,KAAK,IAAI,GAE7B;CAGF,OAAO;AACT"}
1
+ {"version":3,"file":"provider-state-cookie.mjs","names":[],"sources":["../../../../../../../auth/src/providers/provider-state-cookie.ts"],"sourcesContent":["import type { Request, Response } from \"@warlock.js/core\";\nimport { createHmac, randomBytes } from \"node:crypto\";\nimport type { ProviderAuthorizationState } from \"../contracts/providers\";\nimport { authConfig } from \"../services/auth-config\";\nimport { safeEqual } from \"../utils/safe-equal\";\n\n/** Cookie carrying a redirect login's state from the start to the callback. */\nexport const PROVIDER_STATE_COOKIE = \"auth_provider_state\";\n\n/** How long a started provider login stays completable. */\nconst PROVIDER_STATE_TTL_SECONDS = 600;\n\n/** What the signed cookie holds. */\nexport type StoredProviderState = ProviderAuthorizationState & {\n provider: string;\n expiresAt: number;\n callbackMode: \"query\" | \"form_post\";\n};\n\n/** 32 random bytes, base64url — used for `state`, `nonce` and the PKCE verifier. */\nexport function randomUrlSafe(): string {\n return randomBytes(32).toString(\"base64url\");\n}\n\n/**\n * HMAC over the payload with a key DERIVED from the access-token secret, so\n * the state cookie never shares a MAC key with the JWTs themselves.\n */\nfunction sign(payload: string): string {\n const key = createHmac(\"sha256\", authConfig.accessToken.secret())\n .update(\"@warlock.js/auth:provider-state\")\n .digest();\n\n return createHmac(\"sha256\", key).update(payload).digest(\"base64url\");\n}\n\n/**\n * Write the signed, 10-minute state cookie for a provider login. `HttpOnly`\n * comes from the `response.cookie()` secure defaults. `callbackMode` picks\n * the `SameSite`/`Secure` pair: `\"query\"` (default) keeps the framework's\n * `SameSite=Lax`, which still rides a top-level GET redirect back to the app;\n * `\"form_post\"` (Apple) overrides to `SameSite=None; Secure`, since a browser\n * drops a `Lax` cookie on the provider's cross-site POST callback. Either\n * way, the signed `state`/`nonce`/PKCE values — not the cookie's SameSite\n * attribute — are what actually defend against CSRF here.\n */\nexport function writeProviderState(\n response: Response,\n provider: string,\n state: ProviderAuthorizationState,\n callbackMode: \"query\" | \"form_post\" = \"query\",\n): void {\n const stored: StoredProviderState = {\n ...state,\n provider,\n expiresAt: Date.now() + PROVIDER_STATE_TTL_SECONDS * 1000,\n callbackMode,\n };\n const payload = Buffer.from(JSON.stringify(stored)).toString(\"base64url\");\n\n response.cookie(PROVIDER_STATE_COOKIE, `${payload}.${sign(payload)}`, {\n raw: true,\n path: \"/\",\n maxAge: PROVIDER_STATE_TTL_SECONDS,\n ...(callbackMode === \"form_post\" ? { sameSite: \"none\", secure: true } : {}),\n });\n}\n\n/**\n * Read AND clear the state cookie, so a started login completes at most once.\n * Resolves `undefined` for an absent, forged (bad MAC), malformed or expired\n * cookie. The clearing `Set-Cookie` repeats whatever `SameSite`/`Secure` pair\n * the cookie was WRITTEN with (recovered from the decoded payload itself, so\n * this needs no mode passed in) — a browser only honours a clearing cookie\n * when it matches the original's attributes, and for a `form_post` (Apple)\n * cookie that means `SameSite=None; Secure` too, or the original survives.\n */\nexport function takeProviderState(\n request: Request,\n response: Response,\n): StoredProviderState | undefined {\n const raw: unknown = request.cookie(PROVIDER_STATE_COOKIE);\n\n let stored: Partial<StoredProviderState> | undefined;\n\n if (typeof raw === \"string\") {\n const [payload, signature, ...rest] = raw.split(\".\");\n\n if (payload && signature && rest.length === 0 && safeEqual(signature, sign(payload))) {\n try {\n stored = JSON.parse(Buffer.from(payload, \"base64url\").toString(\"utf8\"));\n } catch {\n stored = undefined;\n }\n }\n }\n\n response.clearCookie(PROVIDER_STATE_COOKIE, {\n path: \"/\",\n ...(stored?.callbackMode === \"form_post\" ? { sameSite: \"none\", secure: true } : {}),\n });\n\n if (\n typeof stored?.state !== \"string\" ||\n typeof stored.nonce !== \"string\" ||\n typeof stored.codeVerifier !== \"string\" ||\n typeof stored.provider !== \"string\" ||\n typeof stored.expiresAt !== \"number\" ||\n stored.expiresAt <= Date.now()\n ) {\n return undefined;\n }\n\n return stored as StoredProviderState;\n}\n"],"mappings":";;;;;;AAOA,MAAa,wBAAwB;;AAGrC,MAAM,6BAA6B;;AAUnC,SAAgB,gBAAwB;CACtC,OAAO,YAAY,EAAE,CAAC,CAAC,SAAS,WAAW;AAC7C;;;;;AAMA,SAAS,KAAK,SAAyB;CAKrC,OAAO,WAAW,UAJN,WAAW,UAAU,WAAW,YAAY,OAAO,CAAC,CAAC,CAC9D,OAAO,iCAAiC,CAAC,CACzC,OAE2B,CAAC,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,OAAO,WAAW;AACrE;;;;;;;;;;;AAYA,SAAgB,mBACd,UACA,UACA,OACA,eAAsC,SAChC;CACN,MAAM,SAA8B;EAClC,GAAG;EACH;EACA,WAAW,KAAK,IAAI,IAAI,6BAA6B;EACrD;CACF;CACA,MAAM,UAAU,OAAO,KAAK,KAAK,UAAU,MAAM,CAAC,CAAC,CAAC,SAAS,WAAW;CAExE,SAAS,OAAO,uBAAuB,GAAG,QAAQ,GAAG,KAAK,OAAO,KAAK;EACpE,KAAK;EACL,MAAM;EACN,QAAQ;EACR,GAAI,iBAAiB,cAAc;GAAE,UAAU;GAAQ,QAAQ;EAAK,IAAI,CAAC;CAC3E,CAAC;AACH;;;;;;;;;;AAWA,SAAgB,kBACd,SACA,UACiC;CACjC,MAAM,MAAe,QAAQ,OAAO,qBAAqB;CAEzD,IAAI;CAEJ,IAAI,OAAO,QAAQ,UAAU;EAC3B,MAAM,CAAC,SAAS,WAAW,GAAG,QAAQ,IAAI,MAAM,GAAG;EAEnD,IAAI,WAAW,aAAa,KAAK,WAAW,KAAK,UAAU,WAAW,KAAK,OAAO,CAAC,GACjF,IAAI;GACF,SAAS,KAAK,MAAM,OAAO,KAAK,SAAS,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC;EACxE,QAAQ;GACN,SAAS;EACX;CAEJ;CAEA,SAAS,YAAY,uBAAuB;EAC1C,MAAM;EACN,GAAI,QAAQ,iBAAiB,cAAc;GAAE,UAAU;GAAQ,QAAQ;EAAK,IAAI,CAAC;CACnF,CAAC;CAED,IACE,OAAO,QAAQ,UAAU,YACzB,OAAO,OAAO,UAAU,YACxB,OAAO,OAAO,iBAAiB,YAC/B,OAAO,OAAO,aAAa,YAC3B,OAAO,OAAO,cAAc,YAC5B,OAAO,aAAa,KAAK,IAAI,GAE7B;CAGF,OAAO;AACT"}
@@ -0,0 +1,35 @@
1
+ import { AuthProvider, ProviderAuthorizationState, ProviderCallbackParams, ProviderProfile, XProviderConfig } from "../contracts/providers.mjs";
2
+
3
+ //#region ../auth/src/providers/x-provider.d.ts
4
+ /**
5
+ * X (Twitter) sign-in: OAuth 2.0 authorization code flow with PKCE (S256). X
6
+ * is not OpenID Connect — there is no `id_token`. X's confidential clients
7
+ * authenticate the token request with HTTP Basic auth (`client_id:client_secret`),
8
+ * on top of PKCE — both are required together, per X's developer docs (this
9
+ * package has no X test app, so the exchange itself is unverified against a
10
+ * live endpoint). The access token is then redeemed once against
11
+ * `GET /2/users/me`.
12
+ *
13
+ * X does not return an email address from this API at all — there is no
14
+ * "email" scope to request it with — so `email` is always left `undefined`
15
+ * rather than invented, and `resolveProviderUser` rejects it the same way it
16
+ * rejects any other missing email.
17
+ */
18
+ declare class XProvider implements AuthProvider {
19
+ private readonly settings;
20
+ readonly name = "x";
21
+ constructor(settings: XProviderConfig);
22
+ authorizationUrl(state: ProviderAuthorizationState): string;
23
+ handleCallback({
24
+ query,
25
+ expected
26
+ }: ProviderCallbackParams): Promise<ProviderProfile>;
27
+ /** Basic-auth credential for the confidential-client token request. */
28
+ private basicAuth;
29
+ /** Redeem the authorization code (with the PKCE verifier) for an access token. */
30
+ private exchangeCode;
31
+ private fetchUser;
32
+ }
33
+ //#endregion
34
+ export { XProvider };
35
+ //# sourceMappingURL=x-provider.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"x-provider.d.mts","names":[],"sources":["../../../../../../../auth/src/providers/x-provider.ts"],"mappings":";;;;;AAoCA;;;;;;;;;;;;cAAa,SAAA,YAAqB,YAAA;EAAA,iBAGI,QAAA;EAAA,SAFpB,IAAA;cAEoB,QAAA,EAAU,eAAA;EAEvC,gBAAA,CAAiB,KAAA,EAAO,0BAAA;EAclB,cAAA;IACX,KAAA;IACA;EAAA,GACC,sBAAA,GAAyB,OAAA,CAAQ,eAAA;EAnBA;EAAA,QA8C5B,SAAA;EA5CuB;EAAA,QAmDjB,YAAA;EAAA,QAuCA,SAAA;AAAA"}
@@ -0,0 +1,101 @@
1
+ import { InvalidProviderCallbackError } from "../errors/invalid-provider-callback.error.mjs";
2
+ import { pkceChallenge } from "./google-provider.mjs";
3
+
4
+ //#region ../auth/src/providers/x-provider.ts
5
+ const AUTHORIZATION_ENDPOINT = "https://twitter.com/i/oauth2/authorize";
6
+ const TOKEN_ENDPOINT = "https://api.twitter.com/2/oauth2/token";
7
+ const USER_ENDPOINT = "https://api.twitter.com/2/users/me";
8
+ const DEFAULT_SCOPES = ["tweet.read", "users.read"];
9
+ /**
10
+ * X (Twitter) sign-in: OAuth 2.0 authorization code flow with PKCE (S256). X
11
+ * is not OpenID Connect — there is no `id_token`. X's confidential clients
12
+ * authenticate the token request with HTTP Basic auth (`client_id:client_secret`),
13
+ * on top of PKCE — both are required together, per X's developer docs (this
14
+ * package has no X test app, so the exchange itself is unverified against a
15
+ * live endpoint). The access token is then redeemed once against
16
+ * `GET /2/users/me`.
17
+ *
18
+ * X does not return an email address from this API at all — there is no
19
+ * "email" scope to request it with — so `email` is always left `undefined`
20
+ * rather than invented, and `resolveProviderUser` rejects it the same way it
21
+ * rejects any other missing email.
22
+ */
23
+ var XProvider = class {
24
+ constructor(settings) {
25
+ this.settings = settings;
26
+ this.name = "x";
27
+ }
28
+ authorizationUrl(state) {
29
+ const url = new URL(AUTHORIZATION_ENDPOINT);
30
+ url.searchParams.set("client_id", this.settings.clientId);
31
+ url.searchParams.set("redirect_uri", this.settings.redirectUri);
32
+ url.searchParams.set("response_type", "code");
33
+ url.searchParams.set("scope", (this.settings.scopes ?? DEFAULT_SCOPES).join(" "));
34
+ url.searchParams.set("state", state.state);
35
+ url.searchParams.set("code_challenge", pkceChallenge(state.codeVerifier));
36
+ url.searchParams.set("code_challenge_method", "S256");
37
+ return url.toString();
38
+ }
39
+ async handleCallback({ query, expected }) {
40
+ const code = query.code;
41
+ if (typeof code !== "string" || code.length === 0) throw new InvalidProviderCallbackError("missing-code");
42
+ const accessToken = await this.exchangeCode(code, expected.codeVerifier);
43
+ const user = await this.fetchUser(accessToken);
44
+ if (typeof user.id !== "string" || user.id.length === 0) throw new InvalidProviderCallbackError("missing-subject");
45
+ return {
46
+ provider: this.name,
47
+ providerUserId: user.id,
48
+ email: void 0,
49
+ emailVerified: false,
50
+ name: user.name ?? user.username,
51
+ avatar: user.profile_image_url,
52
+ raw: user
53
+ };
54
+ }
55
+ /** Basic-auth credential for the confidential-client token request. */
56
+ basicAuth() {
57
+ return Buffer.from(`${this.settings.clientId}:${this.settings.clientSecret}`).toString("base64");
58
+ }
59
+ /** Redeem the authorization code (with the PKCE verifier) for an access token. */
60
+ async exchangeCode(code, codeVerifier) {
61
+ let body;
62
+ try {
63
+ const response = await fetch(TOKEN_ENDPOINT, {
64
+ method: "POST",
65
+ headers: {
66
+ "content-type": "application/x-www-form-urlencoded",
67
+ authorization: `Basic ${this.basicAuth()}`
68
+ },
69
+ body: new URLSearchParams({
70
+ code,
71
+ client_id: this.settings.clientId,
72
+ redirect_uri: this.settings.redirectUri,
73
+ grant_type: "authorization_code",
74
+ code_verifier: codeVerifier
75
+ })
76
+ });
77
+ if (!response.ok) throw new Error(`X token endpoint answered ${response.status}`);
78
+ body = await response.json();
79
+ } catch (error) {
80
+ throw new InvalidProviderCallbackError("code-exchange-failed", error);
81
+ }
82
+ if (body.error) throw new InvalidProviderCallbackError("code-exchange-failed", body.error);
83
+ if (typeof body.access_token !== "string" || body.access_token.length === 0) throw new InvalidProviderCallbackError("missing-access-token");
84
+ return body.access_token;
85
+ }
86
+ async fetchUser(accessToken) {
87
+ try {
88
+ const url = new URL(USER_ENDPOINT);
89
+ url.searchParams.set("user.fields", "profile_image_url");
90
+ const response = await fetch(url.toString(), { headers: { authorization: `Bearer ${accessToken}` } });
91
+ if (!response.ok) throw new Error(`X /2/users/me endpoint answered ${response.status}`);
92
+ return (await response.json()).data ?? {};
93
+ } catch (error) {
94
+ throw new InvalidProviderCallbackError("profile-fetch-failed", error);
95
+ }
96
+ }
97
+ };
98
+
99
+ //#endregion
100
+ export { XProvider };
101
+ //# sourceMappingURL=x-provider.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"x-provider.mjs","names":[],"sources":["../../../../../../../auth/src/providers/x-provider.ts"],"sourcesContent":["import type {\n AuthProvider,\n ProviderAuthorizationState,\n ProviderCallbackParams,\n ProviderProfile,\n XProviderConfig,\n} from \"../contracts/providers\";\nimport { InvalidProviderCallbackError } from \"../errors/invalid-provider-callback.error\";\nimport { pkceChallenge } from \"./google-provider\";\n\nconst AUTHORIZATION_ENDPOINT = \"https://twitter.com/i/oauth2/authorize\";\nconst TOKEN_ENDPOINT = \"https://api.twitter.com/2/oauth2/token\";\nconst USER_ENDPOINT = \"https://api.twitter.com/2/users/me\";\nconst DEFAULT_SCOPES = [\"tweet.read\", \"users.read\"];\n\ntype XUser = {\n id: string;\n name?: string;\n username?: string;\n profile_image_url?: string;\n};\n\n/**\n * X (Twitter) sign-in: OAuth 2.0 authorization code flow with PKCE (S256). X\n * is not OpenID Connect — there is no `id_token`. X's confidential clients\n * authenticate the token request with HTTP Basic auth (`client_id:client_secret`),\n * on top of PKCE — both are required together, per X's developer docs (this\n * package has no X test app, so the exchange itself is unverified against a\n * live endpoint). The access token is then redeemed once against\n * `GET /2/users/me`.\n *\n * X does not return an email address from this API at all — there is no\n * \"email\" scope to request it with — so `email` is always left `undefined`\n * rather than invented, and `resolveProviderUser` rejects it the same way it\n * rejects any other missing email.\n */\nexport class XProvider implements AuthProvider {\n public readonly name = \"x\";\n\n public constructor(private readonly settings: XProviderConfig) {}\n\n public authorizationUrl(state: ProviderAuthorizationState): string {\n const url = new URL(AUTHORIZATION_ENDPOINT);\n\n url.searchParams.set(\"client_id\", this.settings.clientId);\n url.searchParams.set(\"redirect_uri\", this.settings.redirectUri);\n url.searchParams.set(\"response_type\", \"code\");\n url.searchParams.set(\"scope\", (this.settings.scopes ?? DEFAULT_SCOPES).join(\" \"));\n url.searchParams.set(\"state\", state.state);\n url.searchParams.set(\"code_challenge\", pkceChallenge(state.codeVerifier));\n url.searchParams.set(\"code_challenge_method\", \"S256\");\n\n return url.toString();\n }\n\n public async handleCallback({\n query,\n expected,\n }: ProviderCallbackParams): Promise<ProviderProfile> {\n const code = query.code;\n\n if (typeof code !== \"string\" || code.length === 0) {\n throw new InvalidProviderCallbackError(\"missing-code\");\n }\n\n const accessToken = await this.exchangeCode(code, expected.codeVerifier);\n const user = await this.fetchUser(accessToken);\n\n if (typeof user.id !== \"string\" || user.id.length === 0) {\n throw new InvalidProviderCallbackError(\"missing-subject\");\n }\n\n return {\n provider: this.name,\n providerUserId: user.id,\n // X does not hand back an email address from this API.\n email: undefined,\n emailVerified: false,\n name: user.name ?? user.username,\n avatar: user.profile_image_url,\n raw: user,\n };\n }\n\n /** Basic-auth credential for the confidential-client token request. */\n private basicAuth(): string {\n return Buffer.from(`${this.settings.clientId}:${this.settings.clientSecret}`).toString(\n \"base64\",\n );\n }\n\n /** Redeem the authorization code (with the PKCE verifier) for an access token. */\n private async exchangeCode(code: string, codeVerifier: string): Promise<string> {\n let body: { access_token?: unknown; error?: unknown };\n\n try {\n const response = await fetch(TOKEN_ENDPOINT, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/x-www-form-urlencoded\",\n authorization: `Basic ${this.basicAuth()}`,\n },\n body: new URLSearchParams({\n code,\n client_id: this.settings.clientId,\n redirect_uri: this.settings.redirectUri,\n grant_type: \"authorization_code\",\n code_verifier: codeVerifier,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`X token endpoint answered ${response.status}`);\n }\n\n body = (await response.json()) as { access_token?: unknown; error?: unknown };\n } catch (error) {\n throw new InvalidProviderCallbackError(\"code-exchange-failed\", error);\n }\n\n if (body.error) {\n throw new InvalidProviderCallbackError(\"code-exchange-failed\", body.error);\n }\n\n if (typeof body.access_token !== \"string\" || body.access_token.length === 0) {\n throw new InvalidProviderCallbackError(\"missing-access-token\");\n }\n\n return body.access_token;\n }\n\n private async fetchUser(accessToken: string): Promise<XUser> {\n try {\n const url = new URL(USER_ENDPOINT);\n\n url.searchParams.set(\"user.fields\", \"profile_image_url\");\n\n const response = await fetch(url.toString(), {\n headers: { authorization: `Bearer ${accessToken}` },\n });\n\n if (!response.ok) {\n throw new Error(`X /2/users/me endpoint answered ${response.status}`);\n }\n\n const body = (await response.json()) as { data?: XUser };\n\n return body.data ?? ({} as XUser);\n } catch (error) {\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K,GAAG,KAAK,SAAS,SAAS,GAAG,KAAK,SAAS,cAAc,CAAC,CAAC,SAC5E,QACF;CACF;;CAGA,MAAc,aAAa,MAAc,cAAuC;EAC9E,IAAI;EAEJ,IAAI;GACF,MAAM,WAAW,MAAM,MAAM,gBAAgB;IAC3C,QAAQ;IACR,SAAS;KACP,gBAAgB;KAChB,eAAe,SAAS,KAAK,UAAU;IACzC;IACA,MAAM,IAAI,gBAAgB;KACxB;KACA,WAAW,KAAK,SAAS;KACzB,cAAc,KAAK,SAAS;KAC5B,YAAY;KACZ,eAAe;IACjB,CAAC;GACH,CAAC;GAED,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,6BAA6B,SAAS,QAAQ;GAGhE,OAAQ,MAAM,SAAS,KAAK;EAC9B,SAAS,OAAO;GACd,MAAM,IAAI,6BAA6B,wBAAwB,KAAK;EACtE;EAEA,IAAI,KAAK,OACP,MAAM,IAAI,6BAA6B,wBAAwB,KAAK,KAAK;EAG3E,IAAI,OAAO,KAAK,iBAAiB,YAAY,KAAK,aAAa,WAAW,GACxE,MAAM,IAAI,6BAA6B,sBAAsB;EAG/D,OAAO,KAAK;CACd;CAEA,MAAc,UAAU,aAAqC;EAC3D,IAAI;GACF,MAAM,MAAM,IAAI,IAAI,aAAa;GAEjC,IAAI,aAAa,IAAI,eAAe,mBAAmB;GAEvD,MAAM,WAAW,MAAM,MAAM,IAAI,SAAS,GAAG,EAC3C,SAAS,EAAE,eAAe,UAAU,cAAc,EACpD,CAAC;GAED,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,mCAAmC,SAAS,QAAQ;GAKtE,QAAO,MAFa,SAAS,KAAK,EAEvB,CAAC,QAAS,CAAC;EACxB,SAAS,OAAO;GACd,MAAM,IAAI,6BAA6B,wBAAwB,KAAK;EACtE;CACF;AACF"}
@@ -155,8 +155,23 @@ allowedOrigins: () => config.key("auth.csrf.allowedOrigins", []) },
155
155
  providers: {
156
156
  /** `auth.providers.google`, when configured. */
157
157
  google: () => config.key("auth.providers.google"),
158
+ /** `auth.providers.github`, when configured. */
159
+ github: () => config.key("auth.providers.github"),
160
+ /** `auth.providers.discord`, when configured. */
161
+ discord: () => config.key("auth.providers.discord"),
162
+ /** `auth.providers.linkedin`, when configured. */
163
+ linkedin: () => config.key("auth.providers.linkedin"),
164
+ /** `auth.providers.apple`, when configured. */
165
+ apple: () => config.key("auth.providers.apple"),
166
+ /** `auth.providers.facebook`, when configured. */
167
+ facebook: () => config.key("auth.providers.facebook"),
168
+ /** `auth.providers.x`, when configured. */
169
+ x: () => config.key("auth.providers.x"),
158
170
  /** An app-registered provider under `auth.providers.custom.<name>`. */
159
- custom: (name) => config.key("auth.providers.custom", {})[name],
171
+ custom: (name) => {
172
+ const providers = config.key("auth.providers.custom", {});
173
+ return Object.hasOwn(providers, name) ? providers[name] : void 0;
174
+ },
160
175
  /** User attribute a verified provider email is matched against. @default "email" */
161
176
  emailField: () => config.key("auth.providers.emailField", "email"),
162
177
  /** App-owned user creation for a first provider login. */
@@ -1 +1 @@
1
- {"version":3,"file":"auth-config.mjs","names":[],"sources":["../../../../../../../auth/src/services/auth-config.ts"],"sourcesContent":["import { config } from \"@warlock.js/core\";\r\nimport { log } from \"@warlock.js/logger\";\r\nimport { type Algorithm } from \"fast-jwt\";\r\nimport ms from \"ms\";\r\nimport type {\r\n AuthNotification,\r\n CanAuthenticate,\r\n LogoutWithoutTokenBehavior,\r\n OneTimeTokenUrlBuilder,\r\n PasswordSetter,\r\n} from \"../contracts/types\";\r\nimport type {\r\n AuthProvider,\r\n GoogleProviderConfig,\r\n OtpSender,\r\n PasskeysConfig,\r\n ProviderUserCreator,\r\n} from \"../contracts/providers\";\r\nimport type { Auth } from \"../models/auth.model\";\r\n\r\nconst warnedLegacyKeys = new Set<string>();\r\n\r\nconst permitAuthentication: CanAuthenticate = (): boolean => true;\r\n\r\n/**\r\n * `ms` accepts anything at runtime and answers `undefined` for a string it\r\n * cannot parse (`\"30dayz\"`), a *formatted string* for a number (`2592000` ⇒\r\n * `\"43m\"`), and throws for `\"\"`. Its published types claim the far narrower\r\n * `(value: ms.StringValue) => number`, which is exactly what let an\r\n * `as ms.StringValue` cast smuggle arbitrary config text past the compiler and\r\n * hand `undefined` to the JWT signer. Declare the honest runtime signature once,\r\n * here, so every caller is forced to deal with the `undefined`.\r\n */\r\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\r\n\r\n/**\r\n * Turn a configured lifetime into a positive number of milliseconds, or throw\r\n * naming the key.\r\n *\r\n * A token lifetime is a security boundary, so an unusable value is a hard error\r\n * rather than a silent fallback: substituting a default would trade one\r\n * unintended lifetime for another, just as quietly — and quiet is the whole\r\n * problem. Every non-positive, non-finite or non-numeric parse is rejected:\r\n *\r\n * - `\"30dayz\"` / `\"thirty days\"` ⇒ `undefined` ⇒ a JWT signed with **no `exp`\r\n * claim** and an `Invalid Date` written to the token row.\r\n * - `\"0d\"` ⇒ parses cleanly to `0`, which `fast-jwt` treats as falsy and also\r\n * emits with **no `exp` claim** — it survives any guard that only rejects\r\n * `undefined`. `\"-1h\"` signs an already-expired token.\r\n * - `2592000` (a bare number) ⇒ `ms` *formats* it as `\"43m\"`, a string, which\r\n * then turns `Date.now() + expiresIn` into an `Invalid Date`.\r\n */\r\nfunction parseDuration(key: string, raw: unknown): number {\r\n let parsed: number | string | undefined;\r\n\r\n try {\r\n parsed = parseMs(raw);\r\n } catch {\r\n // ms throws (rather than returning undefined) for \"\" and non-strings\r\n parsed = undefined;\r\n }\r\n\r\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\r\n throw new Error(\r\n `auth.${key}: ${JSON.stringify(raw)} is not a valid ms duration — ` +\r\n `use a positive duration string such as \"1h\", \"7d\", or NO_EXPIRATION.`,\r\n );\r\n }\r\n\r\n return parsed;\r\n}\r\n\r\n/** Email-verification token lifetime used when nothing is configured. */\r\nconst DEFAULT_VERIFICATION_EXPIRES_IN = \"24h\";\r\n\r\n/** Password-reset token lifetime used when nothing is configured. */\r\nconst DEFAULT_PASSWORD_RESET_EXPIRES_IN = \"60m\";\r\n\r\n/** Passkey challenge lifetime used when nothing is configured. */\r\nconst DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN = \"5m\";\r\n\r\n/** OTP lifetime used when nothing is configured. */\r\nconst DEFAULT_OTP_EXPIRES_IN = \"5m\";\r\n\r\n/** Access-token lifetime used when nothing is configured. */\r\nconst DEFAULT_ACCESS_TOKEN_EXPIRES_IN = \"1h\";\r\n\r\n/**\r\n * Resolve an auth setting, preferring the new `auth.accessToken.*` /\r\n * `auth.refreshToken.*` key and falling back to the deprecated `auth.jwt.*`\r\n * shape — warning once per legacy key. Returns `fallback` when neither is set.\r\n *\r\n * This is the backward-compatible shim that lets existing `auth.jwt.*` configs\r\n * keep working after the config split.\r\n */\r\nfunction resolve<T>(newKey: string, legacyKey: string, fallback?: T): T {\r\n const fromNew = config.key(`auth.${newKey}`);\r\n\r\n if (fromNew !== undefined && fromNew !== null) {\r\n return fromNew as T;\r\n }\r\n\r\n const fromLegacy = config.key(`auth.${legacyKey}`);\r\n\r\n if (fromLegacy !== undefined && fromLegacy !== null) {\r\n if (!warnedLegacyKeys.has(legacyKey)) {\r\n warnedLegacyKeys.add(legacyKey);\r\n log.warn(\r\n \"auth\",\r\n \"config-deprecation\",\r\n `auth.${legacyKey} is deprecated — use auth.${newKey}`,\r\n );\r\n }\r\n\r\n return fromLegacy as T;\r\n }\r\n\r\n return fallback as T;\r\n}\r\n\r\n/**\r\n * Typed, backward-compatible access to auth configuration. The service and the\r\n * jwt signer read configuration exclusively through here, so the new split\r\n * config and the legacy `auth.jwt.*` shape both resolve the same way.\r\n */\r\nexport const authConfig = {\r\n canAuthenticate: async (user: Auth): Promise<boolean> => {\r\n const canAuthenticate = config.key<CanAuthenticate>(\r\n \"auth.canAuthenticate\",\r\n permitAuthentication,\r\n );\r\n\r\n return canAuthenticate(user);\r\n },\r\n accessToken: {\r\n /** Signing secret (legacy: `auth.jwt.secret`). Throws if neither is set. */\r\n secret: (): string => {\r\n const secret = resolve<string | undefined>(\"accessToken.secret\", \"jwt.secret\");\r\n\r\n if (!secret) {\r\n throw new Error(\"auth: no JWT secret configured — set `auth.accessToken.secret`.\");\r\n }\r\n\r\n return secret;\r\n },\r\n /** Signing algorithm (legacy: `auth.jwt.algorithm`). */\r\n algorithm: (): Algorithm => resolve(\"accessToken.algorithm\", \"jwt.algorithm\", \"HS256\"),\r\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.expiresIn`). */\r\n expiresIn: (): string | undefined => resolve(\"accessToken.expiresIn\", \"jwt.expiresIn\"),\r\n /**\r\n * Lifetime in milliseconds — the only form a token issuer may use. Defaults\r\n * to 1 hour when unset; throws naming the key when the configured value is\r\n * not a positive `ms` duration. See {@link parseDuration}.\r\n */\r\n expiresInMs: (): number =>\r\n parseDuration(\r\n \"accessToken.expiresIn\",\r\n authConfig.accessToken.expiresIn() ?? DEFAULT_ACCESS_TOKEN_EXPIRES_IN,\r\n ),\r\n },\r\n pageAuth: {\r\n /**\r\n * Login path a guarded PAGE route redirects a logged-out browser to.\r\n *\r\n * Unset (the default) ⇒ page-route auth failures keep the JSON 401 API\r\n * contract, so existing apps see NO behavior change. Set it (e.g. \"/login\")\r\n * to opt a browser-facing app into login-redirect UX: a logged-out human\r\n * navigating to a guarded page lands on the login screen instead of reading\r\n * a raw JSON error blob. Finding b9ab9804.\r\n */\r\n loginPath: (): string | undefined => config.key(\"auth.pageAuth.loginPath\"),\r\n /**\r\n * Query parameter the redirect carries the originally-requested path in, so\r\n * the login flow can send the user back where they were headed. Defaults to\r\n * `\"returnUrl\"`.\r\n */\r\n returnUrlParam: (): string => config.key(\"auth.pageAuth.returnUrlParam\", \"returnUrl\"),\r\n },\r\n cookie: {\r\n /** Cookie name `setAuthCookie`/`clearAuthCookie` use. @default \"access_token\" */\r\n name: (): string => config.key(\"auth.cookie.name\", \"access_token\"),\r\n /** Cookie `Path` attribute `setAuthCookie`/`clearAuthCookie` use. @default \"/\" */\r\n path: (): string => config.key(\"auth.cookie.path\", \"/\"),\r\n },\r\n csrf: {\r\n /**\r\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\r\n * beyond the request's own origin. @default []\r\n */\r\n allowedOrigins: (): string[] => config.key(\"auth.csrf.allowedOrigins\", []),\r\n },\r\n verification: {\r\n /** Lifetime in ms of an email-verification token; throws naming the key when unusable. @default \"24h\" */\r\n expiresInMs: (): number =>\r\n parseDuration(\r\n \"verification.expiresIn\",\r\n config.key(\"auth.verification.expiresIn\", DEFAULT_VERIFICATION_EXPIRES_IN),\r\n ),\r\n /** User attribute stamped with the verification date. @default \"emailVerifiedAt\" */\r\n field: (): string => config.key(\"auth.verification.field\", \"emailVerifiedAt\"),\r\n /** App notification replacing the default verification email. */\r\n notification: (): AuthNotification | undefined => config.key(\"auth.verification.notification\"),\r\n /** Link builder whose result is handed to the notification as `url`. */\r\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.verification.url\"),\r\n },\r\n passwordReset: {\r\n /** Lifetime in ms of a password-reset token; throws naming the key when unusable. @default \"60m\" */\r\n expiresInMs: (): number =>\r\n parseDuration(\r\n \"passwordReset.expiresIn\",\r\n config.key(\"auth.passwordReset.expiresIn\", DEFAULT_PASSWORD_RESET_EXPIRES_IN),\r\n ),\r\n /** User attribute `requestPasswordReset` looks the account up by. @default \"email\" */\r\n identifierField: (): string => config.key(\"auth.passwordReset.identifierField\", \"email\"),\r\n /** App notification replacing the default reset email. */\r\n notification: (): AuthNotification | undefined => config.key(\"auth.passwordReset.notification\"),\r\n /** Link builder whose result is handed to the notification as `url`. */\r\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.passwordReset.url\"),\r\n /** App-owned password writer replacing the default. */\r\n setPassword: (): PasswordSetter | undefined => config.key(\"auth.passwordReset.setPassword\"),\r\n },\r\n providers: {\r\n /** `auth.providers.google`, when configured. */\r\n google: (): GoogleProviderConfig | undefined => config.key(\"auth.providers.google\"),\r\n /** An app-registered provider under `auth.providers.custom.<name>`. */\r\n custom: (name: string): AuthProvider | undefined =>\r\n config.key<Record<string, AuthProvider>>(\"auth.providers.custom\", {})[name],\r\n /** User attribute a verified provider email is matched against. @default \"email\" */\r\n emailField: (): string => config.key(\"auth.providers.emailField\", \"email\"),\r\n /** App-owned user creation for a first provider login. */\r\n createUser: (): ProviderUserCreator | undefined => config.key(\"auth.providers.createUser\"),\r\n },\r\n passkeys: {\r\n /** `auth.passkeys`; throws naming the keys when `rpID`, `rpName` or `origin` is missing. */\r\n settings: (): PasskeysConfig => {\r\n const settings = config.key<PasskeysConfig | undefined>(\"auth.passkeys\");\r\n\r\n if (!settings?.rpID || !settings.rpName || !settings.origin) {\r\n throw new Error(\r\n \"@warlock.js/auth: passkeys need `auth.passkeys.rpID`, `auth.passkeys.rpName` and `auth.passkeys.origin`.\",\r\n );\r\n }\r\n\r\n return settings;\r\n },\r\n /** Allowed ceremony origins, as a list. */\r\n origins: (): string[] => {\r\n const { origin } = authConfig.passkeys.settings();\r\n\r\n return Array.isArray(origin) ? origin : [origin];\r\n },\r\n /** Challenge lifetime in ms; throws naming the key when unusable. @default \"5m\" */\r\n challengeExpiresInMs: (): number =>\r\n parseDuration(\r\n \"passkeys.challengeExpiresIn\",\r\n config.key(\"auth.passkeys.challengeExpiresIn\", DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN),\r\n ),\r\n },\r\n otp: {\r\n /** Notifications channel the code is sent through. @default \"sms\" */\r\n channel: (): string => config.key(\"auth.otp.channel\", \"sms\"),\r\n /** User attribute holding the phone number. @default \"phone\" */\r\n phoneField: (): string => config.key(\"auth.otp.phoneField\", \"phone\"),\r\n /** Code lifetime in ms; throws naming the key when unusable. @default \"5m\" */\r\n expiresInMs: (): number =>\r\n parseDuration(\"otp.expiresIn\", config.key(\"auth.otp.expiresIn\", DEFAULT_OTP_EXPIRES_IN)),\r\n /** Verify attempts before the code is invalidated. @default 5 */\r\n maxAttempts: (): number => config.key(\"auth.otp.maxAttempts\", 5),\r\n /** The message text for a code. */\r\n message: (code: string): string => {\r\n const build = config.key<((code: string) => string) | undefined>(\"auth.otp.message\");\r\n\r\n return build ? build(code) : `Your verification code is ${code}`;\r\n },\r\n /** App-owned delivery replacing the notifications channel send. */\r\n send: (): OtpSender | undefined => config.key(\"auth.otp.send\"),\r\n },\r\n refreshToken: {\r\n /** Separate refresh secret (legacy: `auth.jwt.refresh.secret`); empty ⇒ fall back to the access secret. */\r\n secret: (): string | undefined => resolve(\"refreshToken.secret\", \"jwt.refresh.secret\"),\r\n /** Whether refresh tokens are enabled (legacy: `auth.jwt.refresh.enabled`). */\r\n enabled: (): boolean => resolve(\"refreshToken.enabled\", \"jwt.refresh.enabled\", true),\r\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.refresh.expiresIn`). */\r\n expiresIn: (): string => resolve(\"refreshToken.expiresIn\", \"jwt.refresh.expiresIn\", \"7d\"),\r\n /**\r\n * Lifetime in milliseconds — the only form a token issuer may use. Throws\r\n * naming the key when the configured value is not a positive `ms` duration.\r\n */\r\n expiresInMs: (): number =>\r\n parseDuration(\"refreshToken.expiresIn\", authConfig.refreshToken.expiresIn()),\r\n /** Rotate-on-use (legacy: `auth.jwt.refresh.rotation`). */\r\n rotation: (): boolean => resolve(\"refreshToken.rotation\", \"jwt.refresh.rotation\", true),\r\n /** Max active tokens per user (legacy: `auth.jwt.refresh.maxPerUser`). */\r\n maxPerUser: (): number => resolve(\"refreshToken.maxPerUser\", \"jwt.refresh.maxPerUser\", 5),\r\n /** Logout-without-token behavior (legacy: `auth.jwt.refresh.logoutWithoutToken`). */\r\n logoutWithoutToken: (): LogoutWithoutTokenBehavior =>\r\n resolve(\"refreshToken.logoutWithoutToken\", \"jwt.refresh.logoutWithoutToken\", \"revoke-all\"),\r\n },\r\n};\r\n"],"mappings":";;;;;AAoBA,MAAM,mCAAmB,IAAI,IAAY;AAEzC,MAAM,6BAAuD;;;;;;;;;;AAW7D,MAAM,UAAU;;;;;;;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uB,OAAO,IAAI,oBAAoB,KAAK;;EAE3D,kBAA0B,OAAO,IAAI,uBAAuB,OAAO;;EAEnE,mBACE,cAAc,iBAAiB,OAAO,IAAI,sBAAsB,sBAAsB,CAAC;;EAEzF,mBAA2B,OAAO,IAAI,wBAAwB,CAAC;;EAE/D,UAAU,SAAyB;GACjC,MAAM,QAAQ,OAAO,IAA4C,kBAAkB;GAEnF,OAAO,QAAQ,MAAM,IAAI,IAAI,6BAA6B;EAC5D;;EAEA,YAAmC,OAAO,IAAI,eAAe;CAC/D;CACA,cAAc;;EAEZ,cAAkC,QAAQ,uBAAuB,oBAAoB;;EAErF,eAAwB,QAAQ,wBAAwB,uBAAuB,IAAI;;EAEnF,iBAAyB,QAAQ,0BAA0B,yBAAyB,IAAI;;;;;EAKxF,mBACE,cAAc,0BAA0B,WAAW,aAAa,UAAU,CAAC;;EAE7E,gBAAyB,QAAQ,yBAAyB,wBAAwB,IAAI;;EAEtF,kBAA0B,QAAQ,2BAA2B,0BAA0B,CAAC;;EAExF,0BACE,QAAQ,mCAAmC,kCAAkC,YAAY;CAC7F;AACF"}
1
+ {"version":3,"file":"auth-config.mjs","names":[],"sources":["../../../../../../../auth/src/services/auth-config.ts"],"sourcesContent":["import { config } from \"@warlock.js/core\";\r\nimport { log } from \"@warlock.js/logger\";\r\nimport { type Algorithm } from \"fast-jwt\";\r\nimport ms from \"ms\";\r\nimport type {\r\n AuthNotification,\r\n CanAuthenticate,\r\n LogoutWithoutTokenBehavior,\r\n OneTimeTokenUrlBuilder,\r\n PasswordSetter,\r\n} from \"../contracts/types\";\r\nimport type {\r\n AppleProviderConfig,\r\n AuthProvider,\r\n DiscordProviderConfig,\r\n FacebookProviderConfig,\r\n GitHubProviderConfig,\r\n GoogleProviderConfig,\r\n LinkedInProviderConfig,\r\n OtpSender,\r\n PasskeysConfig,\r\n ProviderUserCreator,\r\n XProviderConfig,\r\n} from \"../contracts/providers\";\r\nimport type { Auth } from \"../models/auth.model\";\r\n\r\nconst warnedLegacyKeys = new Set<string>();\r\n\r\nconst permitAuthentication: CanAuthenticate = (): boolean => true;\r\n\r\n/**\r\n * `ms` accepts anything at runtime and answers `undefined` for a string it\r\n * cannot parse (`\"30dayz\"`), a *formatted string* for a number (`2592000` ⇒\r\n * `\"43m\"`), and throws for `\"\"`. Its published types claim the far narrower\r\n * `(value: ms.StringValue) => number`, which is exactly what let an\r\n * `as ms.StringValue` cast smuggle arbitrary config text past the compiler and\r\n * hand `undefined` to the JWT signer. Declare the honest runtime signature once,\r\n * here, so every caller is forced to deal with the `undefined`.\r\n */\r\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\r\n\r\n/**\r\n * Turn a configured lifetime into a positive number of milliseconds, or throw\r\n * naming the key.\r\n *\r\n * A token lifetime is a security boundary, so an unusable value is a hard error\r\n * rather than a silent fallback: substituting a default would trade one\r\n * unintended lifetime for another, just as quietly — and quiet is the whole\r\n * problem. Every non-positive, non-finite or non-numeric parse is rejected:\r\n *\r\n * - `\"30dayz\"` / `\"thirty days\"` ⇒ `undefined` ⇒ a JWT signed with **no `exp`\r\n * claim** and an `Invalid Date` written to the token row.\r\n * - `\"0d\"` ⇒ parses cleanly to `0`, which `fast-jwt` treats as falsy and also\r\n * emits with **no `exp` claim** — it survives any guard that only rejects\r\n * `undefined`. `\"-1h\"` signs an already-expired token.\r\n * - `2592000` (a bare number) ⇒ `ms` *formats* it as `\"43m\"`, a string, which\r\n * then turns `Date.now() + expiresIn` into an `Invalid Date`.\r\n */\r\nfunction parseDuration(key: string, raw: unknown): number {\r\n let parsed: number | string | undefined;\r\n\r\n try {\r\n parsed = parseMs(raw);\r\n } catch {\r\n // ms throws (rather than returning undefined) for \"\" and non-strings\r\n parsed = undefined;\r\n }\r\n\r\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\r\n throw new Error(\r\n `auth.${key}: ${JSON.stringify(raw)} is not a valid ms duration — ` +\r\n `use a positive duration string such as \"1h\", \"7d\", or NO_EXPIRATION.`,\r\n );\r\n }\r\n\r\n return parsed;\r\n}\r\n\r\n/** Email-verification token lifetime used when nothing is configured. */\r\nconst DEFAULT_VERIFICATION_EXPIRES_IN = \"24h\";\r\n\r\n/** Password-reset token lifetime used when nothing is configured. */\r\nconst DEFAULT_PASSWORD_RESET_EXPIRES_IN = \"60m\";\r\n\r\n/** Passkey challenge lifetime used when nothing is configured. */\r\nconst DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN = \"5m\";\r\n\r\n/** OTP lifetime used when nothing is configured. */\r\nconst DEFAULT_OTP_EXPIRES_IN = \"5m\";\r\n\r\n/** Access-token lifetime used when nothing is configured. */\r\nconst DEFAULT_ACCESS_TOKEN_EXPIRES_IN = \"1h\";\r\n\r\n/**\r\n * Resolve an auth setting, preferring the new `auth.accessToken.*` /\r\n * `auth.refreshToken.*` key and falling back to the deprecated `auth.jwt.*`\r\n * shape — warning once per legacy key. Returns `fallback` when neither is set.\r\n *\r\n * This is the backward-compatible shim that lets existing `auth.jwt.*` configs\r\n * keep working after the config split.\r\n */\r\nfunction resolve<T>(newKey: string, legacyKey: string, fallback?: T): T {\r\n const fromNew = config.key(`auth.${newKey}`);\r\n\r\n if (fromNew !== undefined && fromNew !== null) {\r\n return fromNew as T;\r\n }\r\n\r\n const fromLegacy = config.key(`auth.${legacyKey}`);\r\n\r\n if (fromLegacy !== undefined && fromLegacy !== null) {\r\n if (!warnedLegacyKeys.has(legacyKey)) {\r\n warnedLegacyKeys.add(legacyKey);\r\n log.warn(\r\n \"auth\",\r\n \"config-deprecation\",\r\n `auth.${legacyKey} is deprecated — use auth.${newKey}`,\r\n );\r\n }\r\n\r\n return fromLegacy as T;\r\n }\r\n\r\n return fallback as T;\r\n}\r\n\r\n/**\r\n * Typed, backward-compatible access to auth configuration. The service and the\r\n * jwt signer read configuration exclusively through here, so the new split\r\n * config and the legacy `auth.jwt.*` shape both resolve the same way.\r\n */\r\nexport const authConfig = {\r\n canAuthenticate: async (user: Auth): Promise<boolean> => {\r\n const canAuthenticate = config.key<CanAuthenticate>(\r\n \"auth.canAuthenticate\",\r\n permitAuthentication,\r\n );\r\n\r\n return canAuthenticate(user);\r\n },\r\n accessToken: {\r\n /** Signing secret (legacy: `auth.jwt.secret`). Throws if neither is set. */\r\n secret: (): string => {\r\n const secret = resolve<string | undefined>(\"accessToken.secret\", \"jwt.secret\");\r\n\r\n if (!secret) {\r\n throw new Error(\"auth: no JWT secret configured — set `auth.accessToken.secret`.\");\r\n }\r\n\r\n return secret;\r\n },\r\n /** Signing algorithm (legacy: `auth.jwt.algorithm`). */\r\n algorithm: (): Algorithm => resolve(\"accessToken.algorithm\", \"jwt.algorithm\", \"HS256\"),\r\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.expiresIn`). */\r\n expiresIn: (): string | undefined => resolve(\"accessToken.expiresIn\", \"jwt.expiresIn\"),\r\n /**\r\n * Lifetime in milliseconds — the only form a token issuer may use. Defaults\r\n * to 1 hour when unset; throws naming the key when the configured value is\r\n * not a positive `ms` duration. See {@link parseDuration}.\r\n */\r\n expiresInMs: (): number =>\r\n parseDuration(\r\n \"accessToken.expiresIn\",\r\n authConfig.accessToken.expiresIn() ?? DEFAULT_ACCESS_TOKEN_EXPIRES_IN,\r\n ),\r\n },\r\n pageAuth: {\r\n /**\r\n * Login path a guarded PAGE route redirects a logged-out browser to.\r\n *\r\n * Unset (the default) ⇒ page-route auth failures keep the JSON 401 API\r\n * contract, so existing apps see NO behavior change. Set it (e.g. \"/login\")\r\n * to opt a browser-facing app into login-redirect UX: a logged-out human\r\n * navigating to a guarded page lands on the login screen instead of reading\r\n * a raw JSON error blob. Finding b9ab9804.\r\n */\r\n loginPath: (): string | undefined => config.key(\"auth.pageAuth.loginPath\"),\r\n /**\r\n * Query parameter the redirect carries the originally-requested path in, so\r\n * the login flow can send the user back where they were headed. Defaults to\r\n * `\"returnUrl\"`.\r\n */\r\n returnUrlParam: (): string => config.key(\"auth.pageAuth.returnUrlParam\", \"returnUrl\"),\r\n },\r\n cookie: {\r\n /** Cookie name `setAuthCookie`/`clearAuthCookie` use. @default \"access_token\" */\r\n name: (): string => config.key(\"auth.cookie.name\", \"access_token\"),\r\n /** Cookie `Path` attribute `setAuthCookie`/`clearAuthCookie` use. @default \"/\" */\r\n path: (): string => config.key(\"auth.cookie.path\", \"/\"),\r\n },\r\n csrf: {\r\n /**\r\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\r\n * beyond the request's own origin. @default []\r\n */\r\n allowedOrigins: (): string[] => config.key(\"auth.csrf.allowedOrigins\", []),\r\n },\r\n verification: {\r\n /** Lifetime in ms of an email-verification token; throws naming the key when unusable. @default \"24h\" */\r\n expiresInMs: (): number =>\r\n parseDuration(\r\n \"verification.expiresIn\",\r\n config.key(\"auth.verification.expiresIn\", DEFAULT_VERIFICATION_EXPIRES_IN),\r\n ),\r\n /** User attribute stamped with the verification date. @default \"emailVerifiedAt\" */\r\n field: (): string => config.key(\"auth.verification.field\", \"emailVerifiedAt\"),\r\n /** App notification replacing the default verification email. */\r\n notification: (): AuthNotification | undefined => config.key(\"auth.verification.notification\"),\r\n /** Link builder whose result is handed to the notification as `url`. */\r\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.verification.url\"),\r\n },\r\n passwordReset: {\r\n /** Lifetime in ms of a password-reset token; throws naming the key when unusable. @default \"60m\" */\r\n expiresInMs: (): number =>\r\n parseDuration(\r\n \"passwordReset.expiresIn\",\r\n config.key(\"auth.passwordReset.expiresIn\", DEFAULT_PASSWORD_RESET_EXPIRES_IN),\r\n ),\r\n /** User attribute `requestPasswordReset` looks the account up by. @default \"email\" */\r\n identifierField: (): string => config.key(\"auth.passwordReset.identifierField\", \"email\"),\r\n /** App notification replacing the default reset email. */\r\n notification: (): AuthNotification | undefined => config.key(\"auth.passwordReset.notification\"),\r\n /** Link builder whose result is handed to the notification as `url`. */\r\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.passwordReset.url\"),\r\n /** App-owned password writer replacing the default. */\r\n setPassword: (): PasswordSetter | undefined => config.key(\"auth.passwordReset.setPassword\"),\r\n },\r\n providers: {\r\n /** `auth.providers.google`, when configured. */\r\n google: (): GoogleProviderConfig | undefined => config.key(\"auth.providers.google\"),\r\n /** `auth.providers.github`, when configured. */\r\n github: (): GitHubProviderConfig | undefined => config.key(\"auth.providers.github\"),\r\n /** `auth.providers.discord`, when configured. */\r\n discord: (): DiscordProviderConfig | undefined => config.key(\"auth.providers.discord\"),\r\n /** `auth.providers.linkedin`, when configured. */\r\n linkedin: (): LinkedInProviderConfig | undefined => config.key(\"auth.providers.linkedin\"),\r\n /** `auth.providers.apple`, when configured. */\r\n apple: (): AppleProviderConfig | undefined => config.key(\"auth.providers.apple\"),\r\n /** `auth.providers.facebook`, when configured. */\r\n facebook: (): FacebookProviderConfig | undefined => config.key(\"auth.providers.facebook\"),\r\n /** `auth.providers.x`, when configured. */\r\n x: (): XProviderConfig | undefined => config.key(\"auth.providers.x\"),\r\n /** An app-registered provider under `auth.providers.custom.<name>`. */\r\n custom: (name: string): AuthProvider | undefined => {\r\n const providers = config.key<Record<string, AuthProvider>>(\"auth.providers.custom\", {});\r\n\r\n // Own keys only: `name` arrives from a URL, and \"constructor\" must not resolve to Object.\r\n return Object.hasOwn(providers, name) ? providers[name] : undefined;\r\n },\r\n /** User attribute a verified provider email is matched against. @default \"email\" */\r\n emailField: (): string => config.key(\"auth.providers.emailField\", \"email\"),\r\n /** App-owned user creation for a first provider login. */\r\n createUser: (): ProviderUserCreator | undefined => config.key(\"auth.providers.createUser\"),\r\n },\r\n passkeys: {\r\n /** `auth.passkeys`; throws naming the keys when `rpID`, `rpName` or `origin` is missing. */\r\n settings: (): PasskeysConfig => {\r\n const settings = config.key<PasskeysConfig | undefined>(\"auth.passkeys\");\r\n\r\n if (!settings?.rpID || !settings.rpName || !settings.origin) {\r\n throw new Error(\r\n \"@warlock.js/auth: passkeys need `auth.passkeys.rpID`, `auth.passkeys.rpName` and `auth.passkeys.origin`.\",\r\n );\r\n }\r\n\r\n return settings;\r\n },\r\n /** Allowed ceremony origins, as a list. */\r\n origins: (): string[] => {\r\n const { origin } = authConfig.passkeys.settings();\r\n\r\n return Array.isArray(origin) ? origin : [origin];\r\n },\r\n /** Challenge lifetime in ms; throws naming the key when unusable. @default \"5m\" */\r\n challengeExpiresInMs: (): number =>\r\n parseDuration(\r\n \"passkeys.challengeExpiresIn\",\r\n config.key(\"auth.passkeys.challengeExpiresIn\", DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN),\r\n ),\r\n },\r\n otp: {\r\n /** Notifications channel the code is sent through. @default \"sms\" */\r\n channel: (): string => config.key(\"auth.otp.channel\", \"sms\"),\r\n /** User attribute holding the phone number. @default \"phone\" */\r\n phoneField: (): string => config.key(\"auth.otp.phoneField\", \"phone\"),\r\n /** Code lifetime in ms; throws naming the key when unusable. @default \"5m\" */\r\n expiresInMs: (): number =>\r\n parseDuration(\"otp.expiresIn\", config.key(\"auth.otp.expiresIn\", DEFAULT_OTP_EXPIRES_IN)),\r\n /** Verify attempts before the code is invalidated. @default 5 */\r\n maxAttempts: (): number => config.key(\"auth.otp.maxAttempts\", 5),\r\n /** The message text for a code. */\r\n message: (code: string): string => {\r\n const build = config.key<((code: string) => string) | undefined>(\"auth.otp.message\");\r\n\r\n return build ? build(code) : `Your verification code is ${code}`;\r\n },\r\n /** App-owned delivery replacing the notifications channel send. */\r\n send: (): OtpSender | undefined => config.key(\"auth.otp.send\"),\r\n },\r\n refreshToken: {\r\n /** Separate refresh secret (legacy: `auth.jwt.refresh.secret`); empty ⇒ fall back to the access secret. */\r\n secret: (): string | undefined => resolve(\"refreshToken.secret\", \"jwt.refresh.secret\"),\r\n /** Whether refresh tokens are enabled (legacy: `auth.jwt.refresh.enabled`). */\r\n enabled: (): boolean => resolve(\"refreshToken.enabled\", \"jwt.refresh.enabled\", true),\r\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.refresh.expiresIn`). */\r\n expiresIn: (): string => resolve(\"refreshToken.expiresIn\", \"jwt.refresh.expiresIn\", \"7d\"),\r\n /**\r\n * Lifetime in milliseconds — the only form a token issuer may use. Throws\r\n * naming the key when the configured value is not a positive `ms` duration.\r\n */\r\n expiresInMs: (): number =>\r\n parseDuration(\"refreshToken.expiresIn\", authConfig.refreshToken.expiresIn()),\r\n /** Rotate-on-use (legacy: `auth.jwt.refresh.rotation`). */\r\n rotation: (): boolean => resolve(\"refreshToken.rotation\", \"jwt.refresh.rotation\", true),\r\n /** Max active tokens per user (legacy: `auth.jwt.refresh.maxPerUser`). */\r\n maxPerUser: (): number => resolve(\"refreshToken.maxPerUser\", \"jwt.refresh.maxPerUser\", 5),\r\n /** Logout-without-token behavior (legacy: `auth.jwt.refresh.logoutWithoutToken`). */\r\n logoutWithoutToken: (): LogoutWithoutTokenBehavior =>\r\n resolve(\"refreshToken.logoutWithoutToken\", \"jwt.refresh.logoutWithoutToken\", \"revoke-all\"),\r\n },\r\n};\r\n"],"mappings":";;;;;AA0BA,MAAM,mCAAmB,IAAI,IAAY;AAEzC,MAAM,6BAAuD;;;;;;;;;;AAW7D,MAAM,UAAU;;;;;;;;;;;;;;;;;;AAmBhB,SAAS,cAAc,KAAa,KAAsB;CACxD,IAAI;CAEJ,IAAI;EACF,SAAS,QAAQ,GAAG;CACtB,QAAQ;EAEN,SAAS;CACX;CAEA,IAAI,OAAO,WAAW,YAAY,CAAC,OAAO,SAAS,MAAM,KAAK,UAAU,GACtE,MAAM,IAAI,MACR,QAAQ,IAAI,IAAI,KAAK,UAAU,GAAG,EAAE,mGAEtC;CAGF,OAAO;AACT;;AAGA,MAAM,kCAAkC;;AAGxC,MAAM,oCAAoC;;AAG1C,MAAM,uCAAuC;;AAG7C,MAAM,yBAAyB;;AAG/B,MAAM,kCAAkC;;;;;;;;;AAUxC,SAAS,QAAW,QAAgB,WAAmB,UAAiB;CACtE,MAAM,UAAU,OAAO,IAAI,QAAQ,QAAQ;CAE3C,IAAI,YAAY,UAAa,YAAY,MACvC,OAAO;CA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