@warlock.js/auth 5.53.0 โ 5.53.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/esm/commands/auth-cleanup-command.mjs.map +1 -1
- package/esm/commands/auth-purge-never-expiring-command.mjs.map +1 -1
- package/esm/commands/jwt-secret-generator-command.mjs.map +1 -1
- package/esm/contracts/types.mjs.map +1 -1
- package/esm/errors/auth-provider-sdk-missing.error.mjs.map +1 -1
- package/esm/errors/email-not-verified.error.mjs.map +1 -1
- package/esm/errors/invalid-one-time-token.error.mjs.map +1 -1
- package/esm/errors/invalid-passkey.error.mjs.map +1 -1
- package/esm/errors/invalid-provider-callback.error.mjs.map +1 -1
- package/esm/errors/notifications-unavailable.error.mjs.map +1 -1
- package/esm/errors/provider-account-link-blocked.error.mjs.map +1 -1
- package/esm/errors/provider-email-not-verified.error.mjs.map +1 -1
- package/esm/localization/ar.translations.mjs.map +1 -1
- package/esm/localization/auth-default-translations.mjs.map +1 -1
- package/esm/localization/en.translations.mjs.map +1 -1
- package/esm/localization/init.mjs.map +1 -1
- package/esm/localization/register-auth-translations.mjs.map +1 -1
- package/esm/middleware/auth.middleware.mjs.map +1 -1
- package/esm/middleware/csrf-origin-check.mjs.map +1 -1
- package/esm/middleware/localized-login-path.mjs.map +1 -1
- package/esm/middleware/login-throttle.middleware.mjs.map +1 -1
- package/esm/middleware/one-time-token-throttle.middleware.mjs.map +1 -1
- package/esm/middleware/otp-throttle.middleware.mjs.map +1 -1
- package/esm/middleware/require-verified-email.middleware.mjs.map +1 -1
- package/esm/models/access-token/access-token.model.mjs.map +1 -1
- package/esm/models/access-token/family-association.migration.mjs.map +1 -1
- package/esm/models/access-token/migration.mjs.map +1 -1
- package/esm/models/auth-token-family/auth-token-family.model.mjs.map +1 -1
- package/esm/models/auth-token-family/migration.mjs.map +1 -1
- package/esm/models/auth.model.mjs.map +1 -1
- package/esm/models/index.mjs.map +1 -1
- package/esm/models/one-time-token/migration.mjs.map +1 -1
- package/esm/models/one-time-token/one-time-token.model.mjs.map +1 -1
- package/esm/models/passkey-credential/migration.mjs.map +1 -1
- package/esm/models/passkey-credential/passkey-credential.model.mjs.map +1 -1
- package/esm/models/provider-account/migration.mjs.map +1 -1
- package/esm/models/provider-account/provider-account.model.mjs.map +1 -1
- package/esm/models/refresh-token/migration.mjs.map +1 -1
- package/esm/models/refresh-token/refresh-token.model.mjs.map +1 -1
- package/esm/models/refresh-token/successor-association.migration.mjs.map +1 -1
- package/esm/otp/otp.mjs.map +1 -1
- package/esm/passkeys/passkey-authentication.mjs.map +1 -1
- package/esm/passkeys/passkey-challenges.mjs.map +1 -1
- package/esm/passkeys/passkey-registration.mjs.map +1 -1
- package/esm/passkeys/simplewebauthn.mjs.map +1 -1
- package/esm/providers/apple-provider.mjs.map +1 -1
- package/esm/providers/discord-provider.mjs.map +1 -1
- package/esm/providers/facebook-provider.mjs.map +1 -1
- package/esm/providers/github-provider.mjs.map +1 -1
- package/esm/providers/google-provider.mjs.map +1 -1
- package/esm/providers/linkedin-provider.mjs.map +1 -1
- package/esm/providers/provider-login.mjs.map +1 -1
- package/esm/providers/provider-state-cookie.mjs.map +1 -1
- package/esm/providers/provider-timeout.mjs.map +1 -1
- package/esm/providers/resolve-provider-user.mjs.map +1 -1
- package/esm/providers/x-provider.mjs.map +1 -1
- package/esm/services/auth-config.mjs.map +1 -1
- package/esm/services/auth-cookie-names.mjs.map +1 -1
- package/esm/services/auth-events.mjs.map +1 -1
- package/esm/services/auth.service.mjs.map +1 -1
- package/esm/services/current-user.mjs.map +1 -1
- package/esm/services/email-verification.mjs.map +1 -1
- package/esm/services/generate-jwt-secret.mjs.map +1 -1
- package/esm/services/jwt.mjs.map +1 -1
- package/esm/services/one-time-tokens.mjs.map +1 -1
- package/esm/services/optional-peer.mjs.map +1 -1
- package/esm/services/password-reset.mjs.map +1 -1
- package/esm/services/resolve-request-user.mjs.map +1 -1
- package/esm/services/token-family-operation.mjs.map +1 -1
- package/esm/services/token-notifications.mjs.map +1 -1
- package/esm/session/page-session.mjs.map +1 -1
- package/esm/utils/auth-error-codes.mjs.map +1 -1
- package/esm/utils/normalize-credentials.mjs.map +1 -1
- package/esm/utils/safe-equal.mjs.map +1 -1
- package/esm/utils/token-digest.mjs.map +1 -1
- package/esm/utils/token-expiry.mjs.map +1 -1
- package/package.json +8 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-cleanup-command.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/commands/auth-cleanup-command.ts"],"mappings":";;;;;;;;;;;;;AAYA,SAAgB,6BAA6B;CAC3C,OAAO,QAAQ;EACb,MAAM;EACN,aAAa;EACb,SAAS;GACP,KAAK;GACL,QAAQ,CAAC,QAAQ,UAAU;GAC3B,YAAY,CAAC,UAAU;EACzB;EACA,QAAQ,YAAY;GAClB,QAAQ,IAAI,OAAO,KAAK,kCAAkC,CAAC;GAE3D,MAAM,QAAQ,MAAM,YAAY,qBAAqB;GAErD,IAAI,UAAU,GACZ,QAAQ,IAAI,OAAO,MAAM,4BAA4B,CAAC;QAEtD,QAAQ,IAAI,OAAO,MAAM,aAAa,MAAM,mBAAmB,CAAC;EAEpE;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"auth-cleanup-command.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/commands/auth-cleanup-command.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport { command } from \"@warlock.js/core\";\nimport { authService } from \"../services/auth.service\";\n\n/**\n * Register the auth:cleanup CLI command\n *\n * @example\n * ```bash\n * warlock auth:cleanup\n * ```\n */\nexport function registerAuthCleanupCommand() {\n return command({\n name: \"auth.cleanup\",\n description: \"Remove expired access/refresh tokens and spent one-time tokens from the database\",\n preload: {\n env: true,\n config: [\"auth\", \"database\"],\n connectors: [\"database\"],\n },\n action: async () => {\n console.log(colors.cyan(\"๐งน Cleaning up expired tokens...\"));\n\n const count = await authService.cleanupExpiredTokens();\n\n if (count === 0) {\n console.log(colors.green(\"โ
No expired tokens found.\"));\n } else {\n console.log(colors.green(`โ
Removed ${count} expired token(s).`));\n }\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,SAAgB,6BAA6B;CAC3C,OAAO,QAAQ;EACb,MAAM;EACN,aAAa;EACb,SAAS;GACP,KAAK;GACL,QAAQ,CAAC,QAAQ,UAAU;GAC3B,YAAY,CAAC,UAAU;EACzB;EACA,QAAQ,YAAY;GAClB,QAAQ,IAAI,OAAO,KAAK,kCAAkC,CAAC;GAE3D,MAAM,QAAQ,MAAM,YAAY,qBAAqB;GAErD,IAAI,UAAU,GACZ,QAAQ,IAAI,OAAO,MAAM,4BAA4B,CAAC;QAEtD,QAAQ,IAAI,OAAO,MAAM,aAAa,MAAM,mBAAmB,CAAC;EAEpE;CACF,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-purge-never-expiring-command.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/commands/auth-purge-never-expiring-command.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,wCAAwC;CACtD,OAAO,QAAQ;EACb,MAAM;EACN,aACE;EACF,SAAS,CACP;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR,CACF;EACA,SAAS;GACP,KAAK;GACL,QAAQ,CAAC,QAAQ,UAAU;GAC3B,YAAY,CAAC,UAAU;EACzB;EACA,QAAQ,OAAO,OAA8C,CAAC,MAAM;GAQlE,MAAM,QAAQ,KAAK,WAAW,CAAC;GAC/B,MAAM,OAAO,MAAM,aAAa,MAAM;GACtC,MAAM,SAAS,SAAS,UAAa,SAAS,SAAS,SAAS;GAEhE,QAAQ,IAAI,OAAO,KAAK,iDAAiD,CAAC;GAE1E,MAAM,EAAE,cAAc,kBAAkB,MAAM,YAAY,wBAAwB;GAClF,MAAM,QAAQ,aAAa,SAAS,cAAc;GAElD,IAAI,UAAU,GAAG;IACf,QAAQ,IAAI,OAAO,MAAM,mCAAmC,CAAC;IAE7D;GACF;GAEA,QAAQ,IACN,OAAO,OACL,OAAO,MAAM,4BACR,aAAa,OAAO,WAAW,cAAc,OAAO,UAC3D,CACF;GAKA,KAAK,MAAM,SAAS,cAClB,QAAQ,IACN,OAAO,OACL,gBAAgB,MAAM,GAAG,WAAW,MAAM,IAAI,SAAS,EAAE,aAC1C,MAAM,IAAI,WAAW,EAAE,cAAc,OAAO,MAAM,IAAI,YAAY,CAAC,GACpF,CACF;GAGF,KAAK,MAAM,SAAS,eAClB,QAAQ,IACN,OAAO,OACL,gBAAgB,MAAM,GAAG,WAAW,MAAM,IAAI,SAAS,EAAE,aAC1C,MAAM,IAAI,WAAW,EAAE,cAAc,OAAO,MAAM,IAAI,YAAY,CAAC,GACpF,CACF;GAGF,IAAI,QAAQ;IACV,QAAQ,IACN,OAAO,KACL,6EACF,CACF;IAEA;GACF;GAMA,MAAM,SAAS,MAAM,YAAY,yBAAyB;GAE1D,QAAQ,IACN,OAAO,MACL,aAAa,OAAO,aAAa,uBAC5B,OAAO,cAAc,qDAC5B,CACF;EACF;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"auth-purge-never-expiring-command.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/commands/auth-purge-never-expiring-command.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport { command } from \"@warlock.js/core\";\nimport { authService } from \"../services/auth.service\";\n\n/**\n * Register the `auth.purge-never-expiring` CLI command โ remediation for the\n * pre-4.12.0 `expiresIn` defect (#25).\n *\n * **Why a command and not a migration.** The rows this removes cannot be\n * selected by a date predicate (an `Invalid Date` compares `false` against\n * every date, so `WHERE expires_at < now()` never matches one) and the\n * definitive signal โ a token with no `exp` claim โ lives inside the JWT\n * string, not in a column. A migration would also run once, silently, at deploy\n * time; an operator dealing with possibly-leaked credentials needs to *look*\n * first, then act, and to repeat it. Hence `--dry-run`, which is the default\n * posture this command is expected to be run in first.\n *\n * A migration is additionally the wrong shape for a fix that must reach both\n * supported stores: the same row is a different thing in MongoDB and Postgres,\n * and this goes through the models so a registered override\n * (`config.auth.accessToken.model`) is honoured.\n *\n * @example\n * ```bash\n * warlock auth.purge-never-expiring --dry-run # report only\n * warlock auth.purge-never-expiring # report, then delete\n * ```\n */\nexport function registerAuthPurgeNeverExpiringCommand() {\n return command({\n name: \"auth.purge-never-expiring\",\n description:\n \"Find (and delete) token rows that can never expire โ an unusable expires_at, or a token with no exp claim\",\n options: [\n {\n text: \"--dry-run\",\n description: \"Report the affected rows without deleting anything\",\n type: \"boolean\",\n },\n ],\n preload: {\n env: true,\n config: [\"auth\", \"database\"],\n connectors: [\"database\"],\n },\n action: async (data: { options?: Record<string, unknown> } = {}) => {\n // Core camelCases flags (`--dry-run` โ `dryRun`); both spellings are read\n // so the command does not depend on that detail staying true.\n //\n // Read fail-safe: the flag counts as set unless it is *explicitly* false\n // (`--dry-run=false`). An operator who asked to look before deleting and\n // got a delete because a flag arrived as `\"true\"` instead of `true` would\n // lose live credentials to a parsing detail.\n const flags = data.options ?? {};\n const flag = flags[\"dryRun\"] ?? flags[\"dry-run\"];\n const dryRun = flag !== undefined && flag !== false && flag !== \"false\";\n\n console.log(colors.cyan(\"๐ Scanning for tokens that can never expire...\"));\n\n const { accessTokens, refreshTokens } = await authService.findNeverExpiringTokens();\n const total = accessTokens.length + refreshTokens.length;\n\n if (total === 0) {\n console.log(colors.green(\"โ
No never-expiring tokens found.\"));\n\n return;\n }\n\n console.log(\n colors.yellow(\n `โ ๏ธ ${total} never-expiring token(s): ` +\n `${accessTokens.length} access, ${refreshTokens.length} refresh.`,\n ),\n );\n\n // Identify each row so an operator can correlate with their own audit\n // trail before (or after) the rows are gone. The token string itself is\n // never printed โ it is a live credential until this command removes it.\n for (const token of accessTokens) {\n console.log(\n colors.yellow(\n ` access id=${token.id} user_id=${token.get(\"user_id\")} ` +\n `user_type=${token.get(\"user_type\")} expires_at=${String(token.get(\"expires_at\"))}`,\n ),\n );\n }\n\n for (const token of refreshTokens) {\n console.log(\n colors.yellow(\n ` refresh id=${token.id} user_id=${token.get(\"user_id\")} ` +\n `user_type=${token.get(\"user_type\")} expires_at=${String(token.get(\"expires_at\"))}`,\n ),\n );\n }\n\n if (dryRun) {\n console.log(\n colors.cyan(\n \"Dry run โ nothing deleted. Re-run without --dry-run to revoke these tokens.\",\n ),\n );\n\n return;\n }\n\n // Re-selects rather than deleting the rows just listed: the delete then\n // acts on the table's current state instead of a snapshot taken before\n // the operator read the report. A second full scan is affordable here โ\n // this is a one-off remediation, not a request path.\n const purged = await authService.purgeNeverExpiringTokens();\n\n console.log(\n colors.green(\n `โ
Revoked ${purged.accessTokens} access token(s) and ` +\n `${purged.refreshTokens} refresh token(s). Affected users must log in again.`,\n ),\n );\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,wCAAwC;CACtD,OAAO,QAAQ;EACb,MAAM;EACN,aACE;EACF,SAAS,CACP;GACE,MAAM;GACN,aAAa;GACb,MAAM;EACR,CACF;EACA,SAAS;GACP,KAAK;GACL,QAAQ,CAAC,QAAQ,UAAU;GAC3B,YAAY,CAAC,UAAU;EACzB;EACA,QAAQ,OAAO,OAA8C,CAAC,MAAM;GAQlE,MAAM,QAAQ,KAAK,WAAW,CAAC;GAC/B,MAAM,OAAO,MAAM,aAAa,MAAM;GACtC,MAAM,SAAS,SAAS,UAAa,SAAS,SAAS,SAAS;GAEhE,QAAQ,IAAI,OAAO,KAAK,iDAAiD,CAAC;GAE1E,MAAM,EAAE,cAAc,kBAAkB,MAAM,YAAY,wBAAwB;GAClF,MAAM,QAAQ,aAAa,SAAS,cAAc;GAElD,IAAI,UAAU,GAAG;IACf,QAAQ,IAAI,OAAO,MAAM,mCAAmC,CAAC;IAE7D;GACF;GAEA,QAAQ,IACN,OAAO,OACL,OAAO,MAAM,4BACR,aAAa,OAAO,WAAW,cAAc,OAAO,UAC3D,CACF;GAKA,KAAK,MAAM,SAAS,cAClB,QAAQ,IACN,OAAO,OACL,gBAAgB,MAAM,GAAG,WAAW,MAAM,IAAI,SAAS,EAAE,aAC1C,MAAM,IAAI,WAAW,EAAE,cAAc,OAAO,MAAM,IAAI,YAAY,CAAC,GACpF,CACF;GAGF,KAAK,MAAM,SAAS,eAClB,QAAQ,IACN,OAAO,OACL,gBAAgB,MAAM,GAAG,WAAW,MAAM,IAAI,SAAS,EAAE,aAC1C,MAAM,IAAI,WAAW,EAAE,cAAc,OAAO,MAAM,IAAI,YAAY,CAAC,GACpF,CACF;GAGF,IAAI,QAAQ;IACV,QAAQ,IACN,OAAO,KACL,6EACF,CACF;IAEA;GACF;GAMA,MAAM,SAAS,MAAM,YAAY,yBAAyB;GAE1D,QAAQ,IACN,OAAO,MACL,aAAa,OAAO,aAAa,uBAC5B,OAAO,cAAc,qDAC5B,CACF;EACF;CACF,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jwt-secret-generator-command.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/commands/jwt-secret-generator-command.ts"],"mappings":";;;;AAGA,SAAgB,oCAAoC;CAClD,OAAO,QAAQ;EACb,MAAM;EACN,aAAa;EACb,QAAQ;CACV,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"jwt-secret-generator-command.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/commands/jwt-secret-generator-command.ts"],"sourcesContent":["import { command } from \"@warlock.js/core\";\nimport { generateJWTSecret } from \"../services/generate-jwt-secret\";\n\nexport function registerJWTSecretGeneratorCommand() {\n return command({\n name: \"jwt.generate\",\n description: \"Generate JWT Secret key in .env file\",\n action: generateJWTSecret,\n });\n}\n"],"mappings":";;;;AAGA,SAAgB,oCAAoC;CAClD,OAAO,QAAQ;EACb,MAAM;EACN,aAAa;EACb,QAAQ;CACV,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/contracts/types.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,gBAAgB"}
|
|
1
|
+
{"version":3,"file":"types.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/contracts/types.ts"],"sourcesContent":["import { type ChildModel } from \"@warlock.js/cascade\";\nimport type { Request } from \"@warlock.js/core\";\nimport { type Algorithm } from \"fast-jwt\";\nimport type { AccessToken } from \"../models/access-token\";\nimport type { Auth } from \"../models/auth.model\";\nimport type { OneTimeToken } from \"../models/one-time-token\";\nimport type { OtpConfig, PasskeysConfig, ProvidersConfig } from \"./providers\";\nimport type { RefreshToken } from \"../models/refresh-token\";\n\n/**\n * Symbol to indicate no expiration for tokens\n * Use this when you explicitly want tokens to never expire\n *\n * @example\n * ```typescript\n * // src/config/auth.ts\n * import { NO_EXPIRATION, type AuthConfigurations } from \"@warlock.js/auth\";\n *\n * const authConfigurations: AuthConfigurations = {\n * accessToken: {\n * secret: env(\"JWT_SECRET\"),\n * expiresIn: NO_EXPIRATION, // Token expires within 100 years\n * },\n * };\n *\n * export default authConfigurations;\n * ```\n */\nexport const NO_EXPIRATION = \"100y\";\n\n/**\n * Behavior when logout is called without a refresh token\n * - \"revoke-all\": Revoke all refresh tokens for the user (secure default)\n * - \"error\": Return an error requiring the refresh token\n */\nexport type LogoutWithoutTokenBehavior = \"revoke-all\" | \"error\";\n\n/** The single request credential source an auth middleware instance accepts. */\nexport type TokenFrom = \"header\" | `cookie:${string}`;\n\n/** One explicitly named credential location accepted by auth middleware. */\nexport interface AuthCredentialDescriptor {\n source: \"header\" | \"cookie\";\n key?: string;\n}\n\n/** Cookie credential and bounded duplicate window for automatic renewal. */\nexport interface AuthRefreshCredentialDescriptor extends AuthCredentialDescriptor {\n /** Milliseconds; the service clamps this to the 0รขโฌโ10 second range (default 5 seconds). */\n overlapMs?: number;\n}\n\n/** Per-route authentication behavior for the object middleware overload. */\nexport interface AuthMiddlewareOptions extends Partial<AuthCredentialDescriptor> {\n optional?: boolean;\n /**\n * Accept both a header and a cookie credential (at most one of each).\n * Precedence is fixed and independent of array order: a present\n * `Authorization` header wins, an invalid header rejects and never falls back\n * to the cookie, and renewal plus the CSRF Origin check apply only when the\n * cookie is the credential actually used. Cannot be combined with `source`.\n */\n sources?: AuthCredentialDescriptor[];\n /** Opt-in automatic renewal credential. Cookie sources only. */\n refresh?: AuthRefreshCredentialDescriptor;\n redirect?: { to: string; returnUrlParam?: string };\n}\n\n/** Application policy that decides whether a resolved user may authenticate. */\nexport type CanAuthenticate = (user: Auth) => boolean | Promise<boolean>;\n\n/** Password credentials plus the application-defined identity fields. */\nexport type AuthCredentials = Record<string, unknown> & {\n password: string;\n};\n\n/**\n * Rewrites the identity fields of a login (everything except `password`)\n * before the user lookup.\n */\nexport type NormalizeCredentials = (\n identifiers: Omit<AuthCredentials, \"password\">,\n) => Omit<AuthCredentials, \"password\">;\n\n/**\n * Access-token configuration.\n *\n * `secret` may also be supplied via the deprecated `jwt.secret` (resolved by a\n * backward-compatible shim); one of the two is required at runtime.\n */\nexport type AccessTokenConfig = {\n /**\n * Override the persisted access-token model โ extend {@link AccessToken} to\n * add columns (e.g. a tenant key) or rename them, then register the subclass\n * here. Defaults to the package's `AccessToken`.\n */\n model?: typeof AccessToken;\n /**\n * Secret used to sign access tokens.\n */\n secret?: string;\n /**\n * JWT algorithm.\n * @default \"HS256\"\n */\n algorithm?: Algorithm;\n /**\n * Access-token lifetime โ a duration string `ms` parses to a **positive**\n * number of milliseconds. A value `ms` cannot parse (`\"30dayz\"`), a\n * non-positive one (`\"0d\"`), or a bare number throws naming this key on the\n * first token issue: each of them would otherwise sign a token with no `exp`\n * claim at all.\n * @example \"1h\" or NO_EXPIRATION\n * @default \"1h\"\n */\n expiresIn?: string;\n /**\n * Issuer (`iss` claim) stamped on every access and refresh token this app\n * signs, and required on every token it accepts. Set it when several apps\n * or services share a signing secret, so a token minted by one is refused\n * by the others. Unset (the default) โ no `iss` is stamped or checked.\n *\n * Tokens signed before it was set carry no `iss` and are refused once it is\n * set, so every signed-in user signs in again once.\n * @example \"https://api.example.com\"\n */\n issuer?: string;\n /**\n * Audience (`aud` claim) stamped on every token this app signs, and\n * required on every token it accepts (a token matches when its `aud`\n * includes one of the values). Unset (the default) โ no `aud` is stamped or\n * checked. Like `issuer`, setting it signs everyone out once.\n * @example \"web-app\"\n */\n audience?: string | string[];\n};\n\n/**\n * Refresh-token configuration.\n */\nexport type RefreshTokenConfig = {\n /**\n * Override the persisted refresh-token model โ extend {@link RefreshToken}.\n * Defaults to the package's `RefreshToken`.\n */\n model?: typeof RefreshToken;\n /**\n * Enable refresh tokens.\n * @default true\n */\n enabled?: boolean;\n /**\n * Separate secret for refresh tokens (recommended for security). Falls back\n * to the access-token secret when omitted.\n */\n secret?: string;\n /**\n * Refresh-token lifetime โ a duration string `ms` parses to a **positive**\n * number of milliseconds; an unusable value throws naming this key on issue\n * (see {@link AccessTokenConfig.expiresIn}).\n * @example \"7d\" or \"1w\"\n * @default \"7d\"\n */\n expiresIn?: string;\n /**\n * Rotate the refresh token on each use (old token revoked, replay detected).\n * @default true\n */\n rotation?: boolean;\n /**\n * Maximum active refresh tokens per user; the oldest are revoked past it.\n * @default 5\n */\n maxPerUser?: number;\n /**\n * Behavior when logout is called without a refresh token.\n * @default \"revoke-all\"\n */\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n};\n\n/**\n * Legacy JWT configuration shape. Still honored by the resolver shim with a\n * deprecation warning.\n *\n * @deprecated Use the top-level `accessToken` / `refreshToken` blocks.\n */\nexport type LegacyJwtConfig = {\n secret?: string;\n algorithm?: Algorithm;\n expiresIn?: string;\n refresh?: {\n secret?: string;\n enabled?: boolean;\n expiresIn?: string;\n rotation?: boolean;\n maxPerUser?: number;\n logoutWithoutToken?: LogoutWithoutTokenBehavior;\n };\n};\n\n/**\n * Page-route auth-failure behavior. When a guarded PAGE route (a React-SSR page,\n * `route.isPage`) rejects a logged-out browser, this decides whether it redirects\n * to a login page instead of returning the API-style JSON 401.\n *\n * Read at runtime through `authConfig.pageAuth` (`auth.pageAuth.*`). API routes\n * always keep the JSON 401 contract regardless of this setting.\n */\nexport type PageAuthConfig = {\n /**\n * Login path a guarded page route redirects a logged-out browser to (e.g.\n * `\"/login\"`). Unset โ page-route auth failures keep the JSON 401, so the\n * behavior is opt-in and backward-compatible.\n */\n loginPath?: string;\n /**\n * Query parameter the redirect carries the originally-requested path in, so\n * the login flow can send the user back where they were headed.\n * @default \"returnUrl\"\n */\n returnUrlParam?: string;\n};\n\n/**\n * Data every email-verification / password-reset notification receives.\n */\nexport type OneTimeTokenNotificationData = {\n /** The raw token โ the only place it exists; only its SHA-256 hash is stored. */\n token: string;\n /** When the token stops working. */\n expiresAt: Date;\n /** The link built by `auth.verification.url` / `auth.passwordReset.url`, when configured. */\n url?: string;\n};\n\n/**\n * Anything auth can deliver a token through โ a `defineNotification(...)`\n * result satisfies it, as does any object with a compatible `send`.\n */\nexport type AuthNotification = {\n send: (to: Auth, data: OneTimeTokenNotificationData) => unknown;\n};\n\n/** Builds the link a token notification points at. */\nexport type OneTimeTokenUrlBuilder = (token: string, user: Auth) => string;\n\n/** Persists a new plaintext password for a user during a password reset. */\nexport type PasswordSetter = (user: Auth, plainPassword: string) => void | Promise<void>;\n\n/**\n * Email-verification configuration (`auth.verification`).\n */\nexport type EmailVerificationConfig = {\n /**\n * Token lifetime โ a positive `ms` duration string.\n * @default \"24h\"\n */\n expiresIn?: string;\n /**\n * User attribute stamped with the verification `Date`. Declare it in the\n * user schema (e.g. `emailVerifiedAt: v.date().optional()`).\n * @default \"emailVerifiedAt\"\n */\n field?: string;\n /** Replace the default verification email. */\n notification?: AuthNotification;\n /** Build the verification link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n};\n\n/**\n * Password-reset configuration (`auth.passwordReset`).\n */\nexport type PasswordResetConfig = {\n /**\n * Token lifetime โ a positive `ms` duration string.\n * @default \"60m\"\n */\n expiresIn?: string;\n /**\n * User attribute `requestPasswordReset` looks the account up by.\n * @default \"email\"\n */\n identifierField?: string;\n /** Replace the default reset email. */\n notification?: AuthNotification;\n /** Build the reset link passed to the notification as `url`. */\n url?: OneTimeTokenUrlBuilder;\n /**\n * Persist the new password yourself. By default auth saves a hash made by\n * the same `hashPassword` login verifies against, and falls back to the\n * plaintext when the model hashes on save (`useHashedPassword()`), checking\n * the stored value with `verifyPassword` either way.\n */\n setPassword?: PasswordSetter;\n /**\n * Wait for the reset notification before `requestPasswordReset` resolves,\n * so a delivery error reaches the caller. Off by default: the notification\n * is sent in the background, so the response time does not reveal whether\n * the account exists. A background failure is logged and emitted as\n * `password.resetDeliveryFailed`.\n * @default false\n */\n awaitDelivery?: boolean;\n};\n\n/**\n * One-time token storage configuration (`auth.oneTimeToken`).\n */\nexport type OneTimeTokenConfig = {\n /** Override the persisted model โ extend {@link OneTimeToken}. */\n model?: typeof OneTimeToken;\n};\n\nexport type AuthConfigurations = {\n /**\n * Define all user types โ maps a user-type slug to its `Auth` model class so\n * tokens and the middleware can resolve the right model.\n */\n userType: {\n [userType: string]: ChildModel<Auth>;\n };\n /** Default user type used by `authMiddleware()` and options-only overloads. */\n defaultUserType?: string;\n /**\n * Decide whether a resolved user may authenticate or receive new tokens.\n * @default () => true\n */\n canAuthenticate?: CanAuthenticate;\n /**\n * How login identifiers are normalized before the user lookup. Default:\n * string values are trimmed and the `email` field is lower-cased, so\n * `\" Sara@x.io\"` finds the account stored as `sara@x.io`. If that finds no\n * user and the normalized value differs from what was sent (trimmed), the\n * lookup is retried once with the value as sent, so rows stored with capitals\n * keep working. Pass a function to normalize your own way (the retry still\n * applies), or `false` for exact matching.\n *\n * The login throttle buckets `email` by trimmed, lower-cased value either way.\n * @default trim string values, lower-case `email`\n */\n normalizeCredentials?: false | NormalizeCredentials;\n /**\n * Store only a SHA-256 digest of each access and refresh token in the\n * database, never the token itself, so a copy of the token tables (a\n * backup, a replica, a read-only injection) cannot be replayed as a login.\n *\n * No migration is needed: the digest goes in the existing `token` column,\n * and lookups accept both forms, so rows issued before the switch keep\n * working until they expire, and turning it off again signs no one out.\n * A row loaded from storage no longer carries its raw token; a freshly\n * issued one exposes it as `row.plainToken`.\n * @default false\n */\n hashTokensAtRest?: boolean;\n /**\n * Access-token configuration (secret, expiry, algorithm, model override).\n */\n accessToken?: AccessTokenConfig;\n /**\n * Refresh-token configuration (rotation, lifetime, cap, model override).\n */\n refreshToken?: RefreshTokenConfig;\n /**\n * Page-route auth-failure behavior โ set `loginPath` to redirect a logged-out\n * browser on a guarded PAGE route to a login page instead of the JSON 401.\n * Opt-in; API routes are unaffected. Read via `authConfig.pageAuth`.\n */\n pageAuth?: PageAuthConfig;\n /**\n * Cookie auth session config โ read by `authService.setAuthCookie` /\n * `clearAuthCookie`. Opt-in: unset โ the helpers fall back to their own\n * defaults (`name: \"access_token\"`, `path: \"/\"`).\n */\n cookie?: CookieAuthConfig;\n /**\n * CSRF Origin-check config for cookie-authenticated unsafe-method requests.\n */\n csrf?: CsrfConfig;\n /**\n * Email verification โ token lifetime, verified field, notification override.\n */\n verification?: EmailVerificationConfig;\n /**\n * Password reset โ token lifetime, lookup field, notification and password-writer overrides.\n */\n passwordReset?: PasswordResetConfig;\n /**\n * One-time token (verification / reset) storage โ model override.\n */\n oneTimeToken?: OneTimeTokenConfig;\n /**\n * Redirect login providers (`google`, `custom`) and account-linking policy.\n */\n providers?: ProvidersConfig;\n /**\n * Passkey (WebAuthn) relying-party settings. Requires `@simplewebauthn/server`.\n */\n passkeys?: PasskeysConfig;\n /**\n * Phone one-time-code login โ channel, lifetime, attempts, delivery.\n */\n otp?: OtpConfig;\n /**\n * @deprecated Use `accessToken` / `refreshToken`. Read via a backward-compatible shim.\n */\n jwt?: LegacyJwtConfig;\n};\n\nexport type AccessTokenOutput = {\n /**\n * JWT Token\n */\n token: string;\n /**\n * Exprie time in ISO format UTC time\n */\n expiresAt: string;\n};\n\n/**\n * Token pair returned after login or token refresh\n */\nexport type TokenPair = {\n /**\n * JWT access token (short-lived)\n */\n accessToken: AccessTokenOutput;\n /**\n * JWT refresh token (long-lived)\n */\n refreshToken?: AccessTokenOutput;\n};\n\n/**\n * Device information for session tracking\n */\nexport type DeviceInfo = {\n /**\n * User agent string from request\n */\n userAgent?: string;\n /**\n * Client IP address\n */\n ip?: string;\n /**\n * Optional device identifier\n */\n deviceId?: string;\n /**\n * Token family ID (for rotation tracking)\n * @internal\n */\n familyId?: string;\n /**\n * Access token payload\n */\n payload?: Record<string, unknown>;\n};\n\nexport type LoginResult<UserType extends Auth> = {\n user: UserType;\n tokens: TokenPair;\n};\n\n/** Selects a cookie Domain for one request; return `undefined` for a host-only cookie. */\nexport type CookieDomainResolver = (request: Request) => string | undefined;\n\n/**\n * Configuration for the cookie an app opts into via `authService.setAuthCookie`\n * / `clearAuthCookie` and reads back with `authMiddleware([], \"cookie:<name>\")`.\n * Attribute flags (`httpOnly` / `sameSite` / `secure`) are deliberately NOT\n * configurable here โ they come from core's `secureCookieDefaults()`, the\n * same floor every `response.cookie()` call gets, so a cookie auth session can\n * never be weakened to a laxer policy than the framework default.\n */\nexport type CookieAuthConfig = {\n /**\n * Cookie name `setAuthCookie`/`clearAuthCookie` write and clear, and that a\n * `cookie:<name>` token source must match to read it back.\n * @default \"access_token\"\n */\n name?: string;\n /**\n * Cookie name the session helpers write and clear for the refresh token.\n * @default \"refresh_token\"\n */\n refreshName?: string;\n /**\n * Cookie `Path` attribute.\n * @default \"/\"\n */\n path?: string;\n /** Select a request-scoped Domain; `undefined` keeps the cookie host-only. */\n cookieDomain?: CookieDomainResolver;\n /**\n * Write the auth cookies under a `__Host-` name prefix (`__Host-access_token`,\n * `__Host-refresh_token`). Browsers accept such a cookie only when it is\n * Secure, has `Path=/` and no `Domain`, so a subdomain or a plain-HTTP page\n * cannot plant or overwrite the session cookie. Requires `path: \"/\"` and no\n * `cookieDomain`; a write that breaks either rule throws naming the setting.\n *\n * While switching, the unprefixed cookie is still read (so signed-in users\n * stay signed in) and both names are cleared on logout.\n * @default false\n */\n hostPrefix?: boolean;\n};\n\n/**\n * CSRF Origin-check configuration. Read via\n * `authConfig.csrf.allowedOrigins()`.\n */\nexport type CsrfConfig = {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * in addition to the request's own origin.\n * @default []\n */\n allowedOrigins?: string[];\n};\n\n/**\n * Per-call overrides for {@link AuthService.setAuthCookie}. Anything omitted\n * falls back to `auth.cookie.*` config, then the package default. Cookie\n * *attribute* flags (`httpOnly`/`sameSite`/`secure`) are never settable here โ\n * see {@link CookieAuthConfig}.\n */\nexport type SetAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). */\n path?: string;\n /** Cookie `Domain` attribute. Omit for a host-only cookie. */\n domain?: string;\n /**\n * `Max-Age`, in seconds. Overrides the expiry `setAuthCookie` would\n * otherwise derive from an `AccessTokenOutput`'s `expiresAt`. Passing a\n * bare token string with no `maxAge` produces a session cookie (cleared\n * when the browser closes).\n */\n maxAge?: number;\n};\n\n/** Per-call overrides for {@link AuthService.clearAuthCookie}. */\nexport type ClearAuthCookieOptions = {\n /** Cookie name; defaults to `auth.cookie.name` (package default `\"access_token\"`). */\n name?: string;\n /** Cookie `Path`; defaults to `auth.cookie.path` (package default `\"/\"`). Must match the `Path` the cookie was set with. */\n path?: string;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4BA,MAAa,gBAAgB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-provider-sdk-missing.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/auth-provider-sdk-missing.error.ts"],"mappings":";;;;;;;;;AAQA,IAAa,8BAAb,cAAiD,YAAY;CAC3D,AAAO,YACL,AAAgB,aAChB,AAAgB,SAChB,OACA;EACA,MACE,8CAA8C,YAAY,gDACnC,QAAQ,IACjC;EAPgB;EACA;EAOhB,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF"}
|
|
1
|
+
{"version":3,"file":"auth-provider-sdk-missing.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/auth-provider-sdk-missing.error.ts"],"sourcesContent":["import { ServerError } from \"@warlock.js/core\";\n\n/**\n * A login method needs a vendor SDK that is an optional peer of\n * `@warlock.js/auth` and is not installed. The message names the package and\n * the `warlock add` command that installs it; the resolver failure is kept on\n * `cause`.\n */\nexport class AuthProviderSdkMissingError extends ServerError {\n public constructor(\n public readonly packageName: string,\n public readonly feature: string,\n cause?: unknown,\n ) {\n super(\n `@warlock.js/auth: this login method needs \"${packageName}\", which is not installed โ ` +\n `run \\`warlock add ${feature}\\`.`,\n );\n this.name = \"AuthProviderSdkMissingError\";\n this.cause = cause;\n }\n}\n"],"mappings":";;;;;;;;;AAQA,IAAa,8BAAb,cAAiD,YAAY;CAC3D,AAAO,YACL,AAAgB,aAChB,AAAgB,SAChB,OACA;EACA,MACE,8CAA8C,YAAY,gDACnC,QAAQ,IACjC;EAPgB;EACA;EAOhB,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"email-not-verified.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/email-not-verified.error.ts"],"mappings":";;;;;;;;;AAQA,IAAa,wBAAb,cAA2C,eAAe;CAGxD,AAAO,YAAY,UAAU,kCAAkC;EAC7D,MAAM,SAAS,EAAE,mBAA2C,CAAC;;EAC7D,KAAK,OAAO;CACd;AACF"}
|
|
1
|
+
{"version":3,"file":"email-not-verified.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/email-not-verified.error.ts"],"sourcesContent":["import { ForbiddenError } from \"@warlock.js/core\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/**\n * The authenticated user has not verified their email address. Thrown by\n * `requireVerifiedEmail()`; core's error handler answers it with `403` and a\n * `payload.errorCode` of `EC007`.\n */\nexport class EmailNotVerifiedError extends ForbiddenError {\n public readonly code = AuthErrorCodes.EmailNotVerified;\n\n public constructor(message = \"Email address is not verified.\") {\n super(message, { errorCode: AuthErrorCodes.EmailNotVerified });\n this.name = \"EmailNotVerifiedError\";\n }\n}\n"],"mappings":";;;;;;;;;AAQA,IAAa,wBAAb,cAA2C,eAAe;CAGxD,AAAO,YAAY,UAAU,kCAAkC;EAC7D,MAAM,SAAS,EAAE,mBAA2C,CAAC;;EAC7D,KAAK,OAAO;CACd;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"invalid-one-time-token.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/invalid-one-time-token.error.ts"],"mappings":";;;;;;;;;;AASA,IAAa,2BAAb,cAA8C,gBAAgB;CAG5D,AAAO,YAAY,UAAU,6BAA6B;EACxD,MAAM,SAAS,EAAE,mBAA8C,CAAC;;EAChE,KAAK,OAAO;CACd;AACF"}
|
|
1
|
+
{"version":3,"file":"invalid-one-time-token.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/invalid-one-time-token.error.ts"],"sourcesContent":["import { BadRequestError } from \"@warlock.js/core\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/**\n * An email-verification or password-reset token was rejected: unknown, issued\n * for the other purpose, expired, or already consumed (including losing a\n * concurrent consumption race). Deliberately ONE error for all of them, so a\n * caller cannot probe which case applies. Answers `400` with `EC008`.\n */\nexport class InvalidOneTimeTokenError extends BadRequestError {\n public readonly code = AuthErrorCodes.InvalidOneTimeToken;\n\n public constructor(message = \"Invalid or expired token.\") {\n super(message, { errorCode: AuthErrorCodes.InvalidOneTimeToken });\n this.name = \"InvalidOneTimeTokenError\";\n }\n}\n"],"mappings":";;;;;;;;;;AASA,IAAa,2BAAb,cAA8C,gBAAgB;CAG5D,AAAO,YAAY,UAAU,6BAA6B;EACxD,MAAM,SAAS,EAAE,mBAA8C,CAAC;;EAChE,KAAK,OAAO;CACd;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"invalid-passkey.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/invalid-passkey.error.ts"],"mappings":";;;;;;;;;;AASA,IAAa,sBAAb,cAAyC,gBAAgB;CAGvD,AAAO,YACL,AAAgB,QAChB,OACA;EACA,MAAM,gCAAgC,EAAE,mBAAyC,CAAC;EAHlE;;EAIhB,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF"}
|
|
1
|
+
{"version":3,"file":"invalid-passkey.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/invalid-passkey.error.ts"],"sourcesContent":["import { BadRequestError } from \"@warlock.js/core\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/**\n * A passkey registration or authentication was rejected โ unknown, expired\n * or used challenge, unknown credential, failed verification, or a signature\n * counter that did not advance. `reason` is for logs; the message stays\n * generic. Answers `400` with `EC011`.\n */\nexport class InvalidPasskeyError extends BadRequestError {\n public readonly code = AuthErrorCodes.InvalidPasskey;\n\n public constructor(\n public readonly reason: string,\n cause?: unknown,\n ) {\n super(\"Passkey verification failed.\", { errorCode: AuthErrorCodes.InvalidPasskey });\n this.name = \"InvalidPasskeyError\";\n this.cause = cause;\n }\n}\n"],"mappings":";;;;;;;;;;AASA,IAAa,sBAAb,cAAyC,gBAAgB;CAGvD,AAAO,YACL,AAAgB,QAChB,OACA;EACA,MAAM,gCAAgC,EAAE,mBAAyC,CAAC;EAHlE;;EAIhB,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"invalid-provider-callback.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/invalid-provider-callback.error.ts"],"mappings":";;;;;;;;;;AASA,IAAa,+BAAb,cAAkD,gBAAgB;CAGhE,AAAO,YACL,AAAgB,QAChB,OACA;EACA,MAAM,mCAAmC,EACvC,mBACF,CAAC;EALe;;EAMhB,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF"}
|
|
1
|
+
{"version":3,"file":"invalid-provider-callback.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/invalid-provider-callback.error.ts"],"sourcesContent":["import { BadRequestError } from \"@warlock.js/core\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/**\n * A redirect-provider callback was rejected โ missing, forged or expired\n * state cookie, `state` mismatch, failed code exchange, or an id_token with a\n * bad signature, issuer, audience, expiry or nonce. `reason` is for logs;\n * the response message stays generic. Answers `400` with `EC009`.\n */\nexport class InvalidProviderCallbackError extends BadRequestError {\n public readonly code = AuthErrorCodes.InvalidProviderCallback;\n\n public constructor(\n public readonly reason: string,\n cause?: unknown,\n ) {\n super(\"Login with the provider failed.\", {\n errorCode: AuthErrorCodes.InvalidProviderCallback,\n });\n this.name = \"InvalidProviderCallbackError\";\n this.cause = cause;\n }\n}\n"],"mappings":";;;;;;;;;;AASA,IAAa,+BAAb,cAAkD,gBAAgB;CAGhE,AAAO,YACL,AAAgB,QAChB,OACA;EACA,MAAM,mCAAmC,EACvC,mBACF,CAAC;EALe;;EAMhB,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"notifications-unavailable.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/notifications-unavailable.error.ts"],"mappings":";;;;;;;;;AAQA,IAAa,gCAAb,cAAmD,YAAY;CAC7D,AAAO,YAAY,QAA4C,OAAiB;EAC9E,MACE,WAAW,kBACP,+JAEA,oLAGN;EACA,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF"}
|
|
1
|
+
{"version":3,"file":"notifications-unavailable.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/notifications-unavailable.error.ts"],"sourcesContent":["import { ServerError } from \"@warlock.js/core\";\n\n/**\n * Email verification / password reset could not send its notification because\n * `@warlock.js/notifications` is not installed or not configured. Thrown BEFORE\n * any token is issued โ auth never issues a token it cannot deliver, and never\n * skips the send silently. The original failure is kept on `cause`.\n */\nexport class NotificationsUnavailableError extends ServerError {\n public constructor(reason: \"not-installed\" | \"not-configured\", cause?: unknown) {\n super(\n reason === \"not-installed\"\n ? \"@warlock.js/auth: email verification and password reset send through \" +\n \"@warlock.js/notifications, which is not installed โ add it to the app's dependencies.\"\n : \"@warlock.js/auth: email verification and password reset send through \" +\n \"@warlock.js/notifications, which is not configured โ add `src/config/notifications.ts` \" +\n \"with a `mail` channel.\",\n );\n this.name = \"NotificationsUnavailableError\";\n this.cause = cause;\n }\n}\n"],"mappings":";;;;;;;;;AAQA,IAAa,gCAAb,cAAmD,YAAY;CAC7D,AAAO,YAAY,QAA4C,OAAiB;EAC9E,MACE,WAAW,kBACP,+JAEA,oLAGN;EACA,KAAK,OAAO;EACZ,KAAK,QAAQ;CACf;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-account-link-blocked.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/provider-account-link-blocked.error.ts"],"mappings":";;;;;;;;;;;AAUA,IAAa,kCAAb,cAAqD,eAAe;CAGlE,AAAO,YACL,UAAU,oIACV;EACA,MAAM,SAAS,EAAE,mBAAqD,CAAC;;EACvE,KAAK,OAAO;CACd;AACF"}
|
|
1
|
+
{"version":3,"file":"provider-account-link-blocked.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/provider-account-link-blocked.error.ts"],"sourcesContent":["import { ForbiddenError } from \"@warlock.js/core\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/**\n * A provider login found an existing account with the same email, but\n * `auth.providers.linkExisting` does not allow linking it automatically โ\n * by default because that account never verified the address. Answers `403`\n * with `EC012`. The user signs in with their password (or verifies their\n * email) first; the provider can then be linked from a signed-in session.\n */\nexport class ProviderAccountLinkBlockedError extends ForbiddenError {\n public readonly code = AuthErrorCodes.ProviderAccountLinkBlocked;\n\n public constructor(\n message = \"An account with this email already exists. Sign in with your password first, then link this provider from your account settings.\",\n ) {\n super(message, { errorCode: AuthErrorCodes.ProviderAccountLinkBlocked });\n this.name = \"ProviderAccountLinkBlockedError\";\n }\n}\n"],"mappings":";;;;;;;;;;;AAUA,IAAa,kCAAb,cAAqD,eAAe;CAGlE,AAAO,YACL,UAAU,oIACV;EACA,MAAM,SAAS,EAAE,mBAAqD,CAAC;;EACvE,KAAK,OAAO;CACd;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-email-not-verified.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/provider-email-not-verified.error.ts"],"mappings":";;;;;;;;;AAQA,IAAa,gCAAb,cAAmD,eAAe;CAGhE,AAAO,YAAY,UAAU,qDAAqD;EAChF,MAAM,SAAS,EAAE,mBAAmD,CAAC;;EACrE,KAAK,OAAO;CACd;AACF"}
|
|
1
|
+
{"version":3,"file":"provider-email-not-verified.error.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/errors/provider-email-not-verified.error.ts"],"sourcesContent":["import { ForbiddenError } from \"@warlock.js/core\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/**\n * The provider did not verify the email on a profile with no existing link,\n * so auth refused to link it to (or create) an account. Answers `403` with\n * `EC010`.\n */\nexport class ProviderEmailNotVerifiedError extends ForbiddenError {\n public readonly code = AuthErrorCodes.ProviderEmailNotVerified;\n\n public constructor(message = \"The provider has not verified this email address.\") {\n super(message, { errorCode: AuthErrorCodes.ProviderEmailNotVerified });\n this.name = \"ProviderEmailNotVerifiedError\";\n }\n}\n"],"mappings":";;;;;;;;;AAQA,IAAa,gCAAb,cAAmD,eAAe;CAGhE,AAAO,YAAY,UAAU,qDAAqD;EAChF,MAAM,SAAS,EAAE,mBAAmD,CAAC;;EACrE,KAAK,OAAO;CACd;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ar.translations.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/ar.translations.ts"],"mappings":";;;;;AAMA,MAAa,yBAA2C,EACtD,MAAM,EACJ,QAAQ;CACN,oBAAoB;CACpB,oBAAoB;CACpB,cAAc;CACd,oBAAoB;CACpB,iBAAiB;AACnB,EACF,EACF"}
|
|
1
|
+
{"version":3,"file":"ar.translations.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/ar.translations.ts"],"sourcesContent":["import type { AuthTranslations } from \"./auth-translations.type\";\n\n/**\n * Built-in Arabic text for auth's translation keys. Applications override\n * any of these by registering the same key in their own locale files.\n */\nexport const authArabicTranslations: AuthTranslations = {\n auth: {\n errors: {\n missingAccessToken: \"ุฑู
ุฒ ุงููุตูู ู
ูููุฏ.\",\n invalidAccessToken: \"ุฑู
ุฒ ุงููุตูู ุบูุฑ ุตุงูุญ ุฃู ู
ูุชูู ุงูุตูุงุญูุฉ.\",\n unauthorized: \"ุบูุฑ ู
ุตุฑุญ ูู ุจุงููุตูู ุฅูู ูุฐุง ุงูู
ูุฑุฏ.\",\n csrfOriginMismatch: \"ู
ุตุฏุฑ ุงูุทูุจ ุบูุฑ ู
ุณู
ูุญ ุจู.\",\n tooManyAttempts: \"ู
ุญุงููุงุช ูุซูุฑุฉ ุฌุฏูุง. ูุฑุฌู ุงูู
ุญุงููุฉ ู
ุฑุฉ ุฃุฎุฑู ูุงุญููุง.\",\n },\n },\n};\n"],"mappings":";;;;;AAMA,MAAa,yBAA2C,EACtD,MAAM,EACJ,QAAQ;CACN,oBAAoB;CACpB,oBAAoB;CACpB,cAAc;CACd,oBAAoB;CACpB,iBAAiB;AACnB,EACF,EACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-default-translations.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/auth-default-translations.ts"],"mappings":";;;;;;;AAOA,MAAa,0BAA4D;CACvE,IAAI;CACJ,IAAI;AACN"}
|
|
1
|
+
{"version":3,"file":"auth-default-translations.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/auth-default-translations.ts"],"sourcesContent":["import { authArabicTranslations } from \"./ar.translations\";\nimport type { AuthTranslations } from \"./auth-translations.type\";\nimport { authEnglishTranslations } from \"./en.translations\";\n\n/**\n * Every locale auth ships default text for, keyed by locale code.\n */\nexport const authDefaultTranslations: Record<string, AuthTranslations> = {\n en: authEnglishTranslations,\n ar: authArabicTranslations,\n};\n"],"mappings":";;;;;;;AAOA,MAAa,0BAA4D;CACvE,IAAI;CACJ,IAAI;AACN"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"en.translations.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/en.translations.ts"],"mappings":";;;;;AAMA,MAAa,0BAA4C,EACvD,MAAM,EACJ,QAAQ;CACN,oBAAoB;CACpB,oBAAoB;CACpB,cAAc;CACd,oBAAoB;CACpB,iBAAiB;AACnB,EACF,EACF"}
|
|
1
|
+
{"version":3,"file":"en.translations.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/en.translations.ts"],"sourcesContent":["import type { AuthTranslations } from \"./auth-translations.type\";\n\n/**\n * Built-in English text for auth's translation keys. Applications override\n * any of these by registering the same key in their own locale files.\n */\nexport const authEnglishTranslations: AuthTranslations = {\n auth: {\n errors: {\n missingAccessToken: \"Missing access token.\",\n invalidAccessToken: \"Invalid or expired access token.\",\n unauthorized: \"You are not authorized to access this resource.\",\n csrfOriginMismatch: \"Request origin is not allowed.\",\n tooManyAttempts: \"Too many attempts. Please try again later.\",\n },\n },\n};\n"],"mappings":";;;;;AAMA,MAAa,0BAA4C,EACvD,MAAM,EACJ,QAAQ;CACN,oBAAoB;CACpB,oBAAoB;CACpB,cAAc;CACd,oBAAoB;CACpB,iBAAiB;AACnB,EACF,EACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/init.ts"],"mappings":";;;AAIA,yBAAyB"}
|
|
1
|
+
{"version":3,"file":"init.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/init.ts"],"sourcesContent":["import { registerAuthTranslations } from \"./register-auth-translations\";\n\n// Side-effect module: importing `@warlock.js/auth` registers its default\n// translations, so `t(\"auth.errors.*\")` never returns the raw key.\nregisterAuthTranslations();\n"],"mappings":";;;AAIA,yBAAyB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"register-auth-translations.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/register-auth-translations.ts"],"mappings":";;;;;;;;;;;;;;;;;AAgBA,SAAgB,2BAAiC;CAC/C,KAAK,MAAM,CAAC,YAAY,iBAAiB,OAAO,QAAQ,uBAAuB,GAAG;EAChF,MAAM,WAAW,kBAAkB,UAAU,KAAK,CAAC;EACnD,MAAM,UAAoB,CAAC;EAE3B,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,QAAQ,YAAY,CAAC,GAC5D,IAAI,IAAI,UAAU,GAAG,MAAM,QACzB,IAAI,SAAS,KAAK,IAAI;EAI1B,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,GAChC,OAAO,YAAY,OAAO;CAE9B;AACF"}
|
|
1
|
+
{"version":3,"file":"register-auth-translations.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/localization/register-auth-translations.ts"],"sourcesContent":["import { flatten, get, set } from \"@mongez/reinforcements\";\nimport { extend, getKeywordsListOf, type Keywords } from \"@warlock.js/core\";\nimport { authDefaultTranslations } from \"./auth-default-translations\";\n\n/**\n * Register auth's built-in translations with `@mongez/localization`, the\n * same store `t()` from `@warlock.js/core` reads.\n *\n * Only keys the application has NOT already translated are added, so an app\n * translation wins regardless of load order: registered before this runs, it\n * is left untouched; registered after, `extend()` merges it over the default.\n * An app locale file that predates a newer auth key therefore gets the\n * default text for that key instead of the raw key string.\n *\n * Runs once at import of `@warlock.js/auth`; safe to call again.\n */\nexport function registerAuthTranslations(): void {\n for (const [localeCode, translations] of Object.entries(authDefaultTranslations)) {\n const existing = getKeywordsListOf(localeCode) ?? {};\n const missing: Keywords = {};\n\n for (const [key, text] of Object.entries(flatten(translations))) {\n if (get(existing, key) === undefined) {\n set(missing, key, text);\n }\n }\n\n if (Object.keys(missing).length > 0) {\n extend(localeCode, missing);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgBA,SAAgB,2BAAiC;CAC/C,KAAK,MAAM,CAAC,YAAY,iBAAiB,OAAO,QAAQ,uBAAuB,GAAG;EAChF,MAAM,WAAW,kBAAkB,UAAU,KAAK,CAAC;EACnD,MAAM,UAAoB,CAAC;EAE3B,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,QAAQ,YAAY,CAAC,GAC5D,IAAI,IAAI,UAAU,GAAG,MAAM,QACzB,IAAI,SAAS,KAAK,IAAI;EAI1B,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,GAChC,OAAO,YAAY,OAAO;CAE9B;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/auth.middleware.ts"],"mappings":";;;;;;;;;;;;;;AAsBA,MAAa,6BAA6B,OAAO,IAAI,cAAc;;;;;;;;;;;;;;;;;;;AAsCnE,SAAS,mBACP,EAAE,SAAS,YACX,SACA,UACA;CACA,MAAM,YAAY,UAAU,MAAM,WAAW,SAAS,UAAU;CAChE,MAAM,iBAAiB,UAAU,kBAAkB,WAAW,SAAS,eAAe;CAEtF,IAAI,aAAa,QAAQ,OAAO,QAAQ;EAMtC,MAAM,cAAc,mBAAmB,WAAW,QAAQ,MAAM;EAChE,MAAM,YAAY,YAAY,SAAS,GAAG,IAAI,MAAM;EACpD,MAAM,YAAY,mBAAmB,QAAQ,GAAG;EAEhD,OAAO,SAAS,SAAS,GAAG,cAAc,YAAY,eAAe,GAAG,WAAW;CACrF;CAEA,OAAO,SAAS,aAAa,OAAO;AACtC;AAEA,SAAS,oBAAoB,YAA0D;CACrF,IAAI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E,0BAA0B;GACnC;EACF,CAAC;EAGH,OAAO,OAAO;GACZ,OAAO,EAAE,gCAAgC;GACzC;EACF,CAAC;CACH;CAEA,MAAM,oBAAsD,cACxD,CAAC,GAAI,aAAc,CAAC,QAAQ,IAAc,CAAC,GAAI,GAAG,YAAY,IAAI,gBAAgB,CAAC,IACnF,CAAC,iBAAiB,SAAS,CAAC;CAChC,MAAM,aAAuC,OAAO,OAAO;EACzD,GAAI,WAAW,EAAE,UAAU,MAAM,IAAI,CAAC;EACtC,SAAS,OAAO,OACd,kBAAkB,KAAK,WACrB,OAAO,WAAW,WAAW,SAAS,OAAO,OAAO,EAAE,GAAG,OAAO,CAAC,CACnE,CACF;EACA,WAAW,OAAO,OAAO,CAAC,GAAG,YAAY,CAAC;CAC5C,CAAC;CAGD,OAAO,eAAe,MAAM,4BAA4B;EAAE,OAAO;EAAY,YAAY;CAAM,CAAC;CAKhG,OAAO,cAAc,MAAM,CAAC,QAAQ;AACtC"}
|
|
1
|
+
{"version":3,"file":"auth.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/auth.middleware.ts"],"sourcesContent":["import { config, type HttpContext, markAuthGuard, t, type Middleware } from \"@warlock.js/core\";\nimport { log } from \"@warlock.js/logger\";\nimport type {\n AuthCredentialDescriptor,\n AuthMiddlewareOptions,\n TokenFrom,\n} from \"../contracts/types\";\nimport { authConfig } from \"../services/auth-config\";\nimport { readCredential, resolveRequestUserOutcome } from \"../services/resolve-request-user\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\nimport {\n assertCsrfOriginAllowed,\n CsrfOriginMismatchError,\n requiresCsrfOriginCheck,\n} from \"./csrf-origin-check\";\nimport { localizedLoginPath } from \"./localized-login-path\";\n\n/**\n * Well-known symbol under which `authMiddleware()` tags the middleware it\n * returns. Shared via the global symbol registry so other packages can read the\n * descriptor structurally (`Symbol.for(\"warlock.auth\")`) without importing auth.\n */\nexport const AUTH_MIDDLEWARE_DESCRIPTOR = Symbol.for(\"warlock.auth\");\n\n/** A credential source an auth middleware reads: the Authorization header or a named cookie. */\nexport type AuthMiddlewareDescriptorSource = \"header\" | { cookie: string };\n\n/**\n * Frozen, JSON-safe description of how an `authMiddleware()` instance\n * authenticates, stored (non-enumerably) under {@link AUTH_MIDDLEWARE_DESCRIPTOR}.\n */\nexport type AuthMiddlewareDescriptor = {\n /** Resolved credential sources; with dual sources the header comes first. */\n sources: AuthMiddlewareDescriptorSource[];\n required?: boolean;\n /** Resolved allowed user types; an empty array means any authenticated user. */\n userTypes: string[];\n};\n\n/** The 401 body shape every rejection in this middleware carries. */\ntype UnauthorizedPayload = { error: string; errorCode: string };\n\n/**\n * Reject an unauthenticated request, choosing the representation by ROUTE KIND.\n *\n * An API route always gets the JSON 401 it has always gotten. A PAGE route\n * (`request.route.isPage` โ the React-SSR pages) instead redirects a logged-out\n * browser to the configured login path with a `returnUrl`, so a human\n * navigating to a guarded page lands on the login screen rather than reading a\n * raw JSON error blob โ the defect in finding b9ab9804.\n *\n * The redirect is OPT-IN and backward-compatible: with no `auth.pageAuth.loginPath`\n * configured, even a page route falls back to the JSON 401, so an app that has\n * not asked for page-login UX keeps exactly its current behavior. The API 401\n * contract is never changed for API routes.\n *\n * `returnUrl` carries `request.url` โ the relative path + query the browser was\n * on โ never the absolute URL: a relative target cannot be turned into an\n * open-redirect off this app's origin.\n */\nfunction rejectUnauthorized(\n { request, response }: HttpContext,\n payload: UnauthorizedPayload,\n redirect?: AuthMiddlewareOptions[\"redirect\"],\n) {\n const loginPath = redirect?.to ?? authConfig.pageAuth.loginPath();\n const returnUrlParam = redirect?.returnUrlParam ?? authConfig.pageAuth.returnUrlParam();\n\n if (loginPath && request.route?.isPage) {\n // Under an active `web.localeRouting` strategy, the login destination\n // itself must carry the request's locale prefix โ otherwise an anonymous\n // `/ar/admin` bounces to the DEFAULT locale's `/login` rather than\n // `/ar/login`, even though `returnUrl` below correctly points back at\n // `/ar/admin`. See `./localized-login-path.ts`.\n const destination = localizedLoginPath(loginPath, request.locale);\n const separator = destination.includes(\"?\") ? \"&\" : \"?\";\n const returnUrl = encodeURIComponent(request.url);\n\n return response.redirect(`${destination}${separator}${returnUrlParam}=${returnUrl}`);\n }\n\n return response.unauthorized(payload);\n}\n\nfunction tokenFromDescriptor(descriptor: Partial<AuthCredentialDescriptor>): TokenFrom {\n if (!descriptor.source || descriptor.source === \"header\") return \"header\";\n\n if (!descriptor.key) {\n throw new Error(\"authMiddleware cookie credentials require a cookie key.\");\n }\n\n return `cookie:${descriptor.key}`;\n}\n\nfunction descriptorSource(tokenFrom: TokenFrom): AuthMiddlewareDescriptorSource {\n return tokenFrom === \"header\" ? \"header\" : { cookie: tokenFrom.slice(\"cookie:\".length) };\n}\n\nfunction resolveAllowedTypes(value: string | string[] | undefined): string[] {\n if (value !== undefined) return Array.isArray(value) ? value : [value];\n\n const configuredDefault = config.key(\"auth.defaultUserType\") as string | undefined;\n\n if (configuredDefault) return [configuredDefault];\n\n const userTypes = config.key(\"auth.userType\", {}) as Record<string, unknown>;\n const configuredTypes = Object.keys(userTypes);\n\n if (configuredTypes.length === 1) return configuredTypes;\n\n throw new Error(\n \"authMiddleware requires a user type when auth.defaultUserType is unset and multiple user types exist.\",\n );\n}\n\n/**\n * Build a route gate. Authentication is required unless optional is explicit.\n *\n * An omitted user type selects the configured default; an explicit argument\n * selects which user types may pass:\n * - `[]` โ any authenticated user (token required, type not checked).\n * - `\"admin\"` / `[\"admin\", \"staff\"]` โ token required AND the user's\n * `userType` must be one of the listed types.\n *\n * `{ optional: true }` allows anonymous requests. All other forms reject\n * missing or invalid credentials with 401, or a configured page redirect.\n *\n * `tokenFrom` selects one credential source and defaults to `\"header\"`.\n * A single source avoids making credential precedence depend on array order.\n *\n * @example\n * router.get(\"/account\", authMiddleware([]), accountController);\n * router.get(\"/admin\", authMiddleware(\"admin\"), adminController);\n * router.get(\"/back-office\", authMiddleware([\"admin\", \"staff\"]), backOfficeController);\n * router.get(\"/browser-account\", authMiddleware([], \"cookie:token\"), accountController);\n */\nexport function authMiddleware(): Middleware;\nexport function authMiddleware(options: AuthMiddlewareOptions): Middleware;\nexport function authMiddleware(\n allowedUserType: string | string[],\n options?: AuthMiddlewareOptions,\n): Middleware;\nexport function authMiddleware(\n allowedUserType: string | string[],\n tokenFrom?: TokenFrom,\n): Middleware;\nexport function authMiddleware(\n userTypeOrOptions?: string | string[] | AuthMiddlewareOptions,\n legacyTokenFromOrOptions?: TokenFrom | AuthMiddlewareOptions,\n): Middleware {\n const options =\n typeof userTypeOrOptions === \"object\" && !Array.isArray(userTypeOrOptions)\n ? userTypeOrOptions\n : typeof legacyTokenFromOrOptions === \"object\"\n ? legacyTokenFromOrOptions\n : undefined;\n const selectedUserType =\n typeof userTypeOrOptions === \"string\" || Array.isArray(userTypeOrOptions)\n ? userTypeOrOptions\n : undefined;\n const allowedTypes = resolveAllowedTypes(selectedUserType);\n const legacyTokenFrom =\n typeof legacyTokenFromOrOptions === \"string\" ? legacyTokenFromOrOptions : undefined;\n const dualSources = options?.sources?.length\n ? options.sources.map(tokenFromDescriptor)\n : undefined;\n\n if (dualSources && options?.source) {\n throw new Error(\"authMiddleware accepts either `source` or `sources`, not both.\");\n }\n\n const dualHeader = dualSources?.includes(\"header\") ?? false;\n const dualCookies = dualSources?.filter((source) => source !== \"header\") ?? [];\n\n if (dualSources && (dualCookies.length > 1 || dualSources.length - dualCookies.length > 1)) {\n throw new Error(\"authMiddleware `sources` accepts at most one header and one cookie.\");\n }\n\n // With dual sources the configured cookie is the base credential; the header\n // is chosen per request, ahead of it.\n const cookieTokenFrom: TokenFrom = dualSources\n ? (dualCookies[0] ?? \"header\")\n : options\n ? tokenFromDescriptor(options)\n : (legacyTokenFrom ?? \"header\");\n const tokenFrom = cookieTokenFrom;\n const refreshCredential = options?.refresh ? tokenFromDescriptor(options.refresh) : undefined;\n const renewalUserType = allowedTypes.length === 1 ? allowedTypes[0] : undefined;\n\n if (\n refreshCredential &&\n (tokenFrom === \"header\" || refreshCredential === \"header\" || !renewalUserType)\n ) {\n throw new Error(\n \"authMiddleware automatic renewal requires one allowed user type and cookie access and refresh credentials.\",\n );\n }\n\n const optional = options?.optional === true;\n\n const auth: Middleware = async ({ request, response }) => {\n const reject = (payload: UnauthorizedPayload) =>\n rejectUnauthorized({ request, response }, payload, options?.redirect);\n\n // A present Authorization header always wins and never falls back to the\n // cookie: the credential used is the header, so no renewal and no CSRF check.\n const headerWins = dualHeader && Boolean(request.authorizationValue);\n const usedTokenFrom: TokenFrom = headerWins ? \"header\" : tokenFrom;\n const usedRefresh = headerWins ? undefined : refreshCredential;\n\n // Renewal can mint cookies, so a cookie-authenticated unsafe request must\n // pass the same CSRF check even when its access cookie is missing.\n if (\n (readCredential(request, usedTokenFrom) ||\n (usedRefresh && readCredential(request, usedRefresh))) &&\n requiresCsrfOriginCheck(usedTokenFrom, request.method)\n ) {\n try {\n assertCsrfOriginAllowed(request);\n } catch (error) {\n if (!(error instanceof CsrfOriginMismatchError)) throw error;\n\n // A client error any cross-site page can trigger: debug, not error.\n log.debug(\"http\", \"auth\", error);\n return response.forbidden({\n error: t(\"auth.errors.csrfOriginMismatch\"),\n errorCode: AuthErrorCodes.CsrfOriginMismatch,\n });\n }\n }\n\n const outcome = await resolveRequestUserOutcome(request, response, {\n tokenFrom: usedTokenFrom,\n refreshCredential: usedRefresh,\n overlapMs: options?.refresh?.overlapMs,\n allowedTypes,\n renewalUserType,\n });\n\n if (outcome.user) {\n request.locals.user = outcome.user;\n return;\n }\n\n if (outcome.failure === \"forbidden\") {\n return response.forbidden({\n error: t(\"auth.errors.unauthorized\"),\n errorCode: AuthErrorCodes.Unauthorized,\n });\n }\n\n if (optional) return;\n\n if (outcome.failure === \"missing\") {\n return reject({\n error: t(\"auth.errors.missingAccessToken\"),\n errorCode: AuthErrorCodes.MissingAccessToken,\n });\n }\n\n if (outcome.failure === \"unauthorized\") {\n return reject({\n error: t(\"auth.errors.unauthorized\"),\n errorCode: AuthErrorCodes.Unauthorized,\n });\n }\n\n return reject({\n error: t(\"auth.errors.invalidAccessToken\"),\n errorCode: AuthErrorCodes.InvalidAccessToken,\n });\n };\n\n const descriptorSources: AuthMiddlewareDescriptorSource[] = dualSources\n ? [...(dualHeader ? ([\"header\"] as const) : []), ...dualCookies.map(descriptorSource)]\n : [descriptorSource(tokenFrom)];\n const descriptor: AuthMiddlewareDescriptor = Object.freeze({\n ...(optional ? { required: false } : {}),\n sources: Object.freeze(\n descriptorSources.map((source) =>\n typeof source === \"string\" ? source : Object.freeze({ ...source }),\n ),\n ) as AuthMiddlewareDescriptorSource[],\n userTypes: Object.freeze([...allowedTypes]) as string[],\n });\n\n // Non-enumerable so the tag never shows up in logs, spreads or JSON.\n Object.defineProperty(auth, AUTH_MIDDLEWARE_DESCRIPTOR, { value: descriptor, enumerable: false });\n\n // Tells `warlock dev` and `warlock inspect` that routes behind this\n // middleware are authenticated. `{ optional: true }`\n // lets anonymous requests through, so it does not count as a guard.\n return markAuthGuard(auth, !optional);\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,MAAa,6BAA6B,OAAO,IAAI,cAAc;;;;;;;;;;;;;;;;;;;AAsCnE,SAAS,mBACP,EAAE,SAAS,YACX,SACA,UACA;CACA,MAAM,YAAY,UAAU,MAAM,WAAW,SAAS,UAAU;CAChE,MAAM,iBAAiB,UAAU,kBAAkB,WAAW,SAAS,eAAe;CAEtF,IAAI,aAAa,QAAQ,OAAO,QAAQ;EAMtC,MAAM,cAAc,mBAAmB,WAAW,QAAQ,MAAM;EAChE,MAAM,YAAY,YAAY,SAAS,GAAG,IAAI,MAAM;EACpD,MAAM,YAAY,mBAAmB,QAAQ,GAAG;EAEhD,OAAO,SAAS,SAAS,GAAG,cAAc,YAAY,eAAe,GAAG,WAAW;CACrF;CAEA,OAAO,SAAS,aAAa,OAAO;AACtC;AAEA,SAAS,oBAAoB,YAA0D;CACrF,IAAI,CAAC,WAAW,UAAU,WAAW,WAAW,UAAU,OAAO;CAEjE,IAAI,CAAC,WAAW,K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C;GACzC;EACF,CAAC;CACH;CAEA,MAAM,oBAAsD,cACxD,CAAC,GAAI,aAAc,CAAC,QAAQ,IAAc,CAAC,GAAI,GAAG,YAAY,IAAI,gBAAgB,CAAC,IACnF,CAAC,iBAAiB,SAAS,CAAC;CAChC,MAAM,aAAuC,OAAO,OAAO;EACzD,GAAI,WAAW,EAAE,UAAU,MAAM,IAAI,CAAC;EACtC,SAAS,OAAO,OACd,kBAAkB,KAAK,WACrB,OAAO,WAAW,WAAW,SAAS,OAAO,OAAO,EAAE,GAAG,OAAO,CAAC,CACnE,CACF;EACA,WAAW,OAAO,OAAO,CAAC,GAAG,YAAY,CAAC;CAC5C,CAAC;CAGD,OAAO,eAAe,MAAM,4BAA4B;EAAE,OAAO;EAAY,YAAY;CAAM,CAAC;CAKhG,OAAO,cAAc,MAAM,CAAC,QAAQ;AACtC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"csrf-origin-check.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/csrf-origin-check.ts"],"mappings":";;;;;AAKA,MAAM,+BAAe,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAS,CAAC;;;;;;;AAcvD,IAAa,0BAAb,cAA6C,MAAM;CAGjD,YAAY,AAAgB,QAAkC;EAC5D,MAAM,6BAA6B,QAAQ;EADjB;;EAE1B,KAAK,OAAO;CACd;AACF;;;;;;;;AASA,SAAgB,wBAAwB,WAAsB,QAAyB;CACrF,OAAO,UAAU,WAAW,SAAS,KAAK,CAAC,aAAa,IAAI,OAAO,YAAY,CAAC;AAClF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,wBAAwB,SAAwB;CAC9D,MAAM,UAAU,yBAAyB,OAAO;CAEhD,IAAI,CAAC,QAAQ,SACX,MAAM,IAAI,wBAAwB,QAAQ,MAAM;AAEpD"}
|
|
1
|
+
{"version":3,"file":"csrf-origin-check.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/csrf-origin-check.ts"],"sourcesContent":["import { resolveCsrfOriginVerdict, type Request } from \"@warlock.js/core\";\nimport type { TokenFrom } from \"../contracts/types\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/** HTTP methods the CSRF Origin check exempts โ reads, never state changes. */\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\n/** Why {@link assertCsrfOriginAllowed} refused a request. */\nexport type CsrfOriginMismatchReason =\n | \"origin-mismatch\"\n | \"referer-mismatch\"\n | \"missing-origin-and-referer\";\n\n/**\n * A cookie-authenticated, unsafe-method request whose `Origin`/`Referer`\n * failed the check. `reason` names exactly why,\n * so an error transformer or an incident log never has to string-match the\n * message.\n */\nexport class CsrfOriginMismatchError extends Error {\n readonly code = AuthErrorCodes.CsrfOriginMismatch;\n\n constructor(public readonly reason: CsrfOriginMismatchReason) {\n super(`CSRF Origin check failed: ${reason}`);\n this.name = \"CsrfOriginMismatchError\";\n }\n}\n\n/**\n * Whether a request is in scope for the CSRF Origin check at all โ only a\n * `cookie:`-sourced credential on an unsafe method (POST/PUT/PATCH/DELETE) is.\n * Header-token auth and safe methods (GET/HEAD/OPTIONS) are always exempt:\n * only a cookie-sourced credential can be silently replayed cross-site by a\n * browser, so only it needs the check.\n */\nexport function requiresCsrfOriginCheck(tokenFrom: TokenFrom, method: string): boolean {\n return tokenFrom.startsWith(\"cookie:\") && !SAFE_METHODS.has(method.toUpperCase());\n}\n\n/**\n * CSRF Origin check for a cookie-authenticated unsafe-method request (lead\n * decision 3). Allowed when `Origin` โ or, when `Origin` is absent, `Referer`\n * โ names the request's own origin or an entry in `auth.csrf.allowedOrigins`.\n * Throws {@link CsrfOriginMismatchError} otherwise, including when BOTH\n * headers are absent.\n *\n * Delegates the actual same-origin/allowedOrigins/trustProxy-aware\n * comparison to `@warlock.js/core`'s `resolveCsrfOriginVerdict`\n * (`core/src/http/csrf-origin-policy.ts`) โ SECURITY card 8a752ab2 moved that\n * logic down into `core` so this middleware's check and core's own default\n * CSRF-Origin guard (`core/src/http/csrf-default-guard.ts`, which now runs\n * even earlier, ahead of this middleware, for cookie-carrying unsafe-method\n * requests generally) share one implementation instead of two copies that\n * could drift apart.\n *\n * Callers gate this behind {@link requiresCsrfOriginCheck} โ this function\n * itself does not re-check the token source or the method.\n */\nexport function assertCsrfOriginAllowed(request: Request): void {\n const verdict = resolveCsrfOriginVerdict(request);\n\n if (!verdict.allowed) {\n throw new CsrfOriginMismatchError(verdict.reason);\n }\n}\n"],"mappings":";;;;;AAKA,MAAM,+BAAe,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAS,CAAC;;;;;;;AAcvD,IAAa,0BAAb,cAA6C,MAAM;CAGjD,YAAY,AAAgB,QAAkC;EAC5D,MAAM,6BAA6B,QAAQ;EADjB;;EAE1B,KAAK,OAAO;CACd;AACF;;;;;;;;AASA,SAAgB,wBAAwB,WAAsB,QAAyB;CACrF,OAAO,UAAU,WAAW,SAAS,KAAK,CAAC,aAAa,IAAI,OAAO,YAAY,CAAC;AAClF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,wBAAwB,SAAwB;CAC9D,MAAM,UAAU,yBAAyB,OAAO;CAEhD,IAAI,CAAC,QAAQ,SACX,MAAM,IAAI,wBAAwB,QAAQ,MAAM;AAEpD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localized-login-path.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/localized-login-path.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,mBAAmB,WAAmB,QAAwB;CAC5E,IAAI,2BAA2B,KAAK,SAAS,GAAG,OAAO;CAEvD,MAAM,WAAW,OAAO,IAAY,8BAA8B,MAAM;CAExE,IAAI,aAAa,YAAY,aAAa,yBAAyB,OAAO;CAE1E,MAAM,QAAQ,OAAO,IAAc,mBAAmB,CAAC,CAAC,KAAK,CAAC;CAE9D,IAAI,kBAAkB,WAAW,KAAK,GAAG,OAAO;CAEhD,IAAI,CAAC,MAAM,SAAS,MAAM,GAAG,OAAO;CAEpC,IAAI,aAAa,yBAGf;MAAI,WAFkB,OAAO,IAAY,kBAAkB,EAEhC,GAAG,OAAO;CAAS;CAGhD,OAAO,cAAc,MAAM,IAAI,WAAW,IAAI,SAAS;AACzD;;AAGA,SAAS,kBAAkB,MAAc,OAAmC;CAC1E,OAAO,MAAM,MAAM,SAAS,SAAS,IAAI,UAAU,KAAK,WAAW,IAAI,KAAK,EAAE,CAAC;AACjF"}
|
|
1
|
+
{"version":3,"file":"localized-login-path.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/localized-login-path.ts"],"sourcesContent":["import { config } from \"@warlock.js/core\";\n\n/**\n * Prefixes `loginPath` with `locale` when `web`'s locale-URL routing is\n * active for that locale โ so a guarded `/ar/admin` page redirects an\n * anonymous request to `/ar/login`, not the bare `/login` (finding: the\n * `returnUrl` carried the locale, the login destination itself did not).\n *\n * `auth` is not on `web`'s dependency graph, and `web` is not on `auth`'s\n * (neither package declares the other, in either `dependencies` or\n * `peerDependencies`) โ so this cannot import `web`'s\n * `resolveLocaleRouting()` / `withLocalePrefix()` / `isPrefixedLocale()`\n * (`web/src/routing/locale-routing.ts`, `web/src/routing/locale-prefixed-paths.ts`).\n * Instead it reads the SAME config keys those read โ `web.localeRouting.strategy`,\n * `app.localeCodes`, `app.localeCode` โ by convention rather than by import,\n * the same pattern `web/src/server/auth-cookie-name.ts` uses in the other\n * direction for `auth.cookie.name`.\n *\n * Left alone (returned unchanged) when:\n * - `loginPath` is absolute (`http://โฆ`, `https://โฆ`) โ a redirect target\n * outside this app has no \"locale prefix\" to add.\n * - `loginPath` is already prefixed with a known locale code (an app that\n * configured `auth.pageAuth.loginPath` as `/ar/login` itself).\n * - `web.localeRouting.strategy` is `\"none\"` (the default) or unset.\n * - `locale` is not one of `app.localeCodes`, or โ under\n * `\"prefix-except-default\"` โ `locale` is the default locale.\n */\nexport function localizedLoginPath(loginPath: string, locale: string): string {\n if (/^[a-z][a-z0-9+.-]*:\\/\\//i.test(loginPath)) return loginPath;\n\n const strategy = config.key<string>(\"web.localeRouting.strategy\", \"none\");\n\n if (strategy !== \"prefix\" && strategy !== \"prefix-except-default\") return loginPath;\n\n const codes = config.key<string[]>(\"app.localeCodes\", []) ?? [];\n\n if (isAlreadyPrefixed(loginPath, codes)) return loginPath;\n\n if (!codes.includes(locale)) return loginPath;\n\n if (strategy === \"prefix-except-default\") {\n const defaultLocale = config.key<string>(\"app.localeCode\", \"\");\n\n if (locale === defaultLocale) return loginPath;\n }\n\n return loginPath === \"/\" ? `/${locale}` : `/${locale}${loginPath}`;\n}\n\n/** `true` when `path` already starts with one of `codes` as its own URL segment. */\nfunction isAlreadyPrefixed(path: string, codes: readonly string[]): boolean {\n return codes.some((code) => path === `/${code}` || path.startsWith(`/${code}/`));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,mBAAmB,WAAmB,QAAwB;CAC5E,IAAI,2BAA2B,KAAK,SAAS,GAAG,OAAO;CAEvD,MAAM,WAAW,OAAO,IAAY,8BAA8B,MAAM;CAExE,IAAI,aAAa,YAAY,aAAa,yBAAyB,OAAO;CAE1E,MAAM,QAAQ,OAAO,IAAc,mBAAmB,CAAC,CAAC,KAAK,CAAC;CAE9D,IAAI,kBAAkB,WAAW,KAAK,GAAG,OAAO;CAEhD,IAAI,CAAC,MAAM,SAAS,MAAM,GAAG,OAAO;CAEpC,IAAI,aAAa,yBAGf;MAAI,WAFkB,OAAO,IAAY,kBAAkB,EAEhC,GAAG,OAAO;CAAS;CAGhD,OAAO,cAAc,MAAM,IAAI,WAAW,IAAI,SAAS;AACzD;;AAGA,SAAS,kBAAkB,MAAc,OAAmC;CAC1E,OAAO,MAAM,MAAM,SAAS,SAAS,IAAI,UAAU,KAAK,WAAW,IAAI,KAAK,EAAE,CAAC;AACjF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"login-throttle.middleware.mjs","names":[],"sources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,CAAC;IAE3D,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,GAAG;IAE1D,OAAO,IAAI,WAAW,KAAK,KAAK;IAEhC,IAAI,QAAQ,WAAW,KAAK;KAC1B,IAAI,UAAU,WAAW,MAAM,GAC7B,MAAM,KAAK,WAAW,KAAK,KAAK;KAGlC,OAAO,gBAAgB;IACzB;GACF;EACF,SAAS,OAAO;GAKd,IAAI,MAAM,QAAQ,kBAAkB,KAAK;GAEzC;EACF;EAEA,SAAS,OAAO,OAAO,qBAA+B;GACpD,IAAI;IAKF,IAAI,EAJW,QAAQ,YACnB,QAAQ,UAAU,gBAAgB,IAClC,CAAC,iBAAiB,OAET;KACX,KAAK,MAAM,cAAc,aAAa;MAGpC,MAAM,MAAM,IAAI,WAAW,WAAW,GAAG,GAAG,GAAG,EAAE,KAAK,OAAO,CAAC;MAC9D,MAAM,MAAM,OAAO,QAAQ,WAAW,GAAG,CAAC;KAC5C;KAEA;IACF;IAMA,KAAK,MAAM,cAAc,aAAa;KACpC,MAAM,QAAQ,OAAO,IAAI,WAAW,GAAG;KAEvC,IAAI,UAAU,UAAa,QAAQ,WAAW,KAAK;KAEnD,IAAI,MAAM,gBAAgB,WAAW,KAAK,KAAK,GAAG;KAElD,MAAM,KAAK,WAAW,KAAK,KAAK;IAClC;GACF,SAAS,OAAO;IACd,IAAI,MAAM,QAAQ,kBAAkB,KAAK;GAC3C;EACF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"login-throttle.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/login-throttle.middleware.ts"],"sourcesContent":["import { createHash, createHmac } from \"node:crypto\";\nimport { cache } from \"@warlock.js/cache\";\nimport { t, type Middleware, type Request, type Response } from \"@warlock.js/core\";\nimport { log } from \"@warlock.js/logger\";\nimport ms from \"ms\";\nimport { authConfig } from \"../services/auth-config\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\nimport { normalizeEmailIdentifier } from \"../utils/normalize-credentials\";\n\n/**\n * Built-in identifier kinds the throttle knows how to extract from a request.\n *\n * - `\"email\"` tracks per-account, so an attacker can't spray one user from\n * many IPs.\n * - `\"ip\"` tracks per-source, so an attacker can't stuff many accounts from\n * one IP.\n *\n * Lockout trips when ANY tracked identifier crosses `max` โ defense-in-depth.\n */\nexport type LoginThrottleIdentifier = \"email\" | \"ip\";\n\n/**\n * Options for {@link loginThrottleMiddleware}.\n *\n * Failure-aware by design: every attempt is counted when it arrives (so a\n * burst of concurrent requests cannot outrun the limit), and a successful\n * response (2xx, or whatever `isFailure` says) resets the count, so a user who\n * types a wrong password three times then the right one is not penalised.\n *\n * @example\n * loginThrottleMiddleware({ max: 5, window: \"15m\", lockoutDuration: \"15m\" });\n */\nexport type LoginThrottleOptions = {\n /**\n * Failures allowed within the window before the identifier is locked. It\n * also caps how many attempts may be in flight at once: a request beyond it\n * is refused with `429` before the controller runs.\n *\n * @default 5\n */\n max?: number;\n\n /**\n * Counting window. `ms`-format string (`\"15m\"`, `\"1h\"`) or seconds as a number.\n *\n * @default \"15m\"\n */\n window?: string | number;\n\n /**\n * Lockout duration once the threshold is tripped. `ms`-format string or seconds.\n *\n * @default \"15m\"\n */\n lockoutDuration?: string | number;\n\n /**\n * Identifiers tracked. Each is counted and locked independently.\n *\n * @default [\"email\", \"ip\"]\n */\n by?: LoginThrottleIdentifier[];\n\n /**\n * Credential field consulted when `\"email\"` is tracked. Switch to\n * `\"username\"` (or any other input field) for systems that don't\n * authenticate by email.\n *\n * @default \"email\"\n */\n identifierKey?: string;\n\n /**\n * Who an account lock applies to when both `\"email\"` and `\"ip\"` are tracked.\n *\n * - `\"global\"` โ `max` failures for an email, from any source, lock that\n * email for everyone (the account owner included).\n * - `\"pair\"` โ the `max` lock applies to the (email, source IP) pair, so a\n * stranger guessing from their own IP cannot lock the owner out. The email\n * alone keeps a wider bucket (`accountMax`) that still stops guessing\n * spread across many IPs.\n *\n * Ignored when `identify` is set or `by` does not track both.\n *\n * @default \"global\"\n */\n emailLock?: \"pair\" | \"global\";\n\n /**\n * Attempts one email may take from all sources together within the window\n * before it is locked, when `emailLock` is `\"pair\"`.\n *\n * @default max * 10\n */\n accountMax?: number;\n\n /**\n * Override the default error message returned with the 429 response.\n */\n errorMessage?: string;\n\n /**\n * Decide whether the response represents a failed login. Defaults to\n * \"non-2xx is a failure\"; override if your controller signals failure\n * through a 200-style body.\n *\n * @default (response) => !response.isOk\n */\n isFailure?: (response: Response) => boolean;\n\n /**\n * Compute the identifiers tracked for this request. Override to derive the\n * account key from a header, a JWT subject, or any other shape that does\n * not match the built-in `email` / `ip` extraction.\n */\n identify?: (request: Request) => string[];\n};\n\nconst COUNTER_PREFIX = \"auth.throttle.count.\";\nconst LOCK_PREFIX = \"auth.throttle.lock.\";\n\nconst counterKey = (identifier: string): string => `${COUNTER_PREFIX}${identifier}`;\nconst lockKey = (identifier: string): string => `${LOCK_PREFIX}${identifier}`;\n\n/**\n * The key a throttle identifier is hashed with: an HMAC key derived from\n * `auth.accessToken.secret` (the same root the OTP code MAC uses), or\n * `undefined` when no secret is configured.\n */\nfunction throttleHashKey(): Buffer | undefined {\n let secret: string | undefined;\n\n try {\n secret = authConfig.accessToken.secret();\n } catch {\n return undefined;\n }\n\n return createHmac(\"sha256\", secret).update(\"@warlock.js/auth:throttle\").digest();\n}\n\n/**\n * Hash of a throttle identifier (`kind` is `\"email\"`, `\"ip\"`, ...). The value\n * is trimmed and lower-cased first, so `\" Sara@x.io\"` and `\"sara@x.io\"` share\n * one bucket.\n *\n * Identifiers become part of cache keys, and cache drivers log their keys: a\n * raw email or IP there is personal data in a log line. A plain SHA-256 of an\n * email is reversible by anyone with a list of addresses, so the hash is\n * keyed (HMAC) with a key derived from `auth.accessToken.secret`. Without a\n * configured secret it falls back to SHA-256, which still keeps the address\n * out of the key.\n *\n * Exported for tests and for apps that inspect throttle keys.\n */\nexport function throttleIdentifierHash(kind: string, value: string): string {\n const normalized = `${kind}:${normalizeEmailIdentifier(value)}`;\n const key = throttleHashKey();\n\n return key\n ? createHmac(\"sha256\", key).update(normalized).digest(\"hex\")\n : createHash(\"sha256\").update(normalized).digest(\"hex\");\n}\n\nlet warnedNullDriver = false;\n\n/**\n * The `null` cache driver stores nothing: every count reads back as 1 and no\n * lock is ever found, so the throttle silently never trips. Say so once.\n */\nfunction warnIfNullDriver(): void {\n if (warnedNullDriver) return;\n\n const driverName = (cache as { currentDriver?: { name?: string } }).currentDriver?.name;\n\n if (driverName !== \"null\") return;\n\n warnedNullDriver = true;\n log.warn(\n \"auth\",\n \"login-throttle\",\n \"The cache driver is `null`, so login, token and OTP throttles never lock. Use a real cache driver (redis, pg, or memory for one process).\",\n );\n}\n\n/**\n * A lock value is the lockout deadline (epoch ms). `true`, written by 5.29\n * and earlier, still counts as locked until the key expires.\n */\nfunction isLocked(value: unknown): boolean {\n if (typeof value === \"number\") {\n return value > Date.now();\n }\n\n return Boolean(value);\n}\n\n/**\n * `ms`'s honest runtime signature (see `services/auth-config.ts`): it returns\n * `undefined` for text it cannot parse and throws for `\"\"`.\n */\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\n\n/**\n * `\"15m\"` / `\"1h\"` / seconds as a number โ seconds, or `undefined` when the\n * value cannot be parsed (the cache rejects such a TTL anyway).\n */\nfunction durationSeconds(duration: string | number): number | undefined {\n if (typeof duration === \"number\") {\n return Number.isFinite(duration) && duration > 0 ? duration : undefined;\n }\n\n let milliseconds: number | string | undefined;\n\n try {\n milliseconds = parseMs(duration);\n } catch {\n milliseconds = undefined;\n }\n\n return typeof milliseconds === \"number\" && Number.isFinite(milliseconds) && milliseconds > 0\n ? milliseconds / 1000\n : undefined;\n}\n\n/**\n * Built-in identifier extractor โ reads the configured credential field from\n * the request body for the per-account key, and `request.detectIp()` for the\n * per-source key. Untruthy values are dropped; a request that yields zero\n * identifiers is left untracked so the middleware no-ops for it.\n */\nfunction buildDefaultIdentifiers(\n request: Request,\n tracked: LoginThrottleIdentifier[],\n credentialField: string,\n max: number,\n pair: { accountMax: number } | undefined,\n): TrackedIdentifier[] {\n const identifiers: TrackedIdentifier[] = [];\n const value = tracked.includes(\"email\") ? request.input(credentialField) : undefined;\n const email = typeof value === \"string\" && value.trim().length > 0 ? value : undefined;\n const ip = tracked.includes(\"ip\") ? request.detectIp() : undefined;\n\n if (email !== undefined) {\n if (pair && ip) {\n // The hard lock belongs to this source only; the email-wide bucket is\n // wider, so a stranger cannot lock the owner out with `max` guesses.\n const pairValue = `${normalizeEmailIdentifier(email)}|${ip}`;\n\n identifiers.push({ key: `email-ip.${throttleIdentifierHash(\"email-ip\", pairValue)}`, max });\n identifiers.push({\n key: `email.${throttleIdentifierHash(\"email\", email)}`,\n max: pair.accountMax,\n });\n } else {\n identifiers.push({ key: `email.${throttleIdentifierHash(\"email\", email)}`, max });\n }\n }\n\n if (ip) {\n identifiers.push({ key: `ip.${throttleIdentifierHash(\"ip\", ip)}`, max });\n }\n\n return identifiers;\n}\n\n/** One throttle bucket: its cache-key suffix and the attempts it allows. */\ntype TrackedIdentifier = { key: string; max: number };\n\n/**\n * Whether the counter now reads a number below `count`, i.e. a success reset\n * it while this attempt ran. Fails closed: a missing value (expired, evicted,\n * a driver that stores nothing), a non-numeric one or a failed read all answer\n * `false`, so the caller locks.\n */\nasync function counterWasReset(identifier: string, count: number): Promise<boolean> {\n let current: unknown;\n\n try {\n current = await cache.get(counterKey(identifier));\n } catch (error) {\n log.error(\"auth\", \"login-throttle\", error);\n\n return false;\n }\n\n if (typeof current === \"string\" && current.trim() !== \"\") current = Number(current);\n\n return typeof current === \"number\" && Number.isFinite(current) && current < count;\n}\n\n/**\n * Failure-aware login throttle. Locks an identifier (account, IP, or both)\n * after too many failed login attempts within a window โ without penalising\n * a user who eventually types the right password.\n *\n * Mechanism (per identifier):\n *\n * 1. **Before the controller** โ reject with `429` if a lock key is set,\n * skipping the DB lookup AND the bcrypt verify (this also neutralises the\n * CPU-DoS angle of brute-forcing). Otherwise count the attempt in a\n * fixed-window counter right away, and reject with `429` (setting the lock)\n * when it goes past `max`. Counting at entry is what bounds a burst of\n * concurrent requests: at most `max` attempts per window reach the\n * controller, however many arrive at once.\n * 2. **After the controller** โ observe the outcome via `response.onSent`.\n * On failure (non-2xx by default), set a lock key with `lockoutDuration`\n * TTL once the attempt count has reached `max` (unless a success reset the\n * counter meanwhile). On success, reset the counter to 0 and clear the lock\n * for that identifier.\n *\n * Storage is `@warlock.js/cache` (a peer dependency of `@warlock.js/auth`,\n * transitively guaranteed via `@warlock.js/core`). Lockout state is shared\n * across replicas โ correct security model, because an attacker can't bypass\n * by round-robin to a different pod. Every cache call is guarded so a\n * misconfigured driver fails open (a throttle outage must never escalate\n * into a full auth outage).\n *\n * @example\n * import { loginThrottleMiddleware } from \"@warlock.js/auth\";\n * import { router } from \"@warlock.js/core\";\n *\n * router.post(\"/auth/login\", loginController, {\n * middleware: [loginThrottleMiddleware({ max: 5, window: \"15m\" })],\n * });\n *\n * @example\n * // Per-IP only โ avoid account-lockout-as-DoS on anonymous-attack vectors\n * router.post(\"/auth/refresh-token\", refreshController, {\n * middleware: [loginThrottleMiddleware({ by: [\"ip\"], max: 10, window: \"1m\" })],\n * });\n */\nexport function loginThrottleMiddleware(options: LoginThrottleOptions = {}): Middleware {\n const max = options.max ?? 5;\n const window = options.window ?? \"15m\";\n const lockoutDuration = options.lockoutDuration ?? \"15m\";\n const tracked = options.by ?? [\"email\", \"ip\"];\n const credentialField = options.identifierKey ?? \"email\";\n const pair =\n options.emailLock === \"pair\" && tracked.includes(\"email\") && tracked.includes(\"ip\")\n ? { accountMax: options.accountMax ?? max * 10 }\n : undefined;\n\n /**\n * Lock an identifier for `lockoutDuration`. The counter is rewritten with\n * the same TTL, so the two expire together and the identifier starts a fresh\n * window once the lockout ends. Rewriting keeps a value of at least `count`,\n * so a request that slipped past the lock check still sees \"over the limit\".\n */\n const lock = async (identifier: string, count: number): Promise<void> => {\n const lockSeconds = durationSeconds(lockoutDuration);\n\n // The lock stores its own deadline: a driver with sliding expiration\n // (`memoryExtended`) pushes the key's TTL forward on every read, but the\n // deadline in the value does not move, so a client that keeps retrying is\n // still released after `lockoutDuration`.\n await cache.set(\n lockKey(identifier),\n lockSeconds === undefined ? true : Date.now() + lockSeconds * 1000,\n { ttl: lockoutDuration },\n );\n await cache.set(counterKey(identifier), count, { ttl: lockoutDuration });\n };\n\n return async ({ request, response }) => {\n const identifiers: TrackedIdentifier[] = options.identify\n ? options.identify(request).map((key) => ({ key, max }))\n : buildDefaultIdentifiers(request, tracked, credentialField, max, pair);\n\n if (identifiers.length === 0) return;\n\n warnIfNullDriver();\n\n const tooManyRequests = () =>\n response.tooManyRequests({\n error: options.errorMessage ?? t(\"auth.errors.tooManyAttempts\"),\n errorCode: AuthErrorCodes.TooManyAttempts,\n });\n\n /** The attempt number this request took in each identifier's window. */\n const counts = new Map<string, number>();\n\n try {\n for (const identifier of identifiers) {\n if (isLocked(await cache.get(lockKey(identifier.key)))) {\n return tooManyRequests();\n }\n }\n\n for (const identifier of identifiers) {\n const key = counterKey(identifier.key);\n\n // Open the window on the first attempt: the create-only write means\n // only one of several racing servers sets the TTL, and an existing\n // window keeps its deadline (fixed window). The bump itself is an\n // atomic increment, so concurrent attempts across servers are never\n // lost (redis INCRBY / pg upsert keep the window's TTL). Passing the\n // TTL on the bump also expires a key recreated after the seed.\n await cache.set(key, 0, { ttl: window, onConflict: \"create\" });\n const count = await cache.increment(key, 1, { ttl: window });\n\n if (typeof count !== \"number\" || !Number.isFinite(count)) continue;\n\n counts.set(identifier.key, count);\n\n if (count > identifier.max) {\n if (count === identifier.max + 1) {\n await lock(identifier.key, count);\n }\n\n return tooManyRequests();\n }\n }\n } catch (error) {\n // Fail open โ a cache outage (driver not initialised, network blip)\n // must never escalate into a full auth outage. Log and let the request\n // through; the onSent recorder below is independently guarded so an\n // outage there is also harmless.\n log.error(\"auth\", \"login-throttle\", error);\n\n return;\n }\n\n response.onSent(async (resolvedResponse: Response) => {\n try {\n const failed = options.isFailure\n ? options.isFailure(resolvedResponse)\n : !resolvedResponse.isOk;\n\n if (!failed) {\n for (const identifier of identifiers) {\n // Reset to 0 rather than delete: a failure still in flight reads\n // the 0 as proof that a success reset the window (see below).\n await cache.set(counterKey(identifier.key), 0, { ttl: window });\n await cache.remove(lockKey(identifier.key));\n }\n\n return;\n }\n\n // Already counted at entry; a failure that used the last allowed\n // attempt starts the lockout, unless a success that finished while it\n // ran reset the counter (a correct login racing a mistyped one must\n // not lock the account it just signed in to).\n for (const identifier of identifiers) {\n const count = counts.get(identifier.key);\n\n if (count === undefined || count < identifier.max) continue;\n\n if (await counterWasReset(identifier.key, count)) continue;\n\n await lock(identifier.key, count);\n }\n } catch (error) {\n log.error(\"auth\", \"login-throttle\", error);\n }\n });\n };\n}\n"],"mappings":";;;;;;;;;;AAsHA,MAAM,iBAAiB;AACvB,MAAM,cAAc;AAEpB,MAAM,cAAc,eAA+B,GAAG,iBAAiB;AACvE,MAAM,WAAW,eAA+B,GAAG,cAAc;;;;;;AAOjE,SAAS,kBAAsC;CAC7C,IAAI;CAEJ,IAAI;EACF,SAAS,WAAW,YAAY,OAAO;CACzC,QAAQ;EACN;CACF;CAEA,OAAO,WAAW,UAAU,MAAM,CAAC,CAAC,OAAO,2BAA2B,CAAC,CAAC,OAAO;AACjF;;;;;;;;;;;;;;;AAgBA,SAAgB,uBAAuB,MAAc,OAAuB;CAC1E,MAAM,aAAa,GAAG,KAAK,GAAG,yBAAyB,KAAK;CAC5D,MAAM,MAAM,gBAAgB;CAE5B,OAAO,MACH,WAAW,UAAU,GAAG,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,OAAO,KAAK,IACzD,WAAW,QAAQ,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,OAAO,KAAK;AAC1D;AAEA,IAAI,mBAAmB;;;;;AAMvB,SAAS,mBAAyB;CAChC,IAAI,kBAAkB;CAItB,IAFoB,MAAgD,eAAe,SAEhE,QAAQ;CAE3B,mBAAmB;CACnB,IAAI,KACF,QACA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KAAK,KAAK;IAClC;GACF,SAAS,OAAO;IACd,IAAI,MAAM,QAAQ,kBAAkB,KAAK;GAC3C;EACF,CAAC;CACH;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"one-time-token-throttle.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/one-time-token-throttle.middleware.ts"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,SAAgB,6BAA6B,UAAgC,CAAC,GAAe;CAC3F,OAAO,wBAAwB;EAC7B,KAAK;EACL,QAAQ;EACR,iBAAiB;EACjB,IAAI,CAAC,SAAS,IAAI;EAClB,iBAAiB;EACjB,GAAG;CACL,CAAC;AACH;;;;;;;;;;;;;;AAeA,SAAgB,+BAA+B,UAAgC,CAAC,GAAe;CAC7F,OAAO,wBAAwB;EAC7B,KAAK;EACL,QAAQ;EACR,iBAAiB;EACjB,IAAI,CAAC,IAAI;EACT,GAAG;CACL,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"one-time-token-throttle.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/one-time-token-throttle.middleware.ts"],"sourcesContent":["import type { Middleware } from \"@warlock.js/core\";\nimport { loginThrottleMiddleware, type LoginThrottleOptions } from \"./login-throttle.middleware\";\n\n/**\n * Throttle for routes that ISSUE a verification or reset token (\"send\n * verification email\", \"forgot password\"). Built on\n * {@link loginThrottleMiddleware}, tracked per email and per IP, with one\n * difference: EVERY request counts. A reset request answers the same success\n * for known and unknown emails, so a failure-aware counter would never trip.\n *\n * Defaults: 3 requests per 1h window, then a 1h lockout (`429`, `EC004`).\n *\n * @example\n * router.post(\"/auth/forgot-password\", forgotPassword, {\n * middleware: [tokenIssueThrottleMiddleware()],\n * });\n */\nexport function tokenIssueThrottleMiddleware(options: LoginThrottleOptions = {}): Middleware {\n return loginThrottleMiddleware({\n max: 3,\n window: \"1h\",\n lockoutDuration: \"1h\",\n by: [\"email\", \"ip\"],\n isFailure: () => true,\n ...options,\n });\n}\n\n/**\n * Throttle for routes that CONSUME a token (\"verify email\", \"reset\n * password\"). Built on {@link loginThrottleMiddleware}: per IP (the body\n * carries a token, not an account), failure-aware โ a rejected token counts,\n * a successful use clears the counter.\n *\n * Defaults: 10 failures per 15m window, then a 15m lockout (`429`, `EC004`).\n *\n * @example\n * router.post(\"/auth/reset-password\", resetPasswordController, {\n * middleware: [tokenConsumeThrottleMiddleware()],\n * });\n */\nexport function tokenConsumeThrottleMiddleware(options: LoginThrottleOptions = {}): Middleware {\n return loginThrottleMiddleware({\n max: 10,\n window: \"15m\",\n lockoutDuration: \"15m\",\n by: [\"ip\"],\n ...options,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,SAAgB,6BAA6B,UAAgC,CAAC,GAAe;CAC3F,OAAO,wBAAwB;EAC7B,KAAK;EACL,QAAQ;EACR,iBAAiB;EACjB,IAAI,CAAC,SAAS,IAAI;EAClB,iBAAiB;EACjB,GAAG;CACL,CAAC;AACH;;;;;;;;;;;;;;AAeA,SAAgB,+BAA+B,UAAgC,CAAC,GAAe;CAC7F,OAAO,wBAAwB;EAC7B,KAAK;EACL,QAAQ;EACR,iBAAiB;EACjB,IAAI,CAAC,IAAI;EACT,GAAG;CACL,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"otp-throttle.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/otp-throttle.middleware.ts"],"mappings":";;;;;;;;;;;;;;AAcA,SAAgB,6BAA6B,UAAgC,CAAC,GAAe;CAC3F,OAAO,6BAA6B;EAAE,eAAe;EAAS,GAAG;CAAQ,CAAC;AAC5E;;;;;;;;;;;;AAaA,SAAgB,4BAA4B,UAAgC,CAAC,GAAe;CAC1F,OAAO,wBAAwB;EAC7B,KAAK;EACL,QAAQ;EACR,iBAAiB;EACjB,IAAI,CAAC,SAAS,IAAI;EAClB,eAAe;EACf,GAAG;CACL,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"otp-throttle.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/otp-throttle.middleware.ts"],"sourcesContent":["import type { Middleware } from \"@warlock.js/core\";\nimport { loginThrottleMiddleware, type LoginThrottleOptions } from \"./login-throttle.middleware\";\nimport { tokenIssueThrottleMiddleware } from \"./one-time-token-throttle.middleware\";\n\n/**\n * Throttle for the route that SENDS a login code. {@link tokenIssueThrottleMiddleware}\n * keyed on the `phone` input and IP: every request counts (the answer is the\n * same for unknown phones), 3 per 1h, then a 1h lockout (`429`, `EC004`).\n *\n * @example\n * router.post(\"/auth/otp/request\", requestOtpController, {\n * middleware: [otpRequestThrottleMiddleware()],\n * });\n */\nexport function otpRequestThrottleMiddleware(options: LoginThrottleOptions = {}): Middleware {\n return tokenIssueThrottleMiddleware({ identifierKey: \"phone\", ...options });\n}\n\n/**\n * Throttle for the route that VERIFIES a login code. {@link loginThrottleMiddleware}\n * keyed on `phone` and IP, failure-aware: 5 failures per 15m, then a 15m lockout\n * (`429`, `EC004`). Complements the per-code attempt cap, which a fresh code\n * would otherwise reset.\n *\n * @example\n * router.post(\"/auth/otp/verify\", verifyOtpController, {\n * middleware: [otpVerifyThrottleMiddleware()],\n * });\n */\nexport function otpVerifyThrottleMiddleware(options: LoginThrottleOptions = {}): Middleware {\n return loginThrottleMiddleware({\n max: 5,\n window: \"15m\",\n lockoutDuration: \"15m\",\n by: [\"email\", \"ip\"],\n identifierKey: \"phone\",\n ...options,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,SAAgB,6BAA6B,UAAgC,CAAC,GAAe;CAC3F,OAAO,6BAA6B;EAAE,eAAe;EAAS,GAAG;CAAQ,CAAC;AAC5E;;;;;;;;;;;;AAaA,SAAgB,4BAA4B,UAAgC,CAAC,GAAe;CAC1F,OAAO,wBAAwB;EAC7B,KAAK;EACL,QAAQ;EACR,iBAAiB;EACjB,IAAI,CAAC,SAAS,IAAI;EAClB,eAAe;EACf,GAAG;CACL,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"require-verified-email.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/require-verified-email.middleware.ts"],"mappings":";;;;;;;;;;;;;;;AAeA,SAAgB,uBAAmC;CACjD,OAAO,OAAO,EAAE,cAAc;EAG5B,IAAI,CAFS,QAAQ,OAAO,MAEjB,MAAM,WAAW,aAAa,MAAM,CAAC,GAC9C,MAAM,IAAI,sBAAsB;CAEpC;AACF"}
|
|
1
|
+
{"version":3,"file":"require-verified-email.middleware.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/middleware/require-verified-email.middleware.ts"],"sourcesContent":["import type { Middleware } from \"@warlock.js/core\";\nimport { EmailNotVerifiedError } from \"../errors/email-not-verified.error\";\nimport { authConfig } from \"../services/auth-config\";\n\n/**\n * Opt-in route gate that rejects a user who has not verified their email with\n * {@link EmailNotVerifiedError} (`403`, `EC007`). Place it AFTER\n * `authMiddleware` โ it reads `request.locals.user`. A request with no user\n * fails closed with the same error.\n *\n * @example\n * router.post(\"/orders\", createOrder, {\n * middleware: [authMiddleware(\"user\"), requireVerifiedEmail()],\n * });\n */\nexport function requireVerifiedEmail(): Middleware {\n return async ({ request }) => {\n const user = request.locals.user as { get?: (key: string) => unknown } | undefined;\n\n if (!user?.get?.(authConfig.verification.field())) {\n throw new EmailNotVerifiedError();\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAeA,SAAgB,uBAAmC;CACjD,OAAO,OAAO,EAAE,cAAc;EAG5B,IAAI,CAFS,QAAQ,OAAO,MAEjB,MAAM,WAAW,aAAa,MAAM,CAAC,GAC9C,MAAM,IAAI,sBAAsB;CAEpC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"access-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/access-token.model.ts"],"mappings":";;;;;;;;;;;;;;AAcA,MAAa,oBAAoB,EAAE,OAAO;CACxC,OAAO,EAAE,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,OAAO;CACZ;;;;CAKA,OAAc,iBAAiB,MAAY;EACzC,OAAO,KAAK,OAAO,EAAE,SAAS,KAAK,GAAG,CAAC;CACzC;;;;;;CAOA,aAAoB,6BAA6B,MAAY,UAAiC;EAC5F,MAAM,KAAK,OAAO;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;GAAU,WAAW;EAAS,CAAC;EACrF,MAAM,KAAK,OAAO;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;GAAU,WAAW;EAAK,CAAC;CACnF;;;;;CAMA,aAAoB,eAAgC;EAClD,MAAM,gBAAgB,MAAM,KAAK,MAAM,CAAC,CAAC,MAAM,cAAc,qBAAK,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI;EAElF,KAAK,MAAM,SAAS,eAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO,cAAc;CACvB;;;;;;;;;;;;CAaA,aAAoB,oBAA4C;EAG9D,QAAO,MAFc,KAAK,MAAM,CAAC,CAAC,IAAI,EAEzB,CAAC,QAAQ,UAAuB,MAAM,YAAY;CACjE;;;;;;CAOA,aAAoB,qBAA6C;EAC/D,MAAM,SAAS,MAAM,KAAK,kBAAkB;EAE5C,KAAK,MAAM,SAAS,QAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"access-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/access-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport { plainTokenOf, storedTokenForms } from \"../../utils/token-digest\";\nimport { isNeverExpiring, isUsableExpiry } from \"../../utils/token-expiry\";\nimport type { Auth } from \"../auth.model\";\n\n/**\n * Seal schema for the persisted access-token record. Exported so an override\n * can spread it and add columns (e.g. a tenant key) without re-declaring the\n * base shape.\n *\n * `last_access` and the `is_active` soft-revoke flag were removed โ neither was\n * ever read; access tokens are revoked by deleting the row.\n */\nexport const accessTokenSchema = v.object({\n token: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n /** Null for tokens issued before family tracking was introduced. */\n family_id: v.string().optional(),\n expires_at: v.date().required(),\n});\n\n/**\n * Persisted access-token record + the data layer for access tokens.\n *\n * **Role.** Owns access-token persistence and lookup. The middleware checks a\n * presented JWT against this table so deleting a row (logout) invalidates the\n * token immediately, before its JWT expiry. The auth service goes through the\n * named statics exclusively, so it never hard-codes a column name and an\n * override can rename/add columns by registering under\n * `config.auth.accessToken.model`.\n */\nexport class AccessToken extends Model {\n public static table = \"access_tokens\";\n\n public static schema = accessTokenSchema;\n\n /**\n * The raw signed JWT is a bearer credential โ never serialize it. `hidden`\n * only strips it from `toJSON()` / `JSON.stringify(model)` (so\n * `response.json(token)` or a resource cannot leak it); `get(\"token\")`,\n * `findByToken` and every query still read the column.\n *\n * With `auth.hashTokensAtRest` on, the column holds the token's SHA-256\n * digest instead, so a copy of the table cannot be replayed; read the raw\n * token of a freshly issued row through {@link plainToken}.\n */\n public static hidden = [\"token\"];\n\n /**\n * Permanent regardless of the data source default โ Mongo's driver default\n * is `\"trash\"`, which would copy live credential material (the JWT itself)\n * into `access_tokensTrash` on every `destroy()` (logout, expiry purge,\n * never-expiring purge). A revoked/expired access token must not survive\n * anywhere.\n */\n public static deleteStrategy = \"permanent\" as const;\n\n /** The user this token was issued for. */\n public get userId() {\n return this.get(\"user_id\");\n }\n\n /** The user-type slug this token was issued for. */\n public get userType(): string {\n return this.get(\"user_type\");\n }\n\n /**\n * The raw token, when it is known: always for a row stored unhashed, and\n * for a hashed row only in the process that just issued it.\n */\n public get plainToken(): string | undefined {\n return plainTokenOf(this, this.get(\"token\"));\n }\n\n /**\n * Whether the persisted expiry has passed.\n *\n * The middleware asks this on every request, which is what makes the row the\n * authority it always looked like it was: before 4.12.0 the gate only checked\n * that the row *existed*, so a row the database knew was dead still let its\n * token through โ the database was never asked.\n *\n * **Fails closed.** A missing or unparseable `expires_at` counts as expired.\n * `expires_at` is `required` in the schema, so a row that cannot answer \"when\n * does this die\" is malformed, and the safe reading of a malformed credential\n * is that it is not one. This is deliberately stricter than a naive\n * `now > expires_at`, which answers `false` for an `Invalid Date` and thereby\n * grants exactly the poisoned rows an unlimited life.\n */\n public get isExpired(): boolean {\n const expiresAt = this.get(\"expires_at\");\n\n if (!isUsableExpiry(expiresAt)) return true;\n\n return new Date(expiresAt).getTime() <= Date.now();\n }\n\n /**\n * Whether nothing about this row can ever retire it โ an unusable\n * `expires_at`, or a token carrying no `exp` claim. See\n * {@link isNeverExpiring}; this is the predicate `purgeNeverExpiring` selects\n * on.\n */\n public get neverExpires(): boolean {\n return isNeverExpiring(this.get(\"token\"), this.get(\"expires_at\"));\n }\n\n /**\n * Persist a freshly-signed access token for the user. `token` is the value\n * to store: the raw JWT, or its digest under `auth.hashTokensAtRest`.\n */\n public static issue(user: Auth, token: string, expiresAt: Date, familyId?: string) {\n return this.create({\n token,\n user_id: user.id,\n user_type: user.userType,\n family_id: familyId,\n expires_at: expiresAt,\n });\n }\n\n /**\n * Find an access-token row by its raw token string, whether the row stores\n * the token hashed or raw (one query).\n */\n public static findByToken(token: string): Promise<AccessToken | null> {\n return this.query().whereIn(\"token\", storedTokenForms(token)).first();\n }\n\n /**\n * Delete a specific token that belongs to the given user, stored hashed or raw.\n */\n public static deleteForUser(user: Auth, token: string) {\n return this.query()\n .where({ user_id: user.id })\n .whereIn(\"token\", storedTokenForms(token))\n .delete();\n }\n\n /**\n * Delete every access token belonging to the user.\n */\n public static deleteAllForUser(user: Auth) {\n return this.delete({ user_id: user.id });\n }\n\n /**\n * Delete every access token attached to one family, plus pre-family rows for\n * the same user type. The latter is deliberately conservative during the\n * additive upgrade: old access rows cannot be assigned safely to a family.\n */\n public static async deleteFamilyAndLegacyForUser(user: Auth, familyId: string): Promise<void> {\n await this.delete({ user_id: user.id, user_type: user.userType, family_id: familyId });\n await this.delete({ user_id: user.id, user_type: user.userType, family_id: null });\n }\n\n /**\n * Hard-delete every expired access-token row. Returns the number removed.\n * Runs from the `auth.cleanup` CLI command (a cold batch path).\n */\n public static async purgeExpired(): Promise<number> {\n const expiredTokens = await this.query().where(\"expires_at\", \"<\", new Date()).get();\n\n for (const token of expiredTokens) {\n await token.destroy();\n }\n\n return expiredTokens.length;\n }\n\n /**\n * Every row that can never retire itself โ see {@link neverExpires}.\n *\n * **A full scan, filtered in memory, on purpose.** The defining case is a row\n * whose `expires_at` is an `Invalid Date`, which no date predicate can select\n * (`< now` and `> now` are both `false` for it), and the definitive case is a\n * token with no `exp` claim, which lives inside the token string rather than\n * in a column. Neither is expressible as a `where`, so the rows have to be\n * read to be judged. This runs from a one-off remediation command, not a\n * request path.\n */\n public static async findNeverExpiring(): Promise<AccessToken[]> {\n const tokens = await this.query().get();\n\n return tokens.filter((token: AccessToken) => token.neverExpires);\n }\n\n /**\n * Hard-delete every never-expiring row, returning the rows removed so the\n * caller can report what it revoked. Deletion *is* revocation for access\n * tokens โ the middleware rejects a token with no row.\n */\n public static async purgeNeverExpiring(): Promise<AccessToken[]> {\n const tokens = await this.findNeverExpiring();\n\n for (const token of tokens) {\n await token.destroy();\n }\n\n return tokens;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAa,oBAAoB,EAAE,OAAO;CACxC,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;;CAE/B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;AAChC,CAAC;;;;;;;;;;;AAYD,IAAa,cAAb,cAAiC,MAAM;;eACf;;;gBAEC;;;gBAYA,CAAC,OAAO;;;wBASA;;;CAG/B,IAAW,SAAS;EAClB,OAAO,KAAK,IAAI,SAAS;CAC3B;;CAGA,IAAW,WAAmB;EAC5B,OAAO,KAAK,IAAI,WAAW;CAC7B;;;;;CAMA,IAAW,aAAiC;EA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,IAAI;EAElF,KAAK,MAAM,SAAS,eAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO,cAAc;CACvB;;;;;;;;;;;;CAaA,aAAoB,oBAA4C;EAG9D,QAAO,MAFc,KAAK,MAAM,CAAC,CAAC,IAAI,EAEzB,CAAC,QAAQ,UAAuB,MAAM,YAAY;CACjE;;;;;;CAOA,aAAoB,qBAA6C;EAC/D,MAAM,SAAS,MAAM,KAAK,kBAAkB;EAE5C,KAAK,MAAM,SAAS,QAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO;CACT;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"family-association.migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/family-association.migration.ts"],"mappings":";;;;;AAIA,MAAa,wCAAwC,QAAQ,aAAa;CACxE,MAAM;CACN,KAAK;EACH,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM;CAChD;CACA,OAAO;EACL,KAAK,WAAW,WAAW;CAC7B;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"family-association.migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/family-association.migration.ts"],"sourcesContent":["import { migrate } from \"@warlock.js/cascade\";\nimport { AccessToken } from \"./access-token.model\";\n\n/** Adds an optional family association without invalidating existing access tokens. */\nexport const AccessTokenFamilyAssociationMigration = migrate(AccessToken, {\n name: \"accessTokenFamilyAssociation\",\n up() {\n this.string(\"family_id\", 64).nullable().index();\n },\n down() {\n this.dropColumn(\"family_id\");\n },\n});\n"],"mappings":";;;;;AAIA,MAAa,wCAAwC,QAAQ,aAAa;CACxE,MAAM;CACN,KAAK;EACH,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM;CAChD;CACA,OAAO;EACL,KAAK,WAAW,WAAW;CAC7B;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/migration.ts"],"mappings":";;;;AAGA,MAAa,uBAAuB,QAAQ,aAAa;CACvD,MAAM;CACN,KAAK;EAEH,KAAK,uBAAuB;EAG5B,KAAK,YAAY;EAGjB,KAAK,KAAK,OAAO,CAAC,CAAC,OAAO;EAO1B,KAAK,UAAU,SAAS,CAAC,CAAC,MAAM;EAChC,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS;EAGtC,KAAK,UAAU,YAAY,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS;EAG9C,KAAK,WAAW;CAClB;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/access-token/migration.ts"],"sourcesContent":["import { migrate } from \"@warlock.js/cascade\";\nimport { AccessToken } from \"./access-token.model\";\n\nexport const AccessTokenMigration = migrate(AccessToken, {\n name: \"accessToken\",\n up() {\n // Create table\n this.createTableIfNotExists();\n\n // Primary key\n this.primaryUuid();\n\n // Token field\n this.text(\"token\").unique();\n\n // User reference (flat columns for cross-driver compatibility).\n // `foreignId` matches the DataSource's default primary-key type, so the\n // column stays compatible with the user model's `id` whether the app uses\n // integer (the default) or uuid PKs โ hardcoding uuid here 500'd every\n // login on a default integer-PK app (finding 5e47bdb3).\n this.foreignId(\"user_id\").index();\n this.string(\"user_type\", 50).nullable();\n\n // Expiry โ enables server-side cleanup of stale access-token rows\n this.timestamp(\"expires_at\").index().nullable();\n\n // Timestamps\n this.timestamps();\n },\n down() {\n this.dropTableIfExists();\n },\n});\n"],"mappings":";;;;AAGA,MAAa,uBAAuB,QAAQ,aAAa;CACvD,MAAM;CACN,KAAK;EAEH,KAAK,uBAAuB;EAG5B,KAAK,YAAY;EAGjB,KAAK,KAAK,OAAO,CAAC,CAAC,OAAO;EAO1B,KAAK,UAAU,SAAS,CAAC,CAAC,MAAM;EAChC,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS;EAGtC,KAAK,UAAU,YAAY,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS;EAG9C,KAAK,WAAW;CAClB;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-token-family.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/auth-token-family/auth-token-family.model.ts"],"mappings":";;;;;AAKA,MAAa,wBAAwB,EAAE,OAAO;CAC5C,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,UAAU,EAAE,OAAO,CAAC,CAAC,QAAQ,CAAC;CAC9B,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;AAChC,CAAC;;AAGD,IAAa,kBAAb,cAAqC,MAAM;;eACnB;;;gBAEC;;;CAGvB,IAAW,YAAqB;EAC9B,OAAO,QAAQ,KAAK,IAAI,YAAY,CAAC;CACvC;;CAGA,OAAc,MAAM,MAAY,UAAkB;EAChD,OAAO,KAAK,OAAO;GACjB,WAAW;GACX,SAAS,KAAK;GACd,WAAW,KAAK;GAChB,UAAU;EACZ,CAAC;CACH;CAEA,OAAc,eAAe,UAAmD;EAC9E,OAAO,KAAK,MAAM,EAAE,WAAW,SAAS,CAAC;CAC3C;;CAGA,aAAoB,OAAO,MAAY,UAA4C;EACjF,MAAM,WAAW,MAAM,KAAK,eAAe,QAAQ;EAEnD,IAAI,UAAU;GACZ,IACE,SAAS,IAAI,SAAS,MAAM,KAAK,MACjC,SAAS,IAAY,WAAW,MAAM,KAAK,UAE3C,MAAM,IAAI,MAAM,0CAA0C;GAG5D,OAAO;EACT;EAEA,MAAM,KAAK,OACT,EAAE,WAAW,SAAS,GACtB,EAAE,cAAc;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;GAAU,UAAU;EAAE,EAAE,GAC5E,EAAE,QAAQ,KAAK,CACjB;EAEA,MAAM,SAAS,MAAM,KAAK,eAAe,QAAQ;EAEjD,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,6CAA6C;EAE1E,IAAI,OAAO,IAAI,SAAS,MAAM,KAAK,MAAM,OAAO,IAAY,WAAW,MAAM,KAAK,UAChF,MAAM,IAAI,MAAM,0CAA0C;EAG5D,OAAO;CACT;;CAGA,OAAc,UAAU,MAAwC;EAC9D,OAAO,KAAK,MAAM,CAAC,CAChB,MAAM;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;GAAU,YAAY;EAAK,CAAC,CAAC,CACvE,IAAI;CACT;;;;;CAMA,OAAc,gBAAgB,UAAkB,kBAA2C;EACzF,OAAO,KAAK,OACV;GAAE,WAAW;GAAU,UAAU;GAAkB,YAAY;EAAK,GACpE,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,CAC1B;CACF;;CAGA,OAAc,OAAO,UAAkB,kBAA2C;EAChF,OAAO,KAAK,OACV;GAAE,WAAW;GAAU,UAAU,mBAAmB;GAAG,YAAY;EAAK,GACxE,EAAE,MAAM,EAAE,4BAAY,IAAI,KAAK,EAAE,EAAE,CACrC;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"auth-token-family.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/auth-token-family/auth-token-family.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport type { Auth } from \"../auth.model\";\n\n/** Durable revision authority for one refresh-token rotation family. */\nexport const authTokenFamilySchema = v.object({\n family_id: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n revision: v.number().default(0),\n revoked_at: v.date().optional(),\n});\n\n/** Coordinates family-wide refresh, replay containment, and logout transitions. */\nexport class AuthTokenFamily extends Model {\n public static table = \"auth_token_families\";\n\n public static schema = authTokenFamilySchema;\n\n /** Whether a family-wide revoke has made every member unusable. */\n public get isRevoked(): boolean {\n return Boolean(this.get(\"revoked_at\"));\n }\n\n /** Create the durable family record before its first token pair is issued. */\n public static issue(user: Auth, familyId: string) {\n return this.create({\n family_id: familyId,\n user_id: user.id,\n user_type: user.userType,\n revision: 0,\n });\n }\n\n public static findByFamilyId(familyId: string): Promise<AuthTokenFamily | null> {\n return this.first({ family_id: familyId });\n }\n\n /** Add a durable row for an existing lineage through a driver-native upsert. */\n public static async ensure(user: Auth, familyId: string): Promise<AuthTokenFamily> {\n const existing = await this.findByFamilyId(familyId);\n\n if (existing) {\n if (\n existing.get(\"user_id\") !== user.id ||\n existing.get<string>(\"user_type\") !== user.userType\n ) {\n throw new Error(\"Token family belongs to a different user\");\n }\n\n return existing;\n }\n\n await this.atomic(\n { family_id: familyId },\n { $setOnInsert: { user_id: user.id, user_type: user.userType, revision: 0 } },\n { upsert: true },\n );\n\n const family = await this.findByFamilyId(familyId);\n\n if (!family) throw new Error(\"Token family upsert did not return a family\");\n\n if (family.get(\"user_id\") !== user.id || family.get<string>(\"user_type\") !== user.userType) {\n throw new Error(\"Token family belongs to a different user\");\n }\n\n return family;\n }\n\n /** Every non-revoked family for a user, including a rotated refresh row. */\n public static activeFor(user: Auth): Promise<AuthTokenFamily[]> {\n return this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .get();\n }\n\n /**\n * Compare-and-set the family revision. A zero result is a concurrent family\n * transition, never a successful no-op.\n */\n public static advanceRevision(familyId: string, expectedRevision: number): Promise<number> {\n return this.atomic(\n { family_id: familyId, revision: expectedRevision, revoked_at: null },\n { $inc: { revision: 1 } },\n );\n }\n\n /** Stamp the durable family revoke marker after a successful CAS. */\n public static revoke(familyId: string, expectedRevision: number): Promise<number> {\n return this.atomic(\n { family_id: familyId, revision: expectedRevision + 1, revoked_at: null },\n { $set: { revoked_at: new Date() } },\n );\n }\n}\n"],"mappings":";;;;;AAKA,MAAa,wBAAwB,EAAE,OAAO;CAC5C,WAAW,EAAE,OAAO,CAAC,CAA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I,WAAW,KAAK;GAAU,YAAY;EAAK,CAAC,CAAC,CACvE,IAAI;CACT;;;;;CAMA,OAAc,gBAAgB,UAAkB,kBAA2C;EACzF,OAAO,KAAK,OACV;GAAE,WAAW;GAAU,UAAU;GAAkB,YAAY;EAAK,GACpE,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,CAC1B;CACF;;CAGA,OAAc,OAAO,UAAkB,kBAA2C;EAChF,OAAO,KAAK,OACV;GAAE,WAAW;GAAU,UAAU,mBAAmB;GAAG,YAAY;EAAK,GACxE,EAAE,MAAM,EAAE,4BAAY,IAAI,KAAK,EAAE,EAAE,CACrC;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/auth-token-family/migration.ts"],"mappings":";;;;;AAIA,MAAa,2BAA2B,QAAQ,iBAAiB;CAC/D,MAAM;CACN,KAAK;EACH,KAAK,uBAAuB;EAC5B,KAAK,YAAY;EACjB,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,OAAO;EACpC,KAAK,UAAU,SAAS,CAAC,CAAC,MAAM;EAChC,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS;EACtC,KAAK,QAAQ,UAAU,CAAC,CAAC,QAAQ,CAAC;EAClC,KAAK,UAAU,YAAY,CAAC,CAAC,SAAS;EACtC,KAAK,WAAW;CAClB;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/auth-token-family/migration.ts"],"sourcesContent":["import { migrate } from \"@warlock.js/cascade\";\nimport { AuthTokenFamily } from \"./auth-token-family.model\";\n\n/** Creates the durable authority shared by every token in a refresh family. */\nexport const AuthTokenFamilyMigration = migrate(AuthTokenFamily, {\n name: \"authTokenFamily\",\n up() {\n this.createTableIfNotExists();\n this.primaryUuid();\n this.string(\"family_id\", 64).unique();\n this.foreignId(\"user_id\").index();\n this.string(\"user_type\", 50).nullable();\n this.integer(\"revision\").default(0);\n this.timestamp(\"revoked_at\").nullable();\n this.timestamps();\n },\n down() {\n this.dropTableIfExists();\n },\n});\n"],"mappings":";;;;;AAIA,MAAa,2BAA2B,QAAQ,iBAAiB;CAC/D,MAAM;CACN,KAAK;EACH,KAAK,uBAAuB;EAC5B,KAAK,YAAY;EACjB,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,OAAO;EACpC,KAAK,UAAU,SAAS,CAAC,CAAC,MAAM;EAChC,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS;EACtC,KAAK,QAAQ,UAAU,CAAC,CAAC,QAAQ,CAAC;EAClC,KAAK,UAAU,YAAY,CAAC,CAAC,SAAS;EACtC,KAAK,WAAW;CAClB;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.model.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/models/auth.model.ts"],"mappings":";;;;;AAQA,IAAsB,OAAtB,cACU,MAEV;;gBAQmC,CAAC,UAAU;;;;;CAU5C,AAAO,qBAAqB;EAC1B,OAAO,YAAY,wBAAwB,IAAI;CACjD;;;;CAKA,MAAa,gBAAgB,YAA6C;EACxE,OAAO,YAAY,gBAAgB,MAAM,UAAU;CACrD;;;;CAKA,MAAa,oBAAoB,MAAwC;EACvE,OAAO,YAAY,oBAAoB,MAAM,IAAI;CACnD;;;;CAKA,MAAa,qBAAqB,YAA4D;EAC5F,OAAO,YAAY,mBAAmB,MAAM,UAAU;CACxD;;;;CAKA,MAAa,kBAAkB,OAA8B;EAC3D,OAAO,YAAY,kBAAkB,MAAM,KAAK;CAClD;;;;CAKA,MAAa,mBAAmB,OAA8B;EAC5D,OAAO,YAAY,mBAAmB,MAAM,KAAK;CACnD;;;;CAKA,MAAa,wBAAuC;EAClD,OAAO,YAAY,sBAAsB,IAAI;CAC/C;;;;CAKA,MAAa,kBAAiC;EAC5C,OAAO,YAAY,gBAAgB,IAAI;CACzC;;;;CAKA,MAAa,iBAA0C;EACrD,OAAO,YAAY,kBAAkB,IAAI;CAC3C;;;;CAKA,aAAoB,QAAgC,MAAiC;EACnF,OAAO,YAAY,aAAa,MAAM,IAAI;CAC5C;;;;CAKA,MAAa,gBAAgB,UAAoC;EAC/D,OAAO,YAAY,eAAe,UAAU,KAAK,OAAO,UAAU,CAAE;CACtE;AACF"}
|
|
1
|
+
{"version":3,"file":"auth.model.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/models/auth.model.ts"],"sourcesContent":["import { type ChildModel, Model, type ModelSchema } from \"@warlock.js/cascade\";\nimport type { Authenticable } from \"../contracts/auth-contract\";\nimport type { AccessTokenOutput, DeviceInfo, TokenPair } from \"../contracts/types\";\nimport { authService } from \"../services\";\nimport type { RefreshToken } from \"./refresh-token/refresh-token.model\";\n\n// `out` keeps a typed auth model assignable to the loose `Auth`, like `Model` itself.\n// @ts-expect-error TS2636: variance cannot be verified through Model's typed get()/set()\nexport abstract class Auth<out Schema extends ModelSchema = ModelSchema>\n extends Model<Schema>\n implements Authenticable\n{\n /**\n * The password hash never leaves the server through serialization:\n * `toJSON()` (so `response.json(user)`), lean query rows and embedded\n * copies all drop it, while `user.get(\"password\")` / `user.string(\"password\")`\n * still read it for verification. A subclass that sets its own `hidden`\n * replaces this list, so keep `\"password\"` in it.\n */\n public static hidden: string[] = [\"password\"];\n\n /**\n * Get user type\n */\n public abstract get userType(): string;\n\n /**\n * Get access token payload\n */\n public accessTokenPayload() {\n return authService.buildAccessTokenPayload(this);\n }\n\n /**\n * Create both access and refresh tokens\n */\n public async createTokenPair(deviceInfo?: DeviceInfo): Promise<TokenPair> {\n return authService.createTokenPair(this, deviceInfo);\n }\n\n /**\n * Generate access token\n */\n public async generateAccessToken(data?: any): Promise<AccessTokenOutput> {\n return authService.generateAccessToken(this, data);\n }\n\n /**\n * Generate refresh token\n */\n public async generateRefreshToken(deviceInfo?: DeviceInfo): Promise<RefreshToken | undefined> {\n return authService.createRefreshToken(this, deviceInfo);\n }\n\n /**\n * Remove current access token\n */\n public async removeAccessToken(token: string): Promise<void> {\n return authService.removeAccessToken(this, token);\n }\n\n /**\n * Remove refresh token\n */\n public async removeRefreshToken(token: string): Promise<void> {\n return authService.removeRefreshToken(this, token);\n }\n\n /**\n * Remove all access tokens\n */\n public async removeAllAccessTokens(): Promise<void> {\n return authService.removeAllAccessTokens(this);\n }\n\n /**\n * Revoke all tokens (logout from all devices)\n */\n public async revokeAllTokens(): Promise<void> {\n return authService.revokeAllTokens(this);\n }\n\n /**\n * Get active sessions\n */\n public async activeSessions(): Promise<RefreshToken[]> {\n return authService.getActiveSessions(this);\n }\n\n /**\n * Attempt to login the user\n */\n public static async attempt(this: ChildModel<Auth>, data: any): Promise<Auth | null> {\n return authService.attemptLogin(this, data);\n }\n\n /**\n * Confirm password\n */\n public async confirmPassword(password: string): Promise<boolean> {\n return authService.verifyPassword(password, this.string(\"password\")!);\n }\n}\n"],"mappings":";;;;;AAQA,IAAsB,OAAtB,cACU,MAEV;;gBAQmC,CAAC,UAAU;;;;;CAU5C,AAAO,qBAAqB;EAC1B,OAAO,YAAY,wBAAwB,IAAI;CACjD;;;;CAKA,MAAa,gBAAgB,YAA6C;EACxE,OAAO,YAAY,gBAAgB,MAAM,UAAU;CACrD;;;;CAKA,MAAa,oBAAoB,MAAwC;EACvE,OAAO,YAAY,oBAAoB,MAAM,IAAI;CACnD;;;;CAKA,MAAa,qBAAqB,YAA4D;EAC5F,OAAO,YAAY,mBAAmB,MAAM,UAAU;CACxD;;;;CAKA,MAAa,kBAAkB,OAA8B;EAC3D,OAAO,YAAY,kBAAkB,MAAM,KAAK;CAClD;;;;CAKA,MAAa,mBAAmB,OAA8B;EAC5D,OAAO,YAAY,mBAAmB,MAAM,KAAK;CACnD;;;;CAKA,MAAa,wBAAuC;EAClD,OAAO,YAAY,sBAAsB,IAAI;CAC/C;;;;CAKA,MAAa,kBAAiC;EAC5C,OAAO,YAAY,gBAAgB,IAAI;CACzC;;;;CAKA,MAAa,iBAA0C;EACrD,OAAO,YAAY,kBAAkB,IAAI;CAC3C;;;;CAKA,aAAoB,QAAgC,MAAiC;EACnF,OAAO,YAAY,aAAa,MAAM,IAAI;CAC5C;;;;CAKA,MAAa,gBAAgB,UAAoC;EAC/D,OAAO,YAAY,eAAe,UAAU,KAAK,OAAO,UAAU,CAAE;CACtE;AACF"}
|
package/esm/models/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/models/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiBA,MAAa,iBAAiB;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/models/index.ts"],"sourcesContent":["import { AccessTokenFamilyAssociationMigration } from \"./access-token/family-association.migration\";\nimport { AccessTokenMigration } from \"./access-token/migration\";\nimport { AuthTokenFamilyMigration } from \"./auth-token-family/migration\";\nimport { OneTimeTokenMigration } from \"./one-time-token/migration\";\nimport { PasskeyCredentialMigration } from \"./passkey-credential/migration\";\nimport { ProviderAccountMigration } from \"./provider-account/migration\";\nimport { RefreshTokenMigration } from \"./refresh-token/migration\";\nimport { RefreshTokenSuccessorAssociationMigration } from \"./refresh-token/successor-association.migration\";\n\nexport * from \"./access-token\";\nexport * from \"./auth-token-family\";\nexport * from \"./auth.model\";\nexport * from \"./one-time-token\";\nexport * from \"./passkey-credential\";\nexport * from \"./provider-account\";\nexport * from \"./refresh-token\";\n\nexport const authMigrations = [\n AccessTokenMigration,\n AccessTokenFamilyAssociationMigration,\n RefreshTokenMigration,\n RefreshTokenSuccessorAssociationMigration,\n AuthTokenFamilyMigration,\n OneTimeTokenMigration,\n ProviderAccountMigration,\n PasskeyCredentialMigration,\n];\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiBA,MAAa,iBAAiB;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/one-time-token/migration.ts"],"mappings":";;;;AAGA,MAAa,wBAAwB,QAAQ,cAAc;CACzD,MAAM;CACN,KAAK;EACH,KAAK,uBAAuB;EAE5B,KAAK,YAAY;EAGjB,KAAK,OAAO,cAAc,EAAE,CAAC,CAAC,OAAO;EACrC,KAAK,OAAO,WAAW,EAAE;EAKzB,KAAK,UAAU,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM;EAC3C,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS;EAEtC,KAAK,UAAU,YAAY,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS;EAC9C,KAAK,UAAU,aAAa,CAAC,CAAC,SAAS;EAGvC,KAAK,QAAQ,UAAU,CAAC,CAAC,QAAQ,CAAC;EAGlC,KAAK,MAAM;GAAC;GAAW;GAAa;EAAS,CAAC;EAE9C,KAAK,WAAW;CAClB;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/one-time-token/migration.ts"],"sourcesContent":["import { migrate } from \"@warlock.js/cascade\";\nimport { OneTimeToken } from \"./one-time-token.model\";\n\nexport const OneTimeTokenMigration = migrate(OneTimeToken, {\n name: \"oneTimeToken\",\n up() {\n this.createTableIfNotExists();\n\n this.primaryUuid();\n\n // SHA-256 hex digest of the raw token โ the raw token is never stored.\n this.string(\"token_hash\", 64).unique();\n this.string(\"purpose\", 32);\n\n // `foreignId` follows the DataSource's default primary-key type, matching\n // the access/refresh token tables. Nullable only for a passkey\n // authentication challenge, which is issued before anyone is identified.\n this.foreignId(\"user_id\").nullable().index();\n this.string(\"user_type\", 50).nullable();\n\n this.timestamp(\"expires_at\").index().nullable();\n this.timestamp(\"consumed_at\").nullable();\n\n // Failed verify attempts โ only OTP codes are capped on it.\n this.integer(\"attempts\").default(0);\n\n // Invalidating a user's previous reset tokens filters on these.\n this.index([\"user_id\", \"user_type\", \"purpose\"]);\n\n this.timestamps();\n },\n down() {\n this.dropTableIfExists();\n },\n});\n"],"mappings":";;;;AAGA,MAAa,wBAAwB,QAAQ,cAAc;CACzD,MAAM;CACN,KAAK;EACH,KAAK,uBAAuB;EAE5B,KAAK,YAAY;EAGjB,KAAK,OAAO,cAAc,EAAE,CAAC,CAAC,OAAO;EACrC,KAAK,OAAO,WAAW,EAAE;EAKzB,KAAK,UAAU,SAAS,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM;EAC3C,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS;EAEtC,KAAK,UAAU,YAAY,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS;EAC9C,KAAK,UAAU,aAAa,CAAC,CAAC,SAAS;EAGvC,KAAK,QAAQ,UAAU,CAAC,CAAC,QAAQ,CAAC;EAGlC,KAAK,MAAM;GAAC;GAAW;GAAa;EAAS,CAAC;EAE9C,KAAK,WAAW;CAClB;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"one-time-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/one-time-token/one-time-token.model.ts"],"mappings":";;;;;;;;;AAiBA,MAAa,qBAAqB,EAAE,OAAO;CACzC,YAAY,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAE7B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;CAC9B,aAAa,EAAE,KAAK,CAAC,CAAC,SAAS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;;;;CAOA,MAAa,cAAc,KAA+B;EAUxD,OAAO,MATY,KAAK,YAES,OAC/B;GAAE,IAAI,KAAK;GAAI,aAAa;GAAM,UAAU,EAAE,KAAK,IAAI;EAAE,GACzD,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,GAExB,EAAE,eAAe,KAAK,CACxB,IAEiB;CACnB;;;;;;;;;;;;CAaA,aAAoB,aAA8B;EAIhD,OAAO,MAHe,KAAK,MAAM,CAAC,CAAC,MAAM,cAAc,qBAAK,IAAI,KAAK,CAAC,CAAC,CAAC,OAAO,IAG9D,MAFM,KAAK,MAAM,CAAC,CAAC,aAAa,aAAa,CAAC,CAAC,OAAO;CAGzE;;CAGA,OAAc,WACZ,WACA,SAC8B;EAC9B,OAAO,KAAK,MAAM;GAAE,YAAY;GAAW;EAAQ,CAAC;CACtD;;;;;CAMA,OAAc,oBAAoB,MAAY,SAA+C;EAC3F,OAAO,KAAK,OACV;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;GAAU;GAAS,aAAa;EAAK,GACzE,EAAE,MAAM,EAAE,6BAAa,IAAI,KAAK,EAAE,EAAE,CACtC;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"one-time-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/one-time-token/one-time-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport { isUsableExpiry } from \"../../utils/token-expiry\";\nimport type { Auth } from \"../auth.model\";\n\n/** What a one-time token may be used for. A token only ever satisfies its own purpose. */\nexport type OneTimeTokenPurpose =\n | \"email-verification\"\n | \"password-reset\"\n | \"otp\"\n | \"passkey-registration\"\n | \"passkey-authentication\";\n\n/**\n * Seal schema for the persisted one-time token. Exported so an override can\n * extend it (e.g. a tenant key).\n */\nexport const oneTimeTokenSchema = v.object({\n token_hash: v.string().required(),\n purpose: v.string().required(),\n // Absent only on a passkey authentication challenge (no user identified yet).\n user_id: v.scalar().optional(),\n user_type: v.string().optional(),\n expires_at: v.date().required(),\n consumed_at: v.date().optional(),\n attempts: v.int().optional(),\n});\n\n/**\n * Persisted one-time secret: email-verification / password-reset token, OTP\n * code, or passkey ceremony challenge.\n *\n * **Only a SHA-256 hash is stored** โ the raw token exists in the notification\n * and nowhere else, so a leaked table cannot be replayed. Single use is\n * enforced by {@link consumeIfActive}, a conditional update in the same shape\n * as `RefreshToken.revokeIfActive`. Override via `config.auth.oneTimeToken.model`.\n */\nexport class OneTimeToken extends Model {\n public static table = \"one_time_tokens\";\n\n public static schema = oneTimeTokenSchema;\n\n /**\n * The SHA-256 of a one-time secret. For a short OTP code the hash is\n * brute-forceable offline, so it is as sensitive as the code itself โ never\n * serialize it. Only `toJSON()` is affected; `findByHash` still queries it.\n */\n public static hidden = [\"token_hash\"];\n\n /**\n * Permanent regardless of the data source default โ Mongo's driver default\n * is `\"trash\"`, which would copy spent token hashes into\n * `one_time_tokensTrash` on every `destroy()`. A purged one-time token must\n * not survive anywhere.\n */\n public static deleteStrategy = \"permanent\" as const;\n\n /** The user this token was issued for. */\n public get userId() {\n return this.get(\"user_id\");\n }\n\n /** The user-type slug this token was issued for. */\n public get userType(): string {\n return this.get(\"user_type\");\n }\n\n /** Whether the token has been used (or invalidated by a newer one). */\n public get isConsumed(): boolean {\n return !!this.get(\"consumed_at\");\n }\n\n /** Whether the expiry has passed. Fails closed: an unusable `expires_at` counts as expired. */\n public get isExpired(): boolean {\n const expiresAt = this.get(\"expires_at\");\n\n if (!isUsableExpiry(expiresAt)) return true;\n\n return new Date(expiresAt).getTime() <= Date.now();\n }\n\n /**\n * Atomically mark this token consumed ONLY if nobody has yet. Resolves `true`\n * for the single caller that won; every concurrent or later caller gets\n * `false`.\n */\n public async consumeIfActive(): Promise<boolean> {\n const modelClass = this.constructor as typeof OneTimeToken;\n\n const consumed = await modelClass.atomic(\n { id: this.id, consumed_at: null },\n { $set: { consumed_at: new Date() } },\n );\n\n return consumed > 0;\n }\n\n /** Persist a new token row. `tokenHash` is the SHA-256 hex digest, never the raw token. */\n public static issue(\n user: Auth,\n purpose: OneTimeTokenPurpose,\n tokenHash: string,\n expiresAt: Date,\n ) {\n return this.create({\n token_hash: tokenHash,\n purpose,\n user_id: user.id,\n user_type: user.userType,\n expires_at: expiresAt,\n consumed_at: null,\n attempts: 0,\n });\n }\n\n /**\n * Persist a passkey ceremony challenge. `user` is omitted for an\n * authentication challenge, issued before anyone is identified.\n */\n public static issueChallenge(\n purpose: OneTimeTokenPurpose,\n tokenHash: string,\n expiresAt: Date,\n user?: Auth,\n ) {\n return this.create({\n token_hash: tokenHash,\n purpose,\n user_id: user?.id ?? null,\n user_type: user?.userType ?? null,\n expires_at: expiresAt,\n consumed_at: null,\n attempts: 0,\n });\n }\n\n /** The user's newest unconsumed token of `purpose` (at most one for OTP). */\n public static findActiveFor(\n user: Auth,\n purpose: OneTimeTokenPurpose,\n ): Promise<OneTimeToken | null> {\n return this.query()\n .where({ user_id: user.id, user_type: user.userType, purpose, consumed_at: null })\n .orderBy(\"created_at\", \"desc\")\n .first();\n }\n\n /**\n * Atomically count one verify attempt, ONLY while fewer than `max` have been\n * counted and the token is unconsumed. Resolves `false` once the cap is\n * reached โ of N concurrent attempts, at most `max` ever resolve `true`.\n */\n public async recordAttempt(max: number): Promise<boolean> {\n const modelClass = this.constructor as typeof OneTimeToken;\n\n const counted = await modelClass.atomic(\n { id: this.id, consumed_at: null, attempts: { $lt: max } },\n { $inc: { attempts: 1 } },\n // Code-authored filter; nothing here comes from the request.\n { trustedFilter: true },\n );\n\n return counted > 0;\n }\n\n /**\n * Hard-delete every spent row โ expired, or consumed (used, invalidated by a\n * newer token, or exhausted). Neither can ever be redeemed again, so nothing\n * reads them. Returns the number removed. Runs from the `auth.cleanup` CLI\n * command.\n *\n * Two set-based deletes, never a read: the rows are not loaded into memory,\n * so a table grown by anonymous passkey-option calls cannot make the cleanup\n * run out of memory. A query-builder delete is a driver-level hard delete,\n * so no token hash is copied into a trash collection.\n */\n public static async purgeSpent(): Promise<number> {\n const expired = await this.query().where(\"expires_at\", \"<\", new Date()).delete();\n const consumed = await this.query().whereNotNull(\"consumed_at\").delete();\n\n return expired + consumed;\n }\n\n /** Find a token by hash, scoped to a purpose โ a token of the other purpose is not found. */\n public static findByHash(\n tokenHash: string,\n purpose: OneTimeTokenPurpose,\n ): Promise<OneTimeToken | null> {\n return this.first({ token_hash: tokenHash, purpose });\n }\n\n /**\n * Consume every still-unused token of `purpose` for the user, returning how\n * many were invalidated. Used before issuing a new password-reset token.\n */\n public static invalidateActiveFor(user: Auth, purpose: OneTimeTokenPurpose): Promise<number> {\n return this.atomic(\n { user_id: user.id, user_type: user.userType, purpose, consumed_at: null },\n { $set: { consumed_at: new Date() } },\n );\n }\n}\n"],"mappings":";;;;;;;;;AAiBA,MAAa,qBAAqB,EAAE,OAAO;CACzC,YAAY,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAE7B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;CAC9B,aAAa,EAAE,KAAK,CAAC,CAAC,SAAS;CAC/B,UAAU,EAAE,IAAI,CAAC,CAAC,SAAS;AAC7B,CAAC;;;;;;;;;;AAWD,IAAa,eAAb,cAAkC,MAAM;;eAChB;;;gBAEC;;;gBAOA,CAAC,YAAY;;;wBAQL;;;CAG/B,IAAW,SAAS;EAClB,OAAO,KAAK,IAAI,SAAS;CAC3B;;CAGA,IAAW,WAAmB;EAC5B,OAAO,KAAK,IAAI,WAAW;CAC7B;;CAGA,IAAW,aAAsB;EAC/B,OAAO,CAAC,CAAC,KAAK,IAAI,aAAa;CACjC;;CAGA,IAAW,YAAqB;EAC9B,MAAM,YAAY,KAAK,IAAI,YAAY;EAEvC,IAAI,CAAC,eAAe,SAAS,GAAG,OAAO;EAEvC,OAAO,IAAI,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EAC9B,OAAO,KAAK,MAAM;GAAE,YAAY;GAAW;EAAQ,CAAC;CACtD;;;;;CAMA,OAAc,oBAAoB,MAAY,SAA+C;EAC3F,OAAO,KAAK,OACV;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;GAAU;GAAS,aAAa;EAAK,GACzE,EAAE,MAAM,EAAE,6BAAa,IAAI,KAAK,EAAE,EAAE,CACtC;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/passkey-credential/migration.ts"],"mappings":";;;;AAGA,MAAa,6BAA6B,QAAQ,mBAAmB;CACnE,MAAM;CACN,KAAK;EACH,KAAK,uBAAuB;EAE5B,KAAK,YAAY;EAEjB,KAAK,KAAK,eAAe,CAAC,CAAC,OAAO;EAClC,KAAK,KAAK,YAAY;EACtB,KAAK,WAAW,SAAS,CAAC,CAAC,QAAQ,CAAC;EACpC,KAAK,KAAK,YAAY,CAAC,CAAC,SAAS;EACjC,KAAK,UAAU,SAAS,CAAC,CAAC,MAAM;EAChC,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS;EAEtC,KAAK,WAAW;CAClB;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/passkey-credential/migration.ts"],"sourcesContent":["import { migrate } from \"@warlock.js/cascade\";\nimport { PasskeyCredential } from \"./passkey-credential.model\";\n\nexport const PasskeyCredentialMigration = migrate(PasskeyCredential, {\n name: \"passkeyCredential\",\n up() {\n this.createTableIfNotExists();\n\n this.primaryUuid();\n\n this.text(\"credential_id\").unique();\n this.text(\"public_key\");\n this.bigInteger(\"counter\").default(0);\n this.json(\"transports\").nullable();\n this.foreignId(\"user_id\").index();\n this.string(\"user_type\", 50).nullable();\n\n this.timestamps();\n },\n down() {\n this.dropTableIfExists();\n },\n});\n"],"mappings":";;;;AAGA,MAAa,6BAA6B,QAAQ,mBAAmB;CACnE,MAAM;CACN,KAAK;EACH,KAAK,uBAAuB;EAE5B,KAAK,YAAY;EAEjB,KAAK,KAAK,eAAe,CAAC,CAAC,OAAO;EAClC,KAAK,KAAK,YAAY;EACtB,KAAK,WAAW,SAAS,CAAC,CAAC,QAAQ,CAAC;EACpC,KAAK,KAAK,YAAY,CAAC,CAAC,SAAS;EACjC,KAAK,UAAU,SAAS,CAAC,CAAC,MAAM;EAChC,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS;EAEtC,KAAK,WAAW;CAClB;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"passkey-credential.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/passkey-credential/passkey-credential.model.ts"],"mappings":";;;;;AAKA,MAAa,0BAA0B,EAAE,OAAO;CAC9C,eAAe,EAAE,OAAO,CAAC,CAAC,SAAS;CACnC,YAAY,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,SAAS,EAAE,IAAI,CAAC,CAAC,SAAS;CAC1B,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;CACzC,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;AACjC,CAAC;;;;;;AAOD,IAAa,oBAAb,cAAuC,MAAM;;eACrB;;;gBAEC;;;wBAQQ;;;CAG/B,IAAW,eAAuB;EAChC,OAAO,KAAK,IAAI,eAAe;CACjC;;CAGA,IAAW,UAAkB;EAC3B,OAAO,OAAO,KAAK,IAAI,SAAS,KAAK,CAAC;CACxC;;CAGA,IAAW,SAAS;EAClB,OAAO,KAAK,IAAI,SAAS;CAC3B;;CAGA,IAAW,WAAmB;EAC5B,OAAO,KAAK,IAAI,WAAW;CAC7B;;CAGA,OAAc,mBAAmB,cAAyD;EACxF,OAAO,KAAK,MAAM,EAAE,eAAe,aAAa,CAAC;CACnD;;CAGA,OAAc,QAAQ,MAA0C;EAC9D,OAAO,KAAK,MAAM,CAAC,CAAC,MAAM;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;EAAS,CAAC,CAAC,CAAC,IAAI;CAChF;;;;;CAMA,MAAa,eAAe,UAAkB,YAAsC;EAQlF,OAAO,MAPY,KAAK,YAES,OAC/B;GAAE,IAAI,KAAK;GAAI,SAAS;EAAS,GACjC,EAAE,MAAM,EAAE,SAAS,WAAW,EAAE,CAClC,IAEiB;CACnB;AACF"}
|
|
1
|
+
{"version":3,"file":"passkey-credential.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/passkey-credential/passkey-credential.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport type { Auth } from \"../auth.model\";\n\n/** Seal schema for a stored passkey. Exported so an override can extend it. */\nexport const passkeyCredentialSchema = v.object({\n credential_id: v.string().required(),\n public_key: v.string().required(),\n counter: v.int().required(),\n transports: v.array(v.string()).optional(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n});\n\n/**\n * A registered WebAuthn credential. `credential_id` and `public_key` are\n * base64url; `counter` is the last signature counter seen, which an\n * authentication must advance (a clone detector).\n */\nexport class PasskeyCredential extends Model {\n public static table = \"passkey_credentials\";\n\n public static schema = passkeyCredentialSchema;\n\n /**\n * Permanent regardless of the data source default โ Mongo's driver default\n * is `\"trash\"`. No call site deletes a credential today, but the public key\n * is credential material, so a future `destroy()` here must not leave a\n * copy in `passkey_credentialsTrash`.\n */\n public static deleteStrategy = \"permanent\" as const;\n\n /** base64url credential id. */\n public get credentialId(): string {\n return this.get(\"credential_id\");\n }\n\n /** Last signature counter seen. */\n public get counter(): number {\n return Number(this.get(\"counter\") ?? 0);\n }\n\n /** The owner's id. */\n public get userId() {\n return this.get(\"user_id\");\n }\n\n /** The owner's type slug. */\n public get userType(): string {\n return this.get(\"user_type\");\n }\n\n /** Find a credential by its base64url id. */\n public static findByCredentialId(credentialId: string): Promise<PasskeyCredential | null> {\n return this.first({ credential_id: credentialId });\n }\n\n /** Every credential the user registered. */\n public static listFor(user: Auth): Promise<PasskeyCredential[]> {\n return this.query().where({ user_id: user.id, user_type: user.userType }).get();\n }\n\n /**\n * Store `newCounter` ONLY if the row still holds `expected` โ a compare-and-set,\n * so two concurrent assertions with the same counter cannot both succeed.\n */\n public async advanceCounter(expected: number, newCounter: number): Promise<boolean> {\n const modelClass = this.constructor as typeof PasskeyCredential;\n\n const updated = await modelClass.atomic(\n { id: this.id, counter: expected },\n { $set: { counter: newCounter } },\n );\n\n return updated > 0;\n }\n}\n"],"mappings":";;;;;AAKA,MAAa,0BAA0B,EAAE,OAAO;CAC9C,eAAe,EAAE,OAAO,CAAC,CAAC,SAAS;CACnC,YAAY,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,SAAS,EAAE,IAAI,CAAC,CAAC,SAAS;CAC1B,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS;CACzC,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;AACjC,CAAC;;;;;;AAOD,IAAa,oBAAb,cAAuC,MAAM;;eACrB;;;gBAEC;;;wBAQQ;;;CAG/B,IAAW,eAAuB;EAChC,OAAO,KAAK,IAAI,eAAe;CACjC;;CAGA,IAAW,UAAkB;EAC3B,OAAO,OAAO,KAAK,IAAI,SAAS,KAAK,CAAC;CACxC;;CAGA,IAAW,SAAS;EAClB,OAAO,KAAK,IAAI,SAAS;CAC3B;;CAGA,IAAW,WAAmB;EAC5B,OAAO,KAAK,IAAI,WAAW;CAC7B;;CAGA,OAAc,mBAAmB,cAAyD;EACxF,OAAO,KAAK,MAAM,EAAE,eAAe,aAAa,CAAC;CACnD;;CAGA,OAAc,QAAQ,MAA0C;EAC9D,OAAO,KAAK,MAAM,CAAC,CAAC,MAAM;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;EAAS,CAAC,CAAC,CAAC,IAAI;CAChF;;;;;CAMA,MAAa,eAAe,UAAkB,YAAsC;EAQlF,OAAO,MAPY,KAAK,YAES,OAC/B;GAAE,IAAI,KAAK;GAAI,SAAS;EAAS,GACjC,EAAE,MAAM,EAAE,SAAS,WAAW,EAAE,CAClC,IAEiB;CACnB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/provider-account/migration.ts"],"mappings":";;;;AAGA,MAAa,2BAA2B,QAAQ,iBAAiB;CAC/D,MAAM;CACN,KAAK;EACH,KAAK,uBAAuB;EAE5B,KAAK,YAAY;EAEjB,KAAK,OAAO,YAAY,EAAE;EAC1B,KAAK,OAAO,oBAAoB,GAAG;EACnC,KAAK,UAAU,SAAS,CAAC,CAAC,MAAM;EAChC,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS;EACtC,KAAK,OAAO,SAAS,GAAG,CAAC,CAAC,SAAS;EAGnC,KAAK,OAAO,CAAC,YAAY,kBAAkB,CAAC;EAE5C,KAAK,WAAW;CAClB;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/provider-account/migration.ts"],"sourcesContent":["import { migrate } from \"@warlock.js/cascade\";\nimport { ProviderAccount } from \"./provider-account.model\";\n\nexport const ProviderAccountMigration = migrate(ProviderAccount, {\n name: \"providerAccount\",\n up() {\n this.createTableIfNotExists();\n\n this.primaryUuid();\n\n this.string(\"provider\", 50);\n this.string(\"provider_user_id\", 255);\n this.foreignId(\"user_id\").index();\n this.string(\"user_type\", 50).nullable();\n this.string(\"email\", 255).nullable();\n\n // One app user per provider identity.\n this.unique([\"provider\", \"provider_user_id\"]);\n\n this.timestamps();\n },\n down() {\n this.dropTableIfExists();\n },\n});\n"],"mappings":";;;;AAGA,MAAa,2BAA2B,QAAQ,iBAAiB;CAC/D,MAAM;CACN,KAAK;EACH,KAAK,uBAAuB;EAE5B,KAAK,YAAY;EAEjB,KAAK,OAAO,YAAY,EAAE;EAC1B,KAAK,OAAO,oBAAoB,GAAG;EACnC,KAAK,UAAU,SAAS,CAAC,CAAC,MAAM;EAChC,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS;EACtC,KAAK,OAAO,SAAS,GAAG,CAAC,CAAC,SAAS;EAGnC,KAAK,OAAO,CAAC,YAAY,kBAAkB,CAAC;EAE5C,KAAK,WAAW;CAClB;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-account.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/provider-account/provider-account.model.ts"],"mappings":";;;;;AAKA,MAAa,wBAAwB,EAAE,OAAO;CAC5C,UAAU,EAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,kBAAkB,EAAE,OAAO,CAAC,CAAC,SAAS;CACtC,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;AAC7B,CAAC;;;;;;;AAQD,IAAa,kBAAb,cAAqC,MAAM;;eACnB;;;gBAEC;;;CAGvB,IAAW,SAAS;EAClB,OAAO,KAAK,IAAI,SAAS;CAC3B;;CAGA,IAAW,WAAmB;EAC5B,OAAO,KAAK,IAAI,WAAW;CAC7B;;CAGA,OAAc,SACZ,UACA,gBACiC;EACjC,OAAO,KAAK,MAAM;GAAE;GAAU,kBAAkB;EAAe,CAAC;CAClE;;CAGA,OAAc,KAAK,UAAkB,gBAAwB,MAAY,OAAgB;EACvF,OAAO,KAAK,OAAO;GACjB;GACA,kBAAkB;GAClB,SAAS,KAAK;GACd,WAAW,KAAK;GAChB,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;EAC3B,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"provider-account.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/provider-account/provider-account.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport type { Auth } from \"../auth.model\";\n\n/** Seal schema for a provider link. Exported so an override can extend it. */\nexport const providerAccountSchema = v.object({\n provider: v.string().required(),\n provider_user_id: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n email: v.string().optional(),\n});\n\n/**\n * Links a provider identity (`provider` + the provider's stable user id) to\n * an app user. Created the first time a VERIFIED provider email is matched or\n * a user is created for it; afterwards the link alone resolves the user, so a\n * later email change at the provider cannot move the login to another account.\n */\nexport class ProviderAccount extends Model {\n public static table = \"provider_accounts\";\n\n public static schema = providerAccountSchema;\n\n /** The linked user's id. */\n public get userId() {\n return this.get(\"user_id\");\n }\n\n /** The linked user's type slug. */\n public get userType(): string {\n return this.get(\"user_type\");\n }\n\n /** Find the link for a provider identity. */\n public static findLink(\n provider: string,\n providerUserId: string,\n ): Promise<ProviderAccount | null> {\n return this.first({ provider, provider_user_id: providerUserId });\n }\n\n /** Link a provider identity to a user. */\n public static link(provider: string, providerUserId: string, user: Auth, email?: string) {\n return this.create({\n provider,\n provider_user_id: providerUserId,\n user_id: user.id,\n user_type: user.userType,\n ...(email ? { email } : {}),\n });\n }\n}\n"],"mappings":";;;;;AAKA,MAAa,wBAAwB,EAAE,OAAO;CAC5C,UAAU,EAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,kBAAkB,EAAE,OAAO,CAAC,CAAC,SAAS;CACtC,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;AAC7B,CAAC;;;;;;;AAQD,IAAa,kBAAb,cAAqC,MAAM;;eACnB;;;gBAEC;;;CAGvB,IAAW,SAAS;EAClB,OAAO,KAAK,IAAI,SAAS;CAC3B;;CAGA,IAAW,WAAmB;EAC5B,OAAO,KAAK,IAAI,WAAW;CAC7B;;CAGA,OAAc,SACZ,UACA,gBACiC;EACjC,OAAO,KAAK,MAAM;GAAE;GAAU,kBAAkB;EAAe,CAAC;CAClE;;CAGA,OAAc,KAAK,UAAkB,gBAAwB,MAAY,OAAgB;EACvF,OAAO,KAAK,OAAO;GACjB;GACA,kBAAkB;GAClB,SAAS,KAAK;GACd,WAAW,KAAK;GAChB,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;EAC3B,CAAC;CACH;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/refresh-token/migration.ts"],"mappings":";;;;AAGA,MAAa,wBAAwB,QAAQ,cAAc;CACzD,MAAM;CACN,KAAK;EAEH,KAAK,uBAAuB;EAG5B,KAAK,YAAY;EAGjB,KAAK,KAAK,OAAO,CAAC,CAAC,OAAO;EAI1B,KAAK,UAAU,SAAS,CAAC,CAAC,MAAM;EAChC,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS;EACtC,KAAK,KAAK,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS;EACxC,KAAK,UAAU,YAAY,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS;EAC9C,KAAK,UAAU,cAAc,CAAC,CAAC,SAAS;EACxC,KAAK,UAAU,YAAY,CAAC,CAAC,SAAS;EACtC,KAAK,KAAK,aAAa,CAAC,CAAC,SAAS;EAIlC,KAAK,MAAM,CAAC,WAAW,WAAW,CAAC;EAGnC,KAAK,WAAW;CAClB;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/refresh-token/migration.ts"],"sourcesContent":["import { migrate } from \"@warlock.js/cascade\";\nimport { RefreshToken } from \"./refresh-token.model\";\n\nexport const RefreshTokenMigration = migrate(RefreshToken, {\n name: \"refreshToken\",\n up() {\n // Create table\n this.createTableIfNotExists();\n\n // Primary key\n this.primaryUuid();\n\n // Token fields\n this.text(\"token\").unique();\n // `foreignId` matches the DataSource's default primary-key type so the\n // column stays compatible with the user model's `id` (integer by default,\n // or uuid) โ hardcoding uuid here 500'd login on integer-PK apps (5e47bdb3).\n this.foreignId(\"user_id\").index();\n this.string(\"user_type\", 50).nullable();\n this.text(\"family_id\").index().nullable();\n this.timestamp(\"expires_at\").index().nullable();\n this.timestamp(\"last_used_at\").nullable();\n this.timestamp(\"revoked_at\").nullable();\n this.json(\"device_info\").nullable();\n\n // Composite index for the per-user active-session lookups\n // (revokeAllFor / enforceMax / activeFor all filter on user_id + user_type).\n this.index([\"user_id\", \"user_type\"]);\n\n // Timestamps\n this.timestamps();\n },\n down() {\n this.dropTableIfExists();\n },\n});\n"],"mappings":";;;;AAGA,MAAa,wBAAwB,QAAQ,cAAc;CACzD,MAAM;CACN,KAAK;EAEH,KAAK,uBAAuB;EAG5B,KAAK,YAAY;EAGjB,KAAK,KAAK,OAAO,CAAC,CAAC,OAAO;EAI1B,KAAK,UAAU,SAAS,CAAC,CAAC,MAAM;EAChC,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS;EACtC,KAAK,KAAK,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS;EACxC,KAAK,UAAU,YAAY,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS;EAC9C,KAAK,UAAU,cAAc,CAAC,CAAC,SAAS;EACxC,KAAK,UAAU,YAAY,CAAC,CAAC,SAAS;EACtC,KAAK,KAAK,aAAa,CAAC,CAAC,SAAS;EAIlC,KAAK,MAAM,CAAC,WAAW,WAAW,CAAC;EAGnC,KAAK,WAAW;CAClB;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC"}
|