@warlock.js/auth 5.53.0 → 5.54.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- 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/providers.d.mts +1 -1
- package/esm/contracts/types.d.mts +22 -0
- package/esm/contracts/types.d.mts.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.d.mts +1 -1
- package/esm/middleware/login-throttle.middleware.d.mts.map +1 -1
- package/esm/middleware/login-throttle.middleware.mjs +18 -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.d.mts +14 -0
- package/esm/models/auth-token-family/auth-token-family.model.d.mts.map +1 -1
- package/esm/models/auth-token-family/auth-token-family.model.mjs +43 -0
- 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.d.mts.map +1 -1
- package/esm/models/refresh-token/refresh-token.model.mjs +6 -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.d.mts +5 -4
- package/esm/otp/otp.d.mts.map +1 -1
- package/esm/otp/otp.mjs +25 -20
- 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 +40 -3
- 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.d.mts +11 -2
- package/esm/services/auth.service.d.mts.map +1 -1
- package/esm/services/auth.service.mjs +36 -9
- package/esm/services/auth.service.mjs.map +1 -1
- package/esm/services/background-work.mjs +16 -0
- package/esm/services/background-work.mjs.map +1 -0
- 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.d.mts +2 -2
- package/esm/services/jwt.d.mts.map +1 -1
- package/esm/services/jwt.mjs +51 -26
- 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.d.mts +7 -5
- package/esm/services/password-reset.d.mts.map +1 -1
- package/esm/services/password-reset.mjs +25 -19
- 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/llms-full.txt +8 -6
- package/package.json +11 -11
- package/skills/auth-basics/SKILL.md +1 -1
- package/skills/login-with-providers/SKILL.md +2 -2
- package/skills/manage-tokens/SKILL.md +2 -0
- package/skills/throttle-login-attempts/SKILL.md +2 -2
- package/skills/verify-email-and-reset-password/SKILL.md +1 -1
|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,YAAY,OAAO,IAAI,iBAAiB,UAAU;CAExD,IAAI,CAAC,WAGH,MAAM,IAAI,MAAM,aAAa,SAAS,kBAAkB;CAG1D,MAAM,cAAc,MAAM,UAAU,KAAK,QAAQ,EAAE;CAEnD,IAAI,CAAC,aAAa;EAChB,MAAM,YAAY,QAAQ;EAE1B,OAAO,KAAK,SAAS;CACvB;CAEA,IAAI,CAAE,MAAM,YAAY,gBAAgB,WAAW,GACjD,OAAO,KAAK,cAAc;CAG5B,OAAO,EAAE,MAAM,YAAY;AAC7B;;;;;;;;AASA,SAAgB,mBACd,SACA,UACA,UAAqC,CAAC,GACxB;CAId,IAAI,CAAC,QAAQ,OAAO,SAClB,QAAQ,OAAO,UAAU,0BAA0B,SAAS,UAAU,OAAO,CAAC,CAAC,MAC5E,YAAY,QAAQ,IACvB;CAGF,OAAO,QAAQ,OAAO;AACxB"}
|
|
1
|
+
{"version":3,"file":"resolve-request-user.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/resolve-request-user.ts"],"sourcesContent":["import { config, type Request, type Response } from \"@warlock.js/core\";\nimport { log } from \"@warlock.js/logger\";\nimport type { CookieDomainResolver, TokenFrom } from \"../contracts/types\";\nimport { AccessToken } from \"../models/access-token\";\nimport { readAuthCookie } from \"./auth-cookie-names\";\nimport { authService } from \"./auth.service\";\nimport { isInvalidCredentialError, jwt } from \"./jwt\";\n\n/**\n * Decoded access-token claims the resolver reads. The full payload carries\n * more (`created_at`, `tokenType`, `iat`, `exp`) but only these drive routing.\n */\ntype DecodedAccessToken = {\n id: string | number;\n userType?: string;\n};\n\nexport type ResolveRequestUserOptions = {\n /** Where the access token is read from. Defaults to `\"header\"`. */\n tokenFrom?: TokenFrom;\n /** Refresh credential source; enables one automatic renewal per call. */\n refreshCredential?: TokenFrom;\n /** Refresh overlap window forwarded to `authService.renewAutomaticSession`. */\n overlapMs?: number;\n /** User types allowed to pass. Empty means any authenticated type. */\n allowedTypes?: string[];\n /** Absolute family lifetime in ms; rotation never extends a family past it. */\n maxAgeMs?: number;\n /** The single user type a renewal mints for. Required for renewal. */\n renewalUserType?: string;\n /** Select a request-scoped Domain for renewed cookies. */\n cookieDomain?: CookieDomainResolver;\n};\n\n/**\n * Why a request did not resolve to a user. The middleware maps each reason to\n * its own response; `resolveRequestUser` collapses them all to `null`.\n */\nexport type RequestUserFailure = \"missing\" | \"invalid\" | \"forbidden\" | \"unauthorized\";\n\nexport type RequestUserOutcome<TUser = any> =\n | { user: TUser; failure?: undefined }\n | { user: null; failure: RequestUserFailure };\n\n/**\n * Whether the persisted row says the token is dead.\n *\n * The answer belongs to the model (`AccessToken.isExpired`), so a registered\n * override that renames or reshapes its expiry column stays authoritative. A\n * row that cannot answer at all — an override that dropped the getter — is\n * treated as **expired**: a check must never quietly answer \"fine\" when it has\n * nothing to check.\n *\n * This is independent of the `exp` claim required by `jwt.verify`: that guard\n * catches a token whose *claims* carry no deadline; this one catches a token\n * whose *row* says the deadline has passed.\n */\nfunction accessTokenRowIsExpired(accessToken: AccessToken): boolean {\n return typeof accessToken.isExpired === \"boolean\" ? accessToken.isExpired : true;\n}\n\n/**\n * Whether the token's claims name the user its row was issued to. The row is\n * what proves the token was issued and not revoked; the user it resolves to\n * must be that row's user too, never only what the claims say.\n */\nfunction claimsMatchRow(decoded: DecodedAccessToken, accessToken: AccessToken): boolean {\n if (String(decoded.id) !== String(accessToken.userId)) return false;\n\n return decoded.userType === undefined || decoded.userType === accessToken.userType;\n}\n\n/** Read one credential (access or refresh) from the header or a cookie. */\nexport function readCredential(request: Request, tokenFrom: TokenFrom): string {\n if (tokenFrom === \"header\") {\n return request.authorizationValue;\n }\n\n return readAuthCookie(request, tokenFrom.slice(\"cookie:\".length));\n}\n\n/**\n * Resolve a request's credential to a user, reporting WHY it failed.\n *\n * Side effects match what `authMiddleware` always did: `request.locals.user` is\n * cleared on every failure, `request.decodedAccessToken` is set once a token\n * verifies, and stale rows are destroyed. It does NOT set `request.locals.user`\n * on success — the caller decides that.\n *\n * At most one renewal is attempted per call. The renewed access token is\n * checked through the same path; no handler or unsafe request replay happens.\n */\nexport async function resolveRequestUserOutcome(\n request: Request,\n response: Response,\n options: ResolveRequestUserOptions = {},\n): Promise<RequestUserOutcome> {\n const tokenFrom = options.tokenFrom ?? \"header\";\n const allowedTypes = options.allowedTypes ?? [];\n const { refreshCredential } = options;\n let authorizationValue = readCredential(request, tokenFrom);\n let renewalAttempted = false;\n\n const renew = async (): Promise<boolean> => {\n const { renewalUserType } = options;\n if (!refreshCredential || !renewalUserType || renewalAttempted) return false;\n\n renewalAttempted = true;\n const refreshToken = readCredential(request, refreshCredential);\n if (!refreshToken) return false;\n\n const pair = await authService.renewAutomaticSession(refreshToken, renewalUserType, {\n overlapMs: options.overlapMs,\n maxAgeMs: options.maxAgeMs,\n });\n if (!pair?.refreshToken) return false;\n\n authService.setAuthCookie(response, pair.accessToken, {\n name: tokenFrom.slice(\"cookie:\".length),\n domain: options.cookieDomain?.(request),\n });\n authService.setAuthCookie(response, pair.refreshToken, {\n name: refreshCredential.slice(\"cookie:\".length),\n domain: options.cookieDomain?.(request),\n });\n authorizationValue = pair.accessToken.token;\n\n return true;\n };\n\n const fail = (failure: RequestUserFailure): RequestUserOutcome => {\n request.locals.user = undefined;\n\n return { user: null, failure };\n };\n\n let decoded: DecodedAccessToken;\n let accessToken: AccessToken | null;\n\n while (true) {\n if (!authorizationValue) {\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"missing\");\n }\n\n try {\n decoded = await jwt.verify<DecodedAccessToken>(authorizationValue);\n } catch (error) {\n if (!isInvalidCredentialError(error)) throw error;\n // An expired or garbage token is an ordinary client error that any\n // anonymous caller can produce at will: debug, so it cannot flood the\n // error log.\n log.debug(\"http\", \"auth\", error);\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n request.decodedAccessToken = decoded;\n const AccessTokenModel = config.key(\"auth.accessToken.model\", AccessToken);\n accessToken = await AccessTokenModel.findByToken(authorizationValue);\n\n if (!accessToken) {\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n if (accessTokenRowIsExpired(accessToken)) {\n await accessToken.destroy();\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n if (!claimsMatchRow(decoded, accessToken)) {\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n break;\n }\n\n const userType = decoded.userType ?? accessToken.userType;\n\n if (allowedTypes.length && !allowedTypes.includes(userType)) {\n return { user: null, failure: \"forbidden\" };\n }\n\n const UserModel = config.key(`auth.userType.${userType}`);\n\n if (!UserModel) {\n // Configuration, not credentials. Throwing keeps a mis-registered app\n // loudly broken instead of quietly rejecting every request of this type.\n throw new Error(`User type ${userType} is unknown type.`);\n }\n\n const currentUser = await UserModel.find(decoded.id);\n\n if (!currentUser) {\n await accessToken.destroy();\n\n return fail(\"invalid\");\n }\n\n if (!(await authService.canAuthenticate(currentUser))) {\n return fail(\"unauthorized\");\n }\n\n return { user: currentUser };\n}\n\n/**\n * Resolve the request's credential to its user model, or `null` when there is\n * none (missing, invalid, expired, wrong type, or not allowed to authenticate).\n *\n * Includes the middleware's automatic renewal when `options.refreshCredential`\n * is set. Use `resolveRequestUserOutcome` when the failure reason matters.\n */\nexport function resolveRequestUser(\n request: Request,\n response: Response,\n options: ResolveRequestUserOptions = {},\n): Promise<any> {\n // Single-flight: the PROMISE is stored, so concurrent and repeat callers in\n // one request share one verify, one lookup and at most one renewal. The first\n // caller's options win for the rest of the request.\n if (!request.locals.session) {\n request.locals.session = resolveRequestUserOutcome(request, response, options).then(\n (outcome) => outcome.user,\n );\n }\n\n return request.locals.session;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAyDA,SAAS,wBAAwB,aAAmC;CAClE,OAAO,OAAO,YAAY,cAAc,YAAY,YAAY,YAAY;AAC9E;;;;;;AAOA,SAAS,eAAe,SAA6B,aAAmC;CACtF,IAAI,OAAO,QAAQ,EAAE,MA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AAc;CAG5B,OAAO,EAAE,MAAM,YAAY;AAC7B;;;;;;;;AASA,SAAgB,mBACd,SACA,UACA,UAAqC,CAAC,GACxB;CAId,IAAI,CAAC,QAAQ,OAAO,SAClB,QAAQ,OAAO,UAAU,0BAA0B,SAAS,UAAU,OAAO,CAAC,CAAC,MAC5E,YAAY,QAAQ,IACvB;CAGF,OAAO,QAAQ,OAAO;AACxB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token-family-operation.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/token-family-operation.ts"],"mappings":";;;;;;AAIA,MAAM,mBAAmB,IAAI,kBAAqC;;AAGlE,SAAgB,0BAA0B,QAA0B;CAClE,MAAM,UAAU,iBAAiB,SAAS;CAC1C,IAAI,SAAS,QAAQ,KAAK,MAAM;MAC3B,OAAO;AACd;;AAGA,IAAM,2BAAN,cAAuC,MAAM;CAC3C,AAAO,cAAc;EACnB,MAAM,mCAAmC;EACzC,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,8BAAb,cAAiD,MAAM;CACrD,AAAO,cAAc;EACnB,MAAM,6BAA6B;EACnC,KAAK,OAAO;CACd;AACF;AAOA,MAAM,iCAAiC;AAEvC,SAAS,4BAA4B,OAAyB;CAC5D,IAAI,EAAE,iBAAiB,QAAQ,OAAO;CAEtC,MAAM,mBAAmB;CAEzB,OACE,iBAAiB,SAAS,WAC1B,iBAAiB,gBAAgB,2BAA2B,MAAM;AAEtE;;;;;;;;;;;AAYA,eAAsB,wBACpB,UACA,WACY;CACZ,MAAM,2BAA2B,2BAA2B,qBAAqB;CACjF,MAAM,WAAW,2BAA2B,IAAI;CAChD,IAAI;CAEJ,KAAK,IAAI,UAAU,GAAG,UAAU,UAAU,WAAW;EACnD,MAAM,gBAAgB,iBAAiB,SAAS;EAChD,MAAM,UAA6B,CAAC;EACpC,IAAI;EACJ,IAAI;GACF,SAAS,MAAM,iBAAiB,IAAI,eAClC,YACE,YAAY;IACV,MAAM,SAAS,MAAM,gBAAgB,eAAe,QAAQ;IAE5D,IAAI,CAAC,UAAU,OAAO,WACpB,OAAO,EAAE,MAAM,cAAuB;IAGxC,MAAM,WAAW,OAAO,IAAY,UAAU;IAG9C,IAAI,MAFmB,gBAAgB,gBAAgB,UAAU,QAAQ,MAExD,GACf,MAAM,IAAI,yBAAyB;IAGrC,OAAO;KAAE,MAAM;KAAsB,OAAO,MAAM,UAAU,MAAM;IAAE;GACtE,GACA,EAAE,gBAAgB,eAAe,CACnC,CACF;EACF,SAAS,OAAO;GACd,YAAY;GAEZ,IACE,4BACC,CAAC,4BAA4B,KAAK,KAAK,EAAE,iBAAiB,2BAE3D,MAAM;GAER;EACF;EAIA,IAAI,OAAO,SAAS,eAAe,MAAM,IAAI,4BAA4B;EAMzE,IAAI,eAAe,cAAc,KAAK,GAAG,OAAO;OAC3C,KAAK,MAAM,UAAU,SAAS,OAAO;EAC1C,OAAO,OAAO;CAChB;CAEA,MAAM;AACR"}
|
|
1
|
+
{"version":3,"file":"token-family-operation.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/token-family-operation.ts"],"sourcesContent":["import { databaseTransactionContext, transaction } from \"@warlock.js/cascade\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { AuthTokenFamily } from \"../models/auth-token-family\";\n\nconst operationEffects = new AsyncLocalStorage<Array<() => void>>();\n\n/** Defer events until this coordinator's owned transaction commits. */\nexport function afterTokenFamilyOperation(effect: () => void): void {\n const effects = operationEffects.getStore();\n if (effects) effects.push(effect);\n else effect();\n}\n\n/** A CAS miss is retried only when this helper owns the transaction boundary. */\nclass TokenFamilyConflictError extends Error {\n public constructor() {\n super(\"Token family changed concurrently\");\n this.name = \"TokenFamilyConflictError\";\n }\n}\n\n/** A missing or revoked family cannot become usable through a retry. */\nexport class TokenFamilyUnavailableError extends Error {\n public constructor() {\n super(\"Token family is unavailable\");\n this.name = \"TokenFamilyUnavailableError\";\n }\n}\n\ntype TransactionError = {\n code?: unknown;\n hasErrorLabel?: (label: string) => boolean;\n};\n\nconst MAX_OWNED_TRANSACTION_ATTEMPTS = 3;\n\nfunction isRetryableTransactionError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n\n const transactionError = error as Error & TransactionError;\n\n return (\n transactionError.code === \"40001\" ||\n transactionError.hasErrorLabel?.(\"TransientTransactionError\") === true\n );\n}\n\n/**\n * Perform one family state transition in a transaction and advance its durable\n * revision with a conditional update. An existing Cascade transaction is\n * joined, never retried here: PostgreSQL marks an outer transaction aborted on\n * a serialization error, so only that transaction's owner can safely retry.\n *\n * The finite internal cap prevents request handlers from retrying forever.\n * Transaction setup failures are deliberately propagated; this auth boundary\n * has no non-transactional fallback.\n */\nexport async function runTokenFamilyOperation<T>(\n familyId: string,\n operation: (family: AuthTokenFamily) => Promise<T>,\n): Promise<T> {\n const joinsExistingTransaction = databaseTransactionContext.hasActiveTransaction();\n const attempts = joinsExistingTransaction ? 1 : MAX_OWNED_TRANSACTION_ATTEMPTS;\n let lastError: unknown;\n\n for (let attempt = 0; attempt < attempts; attempt++) {\n const parentEffects = operationEffects.getStore();\n const effects: Array<() => void> = [];\n let result: { type: \"unavailable\" } | { type: \"available\"; value: T };\n try {\n result = await operationEffects.run(effects, () =>\n transaction(\n async () => {\n const family = await AuthTokenFamily.findByFamilyId(familyId);\n\n if (!family || family.isRevoked) {\n return { type: \"unavailable\" as const };\n }\n\n const revision = family.get<number>(\"revision\");\n const advanced = await AuthTokenFamily.advanceRevision(familyId, revision);\n\n if (advanced !== 1) {\n throw new TokenFamilyConflictError();\n }\n\n return { type: \"available\" as const, value: await operation(family) };\n },\n { isolationLevel: \"SERIALIZABLE\" },\n ),\n );\n } catch (error) {\n lastError = error;\n\n if (\n joinsExistingTransaction ||\n (!isRetryableTransactionError(error) && !(error instanceof TokenFamilyConflictError))\n ) {\n throw error;\n }\n continue;\n }\n\n // No writes were made for an unavailable family. Reject outside the\n // transaction callback so normal credential rejection is not a DB failure.\n if (result.type === \"unavailable\") throw new TokenFamilyUnavailableError();\n\n // Listener failures must never retry a transaction that already committed.\n // Nested family operations join their parent's queue. An app-owned outer\n // transaction has no Cascade commit hook, so its existing event timing is\n // retained; its owner remains responsible for external side effects.\n if (parentEffects) parentEffects.push(...effects);\n else for (const effect of effects) effect();\n return result.value;\n }\n\n throw lastError;\n}\n\nexport { TokenFamilyConflictError };\n"],"mappings":";;;;;;AAIA,MAAM,mBAAmB,IAAI,kBAAqC;;AAGlE,SAAgB,0BAA0B,QAA0B;CAClE,MAAM,UAAU,iBAAiB,SAAS;CAC1C,IAAI,SAAS,QAAQ,KAAK,MAAM;MAC3B,OAAO;AACd;;AAGA,IAAM,2BAAN,cAAuC,MAAM;CAC3C,AAAO,cAAc;EACnB,MAAM,mCAAmC;EACzC,KAAK,OAAO;CACd;AACF;;AAGA,IAAa,8BAAb,cAAiD,MAAM;CACrD,AAAO,cAAc;EACnB,MAAM,6BAA6B;EACnC,KAAK,OAAO;CACd;AACF;AAOA,MAAM,iCAAiC;AAEvC,SAAS,4BAA4B,OAAyB;CAC5D,IAAI,EAAE,iBAAiB,QAAQ,OAAO;CAEtC,MAAM,mBAAmB;CAEzB,OACE,iBAAiB,SAAS,WAC1B,iBAAiB,gBAAgB,2BAA2B,MAAM;AAEtE;;;;;;;;;;;AAYA,eAAsB,wBACpB,UACA,WACY;CACZ,MAAM,2BAA2B,2BAA2B,qBAAqB;CACjF,MAAM,WAAW,2BAA2B,IAAI;CAChD,IAAI;CAEJ,KAAK,IAAI,UAAU,GAAG,UAAU,UAAU,WAAW;EACnD,MAAM,gBAAgB,iBAAiB,SAAS;EAChD,MAAM,UAA6B,CAAC;EACpC,IAAI;EACJ,IAAI;GACF,SAAS,MAAM,iBAAiB,IAAI,eAClC,YACE,YAAY;IACV,MAAM,SAAS,MAAM,gBAAgB,eAAe,QAAQ;IAE5D,IAAI,CAAC,UAAU,OAAO,WACpB,OAAO,EAAE,MAAM,cAAuB;IAGxC,MAAM,WAAW,OAAO,IAAY,UAAU;IAG9C,IAAI,MAFmB,gBAAgB,gBAAgB,UAAU,QAAQ,MAExD,GACf,MAAM,IAAI,yBAAyB;IAGrC,OAAO;KAAE,MAAM;KAAsB,OAAO,MAAM,UAAU,MAAM;IAAE;GACtE,GACA,EAAE,gBAAgB,eAAe,CACnC,CACF;EACF,SAAS,OAAO;GACd,YAAY;GAEZ,IACE,4BACC,CAAC,4BAA4B,KAAK,KAAK,EAAE,iBAAiB,2BAE3D,MAAM;GAER;EACF;EAIA,IAAI,OAAO,SAAS,eAAe,MAAM,IAAI,4BAA4B;EAMzE,IAAI,eAAe,cAAc,KAAK,GAAG,OAAO;OAC3C,KAAK,MAAM,UAAU,SAAS,OAAO;EAC1C,OAAO,OAAO;CAChB;CAEA,MAAM;AACR"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token-notifications.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/token-notifications.ts"],"mappings":";;;;;AAqBA,MAAM,wBAAgC;AAEtC,MAAM,2BAAW,IAAI,IAA6C;;;;;;AAOlE,SAAS,iBAAiB,OAAyB;CACjD,KAAK,IAAI,UAAU,OAAO,QAAQ,GAAG,WAAW,QAAQ,GAAG,SAAS;EAClE,MAAM,EAAE,MAAM,YAAY;EAE1B,KACG,SAAS,0BAA0B,SAAS,uBAC7C,OAAO,YAAY,YACnB,QAAQ,SAAS,IAAI,sBAAsB,EAAE,GAE7C,OAAO;EAGT,UAAW,QAAgC;CAC7C;CAEA,OAAO;AACT;AAEA,eAAe,oBAAkD;CAC/D,IAAI;CAEJ,IAAI;EACF,gBAAiB,MAAM,OAAO;CAChC,SAAS,OAAO;EACd,IAAI,iBAAiB,KAAK,GACxB,MAAM,IAAI,8BAA8B,iBAAiB,KAAK;EAGhE,MAAM;CACR;CAEA,IAAI;EACF,cAAc,sBAAsB;CACtC,SAAS,OAAO;EACd,MAAM,IAAI,8BAA8B,kBAAkB,KAAK;CACjE;CAEA,OAAO;AACT;AAEA,SAAS,WAAW,OAAuB;CACzC,OAAO,MACJ,QAAQ,MAAM,OAAO,CAAC,CACtB,QAAQ,MAAM,MAAM,CAAC,CACrB,QAAQ,MAAM,MAAM,CAAC,CACrB,QAAQ,MAAM,QAAQ;AAC3B;AAEA,SAAS,SAAS,OAAe,MAAoC;CACnE,MAAM,SAAS,KAAK,OAAO,KAAK;CAChC,MAAM,UAAU,KAAK,UAAU,YAAY;CAE3C,OAAO;EACL,MACE,MAAM,MAAM,SACX,KAAK,MACF,eAAe,WAAW,KAAK,GAAG,EAAE,IAAI,WAAW,KAAK,GAAG,EAAE,YAC7D,YAAY,WAAW,KAAK,KAAK,EAAE,gBACvC,2BAA2B,QAAQ;EACrC,MAAM,GAAG,MAAM,MAAM,OAAO,2BAA2B,QAAQ;CACjE;AACF;AAEA,SAAS,cACP,eACA,MACkB;CAClB,IAAI,SAAS,sBACX,OAAO,cAAc,mBAAmB;EACtC,MAAM;EACN,KAAK,CAAC,MAAM;EACZ,OAAO,UAAU;GACf,SAAS;GACT,GAAG,SAAS,iEAAiE,IAAI;EACnF;CACF,CAAC;CAGH,OAAO,cAAc,mBAAmB;EACtC,MAAM;EACN,KAAK,CAAC,MAAM;EACZ,OAAO,UAAU;GACf,SAAS;GACT,GAAG,SAAS,sCAAsC,IAAI;EACxD;CACF,CAAC;AACH;;;;;;;;;AAUA,eAAsB,yBACpB,MAC2B;CAC3B,MAAM,gBAAgB,MAAM,kBAAkB;CAE9C,MAAM,WACJ,SAAS,uBACL,WAAW,aAAa,aAAa,IACrC,WAAW,cAAc,aAAa;CAE5C,IAAI,UAAU,OAAO;CAErB,IAAI,eAAe,SAAS,IAAI,IAAI;CAEpC,IAAI,CAAC,cAAc;EACjB,eAAe,cAAc,eAAe,IAAI;EAChD,SAAS,IAAI,MAAM,YAAY;CACjC;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"token-notifications.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/token-notifications.ts"],"sourcesContent":["import type { AuthNotification, OneTimeTokenNotificationData } from \"../contracts/types\";\nimport { NotificationsUnavailableError } from \"../errors/notifications-unavailable.error\";\nimport { authConfig } from \"./auth-config\";\n\n/** Which token notification to resolve. */\nexport type TokenNotificationType = \"email-verification\" | \"password-reset\";\n\n/**\n * The slice of `@warlock.js/notifications` auth uses. Declared locally because\n * the package is an OPTIONAL peer: auth must type-check and load without it.\n */\ntype NotificationsModule = {\n getNotificationConfig: () => unknown;\n defineNotification: (definition: {\n type: string;\n via: string[];\n mail: (data: OneTimeTokenNotificationData) => { subject: string; html: string; text: string };\n }) => AuthNotification;\n};\n\n/** Non-literal on purpose: keeps type-checkers and bundlers from requiring the optional peer. */\nconst NOTIFICATIONS_PACKAGE: string = \"@warlock.js/notifications\";\n\nconst defaults = new Map<TokenNotificationType, AuthNotification>();\n\n/**\n * Whether `error` (or an error it wraps as `cause`, as some loaders do) is the\n * resolver saying the notifications package itself is absent. A missing\n * TRANSITIVE dependency names a different package and is rethrown untouched.\n */\nfunction isPackageMissing(error: unknown): boolean {\n for (let current = error, depth = 0; current && depth < 5; depth++) {\n const { code, message } = current as { code?: unknown; message?: unknown };\n\n if (\n (code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\") &&\n typeof message === \"string\" &&\n message.includes(`'${NOTIFICATIONS_PACKAGE}'`)\n ) {\n return true;\n }\n\n current = (current as { cause?: unknown }).cause;\n }\n\n return false;\n}\n\nasync function loadNotifications(): Promise<NotificationsModule> {\n let notifications: NotificationsModule;\n\n try {\n notifications = (await import(NOTIFICATIONS_PACKAGE)) as NotificationsModule;\n } catch (error) {\n if (isPackageMissing(error)) {\n throw new NotificationsUnavailableError(\"not-installed\", error);\n }\n\n throw error;\n }\n\n try {\n notifications.getNotificationConfig();\n } catch (error) {\n throw new NotificationsUnavailableError(\"not-configured\", error);\n }\n\n return notifications;\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\");\n}\n\nfunction mailBody(intro: string, data: OneTimeTokenNotificationData) {\n const action = data.url ?? data.token;\n const expires = data.expiresAt.toISOString();\n\n return {\n html:\n `<p>${intro}</p>` +\n (data.url\n ? `<p><a href=\"${escapeHtml(data.url)}\">${escapeHtml(data.url)}</a></p>`\n : `<p><code>${escapeHtml(data.token)}</code></p>`) +\n `<p>This link expires at ${expires}. If you did not request it, ignore this email.</p>`,\n text: `${intro}\\n\\n${action}\\n\\nThis link expires at ${expires}. If you did not request it, ignore this email.`,\n };\n}\n\nfunction defineDefault(\n notifications: NotificationsModule,\n type: TokenNotificationType,\n): AuthNotification {\n if (type === \"email-verification\") {\n return notifications.defineNotification({\n type: \"auth.email-verification\",\n via: [\"mail\"],\n mail: (data) => ({\n subject: \"Verify your email address\",\n ...mailBody(\"Confirm your email address to finish setting up your account.\", data),\n }),\n });\n }\n\n return notifications.defineNotification({\n type: \"auth.password-reset\",\n via: [\"mail\"],\n mail: (data) => ({\n subject: \"Reset your password\",\n ...mailBody(\"Use this to choose a new password.\", data),\n }),\n });\n}\n\n/**\n * Resolve the notification a token of `type` is delivered through — the app's\n * configured override, else auth's default mail notification.\n *\n * Always confirms `@warlock.js/notifications` is installed AND configured\n * first, even when an override is set, so an app can never issue a token that\n * silently goes nowhere. Throws {@link NotificationsUnavailableError}.\n */\nexport async function resolveTokenNotification(\n type: TokenNotificationType,\n): Promise<AuthNotification> {\n const notifications = await loadNotifications();\n\n const override =\n type === \"email-verification\"\n ? authConfig.verification.notification()\n : authConfig.passwordReset.notification();\n\n if (override) return override;\n\n let notification = defaults.get(type);\n\n if (!notification) {\n notification = defineDefault(notifications, type);\n defaults.set(type, notification);\n }\n\n return notification;\n}\n"],"mappings":";;;;;AAqBA,MAAM,wBAAgC;AAEtC,MAAM,2BAAW,IAAI,IAA6C;;;;;;AAOlE,SAAS,iBAAiB,OAAyB;CACjD,KAAK,IAAI,UAAU,OAAO,QAAQ,GAAG,WAAW,QAAQ,GAAG,S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aAAa;EACjC,CAAC;EACD,YAAY;CACd,CAAC;CACD,OAAO,cAAc,YAAY,QAAQ,aAAa,IAAI;AAC5D"}
|
|
1
|
+
{"version":3,"file":"page-session.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/session/page-session.ts"],"sourcesContent":["import {\n config,\n markAuthGuard,\n t,\n type Middleware,\n type Request,\n type Response,\n} from \"@warlock.js/core\";\nimport type { CookieDomainResolver } from \"../contracts/types\";\nimport { log } from \"@warlock.js/logger\";\nimport ms from \"ms\";\nimport {\n assertCsrfOriginAllowed,\n CsrfOriginMismatchError,\n requiresCsrfOriginCheck,\n} from \"../middleware/csrf-origin-check\";\nimport { authConfig } from \"../services/auth-config\";\nimport { readAuthCookie } from \"../services/auth-cookie-names\";\nimport { resolveRequestUser } from \"../services/resolve-request-user\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/** Credential sources a session can be read from. */\nexport type SessionSource = \"cookie\" | \"header\";\n\n/** Absolute family lifetime used when `session.maxAge` is not configured. */\nconst DEFAULT_SESSION_MAX_AGE = \"30d\";\n\n/**\n * The seam web consumes. Declared here, not imported: web and auth never\n * depend on each other, and `pageSession()` satisfies web's `SessionResolver`\n * structurally.\n */\nexport type PageSessionResolver<TModel = unknown, TUser = unknown> = {\n resolve(request: Request, response: Response): Promise<{ model: TModel; user: TUser } | null>;\n};\n\nexport type SessionResolverOptions = {\n /** Access cookie name. @default auth.cookie.name */\n cookie?: string;\n /** Refresh cookie name. @default auth.cookie.refreshName */\n refreshCookie?: string;\n /** Credential sources. A present Authorization header always wins. @default [\"cookie\", \"header\"] */\n sources?: SessionSource[];\n /** Renew an expired access cookie from the refresh cookie. Cookie source only. @default true */\n renew?: boolean;\n /** Allowed user types. @default auth.defaultUserType */\n userTypes?: string | string[];\n /** Absolute family lifetime, an `ms` string or milliseconds. @default auth.session.maxAge, else \"30d\" */\n maxAge?: string | number;\n /** Refresh overlap window forwarded to renewal. */\n overlapMs?: number;\n /** Select a request-scoped Domain for renewed cookies; `undefined` keeps them host-only. */\n cookieDomain?: CookieDomainResolver;\n};\n\nexport type PageSessionOptions<TModel, TUser> = SessionResolverOptions & {\n /** Model → wire projection. Required: a model never crosses the wire by default. */\n project: (model: TModel) => TUser | Promise<TUser>;\n};\n\nexport type SessionMiddlewareOptions = SessionResolverOptions & {\n /** Let guests through with no user instead of a 401. @default false */\n optional?: boolean;\n};\n\nfunction resolveMaxAgeMs(maxAge: string | number | undefined): number {\n const raw = maxAge ?? config.key(\"auth.session.maxAge\", DEFAULT_SESSION_MAX_AGE);\n const parsed = typeof raw === \"number\" ? raw : ms(raw as ms.StringValue);\n\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(\n `session.maxAge: ${JSON.stringify(raw)} is not a valid ms duration — use a positive duration such as \"30d\".`,\n );\n }\n\n return parsed;\n}\n\nfunction resolveUserTypes(value: string | string[] | undefined): string[] {\n if (value !== undefined) return Array.isArray(value) ? value : [value];\n\n const configured = config.key(\"auth.defaultUserType\");\n\n return configured ? [configured as string] : [];\n}\n\n/**\n * The shared \"credential → model\" step behind `pageSession` and\n * `sessionMiddleware`. Resolved once per request through\n * `resolveRequestUser`'s single-flight memo.\n */\nfunction createModelResolver(options: SessionResolverOptions) {\n const sources = options.sources?.length ? options.sources : ([\"cookie\", \"header\"] as const);\n const useHeader = sources.includes(\"header\");\n const useCookie = sources.includes(\"cookie\");\n const renew = options.renew ?? true;\n\n const resolveModel = async (\n request: Request,\n response: Response,\n ): Promise<{ model: unknown; source: \"header\" | \"cookie\" } | null> => {\n const accessName = options.cookie ?? authConfig.cookie.name();\n const refreshName = options.refreshCookie ?? authConfig.cookie.refreshName();\n // A present Authorization header wins and never falls back to the cookie.\n const headerWins = useHeader && Boolean(request.authorizationValue);\n\n if (!headerWins && !useCookie) return null;\n\n // Cheap guest path: nothing to decode, so nothing is marked auth-derived.\n const hasCookie =\n Boolean(readAuthCookie(request, accessName)) || Boolean(readAuthCookie(request, refreshName));\n\n if (!headerWins && !hasCookie) return null;\n\n const allowedTypes = resolveUserTypes(options.userTypes);\n const renewalUserType = allowedTypes.length === 1 ? allowedTypes[0] : undefined;\n const canRenew = !headerWins && renew && Boolean(renewalUserType);\n\n const model = await resolveRequestUser(request, response, {\n tokenFrom: headerWins ? \"header\" : `cookie:${accessName}`,\n refreshCredential: canRenew ? `cookie:${refreshName}` : undefined,\n overlapMs: options.overlapMs,\n maxAgeMs: resolveMaxAgeMs(options.maxAge),\n allowedTypes,\n renewalUserType,\n cookieDomain: options.cookieDomain ?? authConfig.cookie.cookieDomain(),\n });\n\n if (!model) return null;\n\n request.locals.user = model;\n\n return { model, source: headerWins ? \"header\" : \"cookie\" };\n };\n\n return resolveModel;\n}\n\n/**\n * Session resolver for pages: cookie-or-header credential, reactive renewal,\n * one resolution per request. Plug it into `web.session`.\n *\n * @example\n * export default { session: pageSession({ project: (user: User) => userResource(user) }) };\n */\nexport function pageSession<TModel = unknown, TUser = unknown>(\n options: PageSessionOptions<TModel, TUser>,\n): PageSessionResolver<TModel, TUser> {\n if (typeof options?.project !== \"function\") {\n throw new Error(\n \"pageSession requires a `project(model)` function: a model never crosses the wire by default.\",\n );\n }\n\n const resolveModel = createModelResolver(options);\n const projections = new WeakMap<object, Promise<unknown>>();\n\n return {\n async resolve(request, response) {\n const resolved = await resolveModel(request, response);\n\n if (!resolved) return null;\n\n const model = resolved.model as TModel;\n let projected = projections.get(request as object);\n\n if (!projected) {\n projected = Promise.resolve(options.project(model));\n projections.set(request as object, projected);\n }\n\n return { model, user: (await projected) as TUser };\n },\n };\n}\n\n/**\n * Middleware for cookie API routes over the same resolver as `pageSession`.\n * A cookie-authenticated unsafe request must pass the Origin/Referer check\n * (renewal can mint cookies, so it runs even when the access cookie is gone).\n * Guests get a 401 unless `optional`. The user lands on `request.locals.user`.\n */\nexport function sessionMiddleware(options: SessionMiddlewareOptions = {}): Middleware {\n const resolveModel = createModelResolver(options);\n const sources = options.sources?.length ? options.sources : [\"cookie\", \"header\"];\n\n const middleware: Middleware = async ({ request, response }) => {\n const headerWins = sources.includes(\"header\") && Boolean(request.authorizationValue);\n\n if (!headerWins && requiresCsrfOriginCheck(\"cookie:x\", request.method)) {\n const accessName = options.cookie ?? authConfig.cookie.name();\n const refreshName = options.refreshCookie ?? authConfig.cookie.refreshName();\n\n if (readAuthCookie(request, accessName) || readAuthCookie(request, refreshName)) {\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\n return response.forbidden({\n error: t(\"auth.errors.csrfOriginMismatch\"),\n errorCode: AuthErrorCodes.CsrfOriginMismatch,\n });\n }\n }\n }\n\n const resolved = await resolveModel(request, response);\n\n if (resolved || options.optional) return;\n\n return response.unauthorized({\n error: t(\"auth.errors.unauthorized\"),\n errorCode: AuthErrorCodes.Unauthorized,\n });\n };\n Object.defineProperty(middleware, Symbol.for(\"warlock.auth\"), {\n value: Object.freeze({\n sources: Object.freeze(\n sources.map((source) =>\n source === \"header\"\n ? \"header\"\n : Object.freeze({ cookie: options.cookie ?? authConfig.cookie.name() }),\n ),\n ),\n userTypes: Object.freeze([...resolveUserTypes(options.userTypes)]),\n required: options.optional !== true,\n }),\n enumerable: false,\n });\n return markAuthGuard(middleware, options.optional !== true);\n}\n"],"mappings":";;;;;;;;;;;AAyBA,MAAM,0BAA0B;AAwChC,SAAS,gBAAgB,QAA6C;CACpE,MAAM,MAAM,UAAU,OAAO,IAAI,uBAAuB,uBAAuB;CAC/E,MAAM,SAAS,OAAO,QAAQ,WAAW,MAAM,GAAG,GAAqB;CAEvE,IAAI,OAAO,WAAW,YAAY,CAAC,OAAO,SAAS,MAAM,KAAK,UAAU,GACtE,MAAM,IAAI,MACR,mBAAmB,KAAK,UAAU,GAAG,EAAE,qEACzC;CAGF,OAAO;AACT;AAEA,SAAS,iBAAiB,OAAgD;CACxE,IAAI,UAAU,Q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AU;EAElC,OAAO,SAAS,aAAa;GAC3B,OAAO,EAAE,0BAA0B;GACnC;EACF,CAAC;CACH;CACA,OAAO,eAAe,YAAY,OAAO,IAAI,cAAc,GAAG;EAC5D,OAAO,OAAO,OAAO;GACnB,SAAS,OAAO,OACd,QAAQ,KAAK,WACX,WAAW,WACP,WACA,OAAO,OAAO,EAAE,QAAQ,QAAQ,UAAU,WAAW,OAAO,KAAK,EAAE,CAAC,CAC1E,CACF;GACA,WAAW,OAAO,OAAO,CAAC,GAAG,iBAAiB,QAAQ,SAAS,CAAC,CAAC;GACjE,UAAU,QAAQ,aAAa;EACjC,CAAC;EACD,YAAY;CACd,CAAC;CACD,OAAO,cAAc,YAAY,QAAQ,aAAa,IAAI;AAC5D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-error-codes.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/utils/auth-error-codes.ts"],"mappings":";AAAA,IAAY,iBAAL;;;;;CAKL;;;;;CAKA;;;;;CAKA;;;;;;CAMA;;;;;;;;;CASA;;;;;;;;CAQA;;;;;;CAMA;;;;;;;CAOA;;;;;;;CAOA;;;;;;CAMA;;;;;;;CAOA;;;;;;;CAOA;;AACF"}
|
|
1
|
+
{"version":3,"file":"auth-error-codes.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/utils/auth-error-codes.ts"],"sourcesContent":["export enum AuthErrorCodes {\n /**\n * Missing Access Token Error Code EC001\n * EC001 = Missing Access Token\n */\n MissingAccessToken = \"EC001\", // Error Code 001\n /**\n * Invalid Access Token Error Code EC002\n * EC002 = Invalid Access Token\n */\n InvalidAccessToken = \"EC002\", // Error Code 002\n /**\n * Unauthorized Error Code EC003\n * EC003 = Unauthorized\n */\n Unauthorized = \"EC003\", // Error Code 003\n /**\n * Too Many Attempts Error Code EC004\n * EC004 = Too Many Attempts — issued by the login-throttle middleware once\n * a per-account or per-IP failure counter trips its threshold.\n */\n TooManyAttempts = \"EC004\", // Error Code 004\n /**\n * Invalid Token Type Error Code EC005\n * EC005 = Invalid Token Type — the token's `tokenType` claim does not match\n * what the caller expects (e.g. a refresh token presented where an access\n * token is required, or vice versa). Carried on the `code` property of the\n * `Error` thrown by `assertTokenType` (`services/jwt.ts`) so callers can\n * classify it as a credential failure without matching on the message.\n */\n InvalidTokenType = \"EC005\", // Error Code 005\n /**\n * CSRF Origin Mismatch Error Code EC006\n * EC006 = a cookie-authenticated, unsafe-method (POST/PUT/PATCH/DELETE)\n * request whose `Origin` (or, absent that, `Referer`) did not match the\n * request's own origin or an entry in `auth.csrf.allowedOrigins`, or whose\n * request carried neither header at all.\n */\n CsrfOriginMismatch = \"EC006\", // Error Code 006\n /**\n * Email Not Verified Error Code EC007\n * EC007 = the authenticated user has not verified their email address —\n * thrown by `requireVerifiedEmail()` as `EmailNotVerifiedError` (403).\n */\n EmailNotVerified = \"EC007\", // Error Code 007\n /**\n * Invalid One-Time Token Error Code EC008\n * EC008 = an email-verification or password-reset token that is unknown,\n * issued for the other purpose, expired, or already used. One code for all\n * four on purpose: the caller learns nothing about which it was.\n */\n InvalidOneTimeToken = \"EC008\", // Error Code 008\n /**\n * Invalid Provider Callback Error Code EC009\n * EC009 = a redirect-provider callback was rejected: missing, forged or\n * expired state cookie, `state` mismatch, failed code exchange, or an\n * id_token with a bad signature, issuer, audience, expiry or nonce.\n */\n InvalidProviderCallback = \"EC009\", // Error Code 009\n /**\n * Provider Email Not Verified Error Code EC010\n * EC010 = the provider did not verify the email, so auth refused to link or\n * create an account from it.\n */\n ProviderEmailNotVerified = \"EC010\", // Error Code 010\n /**\n * Invalid Passkey Error Code EC011\n * EC011 = a passkey ceremony was rejected: unknown, expired or used\n * challenge, unknown credential, failed verification, or a signature counter\n * that did not advance.\n */\n InvalidPasskey = \"EC011\", // Error Code 011\n /**\n * Provider Account Link Blocked Error Code EC012\n * EC012 = a provider login matched an existing account by email, but\n * `auth.providers.linkExisting` refused to link it automatically (by\n * default: the account never verified that email).\n */\n ProviderAccountLinkBlocked = \"EC012\", // Error Code 012\n}\n"],"mappings":";AAAA,IAAY,iBAAL;;;;;CAKL;;;;;CAKA;;;;;CAKA;;;;;;CAMA;;;;;;;;;CASA;;;;;;;;CAQA;;;;;;CAMA;;;;;;;CAOA;;;;;;;CAOA;;;;;;CAMA;;;;;;;CAOA;;;;;;;CAOA;;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"normalize-credentials.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/utils/normalize-credentials.ts"],"mappings":";;;;;;;AAWA,SAAgB,yBAAyB,OAAuB;CAC9D,OAAO,MAAM,KAAK,CAAC,CAAC,YAAY;AAClC;;;;;AAMA,SAAgB,gBAAgB,aAA+C;CAC7E,MAAM,UAA2B,CAAC;CAElC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,WAAW,GACnD,QAAQ,OAAO,OAAO,UAAU,WAAW,MAAM,KAAK,IAAI;CAG5D,OAAO;AACT;;;;;AAMA,SAAgB,4BAA4B,aAA+C;CACzF,MAAM,aAAa,gBAAgB,WAAW;CAE9C,IAAI,OAAO,WAAW,UAAU,UAC9B,WAAW,QAAQ,yBAAyB,WAAW,KAAK;CAG9D,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"normalize-credentials.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/utils/normalize-credentials.ts"],"sourcesContent":["import type { AuthCredentials } from \"../contracts/types\";\n\n/** Credentials without the password: the identity fields used to look a user up. */\nexport type AuthIdentifiers = Omit<AuthCredentials, \"password\">;\n\n/**\n * Normalize one email-like identifier: trim it and lower-case it.\n *\n * This is the single rule the login lookup and the login throttle both use,\n * so `\" Sara@x.io\"` and `\"sara@x.io\"` are the same account to both.\n */\nexport function normalizeEmailIdentifier(value: string): string {\n return value.trim().toLowerCase();\n}\n\n/**\n * Trim every string identifier value, leaving other values untouched. This is\n * the \"as sent\" form the login lookup falls back to for legacy rows.\n */\nexport function trimIdentifiers(identifiers: AuthIdentifiers): AuthIdentifiers {\n const trimmed: AuthIdentifiers = {};\n\n for (const [key, value] of Object.entries(identifiers)) {\n trimmed[key] = typeof value === \"string\" ? value.trim() : value;\n }\n\n return trimmed;\n}\n\n/**\n * Default credential normalization: trim string values and lower-case the\n * `email` field.\n */\nexport function defaultNormalizeCredentials(identifiers: AuthIdentifiers): AuthIdentifiers {\n const normalized = trimIdentifiers(identifiers);\n\n if (typeof normalized.email === \"string\") {\n normalized.email = normalizeEmailIdentifier(normalized.email);\n }\n\n return normalized;\n}\n"],"mappings":";;;;;;;AAWA,SAAgB,yBAAyB,OAAuB;CAC9D,OAAO,MAAM,KAAK,CAAC,CAAC,YAAY;AAClC;;;;;AAMA,SAAgB,gBAAgB,aAA+C;CAC7E,MAAM,UAA2B,CAAC;CAElC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,WAAW,GACnD,QAAQ,OAAO,OAAO,UAAU,WAAW,MAAM,KAAK,IAAI;CAG5D,OAAO;AACT;;;;;AAMA,SAAgB,4BAA4B,aAA+C;CACzF,MAAM,aAAa,gBAAgB,WAAW;CAE9C,IAAI,OAAO,WAAW,UAAU,UAC9B,WAAW,QAAQ,yBAAyB,WAAW,KAAK;CAG9D,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"safe-equal.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/utils/safe-equal.ts"],"mappings":";;;;AAGA,SAAgB,UAAU,MAAc,OAAwB;CAC9D,MAAM,IAAI,OAAO,KAAK,IAAI;CAC1B,MAAM,IAAI,OAAO,KAAK,KAAK;CAE3B,OAAO,EAAE,WAAW,EAAE,UAAU,gBAAgB,GAAG,CAAC;AACtD"}
|
|
1
|
+
{"version":3,"file":"safe-equal.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/utils/safe-equal.ts"],"sourcesContent":["import { timingSafeEqual } from \"node:crypto\";\n\n/** Constant-time string equality; strings of unequal length are simply unequal. */\nexport function safeEqual(left: string, right: string): boolean {\n const a = Buffer.from(left);\n const b = Buffer.from(right);\n\n return a.length === b.length && timingSafeEqual(a, b);\n}\n"],"mappings":";;;;AAGA,SAAgB,UAAU,MAAc,OAAwB;CAC9D,MAAM,IAAI,OAAO,KAAK,IAAI;CAC1B,MAAM,IAAI,OAAO,KAAK,KAAK;CAE3B,OAAO,EAAE,WAAW,EAAE,UAAU,gBAAgB,GAAG,CAAC;AACtD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token-digest.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/utils/token-digest.ts"],"mappings":";;;;;;;AAMA,SAAgB,YAAY,OAAuB;CACjD,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AACxD;AAEA,MAAM,iBAAiB;;;;;AAMvB,SAAgB,cAAc,QAA0B;CACtD,OAAO,OAAO,WAAW,YAAY,eAAe,KAAK,MAAM;AACjE;;;;;;;AAQA,SAAgB,iBAAiB,OAAyB;CACxD,OAAO,CAAC,YAAY,KAAK,GAAG,KAAK;AACnC;;AAGA,MAAM,8BAAc,IAAI,QAAwB;;AAGhD,SAAgB,mBAAmB,KAAc,OAAqB;CACpE,IAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM,YAAY,IAAI,KAAK,KAAK;AACzE;;;;;;AAOA,SAAgB,aAAa,KAAa,QAAqC;CAC7E,MAAM,aAAa,YAAY,IAAI,GAAG;CAEtC,IAAI,eAAe,QAAW,OAAO;CAErC,OAAO,OAAO,WAAW,YAAY,CAAC,cAAc,MAAM,IAAI,SAAS;AACzE"}
|
|
1
|
+
{"version":3,"file":"token-digest.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/utils/token-digest.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\n\n/**\n * SHA-256 hex digest of a raw access or refresh token — what a token row\n * stores instead of the token when `auth.hashTokensAtRest` is on.\n */\nexport function tokenDigest(token: string): string {\n return createHash(\"sha256\").update(token).digest(\"hex\");\n}\n\nconst DIGEST_PATTERN = /^[0-9a-f]{64}$/;\n\n/**\n * Whether a stored token value is a digest rather than a raw JWT. A JWT always\n * contains dots, so the two forms cannot be confused.\n */\nexport function isTokenDigest(stored: unknown): boolean {\n return typeof stored === \"string\" && DIGEST_PATTERN.test(stored);\n}\n\n/**\n * Every stored form a presented token may have: its digest (rows issued with\n * `auth.hashTokensAtRest` on) and the raw value (rows issued with it off, or\n * before it was turned on). Lookups match either, so switching the option in\n * either direction never signs anyone out.\n */\nexport function storedTokenForms(token: string): string[] {\n return [tokenDigest(token), token];\n}\n\n/** Raw tokens of rows issued in this process, for handing back to the caller. */\nconst plainTokens = new WeakMap<object, string>();\n\n/** Remember the raw token of a freshly issued row whose column holds a digest. */\nexport function rememberPlainToken(row: unknown, token: string): void {\n if (typeof row === \"object\" && row !== null) plainTokens.set(row, token);\n}\n\n/**\n * The raw token of a row: the one remembered at issue, else the stored value\n * when it is not a digest. `undefined` for a hashed row loaded from storage —\n * its raw token exists only with the client.\n */\nexport function plainTokenOf(row: object, stored: unknown): string | undefined {\n const remembered = plainTokens.get(row);\n\n if (remembered !== undefined) return remembered;\n\n return typeof stored === \"string\" && !isTokenDigest(stored) ? stored : undefined;\n}\n"],"mappings":";;;;;;;AAMA,SAAgB,YAAY,OAAuB;CACjD,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AACxD;AAEA,MAAM,iBAAiB;;;;;AAMvB,SAAgB,cAAc,QAA0B;CACtD,OAAO,OAAO,WAAW,YAAY,eAAe,KAAK,MAAM;AACjE;;;;;;;AAQA,SAAgB,iBAAiB,OAAyB;CACxD,OAAO,CAAC,YAAY,KAAK,GAAG,KAAK;AACnC;;AAGA,MAAM,8BAAc,IAAI,QAAwB;;AAGhD,SAAgB,mBAAmB,KAAc,OAAqB;CACpE,IAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM,YAAY,IAAI,KAAK,KAAK;AACzE;;;;;;AAOA,SAAgB,aAAa,KAAa,QAAqC;CAC7E,MAAM,aAAa,YAAY,IAAI,GAAG;CAEtC,IAAI,eAAe,QAAW,OAAO;CAErC,OAAO,OAAO,WAAW,YAAY,CAAC,cAAc,MAAM,IAAI,SAAS;AACzE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token-expiry.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/utils/token-expiry.ts"],"mappings":";;;;;;;;;;;AAUA,MAAM,gBAAgB,cAAc;;;;;;;;;;;AAYpC,SAAgB,eAAe,OAAyB;CACtD,IAAI,UAAU,UAAa,UAAU,QAAQ,UAAU,IAAI,OAAO;CAElE,OAAO,CAAC,OAAO,MAAM,IAAI,KAAK,KAA+B,CAAC,CAAC,QAAQ,CAAC;AAC1E;;;;;;;;;;AAWA,SAAgB,iBAAiB,OAAyB;CACxD,IAAI,OAAO,UAAU,YAAY,UAAU,IAAI,OAAO;CAEtD,IAAI;EACF,MAAM,UAAU,cAAc,KAAK;EAEnC,OAAO,OAAO,SAAS,QAAQ,YAAY,OAAO,SAAS,QAAQ,GAAG;CACxE,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;;;AAaA,SAAgB,gBAAgB,OAAgB,WAA6B;CAC3E,IAAI,CAAC,eAAe,SAAS,GAAG,OAAO;CAKvC,IAAI,cAAc,KAAK,GAAG,OAAO;CAEjC,OAAO,CAAC,iBAAiB,KAAK;AAChC"}
|
|
1
|
+
{"version":3,"file":"token-expiry.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/utils/token-expiry.ts"],"sourcesContent":["import { createDecoder } from \"fast-jwt\";\nimport { isTokenDigest } from \"./token-digest\";\n\n/**\n * Payload decoder. Deliberately signature-*unaware*: these helpers answer\n * \"does this token carry a deadline at all\", which is a property of the claims,\n * not of the signature. Every caller that acts on the answer (the middleware,\n * the purge command) has already verified the signature or is about to delete\n * the row anyway.\n */\nconst decodePayload = createDecoder();\n\n/**\n * Whether a persisted `expires_at` can serve as a deadline at all.\n *\n * Answers `false` for absent, empty, and — the case that matters — `Invalid\n * Date`, which is what a pre-4.12.0 unparseable `expiresIn` wrote to the token\n * row. An `Invalid Date` compares `false` against *every* other date, so a row\n * holding one satisfies neither `expires_at < now` (cleanup never purges it)\n * nor `expires_at > now` (it never shows as an active session): it is outside\n * the reach of every date predicate rather than merely wrong.\n */\nexport function isUsableExpiry(value: unknown): boolean {\n if (value === undefined || value === null || value === \"\") return false;\n\n return !Number.isNaN(new Date(value as string | number | Date).getTime());\n}\n\n/**\n * Whether the JWT carries a finite numeric `exp` claim.\n *\n * This is the store-independent signal for a never-expiring credential: a\n * token with no `exp` has nothing for a verifier to check, so it verifies\n * indefinitely no matter what the row beside it says. An undecodable string\n * answers `false` — it cannot be shown to expire, and a row whose token cannot\n * even be parsed is unusable regardless.\n */\nexport function tokenHasExpClaim(token: unknown): boolean {\n if (typeof token !== \"string\" || token === \"\") return false;\n\n try {\n const payload = decodePayload(token) as { exp?: unknown } | null;\n\n return typeof payload?.exp === \"number\" && Number.isFinite(payload.exp);\n } catch {\n return false;\n }\n}\n\n/**\n * Whether a token row can ever stop being accepted on its own.\n *\n * Two independent ways to answer \"no\", either of which is enough:\n * - the persisted expiry is unusable, so no date check can ever retire the row;\n * - the token itself carries no `exp`, so signature verification never retires it\n * (not checkable for a row stored as a digest, which this package only ever\n * writes for tokens it signed with an `exp`).\n *\n * This is the predicate the `auth.purge-never-expiring` remediation selects on.\n */\nexport function isNeverExpiring(token: unknown, expiresAt: unknown): boolean {\n if (!isUsableExpiry(expiresAt)) return true;\n\n // A row stored hashed (`auth.hashTokensAtRest`) holds a digest, not a JWT,\n // so its claims cannot be read; it was issued with an `exp` by construction,\n // and its persisted expiry is the deadline that applies.\n if (isTokenDigest(token)) return false;\n\n return !tokenHasExpClaim(token);\n}\n"],"mappings":";;;;;;;;;;;AAUA,MAAM,gBAAgB,cAAc;;;;;;;;;;;AAYpC,SAAgB,eAAe,OAAyB;CACtD,IAAI,UAAU,UAAa,UAAU,QAAQ,UAAU,IAAI,OAAO;CAElE,OAAO,CAAC,OAAO,MAAM,IAAI,KAAK,KAA+B,CAAC,CAAC,QAAQ,CAAC;AAC1E;;;;;;;;;;AAWA,SAAgB,iBAAiB,OAAyB;CACxD,IAAI,OAAO,UAAU,YAAY,UAAU,IAAI,OAAO;CAEtD,IAAI;EACF,MAAM,UAAU,cAAc,KAAK;EAEnC,OAAO,OAAO,SAAS,QAAQ,YAAY,OAAO,SAAS,QAAQ,GAAG;CACxE,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;;;AAaA,SAAgB,gBAAgB,OAAgB,WAA6B;CAC3E,IAAI,CAAC,eAAe,SAAS,GAAG,OAAO;CAKvC,IAAI,cAAc,KAAK,GAAG,OAAO;CAEjC,OAAO,CAAC,iBAAiB,KAAK;AAChC"}
|
package/llms-full.txt
CHANGED
|
@@ -150,7 +150,7 @@ export default {
|
|
|
150
150
|
- `hashTokensAtRest: true` (default `false`) — `access_tokens.token` / `refresh_tokens.token` hold the SHA-256 digest, never the JWT, so a copied table cannot be replayed. No migration; lookups accept both forms, so switching it on or off signs no one out. A row loaded from the DB has no raw token any more; a freshly issued row exposes it as `row.plainToken`. Automatic cookie renewal parks the successor pair encrypted in the cache for the overlap window.
|
|
151
151
|
- `accessToken.issuer` / `accessToken.audience` (default unset) — stamped as `iss` / `aud` on every token signed and required on every token accepted. Setting either signs everyone out once (old tokens lack the claim).
|
|
152
152
|
- `cookie.hostPrefix: true` (default `false`) — auth cookies become `__Host-access_token` / `__Host-refresh_token` (Secure, `Path=/`, no Domain; a write with another path or a Domain throws naming the setting). The unprefixed cookie is still read during the switch, and both are cleared on logout.
|
|
153
|
-
- In production a signing secret under 32 bytes, or an access-token lifetime over 30 days, logs a one-time warning.
|
|
153
|
+
- In production a signing secret under 32 bytes, or an access-token lifetime over 30 days, logs a one-time warning (a secret under 32 bytes becomes a boot error in 6.0). `auth.rehashPasswords` (default `true`) re-hashes a stored password after a correct login when `encryption.password` asks for another algorithm or cost.
|
|
154
154
|
- `Auth` hides `password` from serialized output (`static hidden = ["password"]`); a model that sets its own `hidden` must keep `"password"` in it.
|
|
155
155
|
|
|
156
156
|
### Token lifetimes are validated — a bad one throws
|
|
@@ -972,7 +972,7 @@ passkeys: {
|
|
|
972
972
|
rpID: "example.com",
|
|
973
973
|
rpName: "Example",
|
|
974
974
|
origin: "https://example.com",
|
|
975
|
-
userVerification: "
|
|
975
|
+
userVerification: "required", // "preferred" (default until 6.0, warns if unset) also accepts possession only
|
|
976
976
|
},
|
|
977
977
|
```
|
|
978
978
|
|
|
@@ -1071,7 +1071,7 @@ router.post(
|
|
|
1071
1071
|
- Codes have 6 digits and are stored in `one_time_tokens` (purpose `otp`) as a salted HMAC keyed from your access-token secret, never as plain SHA-256, which is trivially reversible for 6 digits. A new request invalidates the previous code.
|
|
1072
1072
|
- Every verify counts an attempt atomically first. After `maxAttempts` the code is invalidated, even if the right code comes next, and even under concurrent guesses.
|
|
1073
1073
|
- Delivery: `notify.channel(channel).send(phone, { body, code, expiresAt })`. Register that channel in `config/notifications.ts`, or set `auth.otp.send(phone, message, channel)`. `auth.otp.message(code)` changes the text.
|
|
1074
|
-
- **Anti-enumeration:** an unknown phone gets the same `requestOtp` result (nothing sent) and the same `InvalidOneTimeTokenError` (400, `EC008`) from `verifyOtp`. The code
|
|
1074
|
+
- **Anti-enumeration:** an unknown phone gets the same `requestOtp` result (nothing sent) and the same `InvalidOneTimeTokenError` (400, `EC008`) from `verifyOtp`. The lookup, the code writes and the delivery run in the background (failures: log + `otp.deliveryFailed` event); `auth.otp.awaitDelivery: true` awaits it instead.
|
|
1075
1075
|
- CSRF: `verifyOtp` is a POST. If the route uses cookie auth, the 5.12 Origin check applies. Otherwise there is no ambient credential to ride.
|
|
1076
1076
|
|
|
1077
1077
|
## Gotchas
|
|
@@ -1280,6 +1280,8 @@ If tokens minted before 4.12.0 may lack an `exp`, see `warlock auth.purge-never-
|
|
|
1280
1280
|
|
|
1281
1281
|
The package signs access and refresh tokens with independent secrets — `config.auth.accessToken.secret` and `config.auth.refreshToken.secret`. Setting a distinct `refresh.secret` is recommended: it prevents an access-token compromise from forging refresh tokens (and vice versa). The refresh secret is **optional** — when `config.auth.refreshToken.secret` is unset, refresh tokens fall back to the main `config.auth.accessToken.secret`, so refresh works out of the box without a second secret.
|
|
1282
1282
|
|
|
1283
|
+
**Rotating a secret:** set the new `accessToken.secret` / `refreshToken.secret` and list the old ones in `accessToken.previousSecrets` / `refreshToken.previousSecrets`. Tokens signed with a retired secret still verify (only on a signature miss; expiry and claim checks stay final), new tokens always use the current secret, and without a refresh secret the retired access secrets apply to refresh tokens too. Remove a retired secret once its tokens have expired.
|
|
1284
|
+
|
|
1283
1285
|
## Things NOT to do
|
|
1284
1286
|
|
|
1285
1287
|
- Don't use raw JWT libraries directly. The package handles signing, verification, secret loading, and the access/refresh split.
|
|
@@ -2065,10 +2067,10 @@ loginThrottleMiddleware({
|
|
|
2065
2067
|
| `errorMessage` | i18n `auth.errors.tooManyAttempts` | 429 message override |
|
|
2066
2068
|
| `isFailure` | `(res) => !res.isOk` | What counts as a failed attempt |
|
|
2067
2069
|
| `identify` | built-in email + ip extraction | Custom identifier list |
|
|
2068
|
-
| `emailLock` | `"global"`
|
|
2070
|
+
| `emailLock` | `"global"` (`"pair"` in 6.0) | `"pair"` locks the (email, IP) pair instead of the email for everyone |
|
|
2069
2071
|
| `accountMax` | `max * 10` | Email-wide limit across all IPs when `emailLock: "pair"` |
|
|
2070
2072
|
|
|
2071
|
-
`emailLock: "pair"` stops a stranger from locking a known account out: their `max` failures lock only their own (email, IP) pair, while the email-wide bucket (`accountMax`) still stops guessing spread over many IPs. It applies when `by` tracks both `"email"` and `"ip"` and no `identify` is set.
|
|
2073
|
+
`emailLock: "pair"` stops a stranger from locking a known account out: their `max` failures lock only their own (email, IP) pair, while the email-wide bucket (`accountMax`) still stops guessing spread over many IPs. It applies when `by` tracks both `"email"` and `"ip"` and no `identify` is set. Leaving it unset in that case logs a one-time warning because the default changes in 6.0: set it explicitly. A successful login clears the account buckets only; the shared IP bucket expires with its window (with `by: ["ip"]` alone a success still resets it).
|
|
2072
2074
|
|
|
2073
2075
|
Throttle the anonymous passkey options route the same way, counting every request: `loginThrottleMiddleware({ by: ["ip"], isFailure: () => true, max: 30, window: "1m" })`.
|
|
2074
2076
|
|
|
@@ -2215,7 +2217,7 @@ router.post("/auth/reset-password", resetPasswordController, {
|
|
|
2215
2217
|
});
|
|
2216
2218
|
```
|
|
2217
2219
|
|
|
2218
|
-
`requestPasswordReset`
|
|
2220
|
+
`requestPasswordReset` runs the account lookup, the token writes and the notification **in the background**, so a known account answers as fast as an unknown one (no database write or SMTP round trip on the response path). A failed send is logged and emitted as `password.resetDeliveryFailed` (`(user, error)`); set `auth.passwordReset.awaitDelivery: true` (default `false`) to await all of it and get its error instead.
|
|
2219
2221
|
|
|
2220
2222
|
`resetPassword` writes the password, then calls `authService.revokeAllTokens(user)`: every refresh token is revoked and every access token deleted, which also kills cookie sessions (a cookie holds an access token). It emits `password.reset`; `requestPasswordReset` emits `password.resetRequested`.
|
|
2221
2223
|
|
package/package.json
CHANGED
|
@@ -5,20 +5,20 @@
|
|
|
5
5
|
"environment": "server"
|
|
6
6
|
},
|
|
7
7
|
"dependencies": {
|
|
8
|
-
"@mongez/copper": "^2.1.
|
|
9
|
-
"@mongez/events": "^2.2.
|
|
10
|
-
"@mongez/reinforcements": "^4.0
|
|
8
|
+
"@mongez/copper": "^2.1.4",
|
|
9
|
+
"@mongez/events": "^2.2.10",
|
|
10
|
+
"@mongez/reinforcements": "^4.1.0",
|
|
11
11
|
"fast-jwt": "^6.3.4",
|
|
12
12
|
"ms": "^2.1.3"
|
|
13
13
|
},
|
|
14
14
|
"peerDependencies": {
|
|
15
|
-
"@warlock.js/fs": "5.
|
|
16
|
-
"@warlock.js/cache": "5.
|
|
17
|
-
"@warlock.js/cascade": "5.
|
|
18
|
-
"@warlock.js/core": "5.
|
|
19
|
-
"@warlock.js/logger": "5.
|
|
20
|
-
"@warlock.js/seal": "5.
|
|
21
|
-
"@warlock.js/notifications": "5.
|
|
15
|
+
"@warlock.js/fs": "5.54.0",
|
|
16
|
+
"@warlock.js/cache": "5.54.0",
|
|
17
|
+
"@warlock.js/cascade": "5.54.0",
|
|
18
|
+
"@warlock.js/core": "5.54.0",
|
|
19
|
+
"@warlock.js/logger": "5.54.0",
|
|
20
|
+
"@warlock.js/seal": "5.54.0",
|
|
21
|
+
"@warlock.js/notifications": "5.54.0",
|
|
22
22
|
"@simplewebauthn/server": "^13.1.0",
|
|
23
23
|
"jose": "^6.1.0"
|
|
24
24
|
},
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
],
|
|
49
49
|
"author": "hassanzohdy",
|
|
50
50
|
"license": "MIT",
|
|
51
|
-
"version": "5.
|
|
51
|
+
"version": "5.54.0",
|
|
52
52
|
"type": "module",
|
|
53
53
|
"main": "./esm/index.mjs",
|
|
54
54
|
"module": "./esm/index.mjs",
|
|
@@ -89,7 +89,7 @@ export default {
|
|
|
89
89
|
- `hashTokensAtRest: true` (default `false`) — `access_tokens.token` / `refresh_tokens.token` hold the SHA-256 digest, never the JWT, so a copied table cannot be replayed. No migration; lookups accept both forms, so switching it on or off signs no one out. A row loaded from the DB has no raw token any more; a freshly issued row exposes it as `row.plainToken`. Automatic cookie renewal parks the successor pair encrypted in the cache for the overlap window.
|
|
90
90
|
- `accessToken.issuer` / `accessToken.audience` (default unset) — stamped as `iss` / `aud` on every token signed and required on every token accepted. Setting either signs everyone out once (old tokens lack the claim).
|
|
91
91
|
- `cookie.hostPrefix: true` (default `false`) — auth cookies become `__Host-access_token` / `__Host-refresh_token` (Secure, `Path=/`, no Domain; a write with another path or a Domain throws naming the setting). The unprefixed cookie is still read during the switch, and both are cleared on logout.
|
|
92
|
-
- In production a signing secret under 32 bytes, or an access-token lifetime over 30 days, logs a one-time warning.
|
|
92
|
+
- In production a signing secret under 32 bytes, or an access-token lifetime over 30 days, logs a one-time warning (a secret under 32 bytes becomes a boot error in 6.0). `auth.rehashPasswords` (default `true`) re-hashes a stored password after a correct login when `encryption.password` asks for another algorithm or cost.
|
|
93
93
|
- `Auth` hides `password` from serialized output (`static hidden = ["password"]`); a model that sets its own `hidden` must keep `"password"` in it.
|
|
94
94
|
|
|
95
95
|
### Token lifetimes are validated — a bad one throws
|
|
@@ -234,7 +234,7 @@ passkeys: {
|
|
|
234
234
|
rpID: "example.com",
|
|
235
235
|
rpName: "Example",
|
|
236
236
|
origin: "https://example.com",
|
|
237
|
-
userVerification: "
|
|
237
|
+
userVerification: "required", // "preferred" (default until 6.0, warns if unset) also accepts possession only
|
|
238
238
|
},
|
|
239
239
|
```
|
|
240
240
|
|
|
@@ -333,7 +333,7 @@ router.post(
|
|
|
333
333
|
- Codes have 6 digits and are stored in `one_time_tokens` (purpose `otp`) as a salted HMAC keyed from your access-token secret, never as plain SHA-256, which is trivially reversible for 6 digits. A new request invalidates the previous code.
|
|
334
334
|
- Every verify counts an attempt atomically first. After `maxAttempts` the code is invalidated, even if the right code comes next, and even under concurrent guesses.
|
|
335
335
|
- Delivery: `notify.channel(channel).send(phone, { body, code, expiresAt })`. Register that channel in `config/notifications.ts`, or set `auth.otp.send(phone, message, channel)`. `auth.otp.message(code)` changes the text.
|
|
336
|
-
- **Anti-enumeration:** an unknown phone gets the same `requestOtp` result (nothing sent) and the same `InvalidOneTimeTokenError` (400, `EC008`) from `verifyOtp`. The code
|
|
336
|
+
- **Anti-enumeration:** an unknown phone gets the same `requestOtp` result (nothing sent) and the same `InvalidOneTimeTokenError` (400, `EC008`) from `verifyOtp`. The lookup, the code writes and the delivery run in the background (failures: log + `otp.deliveryFailed` event); `auth.otp.awaitDelivery: true` awaits it instead.
|
|
337
337
|
- CSRF: `verifyOtp` is a POST. If the route uses cookie auth, the 5.12 Origin check applies. Otherwise there is no ambient credential to ride.
|
|
338
338
|
|
|
339
339
|
## Gotchas
|
|
@@ -187,6 +187,8 @@ If tokens minted before 4.12.0 may lack an `exp`, see `warlock auth.purge-never-
|
|
|
187
187
|
|
|
188
188
|
The package signs access and refresh tokens with independent secrets — `config.auth.accessToken.secret` and `config.auth.refreshToken.secret`. Setting a distinct `refresh.secret` is recommended: it prevents an access-token compromise from forging refresh tokens (and vice versa). The refresh secret is **optional** — when `config.auth.refreshToken.secret` is unset, refresh tokens fall back to the main `config.auth.accessToken.secret`, so refresh works out of the box without a second secret.
|
|
189
189
|
|
|
190
|
+
**Rotating a secret:** set the new `accessToken.secret` / `refreshToken.secret` and list the old ones in `accessToken.previousSecrets` / `refreshToken.previousSecrets`. Tokens signed with a retired secret still verify (only on a signature miss; expiry and claim checks stay final), new tokens always use the current secret, and without a refresh secret the retired access secrets apply to refresh tokens too. Remove a retired secret once its tokens have expired.
|
|
191
|
+
|
|
190
192
|
## Things NOT to do
|
|
191
193
|
|
|
192
194
|
- Don't use raw JWT libraries directly. The package handles signing, verification, secret loading, and the access/refresh split.
|
|
@@ -94,10 +94,10 @@ loginThrottleMiddleware({
|
|
|
94
94
|
| `errorMessage` | i18n `auth.errors.tooManyAttempts` | 429 message override |
|
|
95
95
|
| `isFailure` | `(res) => !res.isOk` | What counts as a failed attempt |
|
|
96
96
|
| `identify` | built-in email + ip extraction | Custom identifier list |
|
|
97
|
-
| `emailLock` | `"global"`
|
|
97
|
+
| `emailLock` | `"global"` (`"pair"` in 6.0) | `"pair"` locks the (email, IP) pair instead of the email for everyone |
|
|
98
98
|
| `accountMax` | `max * 10` | Email-wide limit across all IPs when `emailLock: "pair"` |
|
|
99
99
|
|
|
100
|
-
`emailLock: "pair"` stops a stranger from locking a known account out: their `max` failures lock only their own (email, IP) pair, while the email-wide bucket (`accountMax`) still stops guessing spread over many IPs. It applies when `by` tracks both `"email"` and `"ip"` and no `identify` is set.
|
|
100
|
+
`emailLock: "pair"` stops a stranger from locking a known account out: their `max` failures lock only their own (email, IP) pair, while the email-wide bucket (`accountMax`) still stops guessing spread over many IPs. It applies when `by` tracks both `"email"` and `"ip"` and no `identify` is set. Leaving it unset in that case logs a one-time warning because the default changes in 6.0: set it explicitly. A successful login clears the account buckets only; the shared IP bucket expires with its window (with `by: ["ip"]` alone a success still resets it).
|
|
101
101
|
|
|
102
102
|
Throttle the anonymous passkey options route the same way, counting every request: `loginThrottleMiddleware({ by: ["ip"], isFailure: () => true, max: 30, window: "1m" })`.
|
|
103
103
|
|
|
@@ -86,7 +86,7 @@ router.post("/auth/reset-password", resetPasswordController, {
|
|
|
86
86
|
});
|
|
87
87
|
```
|
|
88
88
|
|
|
89
|
-
`requestPasswordReset`
|
|
89
|
+
`requestPasswordReset` runs the account lookup, the token writes and the notification **in the background**, so a known account answers as fast as an unknown one (no database write or SMTP round trip on the response path). A failed send is logged and emitted as `password.resetDeliveryFailed` (`(user, error)`); set `auth.passwordReset.awaitDelivery: true` (default `false`) to await all of it and get its error instead.
|
|
90
90
|
|
|
91
91
|
`resetPassword` writes the password, then calls `authService.revokeAllTokens(user)`: every refresh token is revoked and every access token deleted, which also kills cookie sessions (a cookie holds an access token). It emits `password.reset`; `requestPasswordReset` emits `password.resetRequested`.
|
|
92
92
|
|