@warlock.js/auth 5.24.0 → 5.26.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 +26 -9
- package/LICENSE +21 -21
- package/esm/contracts/index.d.mts +1 -1
- package/esm/contracts/request-locals.d.mts +1 -1
- package/esm/contracts/types.d.mts +8 -3
- package/esm/contracts/types.d.mts.map +1 -1
- package/esm/contracts/types.mjs.map +1 -1
- package/esm/index.d.mts +3 -3
- package/esm/index.mjs +2 -2
- package/esm/middleware/auth.middleware.mjs +1 -1
- package/esm/middleware/auth.middleware.mjs.map +1 -1
- package/esm/middleware/login-throttle.middleware.mjs.map +1 -1
- package/esm/models/access-token/access-token.model.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.map +1 -1
- package/esm/models/auth-token-family/auth-token-family.model.mjs +5 -0
- package/esm/models/auth-token-family/auth-token-family.model.mjs.map +1 -1
- package/esm/models/auth.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/services/auth-config.mjs +3 -1
- package/esm/services/auth-config.mjs.map +1 -1
- package/esm/services/auth-events.mjs.map +1 -1
- package/esm/services/auth.service.d.mts +9 -4
- package/esm/services/auth.service.d.mts.map +1 -1
- package/esm/services/auth.service.mjs +45 -17
- package/esm/services/auth.service.mjs.map +1 -1
- package/esm/services/index.d.mts +1 -1
- package/esm/services/index.mjs +1 -1
- package/esm/services/resolve-request-user.d.mts +3 -2
- package/esm/services/resolve-request-user.d.mts.map +1 -1
- package/esm/services/resolve-request-user.mjs +8 -2
- package/esm/services/resolve-request-user.mjs.map +1 -1
- package/esm/session/page-session.d.mts +3 -1
- package/esm/session/page-session.d.mts.map +1 -1
- package/esm/session/page-session.mjs +2 -1
- package/esm/session/page-session.mjs.map +1 -1
- package/esm/utils/auth-error-codes.mjs.map +1 -1
- package/llms-full.txt +1946 -1927
- package/package.json +8 -8
- package/skills/auth-basics/SKILL.md +1 -1
- package/skills/customize-token-storage/SKILL.md +160 -160
- package/skills/customize-user-type/SKILL.md +168 -168
- package/skills/handle-login-and-logout/SKILL.md +195 -180
- package/skills/login-with-providers/SKILL.md +283 -283
- package/skills/manage-tokens/SKILL.md +196 -196
- package/skills/overview/SKILL.md +74 -74
- package/skills/protect-routes/SKILL.md +299 -299
- package/skills/register-user/SKILL.md +147 -147
- package/skills/run-auth-commands/SKILL.md +159 -159
- package/skills/throttle-login-attempts/SKILL.md +117 -117
- package/skills/verify-email-and-reset-password/SKILL.md +137 -137
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-token-family.model.mjs","names":[],"sources":["../../../../../../../../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 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,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,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":["../../../../../../../../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,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.model.mjs","names":[],"sources":["../../../../../../../auth/src/models/auth.model.ts"],"sourcesContent":["import { type ChildModel, Model, type ModelSchema } from \"@warlock.js/cascade\";\
|
|
1
|
+
{"version":3,"file":"auth.model.mjs","names":[],"sources":["../../../../../../../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\nexport abstract class Auth<Schema extends ModelSchema = ModelSchema>\n extends Model<Schema>\n implements Authenticable\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":";;;;;AAMA,IAAsB,OAAtB,cACU,MAEV;;;;CASE,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../auth/src/models/refresh-token/migration.ts"],"sourcesContent":["import { migrate } from \"@warlock.js/cascade\";\
|
|
1
|
+
{"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"refresh-token.model.mjs","names":[],"sources":["../../../../../../../../auth/src/models/refresh-token/refresh-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\r\nimport { v } from \"@warlock.js/seal\";\r\nimport type { DeviceInfo } from \"../../contracts/types\";\r\nimport { isNeverExpiring, isUsableExpiry } from \"../../utils/token-expiry\";\r\nimport type { Auth } from \"../auth.model\";\r\n\r\n/**\r\n * Seal schema for the persisted refresh-token record. Exported so an override\r\n * can spread it and add columns (e.g. a tenant key) without re-declaring the\r\n * base shape:\r\n *\r\n * @example\r\n * export class AppRefreshToken extends RefreshToken {\r\n * public static schema = refreshTokenSchema.extend({\r\n * organization_id: v.string().required(),\r\n * });\r\n * }\r\n */\r\nexport const refreshTokenSchema = v.object({\r\n token: v.string().required(),\r\n user_id: v.scalar().required(),\r\n user_type: v.string().required(),\r\n family_id: v.string().required(),\r\n expires_at: v.date().required(),\r\n last_used_at: v.date().default(() => new Date()),\r\n revoked_at: v.date().optional(),\r\n /** The successor pair a bounded concurrent renewal may reuse. */\r\n successor_access_token_id: v.string().optional(),\r\n successor_refresh_token_id: v.string().optional(),\r\n device_info: v.record(v.any()).optional(),\r\n});\r\n\r\n/**\r\n * Extra attributes captured when a refresh token is issued.\r\n */\r\nexport type RefreshTokenIssueOptions = {\r\n familyId: string;\r\n expiresAt: string;\r\n deviceInfo?: DeviceInfo;\r\n};\r\n\r\n/**\r\n * Persisted refresh-token record + the data layer for refresh tokens.\r\n *\r\n * **Role.** Owns every refresh-token read, write, and lifecycle transition.\r\n * The auth service drives refresh-token state exclusively through this model's\r\n * named statics and instance methods, so it never hard-codes a column name —\r\n * which is what makes a snake/camel mismatch (the historical `userId` bug)\r\n * structurally impossible and lets an override rename or add columns by\r\n * extending this class and registering it under `config.auth.refreshToken.model`.\r\n */\r\nexport class RefreshToken extends Model {\r\n public static table = \"refresh_tokens\";\r\n\r\n public static schema = refreshTokenSchema;\r\n\r\n /**\r\n * The raw signed refresh JWT is a bearer credential — never serialize it.\r\n * `hidden` only strips it from `toJSON()` / `JSON.stringify(model)` (e.g. a\r\n * session list returned via `response.json`); `get(\"token\")`,\r\n * `findByToken` / `findForUser` and every query still read the column.\r\n */\r\n public static hidden = [\"token\"];\r\n\r\n /**\r\n * Permanent regardless of the data source default — Mongo's driver default\r\n * is `\"trash\"`, which would copy live credential material (the JWT itself)\r\n * into `refresh_tokensTrash` on every `destroy()` (expiry purge,\r\n * never-expiring purge). A purged refresh token must not survive anywhere.\r\n */\r\n public static deleteStrategy = \"permanent\" as const;\r\n\r\n /** Token family this row belongs to (rotation / replay grouping). */\r\n public get familyId(): string {\r\n return this.get(\"family_id\");\r\n }\r\n\r\n /**\r\n * Whether the token's `expires_at` is in the past.\r\n *\r\n * **Fails closed as of 4.12.0**: a missing or unparseable `expires_at` now\r\n * counts as expired. It previously answered `false` for both — \"no expiry\r\n * recorded ⇒ never expires\" — which handed an unlimited life to precisely the\r\n * malformed rows, including the `Invalid Date` a pre-4.12.0 unparseable\r\n * `expiresIn` could write. `expires_at` is `required` in the schema, so a row\r\n * that cannot say when it dies is malformed, not immortal.\r\n */\r\n public get isExpired(): boolean {\r\n const expiresAt = this.get(\"expires_at\");\r\n\r\n if (!isUsableExpiry(expiresAt)) return true;\r\n\r\n return new Date().getTime() > new Date(expiresAt).getTime();\r\n }\r\n\r\n /**\r\n * Whether nothing can ever retire this row — an unusable `expires_at`, or a\r\n * token carrying no `exp` claim. See {@link isNeverExpiring}.\r\n */\r\n public get neverExpires(): boolean {\r\n return isNeverExpiring(this.get(\"token\"), this.get(\"expires_at\"));\r\n }\r\n\r\n /** Whether the token has been revoked. */\r\n public get isRevoked(): boolean {\r\n return !!this.get(\"revoked_at\");\r\n }\r\n\r\n /** Whether the token is still usable (not expired and not revoked). */\r\n public get isValid(): boolean {\r\n return !this.isExpired && !this.isRevoked;\r\n }\r\n\r\n /**\r\n * Unconditionally stamp `revoked_at` on this token.\r\n */\r\n public async revoke(): Promise<this> {\r\n return this.merge({ revoked_at: new Date() }).save();\r\n }\r\n\r\n /**\r\n * Atomically revoke this token ONLY if it is still active. Resolves to `true`\r\n * when this call performed the revoke, `false` when a concurrent request had\r\n * already revoked it — the win/lose signal that powers rotation replay\r\n * detection. Uses a conditional UPDATE so two concurrent rotations of the\r\n * same token can never both succeed.\r\n */\r\n public async revokeIfActive(): Promise<boolean> {\r\n const modelClass = this.constructor as typeof RefreshToken;\r\n\r\n const revokedCount = await modelClass.atomic(\r\n { id: this.id, revoked_at: null },\r\n { $set: { revoked_at: new Date() } },\r\n );\r\n\r\n return revokedCount > 0;\r\n }\r\n\r\n /**\r\n * Touch `last_used_at` without revoking — the non-rotating refresh path.\r\n */\r\n public async markAsUsed(): Promise<void> {\r\n await this.merge({ last_used_at: new Date() }).save();\r\n }\r\n\r\n /**\r\n * Persist a freshly-signed refresh token for the user.\r\n */\r\n public static issue(user: Auth, token: string, options: RefreshTokenIssueOptions) {\r\n return this.create({\r\n token,\r\n user_id: user.id,\r\n user_type: user.userType,\r\n family_id: options.familyId,\r\n expires_at: options.expiresAt,\r\n device_info: options.deviceInfo\r\n ? {\r\n userAgent: options.deviceInfo.userAgent,\r\n ip: options.deviceInfo.ip,\r\n deviceId: options.deviceInfo.deviceId,\r\n }\r\n : undefined,\r\n });\r\n }\r\n\r\n /**\r\n * Find a refresh-token row by its raw token string.\r\n */\r\n public static findByToken(token: string): Promise<RefreshToken | null> {\r\n return this.first({ token });\r\n }\r\n\r\n /**\r\n * Find a refresh token scoped to a user — used by logout so a caller can only\r\n * revoke a token that actually belongs to them.\r\n */\r\n public static findForUser(user: Auth, token: string): Promise<RefreshToken | null> {\r\n return this.first({ token, user_id: user.id });\r\n }\r\n\r\n /** Find any member of a family, including an already-revoked legacy member. */\r\n public static findInFamily(familyId: string): Promise<RefreshToken | null> {\r\n return this.first({ family_id: familyId });\r\n }\r\n\r\n /**\r\n * Every refresh lineage for a user, including rotated rows. Logout uses this\r\n * to bootstrap durable family records before it starts family revocations.\r\n */\r\n public static familiesForUser(user: Auth): Promise<RefreshToken[]> {\r\n return this.query().where({ user_id: user.id, user_type: user.userType }).get();\r\n }\r\n\r\n /**\r\n * Delete a specific refresh token belonging to the user.\r\n */\r\n public static deleteForUser(user: Auth, token: string) {\r\n return this.delete({ token, user_id: user.id });\r\n }\r\n\r\n /**\r\n * Active, unexpired sessions for the user, newest first.\r\n */\r\n public static activeFor(user: Auth): Promise<RefreshToken[]> {\r\n return this.query()\r\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\r\n .where(\"expires_at\", \">\", new Date())\r\n .orderBy(\"created_at\", \"desc\")\r\n .get();\r\n }\r\n\r\n /**\r\n * Revoke every still-active refresh token for the user, returning the rows\r\n * that were revoked so the caller can emit a per-token event for each.\r\n *\r\n * Rows are fetched BEFORE they are revoked: a bulk `findAndUpdate` keyed on\r\n * `revoked_at: null` would re-query the same predicate after the update and\r\n * match nothing, returning an empty set.\r\n */\r\n public static async revokeAllFor(user: Auth): Promise<RefreshToken[]> {\r\n const tokens = await this.query()\r\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\r\n .get();\r\n\r\n for (const token of tokens) {\r\n await token.revoke();\r\n }\r\n\r\n return tokens;\r\n }\r\n\r\n /**\r\n * Revoke every still-active token in a family (rotation breach containment),\r\n * returning the revoked rows (fetched before revocation — see `revokeAllFor`).\r\n */\r\n public static async revokeFamily(familyId: string): Promise<RefreshToken[]> {\r\n const tokens = await this.query().where({ family_id: familyId, revoked_at: null }).get();\r\n\r\n for (const token of tokens) {\r\n await token.revoke();\r\n }\r\n\r\n return tokens;\r\n }\r\n\r\n /**\r\n * Revoke the oldest active tokens so at most `max - 1` remain — making room\r\n * for the about-to-be-issued one. Bounded by `max`, so the per-row loop is\r\n * small.\r\n */\r\n public static async enforceMax(user: Auth, max: number): Promise<void> {\r\n const activeTokens = await this.query()\r\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\r\n .orderBy(\"created_at\", \"asc\")\r\n .get();\r\n\r\n if (activeTokens.length < max) return;\r\n\r\n const tokensToRevoke = activeTokens.slice(0, activeTokens.length - max + 1);\r\n\r\n for (const token of tokensToRevoke) {\r\n await token.revoke();\r\n }\r\n }\r\n\r\n /**\r\n * Hard-delete every expired refresh token, returning the deleted rows so the\r\n * caller can emit a per-token event. Runs from the `auth.cleanup` CLI command\r\n * (a cold batch path).\r\n */\r\n public static async purgeExpired(): Promise<RefreshToken[]> {\r\n const expiredTokens = await this.query().where(\"expires_at\", \"<\", new Date()).get();\r\n\r\n for (const token of expiredTokens) {\r\n await token.destroy();\r\n }\r\n\r\n return expiredTokens;\r\n }\r\n\r\n /**\r\n * Every row that can never retire itself — see {@link neverExpires}. A full\r\n * scan filtered in memory, for the reason given on\r\n * {@link AccessToken.findNeverExpiring}: neither an `Invalid Date` nor a\r\n * missing `exp` claim is expressible as a `where`.\r\n */\r\n public static async findNeverExpiring(): Promise<RefreshToken[]> {\r\n const tokens = await this.query().get();\r\n\r\n return tokens.filter((token: RefreshToken) => token.neverExpires);\r\n }\r\n\r\n /**\r\n * Hard-delete every never-expiring row, returning the rows removed.\r\n *\r\n * Deleted rather than `revoked_at`-stamped: a revoked row is still a row this\r\n * table has to carry, and one of the two shapes being removed is a row whose\r\n * date column cannot be compared at all — leaving it in place keeps a\r\n * permanently unpurgeable record. Rotation replay-detection is unaffected;\r\n * these rows can no longer be presented successfully either way.\r\n */\r\n public static async purgeNeverExpiring(): Promise<RefreshToken[]> {\r\n const tokens = await this.findNeverExpiring();\r\n\r\n for (const token of tokens) {\r\n await token.destroy();\r\n }\r\n\r\n return tokens;\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;AAkBA,MAAa,qBAAqB,EAAE,OAAO;CACzC,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;CAC9B,cAAc,EAAE,KAAK,CAAC,CAAC,8BAAc,IAAI,KAAK,CAAC;CAC/C,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;;CAE9B,2BAA2B,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/C,4BAA4B,EAAE,OAAO,CAAC,CAAC,SAAS;CAChD,aAAa,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,SAAS;AAC1C,CAAC;;;;;;;;;;;AAqBD,IAAa,eAAb,cAAkC,MAAM;;eAChB;;;gBAEC;;;gBAQA,CAAC,OAAO;;;wBAQA;;;CAG/B,IAAW,WAAmB;EAC5B,OAAO,KAAK,IAAI,WAAW;CAC7B;;;;;;;;;;;CAYA,IAAW,YAAqB;EAC9B,MAAM,YAAY,KAAK,IAAI,YAAY;EAEvC,IAAI,CAAC,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AAiB,aAAa,MAAM,GAAG,aAAa,SAAS,MAAM,CAAC;EAE1E,KAAK,MAAM,SAAS,gBAClB,MAAM,MAAM,OAAO;CAEvB;;;;;;CAOA,aAAoB,eAAwC;EAC1D,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;CACT;;;;;;;CAQA,aAAoB,oBAA6C;EAG/D,QAAO,MAFc,KAAK,MAAM,CAAC,CAAC,IAAI,EAEzB,CAAC,QAAQ,UAAwB,MAAM,YAAY;CAClE;;;;;;;;;;CAWA,aAAoB,qBAA8C;EAChE,MAAM,SAAS,MAAM,KAAK,kBAAkB;EAE5C,KAAK,MAAM,SAAS,QAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"refresh-token.model.mjs","names":[],"sources":["../../../../../../../../auth/src/models/refresh-token/refresh-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport type { DeviceInfo } from \"../../contracts/types\";\nimport { isNeverExpiring, isUsableExpiry } from \"../../utils/token-expiry\";\nimport type { Auth } from \"../auth.model\";\n\n/**\n * Seal schema for the persisted refresh-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 * @example\n * export class AppRefreshToken extends RefreshToken {\n * public static schema = refreshTokenSchema.extend({\n * organization_id: v.string().required(),\n * });\n * }\n */\nexport const refreshTokenSchema = v.object({\n token: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n family_id: v.string().required(),\n expires_at: v.date().required(),\n last_used_at: v.date().default(() => new Date()),\n revoked_at: v.date().optional(),\n /** The successor pair a bounded concurrent renewal may reuse. */\n successor_access_token_id: v.string().optional(),\n successor_refresh_token_id: v.string().optional(),\n device_info: v.record(v.any()).optional(),\n});\n\n/**\n * Extra attributes captured when a refresh token is issued.\n */\nexport type RefreshTokenIssueOptions = {\n familyId: string;\n expiresAt: string;\n deviceInfo?: DeviceInfo;\n};\n\n/**\n * Persisted refresh-token record + the data layer for refresh tokens.\n *\n * **Role.** Owns every refresh-token read, write, and lifecycle transition.\n * The auth service drives refresh-token state exclusively through this model's\n * named statics and instance methods, so it never hard-codes a column name —\n * which is what makes a snake/camel mismatch (the historical `userId` bug)\n * structurally impossible and lets an override rename or add columns by\n * extending this class and registering it under `config.auth.refreshToken.model`.\n */\nexport class RefreshToken extends Model {\n public static table = \"refresh_tokens\";\n\n public static schema = refreshTokenSchema;\n\n /**\n * The raw signed refresh JWT is a bearer credential — never serialize it.\n * `hidden` only strips it from `toJSON()` / `JSON.stringify(model)` (e.g. a\n * session list returned via `response.json`); `get(\"token\")`,\n * `findByToken` / `findForUser` and every query still read the column.\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 `refresh_tokensTrash` on every `destroy()` (expiry purge,\n * never-expiring purge). A purged refresh token must not survive anywhere.\n */\n public static deleteStrategy = \"permanent\" as const;\n\n /** Token family this row belongs to (rotation / replay grouping). */\n public get familyId(): string {\n return this.get(\"family_id\");\n }\n\n /**\n * Whether the token's `expires_at` is in the past.\n *\n * **Fails closed as of 4.12.0**: a missing or unparseable `expires_at` now\n * counts as expired. It previously answered `false` for both — \"no expiry\n * recorded ⇒ never expires\" — which handed an unlimited life to precisely the\n * malformed rows, including the `Invalid Date` a pre-4.12.0 unparseable\n * `expiresIn` could write. `expires_at` is `required` in the schema, so a row\n * that cannot say when it dies is malformed, not immortal.\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().getTime() > new Date(expiresAt).getTime();\n }\n\n /**\n * Whether nothing can ever retire this row — an unusable `expires_at`, or a\n * token carrying no `exp` claim. See {@link isNeverExpiring}.\n */\n public get neverExpires(): boolean {\n return isNeverExpiring(this.get(\"token\"), this.get(\"expires_at\"));\n }\n\n /** Whether the token has been revoked. */\n public get isRevoked(): boolean {\n return !!this.get(\"revoked_at\");\n }\n\n /** Whether the token is still usable (not expired and not revoked). */\n public get isValid(): boolean {\n return !this.isExpired && !this.isRevoked;\n }\n\n /**\n * Unconditionally stamp `revoked_at` on this token.\n */\n public async revoke(): Promise<this> {\n return this.merge({ revoked_at: new Date() }).save();\n }\n\n /**\n * Atomically revoke this token ONLY if it is still active. Resolves to `true`\n * when this call performed the revoke, `false` when a concurrent request had\n * already revoked it — the win/lose signal that powers rotation replay\n * detection. Uses a conditional UPDATE so two concurrent rotations of the\n * same token can never both succeed.\n */\n public async revokeIfActive(): Promise<boolean> {\n const modelClass = this.constructor as typeof RefreshToken;\n\n const revokedCount = await modelClass.atomic(\n { id: this.id, revoked_at: null },\n { $set: { revoked_at: new Date() } },\n );\n\n return revokedCount > 0;\n }\n\n /**\n * Touch `last_used_at` without revoking — the non-rotating refresh path.\n */\n public async markAsUsed(): Promise<void> {\n await this.merge({ last_used_at: new Date() }).save();\n }\n\n /**\n * Persist a freshly-signed refresh token for the user.\n */\n public static issue(user: Auth, token: string, options: RefreshTokenIssueOptions) {\n return this.create({\n token,\n user_id: user.id,\n user_type: user.userType,\n family_id: options.familyId,\n expires_at: options.expiresAt,\n device_info: options.deviceInfo\n ? {\n userAgent: options.deviceInfo.userAgent,\n ip: options.deviceInfo.ip,\n deviceId: options.deviceInfo.deviceId,\n }\n : undefined,\n });\n }\n\n /**\n * Find a refresh-token row by its raw token string.\n */\n public static findByToken(token: string): Promise<RefreshToken | null> {\n return this.first({ token });\n }\n\n /**\n * Find a refresh token scoped to a user — used by logout so a caller can only\n * revoke a token that actually belongs to them.\n */\n public static findForUser(user: Auth, token: string): Promise<RefreshToken | null> {\n return this.first({ token, user_id: user.id });\n }\n\n /** Find any member of a family, including an already-revoked legacy member. */\n public static findInFamily(familyId: string): Promise<RefreshToken | null> {\n return this.first({ family_id: familyId });\n }\n\n /**\n * Every refresh lineage for a user, including rotated rows. Logout uses this\n * to bootstrap durable family records before it starts family revocations.\n */\n public static familiesForUser(user: Auth): Promise<RefreshToken[]> {\n return this.query().where({ user_id: user.id, user_type: user.userType }).get();\n }\n\n /**\n * Delete a specific refresh token belonging to the user.\n */\n public static deleteForUser(user: Auth, token: string) {\n return this.delete({ token, user_id: user.id });\n }\n\n /**\n * Active, unexpired sessions for the user, newest first.\n */\n public static activeFor(user: Auth): Promise<RefreshToken[]> {\n return this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .where(\"expires_at\", \">\", new Date())\n .orderBy(\"created_at\", \"desc\")\n .get();\n }\n\n /**\n * Revoke every still-active refresh token for the user, returning the rows\n * that were revoked so the caller can emit a per-token event for each.\n *\n * Rows are fetched BEFORE they are revoked: a bulk `findAndUpdate` keyed on\n * `revoked_at: null` would re-query the same predicate after the update and\n * match nothing, returning an empty set.\n */\n public static async revokeAllFor(user: Auth): Promise<RefreshToken[]> {\n const tokens = await this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .get();\n\n for (const token of tokens) {\n await token.revoke();\n }\n\n return tokens;\n }\n\n /**\n * Revoke every still-active token in a family (rotation breach containment),\n * returning the revoked rows (fetched before revocation — see `revokeAllFor`).\n */\n public static async revokeFamily(familyId: string): Promise<RefreshToken[]> {\n const tokens = await this.query().where({ family_id: familyId, revoked_at: null }).get();\n\n for (const token of tokens) {\n await token.revoke();\n }\n\n return tokens;\n }\n\n /**\n * Revoke the oldest active tokens so at most `max - 1` remain — making room\n * for the about-to-be-issued one. Bounded by `max`, so the per-row loop is\n * small.\n */\n public static async enforceMax(user: Auth, max: number): Promise<void> {\n const activeTokens = await this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .orderBy(\"created_at\", \"asc\")\n .get();\n\n if (activeTokens.length < max) return;\n\n const tokensToRevoke = activeTokens.slice(0, activeTokens.length - max + 1);\n\n for (const token of tokensToRevoke) {\n await token.revoke();\n }\n }\n\n /**\n * Hard-delete every expired refresh token, returning the deleted rows so the\n * caller can emit a per-token event. Runs from the `auth.cleanup` CLI command\n * (a cold batch path).\n */\n public static async purgeExpired(): Promise<RefreshToken[]> {\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;\n }\n\n /**\n * Every row that can never retire itself — see {@link neverExpires}. A full\n * scan filtered in memory, for the reason given on\n * {@link AccessToken.findNeverExpiring}: neither an `Invalid Date` nor a\n * missing `exp` claim is expressible as a `where`.\n */\n public static async findNeverExpiring(): Promise<RefreshToken[]> {\n const tokens = await this.query().get();\n\n return tokens.filter((token: RefreshToken) => token.neverExpires);\n }\n\n /**\n * Hard-delete every never-expiring row, returning the rows removed.\n *\n * Deleted rather than `revoked_at`-stamped: a revoked row is still a row this\n * table has to carry, and one of the two shapes being removed is a row whose\n * date column cannot be compared at all — leaving it in place keeps a\n * permanently unpurgeable record. Rotation replay-detection is unaffected;\n * these rows can no longer be presented successfully either way.\n */\n public static async purgeNeverExpiring(): Promise<RefreshToken[]> {\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":";;;;;;;;;;;;;;;;;AAkBA,MAAa,qBAAqB,EAAE,OAAO;CACzC,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;CAC9B,cAAc,EAAE,KAAK,CAAC,CAAC,8BAAc,IAAI,KAAK,CAAC;CAC/C,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;;CAE9B,2BAA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MAAM,CAAC,CAAC,MAAM;GAAE,WAAW;GAAU,YAAY;EAAK,CAAC,CAAC,CAAC,IAAI;EAEvF,KAAK,MAAM,SAAS,QAClB,MAAM,MAAM,OAAO;EAGrB,OAAO;CACT;;;;;;CAOA,aAAoB,WAAW,MAAY,KAA4B;EACrE,MAAM,eAAe,MAAM,KAAK,MAAM,CAAC,CACpC,MAAM;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;GAAU,YAAY;EAAK,CAAC,CAAC,CACvE,QAAQ,cAAc,KAAK,CAAC,CAC5B,IAAI;EAEP,IAAI,aAAa,SAAS,KAAK;EAE/B,MAAM,iBAAiB,aAAa,MAAM,GAAG,aAAa,SAAS,MAAM,CAAC;EAE1E,KAAK,MAAM,SAAS,gBAClB,MAAM,MAAM,OAAO;CAEvB;;;;;;CAOA,aAAoB,eAAwC;EAC1D,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;CACT;;;;;;;CAQA,aAAoB,oBAA6C;EAG/D,QAAO,MAFc,KAAK,MAAM,CAAC,CAAC,IAAI,EAEzB,CAAC,QAAQ,UAAwB,MAAM,YAAY;CAClE;;;;;;;;;;CAWA,aAAoB,qBAA8C;EAChE,MAAM,SAAS,MAAM,KAAK,kBAAkB;EAE5C,KAAK,MAAM,SAAS,QAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO;CACT;AACF"}
|
|
@@ -124,7 +124,9 @@ const authConfig = {
|
|
|
124
124
|
/** Refresh-token cookie name the session cookie helpers use. @default "refresh_token" */
|
|
125
125
|
refreshName: () => config.key("auth.cookie.refreshName", "refresh_token"),
|
|
126
126
|
/** Cookie `Path` attribute `setAuthCookie`/`clearAuthCookie` use. @default "/" */
|
|
127
|
-
path: () => config.key("auth.cookie.path", "/")
|
|
127
|
+
path: () => config.key("auth.cookie.path", "/"),
|
|
128
|
+
/** Select the request-scoped cookie Domain; undefined keeps it host-only. */
|
|
129
|
+
cookieDomain: () => config.key("auth.cookie.cookieDomain")
|
|
128
130
|
},
|
|
129
131
|
csrf: {
|
|
130
132
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-config.mjs","names":[],"sources":["../../../../../../../auth/src/services/auth-config.ts"],"sourcesContent":["import { config } from \"@warlock.js/core\";\r\nimport { log } from \"@warlock.js/logger\";\r\nimport { type Algorithm } from \"fast-jwt\";\r\nimport ms from \"ms\";\r\nimport type {\r\n AuthNotification,\r\n CanAuthenticate,\r\n LogoutWithoutTokenBehavior,\r\n OneTimeTokenUrlBuilder,\r\n PasswordSetter,\r\n} from \"../contracts/types\";\r\nimport type {\r\n AppleProviderConfig,\r\n AuthProvider,\r\n DiscordProviderConfig,\r\n FacebookProviderConfig,\r\n GitHubProviderConfig,\r\n GoogleProviderConfig,\r\n LinkedInProviderConfig,\r\n OtpSender,\r\n PasskeysConfig,\r\n ProviderUserCreator,\r\n XProviderConfig,\r\n} from \"../contracts/providers\";\r\nimport type { Auth } from \"../models/auth.model\";\r\n\r\nconst warnedLegacyKeys = new Set<string>();\r\n\r\nconst permitAuthentication: CanAuthenticate = (): boolean => true;\r\n\r\n/**\r\n * `ms` accepts anything at runtime and answers `undefined` for a string it\r\n * cannot parse (`\"30dayz\"`), a *formatted string* for a number (`2592000` ⇒\r\n * `\"43m\"`), and throws for `\"\"`. Its published types claim the far narrower\r\n * `(value: ms.StringValue) => number`, which is exactly what let an\r\n * `as ms.StringValue` cast smuggle arbitrary config text past the compiler and\r\n * hand `undefined` to the JWT signer. Declare the honest runtime signature once,\r\n * here, so every caller is forced to deal with the `undefined`.\r\n */\r\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\r\n\r\n/**\r\n * Turn a configured lifetime into a positive number of milliseconds, or throw\r\n * naming the key.\r\n *\r\n * A token lifetime is a security boundary, so an unusable value is a hard error\r\n * rather than a silent fallback: substituting a default would trade one\r\n * unintended lifetime for another, just as quietly — and quiet is the whole\r\n * problem. Every non-positive, non-finite or non-numeric parse is rejected:\r\n *\r\n * - `\"30dayz\"` / `\"thirty days\"` ⇒ `undefined` ⇒ a JWT signed with **no `exp`\r\n * claim** and an `Invalid Date` written to the token row.\r\n * - `\"0d\"` ⇒ parses cleanly to `0`, which `fast-jwt` treats as falsy and also\r\n * emits with **no `exp` claim** — it survives any guard that only rejects\r\n * `undefined`. `\"-1h\"` signs an already-expired token.\r\n * - `2592000` (a bare number) ⇒ `ms` *formats* it as `\"43m\"`, a string, which\r\n * then turns `Date.now() + expiresIn` into an `Invalid Date`.\r\n */\r\nfunction parseDuration(key: string, raw: unknown): number {\r\n let parsed: number | string | undefined;\r\n\r\n try {\r\n parsed = parseMs(raw);\r\n } catch {\r\n // ms throws (rather than returning undefined) for \"\" and non-strings\r\n parsed = undefined;\r\n }\r\n\r\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\r\n throw new Error(\r\n `auth.${key}: ${JSON.stringify(raw)} is not a valid ms duration — ` +\r\n `use a positive duration string such as \"1h\", \"7d\", or NO_EXPIRATION.`,\r\n );\r\n }\r\n\r\n return parsed;\r\n}\r\n\r\n/** Email-verification token lifetime used when nothing is configured. */\r\nconst DEFAULT_VERIFICATION_EXPIRES_IN = \"24h\";\r\n\r\n/** Password-reset token lifetime used when nothing is configured. */\r\nconst DEFAULT_PASSWORD_RESET_EXPIRES_IN = \"60m\";\r\n\r\n/** Passkey challenge lifetime used when nothing is configured. */\r\nconst DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN = \"5m\";\r\n\r\n/** OTP lifetime used when nothing is configured. */\r\nconst DEFAULT_OTP_EXPIRES_IN = \"5m\";\r\n\r\n/** Access-token lifetime used when nothing is configured. */\r\nconst DEFAULT_ACCESS_TOKEN_EXPIRES_IN = \"1h\";\r\n\r\n/**\r\n * Resolve an auth setting, preferring the new `auth.accessToken.*` /\r\n * `auth.refreshToken.*` key and falling back to the deprecated `auth.jwt.*`\r\n * shape — warning once per legacy key. Returns `fallback` when neither is set.\r\n *\r\n * This is the backward-compatible shim that lets existing `auth.jwt.*` configs\r\n * keep working after the config split.\r\n */\r\nfunction resolve<T>(newKey: string, legacyKey: string, fallback?: T): T {\r\n const fromNew = config.key(`auth.${newKey}`);\r\n\r\n if (fromNew !== undefined && fromNew !== null) {\r\n return fromNew as T;\r\n }\r\n\r\n const fromLegacy = config.key(`auth.${legacyKey}`);\r\n\r\n if (fromLegacy !== undefined && fromLegacy !== null) {\r\n if (!warnedLegacyKeys.has(legacyKey)) {\r\n warnedLegacyKeys.add(legacyKey);\r\n log.warn(\r\n \"auth\",\r\n \"config-deprecation\",\r\n `auth.${legacyKey} is deprecated — use auth.${newKey}`,\r\n );\r\n }\r\n\r\n return fromLegacy as T;\r\n }\r\n\r\n return fallback as T;\r\n}\r\n\r\n/**\r\n * Typed, backward-compatible access to auth configuration. The service and the\r\n * jwt signer read configuration exclusively through here, so the new split\r\n * config and the legacy `auth.jwt.*` shape both resolve the same way.\r\n */\r\nexport const authConfig = {\r\n canAuthenticate: async (user: Auth): Promise<boolean> => {\r\n const canAuthenticate = config.key<CanAuthenticate>(\r\n \"auth.canAuthenticate\",\r\n permitAuthentication,\r\n );\r\n\r\n return canAuthenticate(user);\r\n },\r\n accessToken: {\r\n /** Signing secret (legacy: `auth.jwt.secret`). Throws if neither is set. */\r\n secret: (): string => {\r\n const secret = resolve<string | undefined>(\"accessToken.secret\", \"jwt.secret\");\r\n\r\n if (!secret) {\r\n throw new Error(\"auth: no JWT secret configured — set `auth.accessToken.secret`.\");\r\n }\r\n\r\n return secret;\r\n },\r\n /** Signing algorithm (legacy: `auth.jwt.algorithm`). */\r\n algorithm: (): Algorithm => resolve(\"accessToken.algorithm\", \"jwt.algorithm\", \"HS256\"),\r\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.expiresIn`). */\r\n expiresIn: (): string | undefined => resolve(\"accessToken.expiresIn\", \"jwt.expiresIn\"),\r\n /**\r\n * Lifetime in milliseconds — the only form a token issuer may use. Defaults\r\n * to 1 hour when unset; throws naming the key when the configured value is\r\n * not a positive `ms` duration. See {@link parseDuration}.\r\n */\r\n expiresInMs: (): number =>\r\n parseDuration(\r\n \"accessToken.expiresIn\",\r\n authConfig.accessToken.expiresIn() ?? DEFAULT_ACCESS_TOKEN_EXPIRES_IN,\r\n ),\r\n },\r\n pageAuth: {\r\n /**\r\n * Login path a guarded PAGE route redirects a logged-out browser to.\r\n *\r\n * Unset (the default) ⇒ page-route auth failures keep the JSON 401 API\r\n * contract, so existing apps see NO behavior change. Set it (e.g. \"/login\")\r\n * to opt a browser-facing app into login-redirect UX: a logged-out human\r\n * navigating to a guarded page lands on the login screen instead of reading\r\n * a raw JSON error blob. Finding b9ab9804.\r\n */\r\n loginPath: (): string | undefined => config.key(\"auth.pageAuth.loginPath\"),\r\n /**\r\n * Query parameter the redirect carries the originally-requested path in, so\r\n * the login flow can send the user back where they were headed. Defaults to\r\n * `\"returnUrl\"`.\r\n */\r\n returnUrlParam: (): string => config.key(\"auth.pageAuth.returnUrlParam\", \"returnUrl\"),\r\n },\r\n cookie: {\r\n /** Cookie name `setAuthCookie`/`clearAuthCookie` use. @default \"access_token\" */\r\n name: (): string => config.key(\"auth.cookie.name\", \"access_token\"),\r\n /** Refresh-token cookie name the session cookie helpers use. @default \"refresh_token\" */\r\n refreshName: (): string => config.key(\"auth.cookie.refreshName\", \"refresh_token\"),\r\n /** Cookie `Path` attribute `setAuthCookie`/`clearAuthCookie` use. @default \"/\" */\r\n path: (): string => config.key(\"auth.cookie.path\", \"/\"),\r\n },\r\n csrf: {\r\n /**\r\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\r\n * beyond the request's own origin. @default []\r\n */\r\n allowedOrigins: (): string[] => config.key(\"auth.csrf.allowedOrigins\", []),\r\n },\r\n verification: {\r\n /** Lifetime in ms of an email-verification token; throws naming the key when unusable. @default \"24h\" */\r\n expiresInMs: (): number =>\r\n parseDuration(\r\n \"verification.expiresIn\",\r\n config.key(\"auth.verification.expiresIn\", DEFAULT_VERIFICATION_EXPIRES_IN),\r\n ),\r\n /** User attribute stamped with the verification date. @default \"emailVerifiedAt\" */\r\n field: (): string => config.key(\"auth.verification.field\", \"emailVerifiedAt\"),\r\n /** App notification replacing the default verification email. */\r\n notification: (): AuthNotification | undefined => config.key(\"auth.verification.notification\"),\r\n /** Link builder whose result is handed to the notification as `url`. */\r\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.verification.url\"),\r\n },\r\n passwordReset: {\r\n /** Lifetime in ms of a password-reset token; throws naming the key when unusable. @default \"60m\" */\r\n expiresInMs: (): number =>\r\n parseDuration(\r\n \"passwordReset.expiresIn\",\r\n config.key(\"auth.passwordReset.expiresIn\", DEFAULT_PASSWORD_RESET_EXPIRES_IN),\r\n ),\r\n /** User attribute `requestPasswordReset` looks the account up by. @default \"email\" */\r\n identifierField: (): string => config.key(\"auth.passwordReset.identifierField\", \"email\"),\r\n /** App notification replacing the default reset email. */\r\n notification: (): AuthNotification | undefined => config.key(\"auth.passwordReset.notification\"),\r\n /** Link builder whose result is handed to the notification as `url`. */\r\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.passwordReset.url\"),\r\n /** App-owned password writer replacing the default. */\r\n setPassword: (): PasswordSetter | undefined => config.key(\"auth.passwordReset.setPassword\"),\r\n },\r\n providers: {\r\n /** `auth.providers.google`, when configured. */\r\n google: (): GoogleProviderConfig | undefined => config.key(\"auth.providers.google\"),\r\n /** `auth.providers.github`, when configured. */\r\n github: (): GitHubProviderConfig | undefined => config.key(\"auth.providers.github\"),\r\n /** `auth.providers.discord`, when configured. */\r\n discord: (): DiscordProviderConfig | undefined => config.key(\"auth.providers.discord\"),\r\n /** `auth.providers.linkedin`, when configured. */\r\n linkedin: (): LinkedInProviderConfig | undefined => config.key(\"auth.providers.linkedin\"),\r\n /** `auth.providers.apple`, when configured. */\r\n apple: (): AppleProviderConfig | undefined => config.key(\"auth.providers.apple\"),\r\n /** `auth.providers.facebook`, when configured. */\r\n facebook: (): FacebookProviderConfig | undefined => config.key(\"auth.providers.facebook\"),\r\n /** `auth.providers.x`, when configured. */\r\n x: (): XProviderConfig | undefined => config.key(\"auth.providers.x\"),\r\n /** An app-registered provider under `auth.providers.custom.<name>`. */\r\n custom: (name: string): AuthProvider | undefined => {\r\n const providers = config.key<Record<string, AuthProvider>>(\"auth.providers.custom\", {});\r\n\r\n // Own keys only: `name` arrives from a URL, and \"constructor\" must not resolve to Object.\r\n return Object.hasOwn(providers, name) ? providers[name] : undefined;\r\n },\r\n /** User attribute a verified provider email is matched against. @default \"email\" */\r\n emailField: (): string => config.key(\"auth.providers.emailField\", \"email\"),\r\n /** App-owned user creation for a first provider login. */\r\n createUser: (): ProviderUserCreator | undefined => config.key(\"auth.providers.createUser\"),\r\n },\r\n passkeys: {\r\n /** `auth.passkeys`; throws naming the keys when `rpID`, `rpName` or `origin` is missing. */\r\n settings: (): PasskeysConfig => {\r\n const settings = config.key<PasskeysConfig | undefined>(\"auth.passkeys\");\r\n\r\n if (!settings?.rpID || !settings.rpName || !settings.origin) {\r\n throw new Error(\r\n \"@warlock.js/auth: passkeys need `auth.passkeys.rpID`, `auth.passkeys.rpName` and `auth.passkeys.origin`.\",\r\n );\r\n }\r\n\r\n return settings;\r\n },\r\n /** Allowed ceremony origins, as a list. */\r\n origins: (): string[] => {\r\n const { origin } = authConfig.passkeys.settings();\r\n\r\n return Array.isArray(origin) ? origin : [origin];\r\n },\r\n /** Challenge lifetime in ms; throws naming the key when unusable. @default \"5m\" */\r\n challengeExpiresInMs: (): number =>\r\n parseDuration(\r\n \"passkeys.challengeExpiresIn\",\r\n config.key(\"auth.passkeys.challengeExpiresIn\", DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN),\r\n ),\r\n },\r\n otp: {\r\n /** Notifications channel the code is sent through. @default \"sms\" */\r\n channel: (): string => config.key(\"auth.otp.channel\", \"sms\"),\r\n /** User attribute holding the phone number. @default \"phone\" */\r\n phoneField: (): string => config.key(\"auth.otp.phoneField\", \"phone\"),\r\n /** Code lifetime in ms; throws naming the key when unusable. @default \"5m\" */\r\n expiresInMs: (): number =>\r\n parseDuration(\"otp.expiresIn\", config.key(\"auth.otp.expiresIn\", DEFAULT_OTP_EXPIRES_IN)),\r\n /** Verify attempts before the code is invalidated. @default 5 */\r\n maxAttempts: (): number => config.key(\"auth.otp.maxAttempts\", 5),\r\n /** The message text for a code. */\r\n message: (code: string): string => {\r\n const build = config.key<((code: string) => string) | undefined>(\"auth.otp.message\");\r\n\r\n return build ? build(code) : `Your verification code is ${code}`;\r\n },\r\n /** App-owned delivery replacing the notifications channel send. */\r\n send: (): OtpSender | undefined => config.key(\"auth.otp.send\"),\r\n },\r\n refreshToken: {\r\n /** Separate refresh secret (legacy: `auth.jwt.refresh.secret`); empty ⇒ fall back to the access secret. */\r\n secret: (): string | undefined => resolve(\"refreshToken.secret\", \"jwt.refresh.secret\"),\r\n /** Whether refresh tokens are enabled (legacy: `auth.jwt.refresh.enabled`). */\r\n enabled: (): boolean => resolve(\"refreshToken.enabled\", \"jwt.refresh.enabled\", true),\r\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.refresh.expiresIn`). */\r\n expiresIn: (): string => resolve(\"refreshToken.expiresIn\", \"jwt.refresh.expiresIn\", \"7d\"),\r\n /**\r\n * Lifetime in milliseconds — the only form a token issuer may use. Throws\r\n * naming the key when the configured value is not a positive `ms` duration.\r\n */\r\n expiresInMs: (): number =>\r\n parseDuration(\"refreshToken.expiresIn\", authConfig.refreshToken.expiresIn()),\r\n /** Rotate-on-use (legacy: `auth.jwt.refresh.rotation`). */\r\n rotation: (): boolean => resolve(\"refreshToken.rotation\", \"jwt.refresh.rotation\", true),\r\n /** Max active tokens per user (legacy: `auth.jwt.refresh.maxPerUser`). */\r\n maxPerUser: (): number => resolve(\"refreshToken.maxPerUser\", \"jwt.refresh.maxPerUser\", 5),\r\n /** Logout-without-token behavior (legacy: `auth.jwt.refresh.logoutWithoutToken`). */\r\n logoutWithoutToken: (): LogoutWithoutTokenBehavior =>\r\n resolve(\"refreshToken.logoutWithoutToken\", \"jwt.refresh.logoutWithoutToken\", \"revoke-all\"),\r\n },\r\n};\r\n"],"mappings":";;;;;AA0BA,MAAM,mCAAmB,IAAI,IAAY;AAEzC,MAAM,6BAAuD;;;;;;;;;;AAW7D,MAAM,UAAU;;;;;;;;;;;;;;;;;;AAmBhB,SAAS,cAAc,KAAa,KAAsB;CACxD,IAAI;CAEJ,IAAI;EACF,SAAS,QAAQ,GAAG;CACtB,QAAQ;EAEN,SAAS;CACX;CAEA,IAAI,OAAO,WAAW,YAAY,CAAC,OAAO,SAAS,MAAM,KAAK,UAAU,GACtE,MAAM,IAAI,MACR,QAAQ,IAAI,IAAI,KAAK,UAAU,GAAG,EAAE,mGAEtC;CAGF,OAAO;AACT;;AAGA,MAAM,kCAAkC;;AAGxC,MAAM,oCAAoC;;AAG1C,MAAM,uCAAuC;;AAG7C,MAAM,yBAAyB;;AAG/B,MAAM,kCAAkC;;;;;;;;;AAUxC,SAAS,QAAW,QAAgB,WAAmB,UAAiB;CACtE,MAAM,UAAU,OAAO,IAAI,QAAQ,QAAQ;CAE3C,IAAI,YAAY,UAAa,YAAY,MACvC,OAAO;CAGT,MAAM,aAAa,OAAO,IAAI,QAAQ,WAAW;CAEjD,IAAI,eAAe,UAAa,eAAe,MAAM;EACnD,IAAI,CAAC,iBAAiB,IAAI,SAAS,GAAG;GACpC,iBAAiB,IAAI,SAAS;GAC9B,IAAI,KACF,QACA,sBACA,QAAQ,UAAU,4BAA4B,QAChD;EACF;EAEA,OAAO;CACT;CAEA,OAAO;AACT;;;;;;AAOA,MAAa,aAAa;CACxB,iBAAiB,OAAO,SAAiC;EAMvD,OALwB,OAAO,IAC7B,wBACA,oBAGmB,CAAC,CAAC,IAAI;CAC7B;CACA,aAAa;;EAEX,cAAsB;GACpB,MAAM,SA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A2B,0BAA0B,CAAC;;EAExF,0BACE,QAAQ,mCAAmC,kCAAkC,YAAY;CAC7F;AACF"}
|
|
1
|
+
{"version":3,"file":"auth-config.mjs","names":[],"sources":["../../../../../../../auth/src/services/auth-config.ts"],"sourcesContent":["import { config } from \"@warlock.js/core\";\nimport type { CookieDomainResolver } from \"../contracts/types\";\nimport { log } from \"@warlock.js/logger\";\nimport { type Algorithm } from \"fast-jwt\";\nimport ms from \"ms\";\nimport type {\n AuthNotification,\n CanAuthenticate,\n LogoutWithoutTokenBehavior,\n OneTimeTokenUrlBuilder,\n PasswordSetter,\n} from \"../contracts/types\";\nimport type {\n AppleProviderConfig,\n AuthProvider,\n DiscordProviderConfig,\n FacebookProviderConfig,\n GitHubProviderConfig,\n GoogleProviderConfig,\n LinkedInProviderConfig,\n OtpSender,\n PasskeysConfig,\n ProviderUserCreator,\n XProviderConfig,\n} from \"../contracts/providers\";\nimport type { Auth } from \"../models/auth.model\";\n\nconst warnedLegacyKeys = new Set<string>();\n\nconst permitAuthentication: CanAuthenticate = (): boolean => true;\n\n/**\n * `ms` accepts anything at runtime and answers `undefined` for a string it\n * cannot parse (`\"30dayz\"`), a *formatted string* for a number (`2592000` ⇒\n * `\"43m\"`), and throws for `\"\"`. Its published types claim the far narrower\n * `(value: ms.StringValue) => number`, which is exactly what let an\n * `as ms.StringValue` cast smuggle arbitrary config text past the compiler and\n * hand `undefined` to the JWT signer. Declare the honest runtime signature once,\n * here, so every caller is forced to deal with the `undefined`.\n */\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\n\n/**\n * Turn a configured lifetime into a positive number of milliseconds, or throw\n * naming the key.\n *\n * A token lifetime is a security boundary, so an unusable value is a hard error\n * rather than a silent fallback: substituting a default would trade one\n * unintended lifetime for another, just as quietly — and quiet is the whole\n * problem. Every non-positive, non-finite or non-numeric parse is rejected:\n *\n * - `\"30dayz\"` / `\"thirty days\"` ⇒ `undefined` ⇒ a JWT signed with **no `exp`\n * claim** and an `Invalid Date` written to the token row.\n * - `\"0d\"` ⇒ parses cleanly to `0`, which `fast-jwt` treats as falsy and also\n * emits with **no `exp` claim** — it survives any guard that only rejects\n * `undefined`. `\"-1h\"` signs an already-expired token.\n * - `2592000` (a bare number) ⇒ `ms` *formats* it as `\"43m\"`, a string, which\n * then turns `Date.now() + expiresIn` into an `Invalid Date`.\n */\nfunction parseDuration(key: string, raw: unknown): number {\n let parsed: number | string | undefined;\n\n try {\n parsed = parseMs(raw);\n } catch {\n // ms throws (rather than returning undefined) for \"\" and non-strings\n parsed = undefined;\n }\n\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(\n `auth.${key}: ${JSON.stringify(raw)} is not a valid ms duration — ` +\n `use a positive duration string such as \"1h\", \"7d\", or NO_EXPIRATION.`,\n );\n }\n\n return parsed;\n}\n\n/** Email-verification token lifetime used when nothing is configured. */\nconst DEFAULT_VERIFICATION_EXPIRES_IN = \"24h\";\n\n/** Password-reset token lifetime used when nothing is configured. */\nconst DEFAULT_PASSWORD_RESET_EXPIRES_IN = \"60m\";\n\n/** Passkey challenge lifetime used when nothing is configured. */\nconst DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN = \"5m\";\n\n/** OTP lifetime used when nothing is configured. */\nconst DEFAULT_OTP_EXPIRES_IN = \"5m\";\n\n/** Access-token lifetime used when nothing is configured. */\nconst DEFAULT_ACCESS_TOKEN_EXPIRES_IN = \"1h\";\n\n/**\n * Resolve an auth setting, preferring the new `auth.accessToken.*` /\n * `auth.refreshToken.*` key and falling back to the deprecated `auth.jwt.*`\n * shape — warning once per legacy key. Returns `fallback` when neither is set.\n *\n * This is the backward-compatible shim that lets existing `auth.jwt.*` configs\n * keep working after the config split.\n */\nfunction resolve<T>(newKey: string, legacyKey: string, fallback?: T): T {\n const fromNew = config.key(`auth.${newKey}`);\n\n if (fromNew !== undefined && fromNew !== null) {\n return fromNew as T;\n }\n\n const fromLegacy = config.key(`auth.${legacyKey}`);\n\n if (fromLegacy !== undefined && fromLegacy !== null) {\n if (!warnedLegacyKeys.has(legacyKey)) {\n warnedLegacyKeys.add(legacyKey);\n log.warn(\n \"auth\",\n \"config-deprecation\",\n `auth.${legacyKey} is deprecated — use auth.${newKey}`,\n );\n }\n\n return fromLegacy as T;\n }\n\n return fallback as T;\n}\n\n/**\n * Typed, backward-compatible access to auth configuration. The service and the\n * jwt signer read configuration exclusively through here, so the new split\n * config and the legacy `auth.jwt.*` shape both resolve the same way.\n */\nexport const authConfig = {\n canAuthenticate: async (user: Auth): Promise<boolean> => {\n const canAuthenticate = config.key<CanAuthenticate>(\n \"auth.canAuthenticate\",\n permitAuthentication,\n );\n\n return canAuthenticate(user);\n },\n accessToken: {\n /** Signing secret (legacy: `auth.jwt.secret`). Throws if neither is set. */\n secret: (): string => {\n const secret = resolve<string | undefined>(\"accessToken.secret\", \"jwt.secret\");\n\n if (!secret) {\n throw new Error(\"auth: no JWT secret configured — set `auth.accessToken.secret`.\");\n }\n\n return secret;\n },\n /** Signing algorithm (legacy: `auth.jwt.algorithm`). */\n algorithm: (): Algorithm => resolve(\"accessToken.algorithm\", \"jwt.algorithm\", \"HS256\"),\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.expiresIn`). */\n expiresIn: (): string | undefined => resolve(\"accessToken.expiresIn\", \"jwt.expiresIn\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Defaults\n * to 1 hour when unset; throws naming the key when the configured value is\n * not a positive `ms` duration. See {@link parseDuration}.\n */\n expiresInMs: (): number =>\n parseDuration(\n \"accessToken.expiresIn\",\n authConfig.accessToken.expiresIn() ?? DEFAULT_ACCESS_TOKEN_EXPIRES_IN,\n ),\n },\n pageAuth: {\n /**\n * Login path a guarded PAGE route redirects a logged-out browser to.\n *\n * Unset (the default) ⇒ page-route auth failures keep the JSON 401 API\n * contract, so existing apps see NO behavior change. Set it (e.g. \"/login\")\n * to opt a browser-facing app into login-redirect UX: a logged-out human\n * navigating to a guarded page lands on the login screen instead of reading\n * a raw JSON error blob. Finding b9ab9804.\n */\n loginPath: (): string | undefined => config.key(\"auth.pageAuth.loginPath\"),\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. Defaults to\n * `\"returnUrl\"`.\n */\n returnUrlParam: (): string => config.key(\"auth.pageAuth.returnUrlParam\", \"returnUrl\"),\n },\n cookie: {\n /** Cookie name `setAuthCookie`/`clearAuthCookie` use. @default \"access_token\" */\n name: (): string => config.key(\"auth.cookie.name\", \"access_token\"),\n /** Refresh-token cookie name the session cookie helpers use. @default \"refresh_token\" */\n refreshName: (): string => config.key(\"auth.cookie.refreshName\", \"refresh_token\"),\n /** Cookie `Path` attribute `setAuthCookie`/`clearAuthCookie` use. @default \"/\" */\n path: (): string => config.key(\"auth.cookie.path\", \"/\"),\n /** Select the request-scoped cookie Domain; undefined keeps it host-only. */\n cookieDomain: (): CookieDomainResolver | undefined => config.key(\"auth.cookie.cookieDomain\"),\n },\n csrf: {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * beyond the request's own origin. @default []\n */\n allowedOrigins: (): string[] => config.key(\"auth.csrf.allowedOrigins\", []),\n },\n verification: {\n /** Lifetime in ms of an email-verification token; throws naming the key when unusable. @default \"24h\" */\n expiresInMs: (): number =>\n parseDuration(\n \"verification.expiresIn\",\n config.key(\"auth.verification.expiresIn\", DEFAULT_VERIFICATION_EXPIRES_IN),\n ),\n /** User attribute stamped with the verification date. @default \"emailVerifiedAt\" */\n field: (): string => config.key(\"auth.verification.field\", \"emailVerifiedAt\"),\n /** App notification replacing the default verification email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.verification.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.verification.url\"),\n },\n passwordReset: {\n /** Lifetime in ms of a password-reset token; throws naming the key when unusable. @default \"60m\" */\n expiresInMs: (): number =>\n parseDuration(\n \"passwordReset.expiresIn\",\n config.key(\"auth.passwordReset.expiresIn\", DEFAULT_PASSWORD_RESET_EXPIRES_IN),\n ),\n /** User attribute `requestPasswordReset` looks the account up by. @default \"email\" */\n identifierField: (): string => config.key(\"auth.passwordReset.identifierField\", \"email\"),\n /** App notification replacing the default reset email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.passwordReset.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.passwordReset.url\"),\n /** App-owned password writer replacing the default. */\n setPassword: (): PasswordSetter | undefined => config.key(\"auth.passwordReset.setPassword\"),\n },\n providers: {\n /** `auth.providers.google`, when configured. */\n google: (): GoogleProviderConfig | undefined => config.key(\"auth.providers.google\"),\n /** `auth.providers.github`, when configured. */\n github: (): GitHubProviderConfig | undefined => config.key(\"auth.providers.github\"),\n /** `auth.providers.discord`, when configured. */\n discord: (): DiscordProviderConfig | undefined => config.key(\"auth.providers.discord\"),\n /** `auth.providers.linkedin`, when configured. */\n linkedin: (): LinkedInProviderConfig | undefined => config.key(\"auth.providers.linkedin\"),\n /** `auth.providers.apple`, when configured. */\n apple: (): AppleProviderConfig | undefined => config.key(\"auth.providers.apple\"),\n /** `auth.providers.facebook`, when configured. */\n facebook: (): FacebookProviderConfig | undefined => config.key(\"auth.providers.facebook\"),\n /** `auth.providers.x`, when configured. */\n x: (): XProviderConfig | undefined => config.key(\"auth.providers.x\"),\n /** An app-registered provider under `auth.providers.custom.<name>`. */\n custom: (name: string): AuthProvider | undefined => {\n const providers = config.key<Record<string, AuthProvider>>(\"auth.providers.custom\", {});\n\n // Own keys only: `name` arrives from a URL, and \"constructor\" must not resolve to Object.\n return Object.hasOwn(providers, name) ? providers[name] : undefined;\n },\n /** User attribute a verified provider email is matched against. @default \"email\" */\n emailField: (): string => config.key(\"auth.providers.emailField\", \"email\"),\n /** App-owned user creation for a first provider login. */\n createUser: (): ProviderUserCreator | undefined => config.key(\"auth.providers.createUser\"),\n },\n passkeys: {\n /** `auth.passkeys`; throws naming the keys when `rpID`, `rpName` or `origin` is missing. */\n settings: (): PasskeysConfig => {\n const settings = config.key<PasskeysConfig | undefined>(\"auth.passkeys\");\n\n if (!settings?.rpID || !settings.rpName || !settings.origin) {\n throw new Error(\n \"@warlock.js/auth: passkeys need `auth.passkeys.rpID`, `auth.passkeys.rpName` and `auth.passkeys.origin`.\",\n );\n }\n\n return settings;\n },\n /** Allowed ceremony origins, as a list. */\n origins: (): string[] => {\n const { origin } = authConfig.passkeys.settings();\n\n return Array.isArray(origin) ? origin : [origin];\n },\n /** Challenge lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n challengeExpiresInMs: (): number =>\n parseDuration(\n \"passkeys.challengeExpiresIn\",\n config.key(\"auth.passkeys.challengeExpiresIn\", DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN),\n ),\n },\n otp: {\n /** Notifications channel the code is sent through. @default \"sms\" */\n channel: (): string => config.key(\"auth.otp.channel\", \"sms\"),\n /** User attribute holding the phone number. @default \"phone\" */\n phoneField: (): string => config.key(\"auth.otp.phoneField\", \"phone\"),\n /** Code lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n expiresInMs: (): number =>\n parseDuration(\"otp.expiresIn\", config.key(\"auth.otp.expiresIn\", DEFAULT_OTP_EXPIRES_IN)),\n /** Verify attempts before the code is invalidated. @default 5 */\n maxAttempts: (): number => config.key(\"auth.otp.maxAttempts\", 5),\n /** The message text for a code. */\n message: (code: string): string => {\n const build = config.key<((code: string) => string) | undefined>(\"auth.otp.message\");\n\n return build ? build(code) : `Your verification code is ${code}`;\n },\n /** App-owned delivery replacing the notifications channel send. */\n send: (): OtpSender | undefined => config.key(\"auth.otp.send\"),\n },\n refreshToken: {\n /** Separate refresh secret (legacy: `auth.jwt.refresh.secret`); empty ⇒ fall back to the access secret. */\n secret: (): string | undefined => resolve(\"refreshToken.secret\", \"jwt.refresh.secret\"),\n /** Whether refresh tokens are enabled (legacy: `auth.jwt.refresh.enabled`). */\n enabled: (): boolean => resolve(\"refreshToken.enabled\", \"jwt.refresh.enabled\", true),\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.refresh.expiresIn`). */\n expiresIn: (): string => resolve(\"refreshToken.expiresIn\", \"jwt.refresh.expiresIn\", \"7d\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Throws\n * naming the key when the configured value is not a positive `ms` duration.\n */\n expiresInMs: (): number =>\n parseDuration(\"refreshToken.expiresIn\", authConfig.refreshToken.expiresIn()),\n /** Rotate-on-use (legacy: `auth.jwt.refresh.rotation`). */\n rotation: (): boolean => resolve(\"refreshToken.rotation\", \"jwt.refresh.rotation\", true),\n /** Max active tokens per user (legacy: `auth.jwt.refresh.maxPerUser`). */\n maxPerUser: (): number => resolve(\"refreshToken.maxPerUser\", \"jwt.refresh.maxPerUser\", 5),\n /** Logout-without-token behavior (legacy: `auth.jwt.refresh.logoutWithoutToken`). */\n logoutWithoutToken: (): LogoutWithoutTokenBehavior =>\n resolve(\"refreshToken.logoutWithoutToken\", \"jwt.refresh.logoutWithoutToken\", \"revoke-all\"),\n },\n};\n"],"mappings":";;;;;AA2BA,MAAM,mCAAmB,IAAI,IAAY;AAEzC,MAAM,6BAAuD;;;;;;;;;;AAW7D,MAAM,UAAU;;;;;;;;;;;;;;;;;;AAmBhB,SAAS,cAAc,KAAa,KAAsB;CACxD,IAAI;CAEJ,IAAI;EACF,SAAS,QAAQ,GAAG;CACtB,QAAQ;EAEN,SAAS;CACX;CAEA,IAAI,OAAO,WAAW,YAAY,CAAC,OAAO,SAAS,MAAM,KAAK,UAAU,GACtE,MAAM,IAAI,MACR,QAAQ,IAAI,IAAI,KAAK,UAAU,GAAG,EAAE,mGAEtC;CAGF,OAAO;AACT;;AAGA,MAAM,kCAAkC;;AAGxC,MAAM,oCAAoC;;AAG1C,MAAM,uCAAuC;;AAG7C,MAAM,yBAAyB;;AAG/B,MAAM,kCAAkC;;;;;;;;;AAUxC,SAAS,QAAW,QAAgB,WAAmB,UAAiB;CACtE,MAAM,UAA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BAAiB,OAAO,IAAI,sBAAsB,sBAAsB,CAAC;;EAEzF,mBAA2B,OAAO,IAAI,wBAAwB,CAAC;;EAE/D,UAAU,SAAyB;GACjC,MAAM,QAAQ,OAAO,IAA4C,kBAAkB;GAEnF,OAAO,QAAQ,MAAM,IAAI,IAAI,6BAA6B;EAC5D;;EAEA,YAAmC,OAAO,IAAI,eAAe;CAC/D;CACA,cAAc;;EAEZ,cAAkC,QAAQ,uBAAuB,oBAAoB;;EAErF,eAAwB,QAAQ,wBAAwB,uBAAuB,IAAI;;EAEnF,iBAAyB,QAAQ,0BAA0B,yBAAyB,IAAI;;;;;EAKxF,mBACE,cAAc,0BAA0B,WAAW,aAAa,UAAU,CAAC;;EAE7E,gBAAyB,QAAQ,yBAAyB,wBAAwB,IAAI;;EAEtF,kBAA0B,QAAQ,2BAA2B,0BAA0B,CAAC;;EAExF,0BACE,QAAQ,mCAAmC,kCAAkC,YAAY;CAC7F;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-events.mjs","names":[],"sources":["../../../../../../../auth/src/services/auth-events.ts"],"sourcesContent":["import events, { type EventSubscription } from \"@mongez/events\";\
|
|
1
|
+
{"version":3,"file":"auth-events.mjs","names":[],"sources":["../../../../../../../auth/src/services/auth-events.ts"],"sourcesContent":["import events, { type EventSubscription } from \"@mongez/events\";\nimport { log } from \"@warlock.js/logger\";\nimport type { DeviceInfo, TokenPair } from \"../contracts/types\";\nimport type { Auth } from \"../models/auth.model\";\nimport type { RefreshToken } from \"../models/refresh-token\";\n\n/**\n * Auth event payload types\n */\nexport type AuthEventPayloads = {\n // Login events\n \"login.success\": [user: Auth, tokenPair: TokenPair, deviceInfo?: DeviceInfo];\n \"login.failed\": [credentials: { email?: string; username?: string }, reason: string];\n \"login.attempt\": [credentials: { email?: string; username?: string }];\n\n // Logout events\n logout: [user: Auth];\n \"logout.all\": [user: Auth];\n \"logout.failsafe\": [user: Auth];\n\n // Token events\n \"token.created\": [user: Auth, tokenPair: TokenPair];\n \"token.refreshed\": [user: Auth, newTokenPair: TokenPair, oldRefreshToken: RefreshToken];\n \"token.revoked\": [user: Auth, token: RefreshToken];\n \"token.expired\": [token: RefreshToken];\n \"token.familyRevoked\": [familyId: string, tokens: RefreshToken[]];\n\n // Password events\n \"password.changed\": [user: Auth];\n \"password.resetRequested\": [user: Auth, resetToken: string];\n \"password.reset\": [user: Auth];\n\n // Session events\n \"session.created\": [user: Auth, refreshToken: RefreshToken, deviceInfo?: DeviceInfo];\n \"session.destroyed\": [user: Auth, refreshToken: RefreshToken];\n\n // Cleanup events\n \"cleanup.completed\": [expiredCount: number];\n};\n\n/**\n * Auth event names\n */\nexport type AuthEventName = keyof AuthEventPayloads;\n\n/**\n * Callback type for a specific event\n */\nexport type AuthEventCallback<T extends AuthEventName> = (\n ...args: AuthEventPayloads[T]\n) => void | Promise<void>;\n\n/**\n * Event namespace prefix for auth events\n */\nconst AUTH_EVENT_PREFIX = \"auth.\";\n\n/**\n * Type-safe auth events manager\n *\n * @example\n * ```typescript\n * // Subscribe to events with full autocomplete\n * authEvents.on(\"login.success\", (user, tokenPair, deviceInfo) => {\n * console.log(`User ${user.id} logged in`);\n * });\n *\n * authEvents.on(\"token.refreshed\", (user, newPair, oldToken) => {\n * console.log(`Token refreshed for user ${user.id}`);\n * });\n *\n * // Trigger events\n * authEvents.emit(\"login.success\", user, tokenPair, deviceInfo);\n * ```\n */\nexport const authEvents = {\n /**\n * Subscribe to an auth event\n */\n on<T extends AuthEventName>(event: T, callback: AuthEventCallback<T>): EventSubscription {\n return events.subscribe(AUTH_EVENT_PREFIX + event, callback as Function);\n },\n\n /**\n * Subscribe to an auth event (alias for `on`)\n */\n subscribe<T extends AuthEventName>(event: T, callback: AuthEventCallback<T>): EventSubscription {\n return this.on(event, callback);\n },\n\n /**\n * Emit an auth event\n */\n emit<T extends AuthEventName>(event: T, ...args: AuthEventPayloads[T]): void {\n try {\n events.trigger(AUTH_EVENT_PREFIX + event, ...args);\n } catch (error) {\n // Auth events are fire-and-forget notifications: a throwing listener must\n // never break the flow that emitted it (e.g. turn a completed login into a\n // 500). Log and swallow. NOTE: this guards synchronous listener throws;\n // async listener rejections and \"later listeners still run\" need a fix in\n // @mongez/events (tracked separately).\n log.error(\"auth\", \"event\", error);\n }\n },\n\n /**\n * Emit an auth event (alias for `emit`)\n */\n trigger<T extends AuthEventName>(event: T, ...args: AuthEventPayloads[T]): void {\n this.emit(event, ...args);\n },\n\n /**\n * Unsubscribe from all auth events\n */\n unsubscribeAll(): void {\n events.unsubscribeNamespace(AUTH_EVENT_PREFIX.slice(0, -1));\n },\n\n /**\n * Unsubscribe from a specific auth event\n */\n off(event?: AuthEventName): void {\n if (event) {\n events.unsubscribe(AUTH_EVENT_PREFIX + event);\n } else {\n this.unsubscribeAll();\n }\n },\n};\n"],"mappings":";;;;;;;AAuDA,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;AAoB1B,MAAa,aAAa;;;;CAIxB,GAA4B,OAAU,UAAmD;EACvF,OAAO,OAAO,UAAU,oBAAoB,OAAO,QAAoB;CACzE;;;;CAKA,UAAmC,OAAU,UAAmD;EAC9F,OAAO,KAAK,GAAG,OAAO,QAAQ;CAChC;;;;CAKA,KAA8B,OAAU,GAAG,MAAkC;EAC3E,IAAI;GACF,OAAO,QAAQ,oBAAoB,OAAO,GAAG,IAAI;EACnD,SAAS,OAAO;GAMd,IAAI,MAAM,QAAQ,SAAS,KAAK;EAClC;CACF;;;;CAKA,QAAiC,OAAU,GAAG,MAAkC;EAC9E,KAAK,KAAK,OAAO,GAAG,IAAI;CAC1B;;;;CAKA,iBAAuB;EACrB,OAAO,qBAAqB,kBAAkB,MAAM,GAAG,EAAE,CAAC;CAC5D;;;;CAKA,IAAI,OAA6B;EAC/B,IAAI,OACF,OAAO,YAAY,oBAAoB,KAAK;OAE5C,KAAK,eAAe;CAExB;AACF"}
|
|
@@ -6,6 +6,10 @@ import { Request, Response } from "@warlock.js/core";
|
|
|
6
6
|
import { ChildModel } from "@warlock.js/cascade";
|
|
7
7
|
|
|
8
8
|
//#region ../auth/src/services/auth.service.d.ts
|
|
9
|
+
/** Thrown when a request-scoped cookie Domain cannot be resolved safely. */
|
|
10
|
+
declare class CookieDomainRequestRequiredError extends Error {
|
|
11
|
+
constructor(method: string);
|
|
12
|
+
}
|
|
9
13
|
declare class AuthService {
|
|
10
14
|
/**
|
|
11
15
|
* Resolve the active access-token model — the package default, or a subclass
|
|
@@ -195,6 +199,7 @@ declare class AuthService {
|
|
|
195
199
|
* string (a session cookie) or an unparseable `expiresAt`.
|
|
196
200
|
*/
|
|
197
201
|
private cookieMaxAgeFromToken;
|
|
202
|
+
private cookieDomainFor;
|
|
198
203
|
/**
|
|
199
204
|
* Write the auth cookie on `response` — the write side of the `cookie:<name>`
|
|
200
205
|
* token source `authMiddleware([], "cookie:<name>")` already reads. An explicit
|
|
@@ -227,7 +232,7 @@ declare class AuthService {
|
|
|
227
232
|
* await authService.logout(user, accessToken, refreshToken);
|
|
228
233
|
* authService.clearAuthCookie(response);
|
|
229
234
|
*/
|
|
230
|
-
clearAuthCookie(response: { [K in "cookie" | "clearCookie"]: (...args: Parameters<Response[K]>) => unknown }, options?: ClearAuthCookieOptions): void;
|
|
235
|
+
clearAuthCookie(response: { [K in "cookie" | "clearCookie"]: (...args: Parameters<Response[K]>) => unknown }, options?: ClearAuthCookieOptions, request?: Request): void;
|
|
231
236
|
/**
|
|
232
237
|
* Write the access and refresh cookies of a browser session. Both are
|
|
233
238
|
* `HttpOnly`, `SameSite=Lax`, `Path=/` (the refresh cookie must reach every
|
|
@@ -242,14 +247,14 @@ declare class AuthService {
|
|
|
242
247
|
setSessionCookies(response: { [K in "cookie" | "clearCookie"]: (...args: Parameters<Response[K]>) => unknown }, tokens: {
|
|
243
248
|
accessToken: AccessTokenOutput;
|
|
244
249
|
refreshToken: AccessTokenOutput;
|
|
245
|
-
}): void;
|
|
250
|
+
}, request?: Request): void;
|
|
246
251
|
/**
|
|
247
252
|
* Clear both session cookies {@link setSessionCookies} wrote, on `Path=/`.
|
|
248
253
|
* Pair it with {@link logout} after the token rows are revoked.
|
|
249
254
|
*/
|
|
250
|
-
clearSessionCookies(response: { [K in "cookie" | "clearCookie"]: (...args: Parameters<Response[K]>) => unknown }): void;
|
|
255
|
+
clearSessionCookies(response: { [K in "cookie" | "clearCookie"]: (...args: Parameters<Response[K]>) => unknown }, request?: Request): void;
|
|
251
256
|
}
|
|
252
257
|
declare const authService: AuthService;
|
|
253
258
|
//#endregion
|
|
254
|
-
export { authService };
|
|
259
|
+
export { CookieDomainRequestRequiredError, authService };
|
|
255
260
|
//# sourceMappingURL=auth.service.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.service.d.mts","names":[],"sources":["../../../../../../../auth/src/services/auth.service.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"auth.service.d.mts","names":[],"sources":["../../../../../../../auth/src/services/auth.service.ts"],"mappings":";;;;;;;;;cAoCa,gCAAA,SAAyC,KAAK;cACtC,MAAA;AAAA;AAAA,cAQf,WAAA;EATwC;;;;;;EAAA,YAgBhC,gBAAA;EAfqB;AAMlC;;EANkC,YAsBrB,iBAAA;EAcyB;;;EAAA,YAPzB,iBAAA;EAqDJ;;;EA9CD,uBAAA,CAAwB,IAAA,EAAM,IAAA,GAAO,MAAA;EAiIpC;EAxHK,eAAA,CAAgB,IAAA,EAAM,IAAA,GAAO,OAAA;EAAA,QAI5B,qBAAA;EAAA,QAMA,gBAAA;EAmLqB;;;;;EAzJtB,mBAAA,CACX,IAAA,EAAM,IAAA,EACN,OAAA,GAAU,MAAA,oBACT,OAAA,CAAQ,iBAAA;EAAA,QAMG,iBAAA;EAiQgC;;;;;;EAAA,QAvNhC,qBAAA;EA6aL;;;;EA7YI,kBAAA,CACX,IAAA,EAAM,IAAA,EACN,UAAA,GAAa,UAAA,GACZ,OAAA,CAAQ,YAAA;EAAA,QAcG,cAAA;EA+ZL;;;EA1WI,eA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A;IAAmB,YAAA,EAAc,iBAAA;EAAA,GACxD,OAAA,GAAU,OAAA;EAhS0B;;;;EA0T/B,mBAAA,CACL,QAAA,yCAAiD,IAAA,EAAM,UAAA,CAAW,QAAA,CAAS,CAAA,kBAC3E,OAAA,GAAU,OAAA;AAAA;AAAA,cAcD,WAAA,EAAW,WAAoB"}
|
|
@@ -16,6 +16,13 @@ import { ForbiddenError, config, hashPassword, verifyPassword } from "@warlock.j
|
|
|
16
16
|
import { randomUUID } from "node:crypto";
|
|
17
17
|
|
|
18
18
|
//#region ../auth/src/services/auth.service.ts
|
|
19
|
+
/** Thrown when a request-scoped cookie Domain cannot be resolved safely. */
|
|
20
|
+
var CookieDomainRequestRequiredError = class extends Error {
|
|
21
|
+
constructor(method) {
|
|
22
|
+
super(`${method} requires the request when auth.cookie.cookieDomain is configured because the cookie Domain must be resolved for that request.`);
|
|
23
|
+
this.name = "CookieDomainRequestRequiredError";
|
|
24
|
+
}
|
|
25
|
+
};
|
|
19
26
|
var AuthService = class {
|
|
20
27
|
/**
|
|
21
28
|
* Resolve the active access-token model — the package default, or a subclass
|
|
@@ -79,11 +86,11 @@ var AuthService = class {
|
|
|
79
86
|
await this.assertCanAuthenticate(user);
|
|
80
87
|
return this.issueAccessToken(user, payload);
|
|
81
88
|
}
|
|
82
|
-
async issueRefreshToken(user, deviceInfo) {
|
|
89
|
+
async issueRefreshToken(user, deviceInfo, ensuredFamily) {
|
|
83
90
|
if (!authConfig.refreshToken.enabled()) return;
|
|
84
91
|
const expiresIn = authConfig.refreshToken.expiresInMs();
|
|
85
92
|
const familyId = deviceInfo?.familyId || Random.string(32);
|
|
86
|
-
if ((await AuthTokenFamily.ensure(user, familyId)).isRevoked) throw new Error("Cannot issue tokens for a revoked token family");
|
|
93
|
+
if ((ensuredFamily ?? await AuthTokenFamily.ensure(user, familyId)).isRevoked) throw new Error("Cannot issue tokens for a revoked token family");
|
|
87
94
|
const payload = {
|
|
88
95
|
userId: user.id,
|
|
89
96
|
userType: user.userType,
|
|
@@ -108,7 +115,7 @@ var AuthService = class {
|
|
|
108
115
|
async issueInSuppliedFamily(user, familyId, issue) {
|
|
109
116
|
if ((await AuthTokenFamily.ensure(user, familyId)).isRevoked) throw new Error("Cannot issue tokens for a revoked token family");
|
|
110
117
|
try {
|
|
111
|
-
return await runTokenFamilyOperation(familyId,
|
|
118
|
+
return await runTokenFamilyOperation(familyId, issue);
|
|
112
119
|
} catch (error) {
|
|
113
120
|
if (error instanceof TokenFamilyUnavailableError) throw new Error("Cannot issue tokens for a revoked token family");
|
|
114
121
|
throw error;
|
|
@@ -121,20 +128,21 @@ var AuthService = class {
|
|
|
121
128
|
async createRefreshToken(user, deviceInfo) {
|
|
122
129
|
if (!authConfig.refreshToken.enabled()) return;
|
|
123
130
|
await this.assertCanAuthenticate(user);
|
|
124
|
-
if (deviceInfo?.familyId) return this.issueInSuppliedFamily(user, deviceInfo.familyId, () => this.issueRefreshToken(user, deviceInfo));
|
|
131
|
+
if (deviceInfo?.familyId) return this.issueInSuppliedFamily(user, deviceInfo.familyId, (family) => this.issueRefreshToken(user, deviceInfo, family));
|
|
125
132
|
return this.issueRefreshToken(user, deviceInfo);
|
|
126
133
|
}
|
|
127
|
-
async issueTokenPair(user, deviceInfo) {
|
|
134
|
+
async issueTokenPair(user, deviceInfo, ensuredFamily) {
|
|
128
135
|
const refreshEnabled = authConfig.refreshToken.enabled();
|
|
129
136
|
const familyId = deviceInfo?.familyId || Random.string(32);
|
|
130
|
-
|
|
131
|
-
|
|
137
|
+
const family = refreshEnabled ? ensuredFamily ?? await AuthTokenFamily.ensure(user, familyId) : void 0;
|
|
138
|
+
if (family) {
|
|
139
|
+
if (family.isRevoked) throw new Error("Cannot issue tokens for a revoked token family");
|
|
132
140
|
}
|
|
133
141
|
const accessToken = await this.issueAccessToken(user, deviceInfo?.payload, refreshEnabled ? familyId : void 0);
|
|
134
142
|
const refreshToken = await this.issueRefreshToken(user, refreshEnabled ? {
|
|
135
143
|
...deviceInfo,
|
|
136
144
|
familyId
|
|
137
|
-
} : deviceInfo);
|
|
145
|
+
} : deviceInfo, family);
|
|
138
146
|
const tokenPair = {
|
|
139
147
|
accessToken,
|
|
140
148
|
refreshToken: refreshToken ? {
|
|
@@ -151,7 +159,7 @@ var AuthService = class {
|
|
|
151
159
|
*/
|
|
152
160
|
async createTokenPair(user, deviceInfo) {
|
|
153
161
|
await this.assertCanAuthenticate(user);
|
|
154
|
-
if (authConfig.refreshToken.enabled() && deviceInfo?.familyId) return this.issueInSuppliedFamily(user, deviceInfo.familyId, () => this.issueTokenPair(user, deviceInfo));
|
|
162
|
+
if (authConfig.refreshToken.enabled() && deviceInfo?.familyId) return this.issueInSuppliedFamily(user, deviceInfo.familyId, (family) => this.issueTokenPair(user, deviceInfo, family));
|
|
155
163
|
return this.issueTokenPair(user, deviceInfo);
|
|
156
164
|
}
|
|
157
165
|
/**
|
|
@@ -386,8 +394,8 @@ var AuthService = class {
|
|
|
386
394
|
if (result.tokens.refreshToken) this.setSessionCookies(response, {
|
|
387
395
|
accessToken: result.tokens.accessToken,
|
|
388
396
|
refreshToken: result.tokens.refreshToken
|
|
389
|
-
});
|
|
390
|
-
else this.setAuthCookie(response, result.tokens.accessToken);
|
|
397
|
+
}, request);
|
|
398
|
+
else this.setAuthCookie(response, result.tokens.accessToken, { domain: this.cookieDomainFor("loginWithSessionCookies", request) });
|
|
391
399
|
return result;
|
|
392
400
|
}
|
|
393
401
|
/** The one token-issuing tail every login method shares. */
|
|
@@ -568,6 +576,12 @@ var AuthService = class {
|
|
|
568
576
|
if (Number.isNaN(expiresAt)) return void 0;
|
|
569
577
|
return Math.max(0, Math.round((expiresAt - Date.now()) / 1e3));
|
|
570
578
|
}
|
|
579
|
+
cookieDomainFor(method, request) {
|
|
580
|
+
const resolver = authConfig.cookie.cookieDomain();
|
|
581
|
+
if (!resolver) return;
|
|
582
|
+
if (!request) throw new CookieDomainRequestRequiredError(method);
|
|
583
|
+
return resolver(request);
|
|
584
|
+
}
|
|
571
585
|
/**
|
|
572
586
|
* Write the auth cookie on `response` — the write side of the `cookie:<name>`
|
|
573
587
|
* token source `authMiddleware([], "cookie:<name>")` already reads. An explicit
|
|
@@ -597,6 +611,7 @@ var AuthService = class {
|
|
|
597
611
|
response.cookie(name, tokenValue, {
|
|
598
612
|
raw: true,
|
|
599
613
|
path,
|
|
614
|
+
...options.domain !== void 0 ? { domain: options.domain } : {},
|
|
600
615
|
...maxAge !== void 0 ? { maxAge } : {}
|
|
601
616
|
});
|
|
602
617
|
}
|
|
@@ -610,9 +625,14 @@ var AuthService = class {
|
|
|
610
625
|
* await authService.logout(user, accessToken, refreshToken);
|
|
611
626
|
* authService.clearAuthCookie(response);
|
|
612
627
|
*/
|
|
613
|
-
clearAuthCookie(response, options = {}) {
|
|
628
|
+
clearAuthCookie(response, options = {}, request) {
|
|
614
629
|
const name = options.name ?? authConfig.cookie.name();
|
|
615
630
|
const path = options.path ?? authConfig.cookie.path();
|
|
631
|
+
const domain = this.cookieDomainFor("clearAuthCookie", request);
|
|
632
|
+
if (domain !== void 0) response.clearCookie(name, {
|
|
633
|
+
path,
|
|
634
|
+
domain
|
|
635
|
+
});
|
|
616
636
|
response.clearCookie(name, { path });
|
|
617
637
|
}
|
|
618
638
|
/**
|
|
@@ -626,7 +646,8 @@ var AuthService = class {
|
|
|
626
646
|
* const { tokens } = await authService.login(User, credentials);
|
|
627
647
|
* authService.setSessionCookies(response, tokens);
|
|
628
648
|
*/
|
|
629
|
-
setSessionCookies(response, tokens) {
|
|
649
|
+
setSessionCookies(response, tokens, request) {
|
|
650
|
+
const domain = this.cookieDomainFor("setSessionCookies", request);
|
|
630
651
|
const cookies = [[authConfig.cookie.name(), tokens.accessToken], [authConfig.cookie.refreshName(), tokens.refreshToken]];
|
|
631
652
|
for (const [name, token] of cookies) {
|
|
632
653
|
const maxAge = this.cookieMaxAgeFromToken(token);
|
|
@@ -635,6 +656,7 @@ var AuthService = class {
|
|
|
635
656
|
httpOnly: true,
|
|
636
657
|
sameSite: "lax",
|
|
637
658
|
path: "/",
|
|
659
|
+
...domain !== void 0 ? { domain } : {},
|
|
638
660
|
...maxAge !== void 0 ? { maxAge } : {}
|
|
639
661
|
});
|
|
640
662
|
}
|
|
@@ -643,13 +665,19 @@ var AuthService = class {
|
|
|
643
665
|
* Clear both session cookies {@link setSessionCookies} wrote, on `Path=/`.
|
|
644
666
|
* Pair it with {@link logout} after the token rows are revoked.
|
|
645
667
|
*/
|
|
646
|
-
clearSessionCookies(response) {
|
|
647
|
-
|
|
648
|
-
|
|
668
|
+
clearSessionCookies(response, request) {
|
|
669
|
+
const domain = this.cookieDomainFor("clearSessionCookies", request);
|
|
670
|
+
for (const name of [authConfig.cookie.name(), authConfig.cookie.refreshName()]) {
|
|
671
|
+
if (domain !== void 0) response.clearCookie(name, {
|
|
672
|
+
path: "/",
|
|
673
|
+
domain
|
|
674
|
+
});
|
|
675
|
+
response.clearCookie(name, { path: "/" });
|
|
676
|
+
}
|
|
649
677
|
}
|
|
650
678
|
};
|
|
651
679
|
const authService = new AuthService();
|
|
652
680
|
|
|
653
681
|
//#endregion
|
|
654
|
-
export { authService };
|
|
682
|
+
export { CookieDomainRequestRequiredError, authService };
|
|
655
683
|
//# sourceMappingURL=auth.service.mjs.map
|