@azlib/identity 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +149 -40
  2. package/dist/cookie-header-DptIxRmW.mjs +76 -0
  3. package/dist/cookie-header-DptIxRmW.mjs.map +1 -0
  4. package/dist/cookie-header-Dqd5k5BU.cjs +115 -0
  5. package/dist/cookie-header-LFWHKQ04.d.cts +86 -0
  6. package/dist/cookie-header-LFWHKQ04.d.cts.map +1 -0
  7. package/dist/cookie-header-LFWHKQ04.d.mts +86 -0
  8. package/dist/cookie-header-LFWHKQ04.d.mts.map +1 -0
  9. package/dist/{errors-C2xZAatu.d.cts → errors-0Zh7EG06.d.cts} +4 -3
  10. package/dist/errors-0Zh7EG06.d.cts.map +1 -0
  11. package/dist/{errors-BGMwaW5s.d.mts → errors-DVDEUk9-.d.mts} +4 -3
  12. package/dist/errors-DVDEUk9-.d.mts.map +1 -0
  13. package/dist/express.cjs +34 -0
  14. package/dist/express.d.cts +5 -6
  15. package/dist/express.d.cts.map +1 -1
  16. package/dist/express.d.mts +5 -6
  17. package/dist/express.d.mts.map +1 -1
  18. package/dist/express.mjs +34 -1
  19. package/dist/express.mjs.map +1 -1
  20. package/dist/{identity-Bz9RDOvT.mjs → identity-D0qyca_c.mjs} +37 -3
  21. package/dist/identity-D0qyca_c.mjs.map +1 -0
  22. package/dist/{identity-4eP45YIP.cjs → identity-Yz1BVkrM.cjs} +46 -0
  23. package/dist/{identity-router-DBL20UWT.d.mts → identity-router-BiratpJR.d.mts} +22 -6
  24. package/dist/identity-router-BiratpJR.d.mts.map +1 -0
  25. package/dist/{identity-router-Dib30Waj.d.cts → identity-router-D4oqYI60.d.cts} +22 -6
  26. package/dist/identity-router-D4oqYI60.d.cts.map +1 -0
  27. package/dist/{identity-service-CLzKx8Z7.d.cts → identity-service-DE0Ffguz.d.cts} +3 -4
  28. package/dist/identity-service-DE0Ffguz.d.cts.map +1 -0
  29. package/dist/{identity-service-B9zrvE9z.d.mts → identity-service-JtsoA6lv.d.mts} +3 -4
  30. package/dist/identity-service-JtsoA6lv.d.mts.map +1 -0
  31. package/dist/identity-store-BRRahxcS.d.cts.map +1 -1
  32. package/dist/identity-store-BRRahxcS.d.mts.map +1 -1
  33. package/dist/index-CsYqHPvK.d.cts +54 -0
  34. package/dist/index-CsYqHPvK.d.cts.map +1 -0
  35. package/dist/index-LhSdoWEP.d.mts +54 -0
  36. package/dist/index-LhSdoWEP.d.mts.map +1 -0
  37. package/dist/index.cjs +11 -1
  38. package/dist/index.d.cts +4 -3
  39. package/dist/index.d.mts +4 -3
  40. package/dist/index.mjs +3 -2
  41. package/dist/logger-CcCHJVVe.mjs.map +1 -1
  42. package/dist/nestjs.cjs +4 -5
  43. package/dist/nestjs.d.cts +3 -4
  44. package/dist/nestjs.d.cts.map +1 -1
  45. package/dist/nestjs.d.mts +3 -4
  46. package/dist/nestjs.d.mts.map +1 -1
  47. package/dist/nestjs.mjs +4 -5
  48. package/dist/nestjs.mjs.map +1 -1
  49. package/dist/next.cjs +285 -0
  50. package/dist/next.d.cts +58 -0
  51. package/dist/next.d.cts.map +1 -0
  52. package/dist/next.d.mts +58 -0
  53. package/dist/next.d.mts.map +1 -0
  54. package/dist/next.mjs +274 -0
  55. package/dist/next.mjs.map +1 -0
  56. package/dist/node.cjs +18 -19
  57. package/dist/node.d.cts +5 -5
  58. package/dist/node.d.cts.map +1 -1
  59. package/dist/node.d.mts +5 -5
  60. package/dist/node.d.mts.map +1 -1
  61. package/dist/node.mjs +10 -20
  62. package/dist/node.mjs.map +1 -1
  63. package/dist/test-utils.d.cts +0 -1
  64. package/dist/test-utils.d.cts.map +1 -1
  65. package/dist/test-utils.d.mts +0 -1
  66. package/dist/test-utils.d.mts.map +1 -1
  67. package/dist/test-utils.mjs.map +1 -1
  68. package/package.json +18 -18
  69. package/schema/model.ts +110 -22
  70. package/dist/errors-BGMwaW5s.d.mts.map +0 -1
  71. package/dist/errors-C2xZAatu.d.cts.map +0 -1
  72. package/dist/identity-Bz9RDOvT.mjs.map +0 -1
  73. package/dist/identity-router-DBL20UWT.d.mts.map +0 -1
  74. package/dist/identity-router-Dib30Waj.d.cts.map +0 -1
  75. package/dist/identity-service-B9zrvE9z.d.mts.map +0 -1
  76. package/dist/identity-service-CLzKx8Z7.d.cts.map +0 -1
  77. package/dist/index-CpufYgyn.d.cts +0 -30
  78. package/dist/index-CpufYgyn.d.cts.map +0 -1
  79. package/dist/index-CpufYgyn.d.mts +0 -30
  80. package/dist/index-CpufYgyn.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"nestjs.d.cts","names":[],"sources":["../core/nestjs/identity-controller.ts","../core/nestjs/identity.module.ts"],"mappings":";;;;;;;;;UAkGiB,yBAAA;;;AAAjB;;EAKE,MAAA,GAAS,oBAAoB;AAAA;;;AAAA;AAAA,cC1ElB,gBAAA;;cAGA,oBAAA;AAHb;;;AAAA,UAQiB,qBAAA,SAA8B,yBAAyB;EARJ;AAGpE;;;;AAA4E;EAY1E,MAAM;AAAA;AAAA,UAGS,qBAAA;EAV8B;EAY7C,OAAA,EAAS,eAAA;EAFM;;;;;;;;;AAuBsB;AAGvC;;;;;;;;;;EAHE,MAAA,UAAgB,qBAAqB;AAAA;AAAA,UAGtB,0BAAA;EACf,OAAA,GAAU,aAAA;EAEwB;EAAlC,UAAA,MAAgB,IAAA,cAAkB,eAAA,GAAkB,OAAA,CAAQ,eAAA;EAC5D,MAAA;EAAA;;;;EAKA,MAAA,UAAgB,qBAAA;AAAA;;;;;cAqBL,iBAAA,YAA6B,WAAA;EAAA,iBACe,OAAA;cAAA,OAAA,EAAS,eAAA;EAE1D,WAAA,CAAY,OAAA,EAAS,gBAAA,GAAmB,OAAA;AAAA;;;;;cAoBnC,0BAAA,YAAsC,WAAA;EAAA,iBAEJ,OAAA;EAAA,iBAC1B,SAAA;cAD0B,OAAA,EAAS,eAAA,EACnC,SAAA,EAAW,SAAA;EAGxB,WAAA,CAAY,OAAA,EAAS,gBAAA,GAAmB,OAAA;AAAA;AAPhD;AAAA,cAgCa,oBAAA,GAAoB,WAAA,EAAiB,wBAAA,8BAAwB,eAAA,QAAA,oBAAA;;cAI7D,iBAAA,GAAiB,UAAA,sCAAsB,eAAA,QAAA,oBAAA;;cAIvC,WAAA,MAAW,WAAA,gBAAA,kBAKvB;AAAA,cAiBY,cAAA;EAAA,OACJ,OAAA,CAAQ,OAAA,EAAS,qBAAA,GAAwB,aAAA;EAAA,OAczC,YAAA,CAAa,OAAA,EAAS,0BAAA,GAA6B,aAAA;AAAA"}
1
+ {"version":3,"file":"nestjs.d.cts","names":[],"sources":["../core/nestjs/identity-controller.ts","../core/nestjs/identity.module.ts"],"mappings":";;;;;;;;UAiHiB;;;;;EAKf,SAAS;;;;;cCzFE;;cAGA;;;;UAKI,8BAA8B;;;;;;;EAO7C;;UAGe;;EAEf,SAAS;;;;;;;;;;;;;;;;;;;;;EAqBT,gBAAgB;;UAGD;EACf,UAAU;;EAEV,gBAAgB,kBAAkB,kBAAkB,QAAQ;EAC5D;;;;;EAKA,gBAAgB;;;;;;cAqBL,6BAA6B;mBAEK;EAD7C,YAC6C,SAAS;EAGhD,YAAY,SAAS,mBAAmB;;;;;;cAoBnC,sCAAsC;mBAEJ;mBAC1B;EAFnB,YAC6C,SAAS,iBACnC,WAAW;EAGxB,YAAY,SAAS,mBAAmB;;;cAwBnC,uBAAoB,aAAiB,sDAAwB,uBAAA;;cAI7D,oBAAiB,gDAAsB,uBAAA;;cAMvC,iBAAW,2BAAA;cA2BX;SACJ,QAAQ,SAAS,wBAAwB;SAkBzC,aAAa,SAAS,6BAA6B"}
package/dist/nestjs.d.mts CHANGED
@@ -1,10 +1,9 @@
1
- import { V as AuthorizationRequirement } from "./errors-BGMwaW5s.mjs";
2
- import { t as IdentityService } from "./identity-service-B9zrvE9z.mjs";
3
- import { t as CookieRefreshOptions } from "./identity-router-DBL20UWT.mjs";
1
+ import { H as AuthorizationRequirement } from "./errors-DVDEUk9-.mjs";
2
+ import { t as IdentityService } from "./identity-service-JtsoA6lv.mjs";
3
+ import { t as CookieRefreshOptions } from "./identity-router-BiratpJR.mjs";
4
4
  import { Request, Response } from "express";
5
5
  import { CanActivate, DynamicModule, ExecutionContext } from "@nestjs/common";
6
6
  import { Reflector } from "@nestjs/core";
7
-
8
7
  //#region core/nestjs/identity-controller.d.ts
9
8
  /** Options accepted by {@link createIdentityController}. */
10
9
  interface IdentityControllerOptions {
@@ -1 +1 @@
1
- {"version":3,"file":"nestjs.d.mts","names":[],"sources":["../core/nestjs/identity-controller.ts","../core/nestjs/identity.module.ts"],"mappings":";;;;;;;;;UAkGiB,yBAAA;;;AAAjB;;EAKE,MAAA,GAAS,oBAAoB;AAAA;;;AAAA;AAAA,cC1ElB,gBAAA;;cAGA,oBAAA;AAHb;;;AAAA,UAQiB,qBAAA,SAA8B,yBAAyB;EARJ;AAGpE;;;;AAA4E;EAY1E,MAAM;AAAA;AAAA,UAGS,qBAAA;EAV8B;EAY7C,OAAA,EAAS,eAAA;EAFM;;;;;;;;;AAuBsB;AAGvC;;;;;;;;;;EAHE,MAAA,UAAgB,qBAAqB;AAAA;AAAA,UAGtB,0BAAA;EACf,OAAA,GAAU,aAAA;EAEwB;EAAlC,UAAA,MAAgB,IAAA,cAAkB,eAAA,GAAkB,OAAA,CAAQ,eAAA;EAC5D,MAAA;EAAA;;;;EAKA,MAAA,UAAgB,qBAAA;AAAA;;;;;cAqBL,iBAAA,YAA6B,WAAA;EAAA,iBACe,OAAA;cAAA,OAAA,EAAS,eAAA;EAE1D,WAAA,CAAY,OAAA,EAAS,gBAAA,GAAmB,OAAA;AAAA;;;;;cAoBnC,0BAAA,YAAsC,WAAA;EAAA,iBAEJ,OAAA;EAAA,iBAC1B,SAAA;cAD0B,OAAA,EAAS,eAAA,EACnC,SAAA,EAAW,SAAA;EAGxB,WAAA,CAAY,OAAA,EAAS,gBAAA,GAAmB,OAAA;AAAA;AAPhD;AAAA,cAgCa,oBAAA,GAAoB,WAAA,EAAiB,wBAAA,8BAAwB,eAAA,QAAA,oBAAA;;cAI7D,iBAAA,GAAiB,UAAA,sCAAsB,eAAA,QAAA,oBAAA;;cAIvC,WAAA,MAAW,WAAA,gBAAA,kBAKvB;AAAA,cAiBY,cAAA;EAAA,OACJ,OAAA,CAAQ,OAAA,EAAS,qBAAA,GAAwB,aAAA;EAAA,OAczC,YAAA,CAAa,OAAA,EAAS,0BAAA,GAA6B,aAAA;AAAA"}
1
+ {"version":3,"file":"nestjs.d.mts","names":[],"sources":["../core/nestjs/identity-controller.ts","../core/nestjs/identity.module.ts"],"mappings":";;;;;;;;UAiHiB;;;;;EAKf,SAAS;;;;;cCzFE;;cAGA;;;;UAKI,8BAA8B;;;;;;;EAO7C;;UAGe;;EAEf,SAAS;;;;;;;;;;;;;;;;;;;;;EAqBT,gBAAgB;;UAGD;EACf,UAAU;;EAEV,gBAAgB,kBAAkB,kBAAkB,QAAQ;EAC5D;;;;;EAKA,gBAAgB;;;;;;cAqBL,6BAA6B;mBAEK;EAD7C,YAC6C,SAAS;EAGhD,YAAY,SAAS,mBAAmB;;;;;;cAoBnC,sCAAsC;mBAEJ;mBAC1B;EAFnB,YAC6C,SAAS,iBACnC,WAAW;EAGxB,YAAY,SAAS,mBAAmB;;;cAwBnC,uBAAoB,aAAiB,sDAAwB,uBAAA;;cAI7D,oBAAiB,gDAAsB,uBAAA;;cAMvC,iBAAW,2BAAA;cA2BX;SACJ,QAAQ,SAAS,wBAAwB;SAkBzC,aAAa,SAAS,6BAA6B"}
package/dist/nestjs.mjs CHANGED
@@ -1,19 +1,19 @@
1
1
  import { a as IdentityError, c as UnauthenticatedError } from "./errors-CEmnZxIn.mjs";
2
2
  import { Body, Controller, ForbiddenException, Get, HttpCode, HttpException, Inject, Injectable, Param, Post, Req, Res, SetMetadata, UnauthorizedException, UseGuards, createParamDecorator } from "@nestjs/common";
3
3
  import { Reflector } from "@nestjs/core";
4
- //#region \0@oxc-project+runtime@0.132.0/helpers/decorateMetadata.js
4
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorateMetadata.js
5
5
  function __decorateMetadata(k, v) {
6
6
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
7
7
  }
8
8
  //#endregion
9
- //#region \0@oxc-project+runtime@0.132.0/helpers/decorateParam.js
9
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorateParam.js
10
10
  function __decorateParam(paramIndex, decorator) {
11
11
  return function(target, key) {
12
12
  decorator(target, key, paramIndex);
13
13
  };
14
14
  }
15
15
  //#endregion
16
- //#region \0@oxc-project+runtime@0.132.0/helpers/decorate.js
16
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorate.js
17
17
  function __decorate(decorators, target, key, desc) {
18
18
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
19
19
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -372,7 +372,6 @@ function createIdentityController(prefix, controllerOptions = {}) {
372
372
  * by metadata decorators, and a `@CurrentUser()` param decorator. `@nestjs/common` and
373
373
  * `reflect-metadata` are optional peer dependencies — only required when this entry is used.
374
374
  */
375
- var _ref;
376
375
  /** Token used to inject the configured {@link IdentityService} in Nest providers. */
377
376
  const IDENTITY_SERVICE = Symbol.for("azlib.identity.service");
378
377
  /** Metadata key holding the authorization requirement for a route. */
@@ -428,7 +427,7 @@ let IdentityAuthorizationGuard = class IdentityAuthorizationGuard {
428
427
  IdentityAuthorizationGuard = __decorate([
429
428
  Injectable(),
430
429
  __decorateParam(0, Inject(IDENTITY_SERVICE)),
431
- __decorateMetadata("design:paramtypes", [Object, typeof (_ref = typeof Reflector !== "undefined" && Reflector) === "function" ? _ref : Object])
430
+ __decorateMetadata("design:paramtypes", [Object, typeof Reflector === "undefined" ? Object : Reflector])
432
431
  ], IdentityAuthorizationGuard);
433
432
  /** Declares the authorization requirement for a route or controller. */
434
433
  const RequireAuthorization = (requirement) => SetMetadata(IDENTITY_REQUIREMENT, requirement);
@@ -1 +1 @@
1
- {"version":3,"file":"nestjs.mjs","names":[],"sources":["../core/nestjs/identity-controller.ts","../core/nestjs/identity.module.ts"],"sourcesContent":["/**\n * Pre-built NestJS controller for `@azlib/identity`.\n *\n * Register it automatically via `IdentityModule.forRoot({ routes: true })`.\n * `@nestjs/common` is an optional peer dependency — only required when this file is used.\n */\nimport {\n Body,\n Controller,\n Get,\n HttpCode,\n HttpException,\n type HttpStatus,\n Inject,\n Param,\n Post,\n Req,\n Res,\n UseGuards,\n} from \"@nestjs/common\";\nimport type { Request, Response } from \"express\";\n\nimport { IdentityError, UnauthenticatedError } from \"../errors\";\nimport type { IdentityService } from \"../identity-service\";\nimport type { AuthResult, AuthTokens, LoginResult } from \"../types\";\nimport type { CookieRefreshOptions } from \"../express/identity-router\";\nimport { IdentityAuthGuard, IDENTITY_SERVICE } from \"./identity.module\";\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction resolveCookieName(opts: CookieRefreshOptions): string {\n return opts.name ?? \"azlib_rt\";\n}\n\nfunction rethrowAsHttp(err: unknown): never {\n if (err instanceof IdentityError) {\n throw new HttpException({ code: err.code, message: err.message }, err.statusCode as HttpStatus);\n }\n throw err;\n}\n\nfunction setCookieAndStripRefreshToken(\n res: Response,\n tokens: AuthTokens,\n opts: CookieRefreshOptions,\n): Omit<AuthTokens, \"refreshToken\" | \"refreshTokenExpiresAt\"> {\n const maxAge = tokens.refreshTokenExpiresAt.getTime() - Date.now();\n res.cookie(resolveCookieName(opts), tokens.refreshToken, {\n httpOnly: opts.httpOnly ?? true,\n secure: opts.secure ?? process.env.NODE_ENV === \"production\",\n sameSite: opts.sameSite ?? \"lax\",\n path: opts.path ?? \"/\",\n domain: opts.domain,\n maxAge,\n });\n const { refreshToken: _rt, refreshTokenExpiresAt: _exp, ...bodyTokens } = tokens;\n return bodyTokens;\n}\n\nfunction buildAuthResponse(result: AuthResult, cookieOpts: CookieRefreshOptions | undefined, res: Response) {\n if (cookieOpts) {\n const tokens = setCookieAndStripRefreshToken(res, result.tokens, cookieOpts);\n return { user: result.user, tokens };\n }\n return result;\n}\n\nfunction buildLoginResponse(\n result: LoginResult,\n cookieOpts: CookieRefreshOptions | undefined,\n res: Response,\n) {\n if (\"mfaToken\" in result) {\n return result; // { kind: \"mfa_required\", mfaToken: \"...\" }\n }\n return buildAuthResponse(result, cookieOpts, res);\n}\n\nfunction readRefreshTokenFromRequest(\n req: Request,\n cookieOpts: CookieRefreshOptions | undefined,\n): string | undefined {\n if (cookieOpts) {\n const cookies = req.cookies as Record<string, string> | undefined;\n return cookies?.[resolveCookieName(cookieOpts)];\n }\n const body = req.body as Record<string, unknown> | undefined;\n const token = body?.[\"refreshToken\"];\n return typeof token === \"string\" ? token : undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Controller options\n// ---------------------------------------------------------------------------\n\n/** Options accepted by {@link createIdentityController}. */\nexport interface IdentityControllerOptions {\n /**\n * Cookie-based refresh-token transport. When set, the refresh token is stored in an\n * `HttpOnly` cookie instead of the response body. Omit for body mode.\n */\n cookie?: CookieRefreshOptions;\n}\n\n// ---------------------------------------------------------------------------\n// Controller factory\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a dynamically created NestJS controller class with all standard identity\n * routes pre-wired. The class is registered directly in `IdentityModule.forRoot()`\n * when `routes` is configured — consumers do not need to define this controller.\n *\n * Pre-wired routes (relative to the module prefix, default `\"auth\"`):\n *\n * | Method | Path | Description |\n * |--------|------|-------------|\n * | POST | `/register` | Create a new account |\n * | POST | `/login` | Email + password login; may return MFA challenge |\n * | POST | `/refresh` | Rotate the refresh token |\n * | POST | `/logout` | Revoke the current session |\n * | GET | `/me` | Return the authenticated principal (requires auth) |\n * | POST | `/request-email-verification` | Re-send verification link (requires auth) |\n * | POST | `/verify-email` | Consume an email verification token |\n * | POST | `/request-password-reset` | Send a password reset link |\n * | POST | `/reset-password` | Set a new password using a reset token |\n * | POST | `/mfa/verify` | Complete an MFA challenge after login |\n * | POST | `/2fa/setup` | Begin TOTP 2FA setup (requires auth) |\n * | POST | `/2fa/enable` | Confirm and enable 2FA (requires auth) |\n * | POST | `/2fa/disable` | Disable 2FA (requires auth) |\n * | POST | `/admin/lock/:userId` | Lock an account |\n * | POST | `/admin/unlock/:userId` | Unlock an account |\n * | POST | `/admin/disable/:userId` | Disable an account |\n */\nexport function createIdentityController(\n prefix: string,\n controllerOptions: IdentityControllerOptions = {},\n) {\n const cookieOpts = controllerOptions.cookie;\n\n @Controller(prefix)\n class IdentityController {\n constructor(@Inject(IDENTITY_SERVICE) readonly service: IdentityService) {}\n\n @Post(\"register\")\n async register(\n @Body() body: { email: string; password: string; displayName?: string },\n @Res({ passthrough: true }) res: Response,\n ) {\n try {\n const result = await this.service.register(body);\n return buildAuthResponse(result, cookieOpts, res);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"login\")\n async login(\n @Body() body: { email: string; password: string },\n @Res({ passthrough: true }) res: Response,\n ) {\n try {\n const result = await this.service.login(body);\n return buildLoginResponse(result, cookieOpts, res);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"refresh\")\n async refresh(@Req() req: Request, @Res({ passthrough: true }) res: Response) {\n try {\n const token = readRefreshTokenFromRequest(req, cookieOpts);\n if (!token) {\n throw new UnauthenticatedError(\"Refresh token is missing.\");\n }\n const result = await this.service.refresh(token);\n return buildAuthResponse(result, cookieOpts, res);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"logout\")\n @HttpCode(204)\n async logout(@Req() req: Request, @Res({ passthrough: true }) res: Response) {\n try {\n const token = readRefreshTokenFromRequest(req, cookieOpts);\n if (token) {\n await this.service.logout(token);\n }\n if (cookieOpts) {\n res.clearCookie(resolveCookieName(cookieOpts), { path: cookieOpts.path ?? \"/\" });\n }\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Get(\"me\")\n @UseGuards(IdentityAuthGuard)\n getMe(@Req() req: Request & { identity?: unknown }) {\n return req.identity;\n }\n\n // -------------------------------------------------------------------------\n // Email verification\n // -------------------------------------------------------------------------\n\n @Post(\"request-email-verification\")\n @HttpCode(204)\n @UseGuards(IdentityAuthGuard)\n async requestEmailVerification(@Req() req: Request & { identity?: { userId: string } }) {\n try {\n await this.service.requestEmailVerification(req.identity!.userId);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"verify-email\")\n @HttpCode(204)\n async verifyEmail(@Body() body: { token?: string }) {\n try {\n if (!body.token) throw new UnauthenticatedError(\"token is required.\");\n await this.service.verifyEmail(body.token);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n // -------------------------------------------------------------------------\n // Password reset\n // -------------------------------------------------------------------------\n\n @Post(\"request-password-reset\")\n @HttpCode(204)\n async requestPasswordReset(@Body() body: { email?: string }) {\n try {\n if (!body.email) throw new UnauthenticatedError(\"email is required.\");\n await this.service.requestPasswordReset(body.email);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"reset-password\")\n @HttpCode(204)\n async resetPassword(@Body() body: { token?: string; newPassword?: string }) {\n try {\n if (!body.token || !body.newPassword)\n throw new UnauthenticatedError(\"token and newPassword are required.\");\n await this.service.resetPassword(body.token, body.newPassword);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n // -------------------------------------------------------------------------\n // Two-factor authentication\n // -------------------------------------------------------------------------\n\n @Post(\"mfa/verify\")\n async verifyMfaChallenge(\n @Body() body: { mfaToken?: string; code?: string },\n @Res({ passthrough: true }) res: Response,\n ) {\n try {\n if (!body.mfaToken || !body.code)\n throw new UnauthenticatedError(\"mfaToken and code are required.\");\n const result = await this.service.verifyMfaChallenge(body.mfaToken, body.code);\n return buildAuthResponse(result, cookieOpts, res);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"2fa/setup\")\n @UseGuards(IdentityAuthGuard)\n async setup2FA(@Req() req: Request & { identity?: { userId: string } }) {\n try {\n return await this.service.setup2FA(req.identity!.userId);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"2fa/enable\")\n @HttpCode(204)\n @UseGuards(IdentityAuthGuard)\n async enable2FA(\n @Req() req: Request & { identity?: { userId: string } },\n @Body() body: { code?: string },\n ) {\n try {\n if (!body.code) throw new UnauthenticatedError(\"code is required.\");\n await this.service.enable2FA(req.identity!.userId, body.code);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"2fa/disable\")\n @HttpCode(204)\n @UseGuards(IdentityAuthGuard)\n async disable2FA(\n @Req() req: Request & { identity?: { userId: string } },\n @Body() body: { code?: string },\n ) {\n try {\n if (!body.code) throw new UnauthenticatedError(\"code is required.\");\n await this.service.disable2FA(req.identity!.userId, body.code);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n // -------------------------------------------------------------------------\n // Account management (admin)\n // -------------------------------------------------------------------------\n\n @Post(\"admin/lock/:userId\")\n @HttpCode(204)\n async lockAccount(@Param(\"userId\") userId: string) {\n try {\n await this.service.lockAccount(userId);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"admin/unlock/:userId\")\n @HttpCode(204)\n async unlockAccount(@Param(\"userId\") userId: string) {\n try {\n await this.service.unlockAccount(userId);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"admin/disable/:userId\")\n @HttpCode(204)\n async disableAccount(@Param(\"userId\") userId: string) {\n try {\n await this.service.disableAccount(userId);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n }\n\n return IdentityController;\n}\n","/**\n * NestJS integration for `@azlib/identity`.\n *\n * Provides a configurable module, an authentication guard, an authorization guard driven\n * by metadata decorators, and a `@CurrentUser()` param decorator. `@nestjs/common` and\n * `reflect-metadata` are optional peer dependencies — only required when this entry is used.\n */\nimport {\n type CanActivate,\n type DynamicModule,\n type ExecutionContext,\n ForbiddenException,\n Inject,\n Injectable,\n SetMetadata,\n UnauthorizedException,\n createParamDecorator,\n} from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\n\nimport type { AuthorizationRequirement } from \"../authorization\";\nimport type { IdentityService } from \"../identity-service\";\nimport type { AuthenticatedIdentity } from \"../types\";\nimport {\n createIdentityController,\n type IdentityControllerOptions,\n} from \"./identity-controller\";\n\n/** Token used to inject the configured {@link IdentityService} in Nest providers. */\nexport const IDENTITY_SERVICE = Symbol.for(\"azlib.identity.service\");\n\n/** Metadata key holding the authorization requirement for a route. */\nexport const IDENTITY_REQUIREMENT = Symbol.for(\"azlib.identity.requirement\");\n\n/**\n * Options for enabling the pre-built REST routes in {@link IdentityModule}.\n */\nexport interface IdentityRoutesOptions extends IdentityControllerOptions {\n /**\n * URL prefix for the built-in controller. Default: `\"auth\"`.\n *\n * The controller is mounted at this prefix relative to the application's global\n * prefix (if any).\n */\n prefix?: string;\n}\n\nexport interface IdentityModuleOptions {\n /** A fully wired identity service (see `createIdentityService`). */\n service: IdentityService;\n /**\n * When set, the module automatically registers a built-in REST controller with all\n * standard auth endpoints (`POST /register`, `POST /login`, `POST /refresh`,\n * `POST /logout`, `GET /me`).\n *\n * Pass `true` to use the defaults (`prefix: \"auth\"`, body-mode refresh tokens), or\n * supply an `IdentityRoutesOptions` object to customise the prefix and cookie behaviour.\n *\n * @example\n * ```ts\n * // Minimal — everything works out of the box\n * IdentityModule.forRoot({ service, routes: true })\n *\n * // With a custom prefix and HttpOnly refresh-token cookie\n * IdentityModule.forRoot({\n * service,\n * routes: { prefix: \"v1/auth\", cookie: { name: \"rt\", secure: true } },\n * })\n * ```\n */\n routes?: true | IdentityRoutesOptions;\n}\n\nexport interface IdentityModuleAsyncOptions {\n imports?: DynamicModule[\"imports\"];\n /** Factory returning the configured identity service. */\n useFactory: (...args: never[]) => IdentityService | Promise<IdentityService>;\n inject?: unknown[];\n /**\n * Same as {@link IdentityModuleOptions.routes} — enable built-in REST routes\n * alongside the async service factory.\n */\n routes?: true | IdentityRoutesOptions;\n}\n\ninterface RequestWithIdentity {\n headers: Record<string, string | string[] | undefined>;\n identity?: AuthenticatedIdentity;\n}\n\nconst extractBearerToken = (req: RequestWithIdentity): string | null => {\n const header = req.headers.authorization;\n const value = Array.isArray(header) ? header[0] : header;\n if (!value || !value.startsWith(\"Bearer \")) return null;\n const token = value.slice(\"Bearer \".length).trim();\n return token.length > 0 ? token : null;\n};\n\n/**\n * Authentication guard: verifies the Bearer access token and attaches the hydrated\n * principal to `request.identity`. Apply with `@UseGuards(IdentityAuthGuard)`.\n */\n@Injectable()\nexport class IdentityAuthGuard implements CanActivate {\n constructor(@Inject(IDENTITY_SERVICE) private readonly service: IdentityService) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const req = context.switchToHttp().getRequest<RequestWithIdentity>();\n const token = extractBearerToken(req);\n if (!token) {\n throw new UnauthorizedException(\"Missing bearer token.\");\n }\n try {\n req.identity = await this.service.authenticate(token);\n } catch {\n throw new UnauthorizedException(\"Invalid or expired token.\");\n }\n return true;\n }\n}\n\n/**\n * Authorization guard: enforces the requirement declared by `@RequireAuthorization()`\n * (or `@RequirePermission()`). Must run after {@link IdentityAuthGuard}. Deny-by-default.\n */\n@Injectable()\nexport class IdentityAuthorizationGuard implements CanActivate {\n constructor(\n @Inject(IDENTITY_SERVICE) private readonly service: IdentityService,\n private readonly reflector: Reflector,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const requirement = this.reflector.getAllAndOverride<AuthorizationRequirement | undefined>(\n IDENTITY_REQUIREMENT,\n [context.getHandler(), context.getClass()],\n );\n // No requirement declared: nothing extra to enforce beyond authentication.\n if (!requirement) return true;\n\n const req = context.switchToHttp().getRequest<RequestWithIdentity>();\n const principal = req.identity;\n if (!principal) {\n throw new UnauthorizedException(\"Not authenticated.\");\n }\n const decision = await this.service.authorize(requirement, {\n principal,\n action: requirement.permission ?? \"custom\",\n });\n if (!decision.allowed) {\n throw new ForbiddenException();\n }\n return true;\n }\n}\n\n/** Declares the authorization requirement for a route or controller. */\nexport const RequireAuthorization = (requirement: AuthorizationRequirement) =>\n SetMetadata(IDENTITY_REQUIREMENT, requirement);\n\n/** Convenience: declare a single required permission for a route or controller. */\nexport const RequirePermission = (permission: string) =>\n SetMetadata(IDENTITY_REQUIREMENT, { permission } satisfies AuthorizationRequirement);\n\n/** Param decorator that resolves the authenticated principal from the request. */\nexport const CurrentUser = createParamDecorator(\n (_data: unknown, context: ExecutionContext): AuthenticatedIdentity | undefined => {\n const req = context.switchToHttp().getRequest<RequestWithIdentity>();\n return req.identity;\n },\n);\n\n/**\n * NestJS module exposing the identity service plus guards. Register once at the root:\n *\n * ```ts\n * IdentityModule.forRoot({ service: createIdentityService(config, store) })\n * ```\n */\nfunction buildControllers(routes: true | IdentityRoutesOptions | undefined) {\n if (!routes) return [];\n const routesOpts = routes === true ? {} : routes;\n const prefix = routesOpts.prefix ?? \"auth\";\n const controllerOpts: IdentityControllerOptions = { cookie: routesOpts.cookie };\n return [createIdentityController(prefix, controllerOpts)];\n}\n\nexport class IdentityModule {\n static forRoot(options: IdentityModuleOptions): DynamicModule {\n return {\n module: IdentityModule,\n global: true,\n controllers: buildControllers(options.routes),\n providers: [\n { provide: IDENTITY_SERVICE, useValue: options.service },\n IdentityAuthGuard,\n IdentityAuthorizationGuard,\n ],\n exports: [IDENTITY_SERVICE, IdentityAuthGuard, IdentityAuthorizationGuard],\n };\n }\n\n static forRootAsync(options: IdentityModuleAsyncOptions): DynamicModule {\n return {\n module: IdentityModule,\n global: true,\n imports: options.imports ?? [],\n controllers: buildControllers(options.routes),\n providers: [\n {\n provide: IDENTITY_SERVICE,\n useFactory: options.useFactory,\n inject: options.inject as never[],\n },\n IdentityAuthGuard,\n IdentityAuthorizationGuard,\n ],\n exports: [IDENTITY_SERVICE, IdentityAuthGuard, IdentityAuthorizationGuard],\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;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tE,OAAO;GACL,QAAQ;GACR,QAAQ;GACR,SAAS,QAAQ,WAAW,CAAC;GAC7B,aAAa,iBAAiB,QAAQ,MAAM;GAC5C,WAAW;IACT;KACE,SAAS;KACT,YAAY,QAAQ;KACpB,QAAQ,QAAQ;IAClB;IACA;IACA;GACF;GACA,SAAS;IAAC;IAAkB;IAAmB;GAA0B;EAC3E;CACF;AACF"}
1
+ {"version":3,"file":"nestjs.mjs","names":[],"sources":["../core/nestjs/identity-controller.ts","../core/nestjs/identity.module.ts"],"sourcesContent":["/**\n * Pre-built NestJS controller for `@azlib/identity`.\n *\n * Register it automatically via `IdentityModule.forRoot({ routes: true })`.\n * `@nestjs/common` is an optional peer dependency — only required when this file is used.\n */\nimport {\n Body,\n Controller,\n Get,\n HttpCode,\n HttpException,\n type HttpStatus,\n Inject,\n Param,\n Post,\n Req,\n Res,\n UseGuards,\n} from \"@nestjs/common\";\nimport type { Request, Response } from \"express\";\n\nimport { IdentityError, UnauthenticatedError } from \"../errors\";\nimport type { IdentityService } from \"../identity-service\";\nimport type { AuthResult, AuthTokens, LoginResult } from \"../types\";\nimport type { CookieRefreshOptions } from \"../express/identity-router\";\nimport { IdentityAuthGuard, IDENTITY_SERVICE } from \"./identity.module\";\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction resolveCookieName(opts: CookieRefreshOptions): string {\n return opts.name ?? \"azlib_rt\";\n}\n\nfunction rethrowAsHttp(err: unknown): never {\n if (err instanceof IdentityError) {\n throw new HttpException(\n { code: err.code, message: err.message },\n err.statusCode as HttpStatus,\n );\n }\n throw err;\n}\n\nfunction setCookieAndStripRefreshToken(\n res: Response,\n tokens: AuthTokens,\n opts: CookieRefreshOptions,\n): Omit<AuthTokens, \"refreshToken\" | \"refreshTokenExpiresAt\"> {\n const maxAge = tokens.refreshTokenExpiresAt.getTime() - Date.now();\n res.cookie(resolveCookieName(opts), tokens.refreshToken, {\n httpOnly: opts.httpOnly ?? true,\n secure: opts.secure ?? process.env.NODE_ENV === \"production\",\n sameSite: opts.sameSite ?? \"lax\",\n path: opts.path ?? \"/\",\n domain: opts.domain,\n maxAge,\n });\n const {\n refreshToken: _rt,\n refreshTokenExpiresAt: _exp,\n ...bodyTokens\n } = tokens;\n return bodyTokens;\n}\n\nfunction buildAuthResponse(\n result: AuthResult,\n cookieOpts: CookieRefreshOptions | undefined,\n res: Response,\n) {\n if (cookieOpts) {\n const tokens = setCookieAndStripRefreshToken(\n res,\n result.tokens,\n cookieOpts,\n );\n return { user: result.user, tokens };\n }\n return result;\n}\n\nfunction buildLoginResponse(\n result: LoginResult,\n cookieOpts: CookieRefreshOptions | undefined,\n res: Response,\n) {\n if (\"mfaToken\" in result) {\n return result; // { kind: \"mfa_required\", mfaToken: \"...\" }\n }\n return buildAuthResponse(result, cookieOpts, res);\n}\n\nfunction readRefreshTokenFromRequest(\n req: Request,\n cookieOpts: CookieRefreshOptions | undefined,\n): string | undefined {\n if (cookieOpts) {\n const cookies = req.cookies as Record<string, string> | undefined;\n return cookies?.[resolveCookieName(cookieOpts)];\n }\n const body = req.body as Record<string, unknown> | undefined;\n const token = body?.[\"refreshToken\"];\n return typeof token === \"string\" ? token : undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Controller options\n// ---------------------------------------------------------------------------\n\n/** Options accepted by {@link createIdentityController}. */\nexport interface IdentityControllerOptions {\n /**\n * Cookie-based refresh-token transport. When set, the refresh token is stored in an\n * `HttpOnly` cookie instead of the response body. Omit for body mode.\n */\n cookie?: CookieRefreshOptions;\n}\n\n// ---------------------------------------------------------------------------\n// Controller factory\n// ---------------------------------------------------------------------------\n\n/**\n * Returns a dynamically created NestJS controller class with all standard identity\n * routes pre-wired. The class is registered directly in `IdentityModule.forRoot()`\n * when `routes` is configured — consumers do not need to define this controller.\n *\n * Pre-wired routes (relative to the module prefix, default `\"auth\"`):\n *\n * | Method | Path | Description |\n * |--------|------|-------------|\n * | POST | `/register` | Create a new account |\n * | POST | `/login` | Email + password login; may return MFA challenge |\n * | POST | `/refresh` | Rotate the refresh token |\n * | POST | `/logout` | Revoke the current session |\n * | GET | `/me` | Return the authenticated principal (requires auth) |\n * | POST | `/request-email-verification` | Re-send verification link (requires auth) |\n * | POST | `/verify-email` | Consume an email verification token |\n * | POST | `/request-password-reset` | Send a password reset link |\n * | POST | `/reset-password` | Set a new password using a reset token |\n * | POST | `/mfa/verify` | Complete an MFA challenge after login |\n * | POST | `/2fa/setup` | Begin TOTP 2FA setup (requires auth) |\n * | POST | `/2fa/enable` | Confirm and enable 2FA (requires auth) |\n * | POST | `/2fa/disable` | Disable 2FA (requires auth) |\n * | POST | `/admin/lock/:userId` | Lock an account |\n * | POST | `/admin/unlock/:userId` | Unlock an account |\n * | POST | `/admin/disable/:userId` | Disable an account |\n */\nexport function createIdentityController(\n prefix: string,\n controllerOptions: IdentityControllerOptions = {},\n) {\n const cookieOpts = controllerOptions.cookie;\n\n @Controller(prefix)\n class IdentityController {\n constructor(@Inject(IDENTITY_SERVICE) readonly service: IdentityService) {}\n\n @Post(\"register\")\n async register(\n @Body() body: { email: string; password: string; displayName?: string },\n @Res({ passthrough: true }) res: Response,\n ) {\n try {\n const result = await this.service.register(body);\n return buildAuthResponse(result, cookieOpts, res);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"login\")\n async login(\n @Body() body: { email: string; password: string },\n @Res({ passthrough: true }) res: Response,\n ) {\n try {\n const result = await this.service.login(body);\n return buildLoginResponse(result, cookieOpts, res);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"refresh\")\n async refresh(\n @Req() req: Request,\n @Res({ passthrough: true }) res: Response,\n ) {\n try {\n const token = readRefreshTokenFromRequest(req, cookieOpts);\n if (!token) {\n throw new UnauthenticatedError(\"Refresh token is missing.\");\n }\n const result = await this.service.refresh(token);\n return buildAuthResponse(result, cookieOpts, res);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"logout\")\n @HttpCode(204)\n async logout(\n @Req() req: Request,\n @Res({ passthrough: true }) res: Response,\n ) {\n try {\n const token = readRefreshTokenFromRequest(req, cookieOpts);\n if (token) {\n await this.service.logout(token);\n }\n if (cookieOpts) {\n res.clearCookie(resolveCookieName(cookieOpts), {\n path: cookieOpts.path ?? \"/\",\n });\n }\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Get(\"me\")\n @UseGuards(IdentityAuthGuard)\n getMe(@Req() req: Request & { identity?: unknown }) {\n return req.identity;\n }\n\n // -------------------------------------------------------------------------\n // Email verification\n // -------------------------------------------------------------------------\n\n @Post(\"request-email-verification\")\n @HttpCode(204)\n @UseGuards(IdentityAuthGuard)\n async requestEmailVerification(\n @Req() req: Request & { identity?: { userId: string } },\n ) {\n try {\n await this.service.requestEmailVerification(req.identity!.userId);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"verify-email\")\n @HttpCode(204)\n async verifyEmail(@Body() body: { token?: string }) {\n try {\n if (!body.token) throw new UnauthenticatedError(\"token is required.\");\n await this.service.verifyEmail(body.token);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n // -------------------------------------------------------------------------\n // Password reset\n // -------------------------------------------------------------------------\n\n @Post(\"request-password-reset\")\n @HttpCode(204)\n async requestPasswordReset(@Body() body: { email?: string }) {\n try {\n if (!body.email) throw new UnauthenticatedError(\"email is required.\");\n await this.service.requestPasswordReset(body.email);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"reset-password\")\n @HttpCode(204)\n async resetPassword(\n @Body() body: { token?: string; newPassword?: string },\n ) {\n try {\n if (!body.token || !body.newPassword)\n throw new UnauthenticatedError(\"token and newPassword are required.\");\n await this.service.resetPassword(body.token, body.newPassword);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n // -------------------------------------------------------------------------\n // Two-factor authentication\n // -------------------------------------------------------------------------\n\n @Post(\"mfa/verify\")\n async verifyMfaChallenge(\n @Body() body: { mfaToken?: string; code?: string },\n @Res({ passthrough: true }) res: Response,\n ) {\n try {\n if (!body.mfaToken || !body.code)\n throw new UnauthenticatedError(\"mfaToken and code are required.\");\n const result = await this.service.verifyMfaChallenge(\n body.mfaToken,\n body.code,\n );\n return buildAuthResponse(result, cookieOpts, res);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"2fa/setup\")\n @UseGuards(IdentityAuthGuard)\n async setup2FA(@Req() req: Request & { identity?: { userId: string } }) {\n try {\n return await this.service.setup2FA(req.identity!.userId);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"2fa/enable\")\n @HttpCode(204)\n @UseGuards(IdentityAuthGuard)\n async enable2FA(\n @Req() req: Request & { identity?: { userId: string } },\n @Body() body: { code?: string },\n ) {\n try {\n if (!body.code) throw new UnauthenticatedError(\"code is required.\");\n await this.service.enable2FA(req.identity!.userId, body.code);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"2fa/disable\")\n @HttpCode(204)\n @UseGuards(IdentityAuthGuard)\n async disable2FA(\n @Req() req: Request & { identity?: { userId: string } },\n @Body() body: { code?: string },\n ) {\n try {\n if (!body.code) throw new UnauthenticatedError(\"code is required.\");\n await this.service.disable2FA(req.identity!.userId, body.code);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n // -------------------------------------------------------------------------\n // Account management (admin)\n // -------------------------------------------------------------------------\n\n @Post(\"admin/lock/:userId\")\n @HttpCode(204)\n async lockAccount(@Param(\"userId\") userId: string) {\n try {\n await this.service.lockAccount(userId);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"admin/unlock/:userId\")\n @HttpCode(204)\n async unlockAccount(@Param(\"userId\") userId: string) {\n try {\n await this.service.unlockAccount(userId);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n\n @Post(\"admin/disable/:userId\")\n @HttpCode(204)\n async disableAccount(@Param(\"userId\") userId: string) {\n try {\n await this.service.disableAccount(userId);\n } catch (err) {\n rethrowAsHttp(err);\n }\n }\n }\n\n return IdentityController;\n}\n","/**\n * NestJS integration for `@azlib/identity`.\n *\n * Provides a configurable module, an authentication guard, an authorization guard driven\n * by metadata decorators, and a `@CurrentUser()` param decorator. `@nestjs/common` and\n * `reflect-metadata` are optional peer dependencies — only required when this entry is used.\n */\nimport {\n type CanActivate,\n type DynamicModule,\n type ExecutionContext,\n ForbiddenException,\n Inject,\n Injectable,\n SetMetadata,\n UnauthorizedException,\n createParamDecorator,\n} from \"@nestjs/common\";\nimport { Reflector } from \"@nestjs/core\";\n\nimport type { AuthorizationRequirement } from \"../authorization\";\nimport type { IdentityService } from \"../identity-service\";\nimport type { AuthenticatedIdentity } from \"../types\";\nimport {\n createIdentityController,\n type IdentityControllerOptions,\n} from \"./identity-controller\";\n\n/** Token used to inject the configured {@link IdentityService} in Nest providers. */\nexport const IDENTITY_SERVICE = Symbol.for(\"azlib.identity.service\");\n\n/** Metadata key holding the authorization requirement for a route. */\nexport const IDENTITY_REQUIREMENT = Symbol.for(\"azlib.identity.requirement\");\n\n/**\n * Options for enabling the pre-built REST routes in {@link IdentityModule}.\n */\nexport interface IdentityRoutesOptions extends IdentityControllerOptions {\n /**\n * URL prefix for the built-in controller. Default: `\"auth\"`.\n *\n * The controller is mounted at this prefix relative to the application's global\n * prefix (if any).\n */\n prefix?: string;\n}\n\nexport interface IdentityModuleOptions {\n /** A fully wired identity service (see `createIdentityService`). */\n service: IdentityService;\n /**\n * When set, the module automatically registers a built-in REST controller with all\n * standard auth endpoints (`POST /register`, `POST /login`, `POST /refresh`,\n * `POST /logout`, `GET /me`).\n *\n * Pass `true` to use the defaults (`prefix: \"auth\"`, body-mode refresh tokens), or\n * supply an `IdentityRoutesOptions` object to customise the prefix and cookie behaviour.\n *\n * @example\n * ```ts\n * // Minimal — everything works out of the box\n * IdentityModule.forRoot({ service, routes: true })\n *\n * // With a custom prefix and HttpOnly refresh-token cookie\n * IdentityModule.forRoot({\n * service,\n * routes: { prefix: \"v1/auth\", cookie: { name: \"rt\", secure: true } },\n * })\n * ```\n */\n routes?: true | IdentityRoutesOptions;\n}\n\nexport interface IdentityModuleAsyncOptions {\n imports?: DynamicModule[\"imports\"];\n /** Factory returning the configured identity service. */\n useFactory: (...args: never[]) => IdentityService | Promise<IdentityService>;\n inject?: unknown[];\n /**\n * Same as {@link IdentityModuleOptions.routes} — enable built-in REST routes\n * alongside the async service factory.\n */\n routes?: true | IdentityRoutesOptions;\n}\n\ninterface RequestWithIdentity {\n headers: Record<string, string | string[] | undefined>;\n identity?: AuthenticatedIdentity;\n}\n\nconst extractBearerToken = (req: RequestWithIdentity): string | null => {\n const header = req.headers.authorization;\n const value = Array.isArray(header) ? header[0] : header;\n if (!value || !value.startsWith(\"Bearer \")) return null;\n const token = value.slice(\"Bearer \".length).trim();\n return token.length > 0 ? token : null;\n};\n\n/**\n * Authentication guard: verifies the Bearer access token and attaches the hydrated\n * principal to `request.identity`. Apply with `@UseGuards(IdentityAuthGuard)`.\n */\n@Injectable()\nexport class IdentityAuthGuard implements CanActivate {\n constructor(\n @Inject(IDENTITY_SERVICE) private readonly service: IdentityService,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const req = context.switchToHttp().getRequest<RequestWithIdentity>();\n const token = extractBearerToken(req);\n if (!token) {\n throw new UnauthorizedException(\"Missing bearer token.\");\n }\n try {\n req.identity = await this.service.authenticate(token);\n } catch {\n throw new UnauthorizedException(\"Invalid or expired token.\");\n }\n return true;\n }\n}\n\n/**\n * Authorization guard: enforces the requirement declared by `@RequireAuthorization()`\n * (or `@RequirePermission()`). Must run after {@link IdentityAuthGuard}. Deny-by-default.\n */\n@Injectable()\nexport class IdentityAuthorizationGuard implements CanActivate {\n constructor(\n @Inject(IDENTITY_SERVICE) private readonly service: IdentityService,\n private readonly reflector: Reflector,\n ) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const requirement = this.reflector.getAllAndOverride<\n AuthorizationRequirement | undefined\n >(IDENTITY_REQUIREMENT, [context.getHandler(), context.getClass()]);\n // No requirement declared: nothing extra to enforce beyond authentication.\n if (!requirement) return true;\n\n const req = context.switchToHttp().getRequest<RequestWithIdentity>();\n const principal = req.identity;\n if (!principal) {\n throw new UnauthorizedException(\"Not authenticated.\");\n }\n const decision = await this.service.authorize(requirement, {\n principal,\n action: requirement.permission ?? \"custom\",\n });\n if (!decision.allowed) {\n throw new ForbiddenException();\n }\n return true;\n }\n}\n\n/** Declares the authorization requirement for a route or controller. */\nexport const RequireAuthorization = (requirement: AuthorizationRequirement) =>\n SetMetadata(IDENTITY_REQUIREMENT, requirement);\n\n/** Convenience: declare a single required permission for a route or controller. */\nexport const RequirePermission = (permission: string) =>\n SetMetadata(IDENTITY_REQUIREMENT, {\n permission,\n } satisfies AuthorizationRequirement);\n\n/** Param decorator that resolves the authenticated principal from the request. */\nexport const CurrentUser = createParamDecorator(\n (\n _data: unknown,\n context: ExecutionContext,\n ): AuthenticatedIdentity | undefined => {\n const req = context.switchToHttp().getRequest<RequestWithIdentity>();\n return req.identity;\n },\n);\n\n/**\n * NestJS module exposing the identity service plus guards. Register once at the root:\n *\n * ```ts\n * IdentityModule.forRoot({ service: createIdentityService(config, store) })\n * ```\n */\nfunction buildControllers(routes: true | IdentityRoutesOptions | undefined) {\n if (!routes) return [];\n const routesOpts = routes === true ? {} : routes;\n const prefix = routesOpts.prefix ?? \"auth\";\n const controllerOpts: IdentityControllerOptions = {\n cookie: routesOpts.cookie,\n };\n return [createIdentityController(prefix, controllerOpts)];\n}\n\nexport class IdentityModule {\n static forRoot(options: IdentityModuleOptions): DynamicModule {\n return {\n module: IdentityModule,\n global: true,\n controllers: buildControllers(options.routes),\n providers: [\n { provide: IDENTITY_SERVICE, useValue: options.service },\n IdentityAuthGuard,\n IdentityAuthorizationGuard,\n ],\n exports: [\n IDENTITY_SERVICE,\n IdentityAuthGuard,\n IdentityAuthorizationGuard,\n ],\n };\n }\n\n static forRootAsync(options: IdentityModuleAsyncOptions): DynamicModule {\n return {\n module: IdentityModule,\n global: true,\n imports: options.imports ?? [],\n controllers: buildControllers(options.routes),\n providers: [\n {\n provide: IDENTITY_SERVICE,\n useFactory: options.useFactory,\n inject: options.inject as never[],\n },\n IdentityAuthGuard,\n IdentityAuthorizationGuard,\n ],\n exports: [\n IDENTITY_SERVICE,\n IdentityAuthGuard,\n IdentityAuthorizationGuard,\n ],\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAS,kBAAkB,MAAoC;CAC7D,OAAO,KAAK,QAAQ;AACtB;AAEA,SAAS,cAAc,KAAqB;CAC1C,IAAI,eAAe,eACjB,MAAM,IAAI,cACR;EAAE,MAAM,IAAI;EAAM,SAAS,IAAI;CAAQ,GACvC,IAAI,UACN;CAEF,MAAM;AACR;AAEA,SAAS,8BACP,KACA,QACA,MAC4D;CAC5D,MAAM,SAAS,OAAO,sBAAsB,QAAQ,IAAI,KAAK,IAAI;CACjE,IAAI,OAAO,kBAAkB,IAAI,GAAG,OAAO,cAAc;EACvD,UAAU,KAAK,YAAY;EAC3B,QAAQ,KAAK,UAAU,QAAQ,IAAI,aAAa;EAChD,UAAU,KAAK,YAAY;EAC3B,MAAM,KAAK,QAAQ;EACnB,QAAQ,KAAK;EACb;CACF,CAAC;CACD,MAAM,EACJ,cAAc,KACd,uBAAuB,MACvB,GAAG,eACD;CACJ,OAAO;AACT;AAEA,SAAS,kBACP,QACA,YACA,KACA;CACA,IAAI,YAAY;EACd,MAAM,SAAS,8BACb,KACA,OAAO,QACP,UACF;EACA,OAAO;GAAE,MAAM,OAAO;GAAM;EAAO;CACrC;CACA,OAAO;AACT;AAEA,SAAS,mBACP,QACA,YACA,KACA;CACA,IAAI,cAAc,QAChB,OAAO;CAET,OAAO,kBAAkB,QAAQ,YAAY,GAAG;AAClD;AAEA,SAAS,4BACP,KACA,YACoB;CACpB,IAAI,YAEF,OADgB,IAAI,UACH,kBAAkB,UAAU;CAG/C,MAAM,QADO,IAAI,OACI;CACrB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AEvB,OACA,YACsC;CAEtC,OADY,QAAQ,aAAa,CAAC,CAAC,WAC1B,CAAC,CAAC;AACb,CACF;;;;;;;;AASA,SAAS,iBAAiB,QAAkD;CAC1E,IAAI,CAAC,QAAQ,OAAO,CAAC;CACrB,MAAM,aAAa,WAAW,OAAO,CAAC,IAAI;CAK1C,OAAO,CAAC,yBAJO,WAAW,UAAU,QAIK,EAFvC,QAAQ,WAAW,OAEiC,CAAC,CAAC;AAC1D;AAEA,IAAa,iBAAb,MAAa,eAAe;CAC1B,OAAO,QAAQ,SAA+C;EAC5D,OAAO;GACL,QAAQ;GACR,QAAQ;GACR,aAAa,iBAAiB,QAAQ,MAAM;GAC5C,WAAW;IACT;KAAE,SAAS;KAAkB,UAAU,QAAQ;IAAQ;IACvD;IACA;GACF;GACA,SAAS;IACP;IACA;IACA;GACF;EACF;CACF;CAEA,OAAO,aAAa,SAAoD;EACtE,OAAO;GACL,QAAQ;GACR,QAAQ;GACR,SAAS,QAAQ,WAAW,CAAC;GAC7B,aAAa,iBAAiB,QAAQ,MAAM;GAC5C,WAAW;IACT;KACE,SAAS;KACT,YAAY,QAAQ;KACpB,QAAQ,QAAQ;IAClB;IACA;IACA;GACF;GACA,SAAS;IACP;IACA;IACA;GACF;EACF;CACF;AACF"}
package/dist/next.cjs ADDED
@@ -0,0 +1,285 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_errors = require("./errors-Bcjx9o6g.cjs");
3
+ const require_cookie_header = require("./cookie-header-Dqd5k5BU.cjs");
4
+ //#region core/next/cookies.ts
5
+ function maxAgeSeconds(expiresAt, now) {
6
+ return Math.max(0, Math.floor((expiresAt.getTime() - now.getTime()) / 1e3));
7
+ }
8
+ function writeAttributes(options, expiresAt, now) {
9
+ const attrs = require_cookie_header.resolveCookieAttributes(options);
10
+ return {
11
+ httpOnly: attrs.httpOnly,
12
+ secure: attrs.secure,
13
+ sameSite: attrs.sameSite,
14
+ path: attrs.path,
15
+ domain: attrs.domain,
16
+ maxAge: maxAgeSeconds(expiresAt, now),
17
+ expires: expiresAt
18
+ };
19
+ }
20
+ /**
21
+ * Writes the access and refresh tokens as HttpOnly cookies.
22
+ * `maxAge` is in seconds (Next.js / `Set-Cookie` convention).
23
+ */
24
+ function applyAuthCookies(cookies, tokens, options = {}, now = /* @__PURE__ */ new Date()) {
25
+ const names = require_cookie_header.resolveCookieNames(options);
26
+ cookies.set(names.access, tokens.accessToken, writeAttributes(options, tokens.accessTokenExpiresAt, now));
27
+ cookies.set(names.refresh, tokens.refreshToken, writeAttributes(options, tokens.refreshTokenExpiresAt, now));
28
+ }
29
+ /** Clears both identity cookies (logout or failed session). */
30
+ function clearAuthCookies(cookies, options = {}) {
31
+ const names = require_cookie_header.resolveCookieNames(options);
32
+ const attrs = require_cookie_header.resolveCookieAttributes(options);
33
+ const deleteOpts = {
34
+ path: attrs.path,
35
+ domain: attrs.domain
36
+ };
37
+ cookies.delete(names.access, deleteOpts);
38
+ cookies.delete(names.refresh, deleteOpts);
39
+ }
40
+ /**
41
+ * In-memory {@link CookieStore} for tests and Fetch-based Route Handlers.
42
+ * Not for production browser storage.
43
+ */
44
+ function createMemoryCookieStore(initial = {}) {
45
+ const values = new Map(Object.entries(initial).filter(([, value]) => value.length > 0));
46
+ return {
47
+ get(name) {
48
+ const value = values.get(name);
49
+ return value === void 0 ? void 0 : { value };
50
+ },
51
+ set(name, value) {
52
+ if (value.length === 0) {
53
+ values.delete(name);
54
+ return;
55
+ }
56
+ values.set(name, value);
57
+ },
58
+ delete(name) {
59
+ values.delete(name);
60
+ }
61
+ };
62
+ }
63
+ /** Builds a cookie store seeded from an incoming `Cookie` header. */
64
+ function cookieStoreFromHeader(header) {
65
+ return createMemoryCookieStore(Object.fromEntries(require_cookie_header.parseCookieHeader(header)));
66
+ }
67
+ //#endregion
68
+ //#region core/next/session.ts
69
+ /**
70
+ * Resolves the current principal from identity cookies.
71
+ *
72
+ * - Valid access cookie → `service.authenticate`.
73
+ * - Expired/missing access + refresh cookie → `service.refresh` and rotate cookies.
74
+ * - Failure → clear cookies and return `null` (degrade to logged out).
75
+ *
76
+ * Call this where cookies can be written (Server Actions, Route Handlers). Refresh
77
+ * rotates the refresh token; skipping the write would invalidate the browser session.
78
+ */
79
+ async function getIdentity(service, cookies, options = {}) {
80
+ const names = require_cookie_header.resolveCookieNames(options);
81
+ const access = require_cookie_header.readCookieValue(cookies, names.access);
82
+ const refresh = require_cookie_header.readCookieValue(cookies, names.refresh);
83
+ if (access) try {
84
+ return await service.authenticate(access);
85
+ } catch (error) {
86
+ if (error instanceof require_errors.AccountUnavailableError) {
87
+ clearAuthCookies(cookies, options);
88
+ return null;
89
+ }
90
+ if (!(error instanceof require_errors.InvalidTokenError)) throw error;
91
+ }
92
+ if (!refresh) {
93
+ if (access) clearAuthCookies(cookies, options);
94
+ return null;
95
+ }
96
+ try {
97
+ const result = await service.refresh(refresh);
98
+ applyAuthCookies(cookies, result.tokens, options);
99
+ return result.user;
100
+ } catch (error) {
101
+ clearAuthCookies(cookies, options);
102
+ if (error instanceof require_errors.InvalidTokenError || error instanceof require_errors.AccountUnavailableError) return null;
103
+ throw error;
104
+ }
105
+ }
106
+ //#endregion
107
+ //#region core/next/handlers.ts
108
+ function json(body, status, cookies) {
109
+ const headers = new Headers({ "content-type": "application/json" });
110
+ if (cookies) for (const header of cookies.headers) headers.append("set-cookie", header);
111
+ return new Response(JSON.stringify(body), {
112
+ status,
113
+ headers
114
+ });
115
+ }
116
+ function errorResponse(error) {
117
+ if (error instanceof require_errors.IdentityError) return json({
118
+ code: error.code,
119
+ message: error.message
120
+ }, error.statusCode);
121
+ throw error;
122
+ }
123
+ function serializeSetCookie(cookie) {
124
+ const parts = [`${cookie.name}=${encodeURIComponent(cookie.value)}`];
125
+ const opts = cookie.options ?? {};
126
+ if (opts.maxAge !== void 0) parts.push(`Max-Age=${Math.max(0, Math.floor(opts.maxAge))}`);
127
+ if (opts.expires) parts.push(`Expires=${opts.expires.toUTCString()}`);
128
+ parts.push(`Path=${opts.path ?? "/"}`);
129
+ if (opts.domain) parts.push(`Domain=${opts.domain}`);
130
+ if (opts.httpOnly !== false) parts.push("HttpOnly");
131
+ if (opts.secure) parts.push("Secure");
132
+ const sameSite = opts.sameSite ?? "lax";
133
+ parts.push(`SameSite=${sameSite.charAt(0).toUpperCase()}${sameSite.slice(1)}`);
134
+ return parts.join("; ");
135
+ }
136
+ function recordingStore(header) {
137
+ const inner = cookieStoreFromHeader(header);
138
+ const writes = [];
139
+ const deleted = [];
140
+ const expired = /* @__PURE__ */ new Date(0);
141
+ return {
142
+ store: {
143
+ get: inner.get.bind(inner),
144
+ set(name, value, options) {
145
+ inner.set(name, value, options);
146
+ writes.push({
147
+ name,
148
+ value,
149
+ options
150
+ });
151
+ },
152
+ delete(name, options) {
153
+ inner.delete(name, options);
154
+ deleted.push({
155
+ name,
156
+ value: "",
157
+ options: {
158
+ ...options,
159
+ maxAge: 0,
160
+ expires: expired
161
+ }
162
+ });
163
+ }
164
+ },
165
+ headers() {
166
+ return [...writes.map(serializeSetCookie), ...deleted.map(serializeSetCookie)];
167
+ }
168
+ };
169
+ }
170
+ async function readJsonBody(request) {
171
+ try {
172
+ const body = await request.json();
173
+ if (typeof body === "object" && body !== null && !Array.isArray(body)) return body;
174
+ return {};
175
+ } catch {
176
+ return {};
177
+ }
178
+ }
179
+ function actionFromUrl(url, prefix) {
180
+ const pathname = new URL(url).pathname.replace(/\/+$/, "");
181
+ const normalizedPrefix = prefix.replace(/^\/+|\/+$/g, "");
182
+ if (normalizedPrefix) {
183
+ const marker = `/${normalizedPrefix}/`;
184
+ const idx = pathname.lastIndexOf(marker);
185
+ if (idx >= 0) return pathname.slice(idx + marker.length);
186
+ }
187
+ const slash = pathname.lastIndexOf("/");
188
+ return slash >= 0 ? pathname.slice(slash + 1) : pathname;
189
+ }
190
+ function createIdentityHandlers(service, options = {}) {
191
+ const prefix = options.prefix ?? "";
192
+ const names = require_cookie_header.resolveCookieNames(options);
193
+ const login = async (request) => {
194
+ try {
195
+ const body = await readJsonBody(request);
196
+ const email = typeof body.email === "string" ? body.email : "";
197
+ const password = typeof body.password === "string" ? body.password : "";
198
+ const result = await service.login({
199
+ email,
200
+ password
201
+ });
202
+ if ("kind" in result) return json(result, 200);
203
+ const recorded = recordingStore(request.headers.get("cookie"));
204
+ applyAuthCookies(recorded.store, result.tokens, options);
205
+ return json({ user: result.user }, 200, { headers: recorded.headers() });
206
+ } catch (error) {
207
+ return errorResponse(error);
208
+ }
209
+ };
210
+ const logout = async (request) => {
211
+ try {
212
+ const recorded = recordingStore(request.headers.get("cookie"));
213
+ const refresh = require_cookie_header.readCookieValue(recorded.store, names.refresh);
214
+ if (refresh) await service.logout(refresh);
215
+ clearAuthCookies(recorded.store, options);
216
+ return json({ ok: true }, 200, { headers: recorded.headers() });
217
+ } catch (error) {
218
+ return errorResponse(error);
219
+ }
220
+ };
221
+ const refresh = async (request) => {
222
+ try {
223
+ const recorded = recordingStore(request.headers.get("cookie"));
224
+ const token = require_cookie_header.readCookieValue(recorded.store, names.refresh);
225
+ if (!token) throw new require_errors.InvalidTokenError();
226
+ const result = await service.refresh(token);
227
+ applyAuthCookies(recorded.store, result.tokens, options);
228
+ return json({ user: result.user }, 200, { headers: recorded.headers() });
229
+ } catch (error) {
230
+ const recorded = recordingStore(request.headers.get("cookie"));
231
+ clearAuthCookies(recorded.store, options);
232
+ if (error instanceof require_errors.IdentityError) return json({
233
+ code: error.code,
234
+ message: error.message
235
+ }, error.statusCode, { headers: recorded.headers() });
236
+ throw error;
237
+ }
238
+ };
239
+ const me = async (request) => {
240
+ try {
241
+ const recorded = recordingStore(request.headers.get("cookie"));
242
+ const identity = await getIdentity(service, recorded.store, options);
243
+ if (!identity) return json({
244
+ code: "identity/unauthenticated",
245
+ message: "Authentication is required."
246
+ }, 401, { headers: recorded.headers() });
247
+ return json({ user: identity }, 200, { headers: recorded.headers() });
248
+ } catch (error) {
249
+ return errorResponse(error);
250
+ }
251
+ };
252
+ const dispatch = async (request) => {
253
+ const action = actionFromUrl(request.url, prefix);
254
+ const method = request.method.toUpperCase();
255
+ if (method === "POST" && action === "login") return login(request);
256
+ if (method === "POST" && action === "logout") return logout(request);
257
+ if (method === "POST" && action === "refresh") return refresh(request);
258
+ if (method === "GET" && action === "me") return me(request);
259
+ return json({
260
+ code: "identity/not-found",
261
+ message: "Not found."
262
+ }, 404);
263
+ };
264
+ return {
265
+ login,
266
+ logout,
267
+ refresh,
268
+ me,
269
+ dispatch
270
+ };
271
+ }
272
+ //#endregion
273
+ exports.DEFAULT_ACCESS_COOKIE = require_cookie_header.DEFAULT_ACCESS_COOKIE;
274
+ exports.DEFAULT_REFRESH_COOKIE = require_cookie_header.DEFAULT_REFRESH_COOKIE;
275
+ exports.applyAuthCookies = applyAuthCookies;
276
+ exports.clearAuthCookies = clearAuthCookies;
277
+ exports.cookieStoreFromHeader = cookieStoreFromHeader;
278
+ exports.createIdentityHandlers = createIdentityHandlers;
279
+ exports.createMemoryCookieStore = createMemoryCookieStore;
280
+ exports.getIdentity = getIdentity;
281
+ exports.hasIdentityCookies = require_cookie_header.hasIdentityCookies;
282
+ exports.parseCookieHeader = require_cookie_header.parseCookieHeader;
283
+ exports.readCookieValue = require_cookie_header.readCookieValue;
284
+ exports.resolveCookieAttributes = require_cookie_header.resolveCookieAttributes;
285
+ exports.resolveCookieNames = require_cookie_header.resolveCookieNames;
@@ -0,0 +1,58 @@
1
+ import { d as AuthenticatedIdentity, u as AuthTokens } from "./identity-store-BRRahxcS.cjs";
2
+ import { t as IdentityService } from "./identity-service-DE0Ffguz.cjs";
3
+ import { a as DEFAULT_ACCESS_COOKIE, c as IdentityCookieNames, d as parseCookieHeader, f as readCookieValue, i as CookieWriter, l as IdentityCookieOptions, m as resolveCookieNames, n as CookieSource, o as DEFAULT_REFRESH_COOKIE, p as resolveCookieAttributes, r as CookieStore, s as IdentityCookieAttributes, t as CookieReader, u as hasIdentityCookies } from "./cookie-header-LFWHKQ04.cjs";
4
+ //#region core/next/cookies.d.ts
5
+ /**
6
+ * Writes the access and refresh tokens as HttpOnly cookies.
7
+ * `maxAge` is in seconds (Next.js / `Set-Cookie` convention).
8
+ */
9
+ declare function applyAuthCookies(cookies: CookieWriter, tokens: AuthTokens, options?: IdentityCookieOptions, now?: Date): void;
10
+ /** Clears both identity cookies (logout or failed session). */
11
+ declare function clearAuthCookies(cookies: CookieWriter, options?: IdentityCookieOptions): void;
12
+ /**
13
+ * In-memory {@link CookieStore} for tests and Fetch-based Route Handlers.
14
+ * Not for production browser storage.
15
+ */
16
+ declare function createMemoryCookieStore(initial?: Record<string, string>): CookieStore;
17
+ /** Builds a cookie store seeded from an incoming `Cookie` header. */
18
+ declare function cookieStoreFromHeader(header: string | null | undefined): CookieStore;
19
+ //#endregion
20
+ //#region core/next/session.d.ts
21
+ /** Subset of {@link IdentityService} used to read and rotate a cookie session. */
22
+ type IdentitySessionService = Pick<IdentityService, "authenticate" | "refresh">;
23
+ /**
24
+ * Resolves the current principal from identity cookies.
25
+ *
26
+ * - Valid access cookie → `service.authenticate`.
27
+ * - Expired/missing access + refresh cookie → `service.refresh` and rotate cookies.
28
+ * - Failure → clear cookies and return `null` (degrade to logged out).
29
+ *
30
+ * Call this where cookies can be written (Server Actions, Route Handlers). Refresh
31
+ * rotates the refresh token; skipping the write would invalidate the browser session.
32
+ */
33
+ declare function getIdentity(service: IdentitySessionService, cookies: CookieStore, options?: IdentityCookieOptions): Promise<AuthenticatedIdentity | null>;
34
+ //#endregion
35
+ //#region core/next/handlers.d.ts
36
+ interface IdentityHandlerOptions extends IdentityCookieOptions {
37
+ /**
38
+ * Path prefix used by {@link createIdentityHandlers.dispatch} to match routes.
39
+ * Default: `""` (last path segment is the action: `login`, `logout`, …).
40
+ */
41
+ prefix?: string;
42
+ }
43
+ /**
44
+ * Fetch API Route Handlers for cookie-based identity sessions (Next.js App Router).
45
+ *
46
+ * Mount individually or use {@link IdentityHandlers.dispatch} from a catch-all route.
47
+ */
48
+ interface IdentityHandlers {
49
+ login(request: Request): Promise<Response>;
50
+ logout(request: Request): Promise<Response>;
51
+ refresh(request: Request): Promise<Response>;
52
+ me(request: Request): Promise<Response>;
53
+ dispatch(request: Request): Promise<Response>;
54
+ }
55
+ declare function createIdentityHandlers(service: IdentityService, options?: IdentityHandlerOptions): IdentityHandlers;
56
+ //#endregion
57
+ export { type CookieReader, type CookieSource, type CookieStore, type CookieWriter, DEFAULT_ACCESS_COOKIE, DEFAULT_REFRESH_COOKIE, type IdentityCookieAttributes, type IdentityCookieNames, type IdentityCookieOptions, type IdentityHandlerOptions, type IdentityHandlers, type IdentitySessionService, applyAuthCookies, clearAuthCookies, cookieStoreFromHeader, createIdentityHandlers, createMemoryCookieStore, getIdentity, hasIdentityCookies, parseCookieHeader, readCookieValue, resolveCookieAttributes, resolveCookieNames };
58
+ //# sourceMappingURL=next.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"next.d.cts","names":[],"sources":["../core/next/cookies.ts","../core/next/session.ts","../core/next/handlers.ts"],"mappings":";;;;;;;;iBAqCgB,iBACd,SAAS,cACT,QAAQ,YACR,UAAS,uBACT,MAAK;;iBAgBS,iBACd,SAAS,cACT,UAAS;;;;;iBAaK,wBACd,UAAS,yBACR;;iBAuBa,sBACd,oCACC;;;;KCvFS,yBAAyB,KACnC;;;;;;;;;;;iBAcoB,YACpB,SAAS,wBACT,SAAS,aACT,UAAS,wBACR,QAAQ;;;UCrBM,+BAA+B;;;;;EAK9C;;;;;;;UAwHe;EACf,MAAM,SAAS,UAAU,QAAQ;EACjC,OAAO,SAAS,UAAU,QAAQ;EAClC,QAAQ,SAAS,UAAU,QAAQ;EACnC,GAAG,SAAS,UAAU,QAAQ;EAC9B,SAAS,SAAS,UAAU,QAAQ;;iBAGtB,uBACd,SAAS,iBACT,UAAS,yBACR"}
@@ -0,0 +1,58 @@
1
+ import { d as AuthenticatedIdentity, u as AuthTokens } from "./identity-store-BRRahxcS.mjs";
2
+ import { t as IdentityService } from "./identity-service-JtsoA6lv.mjs";
3
+ import { a as DEFAULT_ACCESS_COOKIE, c as IdentityCookieNames, d as parseCookieHeader, f as readCookieValue, i as CookieWriter, l as IdentityCookieOptions, m as resolveCookieNames, n as CookieSource, o as DEFAULT_REFRESH_COOKIE, p as resolveCookieAttributes, r as CookieStore, s as IdentityCookieAttributes, t as CookieReader, u as hasIdentityCookies } from "./cookie-header-LFWHKQ04.mjs";
4
+ //#region core/next/cookies.d.ts
5
+ /**
6
+ * Writes the access and refresh tokens as HttpOnly cookies.
7
+ * `maxAge` is in seconds (Next.js / `Set-Cookie` convention).
8
+ */
9
+ declare function applyAuthCookies(cookies: CookieWriter, tokens: AuthTokens, options?: IdentityCookieOptions, now?: Date): void;
10
+ /** Clears both identity cookies (logout or failed session). */
11
+ declare function clearAuthCookies(cookies: CookieWriter, options?: IdentityCookieOptions): void;
12
+ /**
13
+ * In-memory {@link CookieStore} for tests and Fetch-based Route Handlers.
14
+ * Not for production browser storage.
15
+ */
16
+ declare function createMemoryCookieStore(initial?: Record<string, string>): CookieStore;
17
+ /** Builds a cookie store seeded from an incoming `Cookie` header. */
18
+ declare function cookieStoreFromHeader(header: string | null | undefined): CookieStore;
19
+ //#endregion
20
+ //#region core/next/session.d.ts
21
+ /** Subset of {@link IdentityService} used to read and rotate a cookie session. */
22
+ type IdentitySessionService = Pick<IdentityService, "authenticate" | "refresh">;
23
+ /**
24
+ * Resolves the current principal from identity cookies.
25
+ *
26
+ * - Valid access cookie → `service.authenticate`.
27
+ * - Expired/missing access + refresh cookie → `service.refresh` and rotate cookies.
28
+ * - Failure → clear cookies and return `null` (degrade to logged out).
29
+ *
30
+ * Call this where cookies can be written (Server Actions, Route Handlers). Refresh
31
+ * rotates the refresh token; skipping the write would invalidate the browser session.
32
+ */
33
+ declare function getIdentity(service: IdentitySessionService, cookies: CookieStore, options?: IdentityCookieOptions): Promise<AuthenticatedIdentity | null>;
34
+ //#endregion
35
+ //#region core/next/handlers.d.ts
36
+ interface IdentityHandlerOptions extends IdentityCookieOptions {
37
+ /**
38
+ * Path prefix used by {@link createIdentityHandlers.dispatch} to match routes.
39
+ * Default: `""` (last path segment is the action: `login`, `logout`, …).
40
+ */
41
+ prefix?: string;
42
+ }
43
+ /**
44
+ * Fetch API Route Handlers for cookie-based identity sessions (Next.js App Router).
45
+ *
46
+ * Mount individually or use {@link IdentityHandlers.dispatch} from a catch-all route.
47
+ */
48
+ interface IdentityHandlers {
49
+ login(request: Request): Promise<Response>;
50
+ logout(request: Request): Promise<Response>;
51
+ refresh(request: Request): Promise<Response>;
52
+ me(request: Request): Promise<Response>;
53
+ dispatch(request: Request): Promise<Response>;
54
+ }
55
+ declare function createIdentityHandlers(service: IdentityService, options?: IdentityHandlerOptions): IdentityHandlers;
56
+ //#endregion
57
+ export { type CookieReader, type CookieSource, type CookieStore, type CookieWriter, DEFAULT_ACCESS_COOKIE, DEFAULT_REFRESH_COOKIE, type IdentityCookieAttributes, type IdentityCookieNames, type IdentityCookieOptions, type IdentityHandlerOptions, type IdentityHandlers, type IdentitySessionService, applyAuthCookies, clearAuthCookies, cookieStoreFromHeader, createIdentityHandlers, createMemoryCookieStore, getIdentity, hasIdentityCookies, parseCookieHeader, readCookieValue, resolveCookieAttributes, resolveCookieNames };
58
+ //# sourceMappingURL=next.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"next.d.mts","names":[],"sources":["../core/next/cookies.ts","../core/next/session.ts","../core/next/handlers.ts"],"mappings":";;;;;;;;iBAqCgB,iBACd,SAAS,cACT,QAAQ,YACR,UAAS,uBACT,MAAK;;iBAgBS,iBACd,SAAS,cACT,UAAS;;;;;iBAaK,wBACd,UAAS,yBACR;;iBAuBa,sBACd,oCACC;;;;KCvFS,yBAAyB,KACnC;;;;;;;;;;;iBAcoB,YACpB,SAAS,wBACT,SAAS,aACT,UAAS,wBACR,QAAQ;;;UCrBM,+BAA+B;;;;;EAK9C;;;;;;;UAwHe;EACf,MAAM,SAAS,UAAU,QAAQ;EACjC,OAAO,SAAS,UAAU,QAAQ;EAClC,QAAQ,SAAS,UAAU,QAAQ;EACnC,GAAG,SAAS,UAAU,QAAQ;EAC9B,SAAS,SAAS,UAAU,QAAQ;;iBAGtB,uBACd,SAAS,iBACT,UAAS,yBACR"}