@azlib/identity 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +44 -0
- package/dist/{errors-C2xZAatu.d.cts → errors-CBbiRO2n.d.cts} +1 -2
- package/dist/errors-CBbiRO2n.d.cts.map +1 -0
- package/dist/{errors-BGMwaW5s.d.mts → errors-_OcodtdV.d.mts} +1 -2
- package/dist/errors-_OcodtdV.d.mts.map +1 -0
- package/dist/express.cjs +34 -0
- package/dist/express.d.cts +5 -6
- package/dist/express.d.cts.map +1 -1
- package/dist/express.d.mts +5 -6
- package/dist/express.d.mts.map +1 -1
- package/dist/express.mjs +34 -1
- package/dist/express.mjs.map +1 -1
- package/dist/identity-Bz9RDOvT.mjs.map +1 -1
- package/dist/{identity-router-DBL20UWT.d.mts → identity-router-D1xJ5H7y.d.cts} +22 -6
- package/dist/identity-router-D1xJ5H7y.d.cts.map +1 -0
- package/dist/{identity-router-Dib30Waj.d.cts → identity-router-tj3-teBI.d.mts} +22 -6
- package/dist/identity-router-tj3-teBI.d.mts.map +1 -0
- package/dist/{identity-service-CLzKx8Z7.d.cts → identity-service---OTann1.d.cts} +2 -3
- package/dist/identity-service---OTann1.d.cts.map +1 -0
- package/dist/{identity-service-B9zrvE9z.d.mts → identity-service-WpOKb0MK.d.mts} +2 -3
- package/dist/identity-service-WpOKb0MK.d.mts.map +1 -0
- package/dist/identity-store-BRRahxcS.d.cts.map +1 -1
- package/dist/identity-store-BRRahxcS.d.mts.map +1 -1
- package/dist/index-CpufYgyn.d.cts.map +1 -1
- package/dist/index-CpufYgyn.d.mts.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/nestjs.cjs +4 -5
- package/dist/nestjs.d.cts +3 -4
- package/dist/nestjs.d.cts.map +1 -1
- package/dist/nestjs.d.mts +3 -4
- package/dist/nestjs.d.mts.map +1 -1
- package/dist/nestjs.mjs +4 -5
- package/dist/nestjs.mjs.map +1 -1
- package/dist/node.d.cts +2 -3
- package/dist/node.d.cts.map +1 -1
- package/dist/node.d.mts +2 -3
- package/dist/node.d.mts.map +1 -1
- package/dist/node.mjs.map +1 -1
- package/dist/test-utils.d.cts +0 -1
- package/dist/test-utils.d.cts.map +1 -1
- package/dist/test-utils.d.mts +0 -1
- package/dist/test-utils.d.mts.map +1 -1
- package/package.json +12 -12
- package/dist/errors-BGMwaW5s.d.mts.map +0 -1
- package/dist/errors-C2xZAatu.d.cts.map +0 -1
- package/dist/identity-router-DBL20UWT.d.mts.map +0 -1
- package/dist/identity-router-Dib30Waj.d.cts.map +0 -1
- package/dist/identity-service-B9zrvE9z.d.mts.map +0 -1
- package/dist/identity-service-CLzKx8Z7.d.cts.map +0 -1
package/README.md
CHANGED
|
@@ -377,6 +377,50 @@ createIdentityService(
|
|
|
377
377
|
mitigate account enumeration, and pays the hash-verification cost even for unknown users.
|
|
378
378
|
- Tokens carry an `authVersion`; bump a user's version to invalidate all outstanding tokens.
|
|
379
379
|
|
|
380
|
+
## AI Agent Quick Reference
|
|
381
|
+
|
|
382
|
+
### Core Exports
|
|
383
|
+
|
|
384
|
+
| Entry Point / Import | Export | Type | Description |
|
|
385
|
+
| --- | --- | --- | --- |
|
|
386
|
+
| `@azlib/identity` | `evaluateAuthorization` | Function | Evaluates custom permission requirements against a user principal. |
|
|
387
|
+
| `@azlib/identity` | `identitySchemaModel` | Object | Relation structures and constraints definitions. |
|
|
388
|
+
| `@azlib/identity/node` | `createIdentityService` | Function | Instantiates the core user authentication / registration service. |
|
|
389
|
+
| `@azlib/identity/node` | `createGoogleOAuthProvider` | Function | Factory for Google OAuth provider link configurations. |
|
|
390
|
+
| `@azlib/identity/express` | `createIdentityRouter` | Function | Mountable Express router containing all login/register endpoints. |
|
|
391
|
+
| `@azlib/identity/express` | `requireAuth` | Middleware | Express middleware checking request Bearer token authorization. |
|
|
392
|
+
| `@azlib/identity/express` | `requirePermission` | Middleware | Express middleware restricting actions to specific permissions. |
|
|
393
|
+
| `@azlib/identity/nestjs` | `IdentityModule` | NestJS Module | Core NestJS DI registration boundary. |
|
|
394
|
+
|
|
395
|
+
### Core Types
|
|
396
|
+
|
|
397
|
+
- `IdentityService`:
|
|
398
|
+
- `register(payload: RegisterInput): Promise<IdentitySession>`
|
|
399
|
+
- `login(payload: LoginInput): Promise<IdentitySession>`
|
|
400
|
+
- `refresh(refreshToken: string): Promise<IdentitySession>`
|
|
401
|
+
- `logout(refreshToken: string): Promise<void>`
|
|
402
|
+
- `evaluateAuthorization(requirement: AuthRequirement, principal: AuthenticatedIdentity): Promise<boolean>`
|
|
403
|
+
- `IdentityStore`: Database persistence contract including `findUserById`, `findUserByEmail`, `saveUser`, `incrementFailedLoginAttempts`, `resetFailedLoginAttempts`, `lockAccount`, `saveSession`, `findSessionByTokenHash`, `revokeSession`.
|
|
404
|
+
|
|
405
|
+
### Common Integration Flow
|
|
406
|
+
|
|
407
|
+
```ts
|
|
408
|
+
import { createIdentityService } from "@azlib/identity/node";
|
|
409
|
+
import { createIdentityRouter } from "@azlib/identity/express";
|
|
410
|
+
|
|
411
|
+
const service = createIdentityService({
|
|
412
|
+
accessTokenSecret: process.env.ACCESS_TOKEN_SECRET!,
|
|
413
|
+
lockout: { maxFailedAttempts: 5, durationSeconds: 900 }
|
|
414
|
+
}, myDatabaseStore);
|
|
415
|
+
|
|
416
|
+
app.use("/auth", createIdentityRouter(service));
|
|
417
|
+
```
|
|
418
|
+
|
|
419
|
+
### Behavioral Gotchas
|
|
420
|
+
- **Deny-by-Default**: Principals have no permissions by default. Access must be explicitly granted via roles or direct grants.
|
|
421
|
+
- **Scrypt Password Hashing**: Hashing is computational and synchronous. Avoid calling login in high-throughput loops without caching/throttling.
|
|
422
|
+
- **Refresh Token Rotation**: Refresh tokens are single-use. Re-using an old token immediately revokes all sessions associated with that user.
|
|
423
|
+
|
|
380
424
|
## Status
|
|
381
425
|
|
|
382
426
|
This package is under active implementation. See
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { c as AuthResult, d as AuthenticatedIdentity, h as IdentityEventType, m as IdentityEvent, r as IdentityStore, s as AccessTokenClaims, x as Permission } from "./identity-store-BRRahxcS.cjs";
|
|
2
|
-
|
|
3
2
|
//#region core/authorization.d.ts
|
|
4
3
|
/**
|
|
5
4
|
* Context passed to authorization checks. `resource` is an opaque consumer-supplied
|
|
@@ -478,4 +477,4 @@ declare class AccountUnavailableError extends IdentityError {
|
|
|
478
477
|
}
|
|
479
478
|
//#endregion
|
|
480
479
|
export { resolveIdentityConfig as A, AuthorizationDecision as B, createTokenService as C, IdentityConfigInput as D, IdentityConfig as E, IdentityLogger as F, PolicyRule as H, consoleLogger as I, noopLogger as L, NotificationService as M, PasswordResetParams as N, IdentityOverrides as O, TwoFactorSmsParams as P, resolveLogger as R, TokenService as S, createAuditLogger as T, evaluateAuthorization as U, AuthorizationRequirement as V, isAuthorized as W, ExchangeCodeParams as _, IdentityError as a, OAuthUserInfo as b, UnauthenticatedError as c, OAuthProviderNotFoundError as d, OAuthService as f, BuildAuthUrlParams as g, createOAuthService as h, IdentityConfigError as i, EmailVerificationParams as j, LockoutConfig as k, OAuthAuthorizationUrl as l, OAuthStateMismatchError as m, EmailAlreadyRegisteredError as n, InvalidCredentialsError as o, OAuthServiceDeps as p, ForbiddenError as r, InvalidTokenError as s, AccountUnavailableError as t, OAuthCallbackParams as u, OAuthProvider as v, AuditLogger as w, SessionDeps as x, OAuthTokens as y, AuthorizationContext as z };
|
|
481
|
-
//# sourceMappingURL=errors-
|
|
480
|
+
//# sourceMappingURL=errors-CBbiRO2n.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-CBbiRO2n.d.cts","names":[],"sources":["../core/authorization.ts","../core/logger.ts","../core/notification.ts","../core/config.ts","../core/audit.ts","../core/token-service.ts","../core/session-state.ts","../core/oauth/oauth-provider.ts","../core/oauth/oauth-service.ts","../core/errors.ts"],"mappings":";;;;;;UAMiB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as IdentityStore, s as AccessTokenClaims, x as Permission } from "./identity-store-BRRahxcS.mjs";
|
|
2
|
-
|
|
3
2
|
//#region core/authorization.d.ts
|
|
4
3
|
/**
|
|
5
4
|
* Context passed to authorization checks. `resource` is an opaque consumer-supplied
|
|
@@ -478,4 +477,4 @@ declare class AccountUnavailableError extends IdentityError {
|
|
|
478
477
|
}
|
|
479
478
|
//#endregion
|
|
480
479
|
export { resolveIdentityConfig as A, AuthorizationDecision as B, createTokenService as C, IdentityConfigInput as D, IdentityConfig as E, IdentityLogger as F, PolicyRule as H, consoleLogger as I, noopLogger as L, NotificationService as M, PasswordResetParams as N, IdentityOverrides as O, TwoFactorSmsParams as P, resolveLogger as R, TokenService as S, createAuditLogger as T, evaluateAuthorization as U, AuthorizationRequirement as V, isAuthorized as W, ExchangeCodeParams as _, IdentityError as a, OAuthUserInfo as b, UnauthenticatedError as c, OAuthProviderNotFoundError as d, OAuthService as f, BuildAuthUrlParams as g, createOAuthService as h, IdentityConfigError as i, EmailVerificationParams as j, LockoutConfig as k, OAuthAuthorizationUrl as l, OAuthStateMismatchError as m, EmailAlreadyRegisteredError as n, InvalidCredentialsError as o, OAuthServiceDeps as p, ForbiddenError as r, InvalidTokenError as s, AccountUnavailableError as t, OAuthCallbackParams as u, OAuthProvider as v, AuditLogger as w, SessionDeps as x, OAuthTokens as y, AuthorizationContext as z };
|
|
481
|
-
//# sourceMappingURL=errors-
|
|
480
|
+
//# sourceMappingURL=errors-_OcodtdV.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-_OcodtdV.d.mts","names":[],"sources":["../core/authorization.ts","../core/logger.ts","../core/notification.ts","../core/config.ts","../core/audit.ts","../core/token-service.ts","../core/session-state.ts","../core/oauth/oauth-provider.ts","../core/oauth/oauth-service.ts","../core/errors.ts"],"mappings":";;;;;;UAMiB,qBAAqB;EACpC,WAAW;;EAEX;;EAEA,WAAW;;;;;;;;KASD,WAAW,wBACrB,SAAS,qBAA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AC3F,kBAAkB,gBAAgB,QAAQ;;;;;EAK1C,mBAAmB;IAAsB;IAAe;;;EAExD,eAAe;;EAEf,iBAAiB;;iBAMH,mBAAmB,QAAQ,iBAAiB;;;;UCtB3C;EACf,QAAQ;EACR,OAAO;EACP,cAAc;;;;;;;;;;;UCDC;EACf;;EAEA;EACA;;EAEA;EACA;EACA;;;;;;UAOe;;EAEf;EACA;;EAEA;EACA;;;UAIe;;EAEf;;;;;EAKA;;EAEA;;;UAIe;EACf;EACA;;;;;;UAOe;;;;;WAKN;;;;;;EAOT,sBAAsB,QAAQ;;;;;EAM9B,aAAa,QAAQ,qBAAqB,QAAQ;;;;;EAMlD,cAAc,QAAQ,cAAc,QAAQ;;;;;UCvE7B;;EAEf;;;;;EAKA;;;UAIe;;EAEf;;EAEA;;;;;EAKA;;EAEA;;EAEA;;;UAIe;;WAEN;;;;;EAMT,sBAAsB,sBAAsB,qBAAqB,oBAAoB;;;;;;;;EASrF,eAAe,sBAAsB,QAAQ,sBAAsB,QAAQ;;;cAIhE,mCAAmC;EAClC,YAAA;;;cAOD,gCAAgC;EAAA;;;UAQ5B;EACf,oBAAoB;EACpB,QAAQ;EACR,OAAO;EACP,aAAa;EACb,OAAO;;;;;;;iBAQO,mBAAmB,MAAM,mBAAmB;;;;;;;;;;cC9E/C,sBAAsB;;WAExB;;WAEA;EAEG,YAAA,cAAc,iBAAiB;;;cAShC,4BAA4B;EAC3B,YAAA;;;cAMD,gCAAgC;EAAA;;;cAOhC,oCAAoC;EAAA;;;cAWpC,0BAA0B;EACzB,YAAA;;;cAMD,6BAA6B;EAC5B,YAAA;;;cAMD,uBAAuB;EACtB,YAAA;;;cAMD,gCAAgC;EAC/B,YAAA"}
|
package/dist/express.cjs
CHANGED
|
@@ -396,8 +396,42 @@ function createIdentityRouter(service, options = {}) {
|
|
|
396
396
|
else outer.use(router);
|
|
397
397
|
return outer;
|
|
398
398
|
}
|
|
399
|
+
/**
|
|
400
|
+
* Factory that creates an Express error-handling middleware which converts
|
|
401
|
+
* {@link IdentityError} instances to structured JSON responses.
|
|
402
|
+
* Mount it after the identity router:
|
|
403
|
+
*
|
|
404
|
+
* ```ts
|
|
405
|
+
* app.use(createIdentityRouter(service, { prefix: "auth" }));
|
|
406
|
+
* app.use(identityErrorHandler()); // default console logger
|
|
407
|
+
* app.use(identityErrorHandler({ logger: false })); // silent
|
|
408
|
+
* ```
|
|
409
|
+
*
|
|
410
|
+
* @param options.logger - Logger for recording serialised error details.
|
|
411
|
+
* Pass `false` to disable. Defaults to the console logger.
|
|
412
|
+
*/
|
|
413
|
+
function identityErrorHandler(options = {}) {
|
|
414
|
+
const log = require_logger.resolveLogger(options.logger);
|
|
415
|
+
return (err, _req, res, next) => {
|
|
416
|
+
if (err instanceof require_errors.IdentityError) {
|
|
417
|
+
log.debug("identity error", {
|
|
418
|
+
code: err.code,
|
|
419
|
+
status: err.statusCode,
|
|
420
|
+
message: err.message
|
|
421
|
+
});
|
|
422
|
+
res.status(err.statusCode).json({
|
|
423
|
+
code: err.code,
|
|
424
|
+
message: err.message
|
|
425
|
+
});
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
log.error("unhandled error in identity router", { error: String(err) });
|
|
429
|
+
next(err);
|
|
430
|
+
};
|
|
431
|
+
}
|
|
399
432
|
//#endregion
|
|
400
433
|
exports.createIdentityRouter = createIdentityRouter;
|
|
434
|
+
exports.identityErrorHandler = identityErrorHandler;
|
|
401
435
|
exports.oauthAuthorize = oauthAuthorize;
|
|
402
436
|
exports.oauthCallback = oauthCallback;
|
|
403
437
|
exports.requireAuth = requireAuth;
|
package/dist/express.d.cts
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { c as AuthResult, d as AuthenticatedIdentity } from "./identity-store-BRRahxcS.cjs";
|
|
2
|
-
import { V as AuthorizationRequirement, f as OAuthService } from "./errors-
|
|
3
|
-
import { t as IdentityService } from "./identity-service
|
|
4
|
-
import { n as IdentityRouterOptions, r as createIdentityRouter, t as CookieRefreshOptions } from "./identity-router-
|
|
5
|
-
import { Request, RequestHandler, Response } from "express";
|
|
6
|
-
|
|
2
|
+
import { V as AuthorizationRequirement, f as OAuthService } from "./errors-CBbiRO2n.cjs";
|
|
3
|
+
import { t as IdentityService } from "./identity-service---OTann1.cjs";
|
|
4
|
+
import { i as identityErrorHandler, n as IdentityRouterOptions, r as createIdentityRouter, t as CookieRefreshOptions } from "./identity-router-D1xJ5H7y.cjs";
|
|
5
|
+
import { NextFunction, Request, RequestHandler, Response } from "express";
|
|
7
6
|
//#region core/express/middleware.d.ts
|
|
8
7
|
declare global {
|
|
9
8
|
namespace Express {
|
|
@@ -83,5 +82,5 @@ declare function oauthAuthorize(oauthService: OAuthService, providerName: string
|
|
|
83
82
|
*/
|
|
84
83
|
declare function oauthCallback(oauthService: OAuthService, providerName: string, options: OAuthRouteOptions): RequestHandler;
|
|
85
84
|
//#endregion
|
|
86
|
-
export { CookieRefreshOptions, IdentityRouterOptions, OAuthRouteOptions, ResourceLoader, createIdentityRouter, oauthAuthorize, oauthCallback, requireAuth, requireAuthorization, requirePermission };
|
|
85
|
+
export { CookieRefreshOptions, IdentityRouterOptions, OAuthRouteOptions, type ResourceLoader, createIdentityRouter, identityErrorHandler, oauthAuthorize, oauthCallback, requireAuth, requireAuthorization, requirePermission };
|
|
87
86
|
//# sourceMappingURL=express.d.cts.map
|
package/dist/express.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express.d.cts","names":[],"sources":["../core/express/middleware.ts","../core/express/oauth-routes.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"express.d.cts","names":[],"sources":["../core/express/middleware.ts","../core/express/oauth-routes.ts"],"mappings":";;;;;;QAOQ;YAEI;cACE;;MAER,WAAW;;;;;KAML,eAAe,cAAc,KAAK,YAAY,YAAY,QAAQ;;;;;;iBAc9D,YAAY,SAAS,kBAAkB;;;;;iBAmBvC,qBAAqB,qBACnC,SAAS,iBACT,aAAa,yBAAyB,YACtC,eAAe,eAAe,aAC7B;;iBAwBa,kBACd,SAAS,iBACT,qBACC;;;;;;UC1Ec;;EAEf;;;;;EAKA,SAAS,KAAK,0BAA0B;;;;;EAKxC,SAAS,KAAK,SAAS,KAAK,UAAU,uBAAuB;;;;;EAK7D,UAAU,KAAK,SAAS,KAAK,UAAU,QAAV,oBAAyD;;;;;;;;;;;;;;;;iBAiBxE,eACd,cAAc,cACd,sBACA,SAAS,KAAK,iDACb;;;;;;;;;;;;;;;iBA0Ba,cACd,cAAc,cACd,sBACA,SAAS,oBACR"}
|
package/dist/express.d.mts
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { c as AuthResult, d as AuthenticatedIdentity } from "./identity-store-BRRahxcS.mjs";
|
|
2
|
-
import { V as AuthorizationRequirement, f as OAuthService } from "./errors-
|
|
3
|
-
import { t as IdentityService } from "./identity-service-
|
|
4
|
-
import { n as IdentityRouterOptions, r as createIdentityRouter, t as CookieRefreshOptions } from "./identity-router-
|
|
5
|
-
import { Request, RequestHandler, Response } from "express";
|
|
6
|
-
|
|
2
|
+
import { V as AuthorizationRequirement, f as OAuthService } from "./errors-_OcodtdV.mjs";
|
|
3
|
+
import { t as IdentityService } from "./identity-service-WpOKb0MK.mjs";
|
|
4
|
+
import { i as identityErrorHandler, n as IdentityRouterOptions, r as createIdentityRouter, t as CookieRefreshOptions } from "./identity-router-tj3-teBI.mjs";
|
|
5
|
+
import { NextFunction, Request, RequestHandler, Response } from "express";
|
|
7
6
|
//#region core/express/middleware.d.ts
|
|
8
7
|
declare global {
|
|
9
8
|
namespace Express {
|
|
@@ -83,5 +82,5 @@ declare function oauthAuthorize(oauthService: OAuthService, providerName: string
|
|
|
83
82
|
*/
|
|
84
83
|
declare function oauthCallback(oauthService: OAuthService, providerName: string, options: OAuthRouteOptions): RequestHandler;
|
|
85
84
|
//#endregion
|
|
86
|
-
export { CookieRefreshOptions, IdentityRouterOptions, OAuthRouteOptions, ResourceLoader, createIdentityRouter, oauthAuthorize, oauthCallback, requireAuth, requireAuthorization, requirePermission };
|
|
85
|
+
export { CookieRefreshOptions, IdentityRouterOptions, OAuthRouteOptions, type ResourceLoader, createIdentityRouter, identityErrorHandler, oauthAuthorize, oauthCallback, requireAuth, requireAuthorization, requirePermission };
|
|
87
86
|
//# sourceMappingURL=express.d.mts.map
|
package/dist/express.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express.d.mts","names":[],"sources":["../core/express/middleware.ts","../core/express/oauth-routes.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"express.d.mts","names":[],"sources":["../core/express/middleware.ts","../core/express/oauth-routes.ts"],"mappings":";;;;;;QAOQ;YAEI;cACE;;MAER,WAAW;;;;;KAML,eAAe,cAAc,KAAK,YAAY,YAAY,QAAQ;;;;;;iBAc9D,YAAY,SAAS,kBAAkB;;;;;iBAmBvC,qBAAqB,qBACnC,SAAS,iBACT,aAAa,yBAAyB,YACtC,eAAe,eAAe,aAC7B;;iBAwBa,kBACd,SAAS,iBACT,qBACC;;;;;;UC1Ec;;EAEf;;;;;EAKA,SAAS,KAAK,0BAA0B;;;;;EAKxC,SAAS,KAAK,SAAS,KAAK,UAAU,uBAAuB;;;;;EAK7D,UAAU,KAAK,SAAS,KAAK,UAAU,QAAV,oBAAyD;;;;;;;;;;;;;;;;iBAiBxE,eACd,cAAc,cACd,sBACA,SAAS,KAAK,iDACb;;;;;;;;;;;;;;;iBA0Ba,cACd,cAAc,cACd,sBACA,SAAS,oBACR"}
|
package/dist/express.mjs
CHANGED
|
@@ -395,7 +395,40 @@ function createIdentityRouter(service, options = {}) {
|
|
|
395
395
|
else outer.use(router);
|
|
396
396
|
return outer;
|
|
397
397
|
}
|
|
398
|
+
/**
|
|
399
|
+
* Factory that creates an Express error-handling middleware which converts
|
|
400
|
+
* {@link IdentityError} instances to structured JSON responses.
|
|
401
|
+
* Mount it after the identity router:
|
|
402
|
+
*
|
|
403
|
+
* ```ts
|
|
404
|
+
* app.use(createIdentityRouter(service, { prefix: "auth" }));
|
|
405
|
+
* app.use(identityErrorHandler()); // default console logger
|
|
406
|
+
* app.use(identityErrorHandler({ logger: false })); // silent
|
|
407
|
+
* ```
|
|
408
|
+
*
|
|
409
|
+
* @param options.logger - Logger for recording serialised error details.
|
|
410
|
+
* Pass `false` to disable. Defaults to the console logger.
|
|
411
|
+
*/
|
|
412
|
+
function identityErrorHandler(options = {}) {
|
|
413
|
+
const log = resolveLogger(options.logger);
|
|
414
|
+
return (err, _req, res, next) => {
|
|
415
|
+
if (err instanceof IdentityError) {
|
|
416
|
+
log.debug("identity error", {
|
|
417
|
+
code: err.code,
|
|
418
|
+
status: err.statusCode,
|
|
419
|
+
message: err.message
|
|
420
|
+
});
|
|
421
|
+
res.status(err.statusCode).json({
|
|
422
|
+
code: err.code,
|
|
423
|
+
message: err.message
|
|
424
|
+
});
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
log.error("unhandled error in identity router", { error: String(err) });
|
|
428
|
+
next(err);
|
|
429
|
+
};
|
|
430
|
+
}
|
|
398
431
|
//#endregion
|
|
399
|
-
export { createIdentityRouter, oauthAuthorize, oauthCallback, requireAuth, requireAuthorization, requirePermission };
|
|
432
|
+
export { createIdentityRouter, identityErrorHandler, oauthAuthorize, oauthCallback, requireAuth, requireAuthorization, requirePermission };
|
|
400
433
|
|
|
401
434
|
//# sourceMappingURL=express.mjs.map
|
package/dist/express.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express.mjs","names":[],"sources":["../core/express/middleware.ts","../core/express/oauth-routes.ts","../core/express/identity-router.ts"],"sourcesContent":["import type { NextFunction, Request, RequestHandler, Response } from \"express\";\n\nimport type { AuthorizationRequirement } from \"../authorization\";\nimport { ForbiddenError, IdentityError, UnauthenticatedError } from \"../errors\";\nimport type { IdentityService } from \"../identity-service\";\nimport type { AuthenticatedIdentity } from \"../types\";\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n /** The authenticated principal, set by {@link requireAuth}. */\n identity?: AuthenticatedIdentity;\n }\n }\n}\n\n/** Loads the resource a policy will be evaluated against. */\nexport type ResourceLoader<TResource> = (req: Request) => TResource | Promise<TResource>;\n\nconst extractBearerToken = (req: Request): string | null => {\n const header = req.headers.authorization;\n if (!header || !header.startsWith(\"Bearer \")) return null;\n const token = header.slice(\"Bearer \".length).trim();\n return token.length > 0 ? token : null;\n};\n\n/**\n * Express middleware that authenticates the request using a Bearer access token and\n * attaches the hydrated principal to `req.identity`. Forwards identity errors to the\n * error-handling middleware.\n */\nexport function requireAuth(service: IdentityService): RequestHandler {\n return async (req: Request, _res: Response, next: NextFunction): Promise<void> => {\n try {\n const token = extractBearerToken(req);\n if (!token) {\n throw new UnauthenticatedError();\n }\n req.identity = await service.authenticate(token);\n next();\n } catch (error) {\n next(error);\n }\n };\n}\n\n/**\n * Express middleware enforcing an authorization requirement (deny-by-default). Must run\n * after {@link requireAuth}. Optionally loads a resource for ownership policies.\n */\nexport function requireAuthorization<TResource = unknown>(\n service: IdentityService,\n requirement: AuthorizationRequirement<TResource>,\n loadResource?: ResourceLoader<TResource>,\n): RequestHandler {\n return async (req: Request, _res: Response, next: NextFunction): Promise<void> => {\n try {\n const principal = req.identity;\n if (!principal) {\n throw new UnauthenticatedError();\n }\n const resource = loadResource ? await loadResource(req) : undefined;\n const decision = await service.authorize(requirement, {\n principal,\n action: requirement.permission ?? \"custom\",\n resource,\n });\n if (!decision.allowed) {\n throw new ForbiddenError();\n }\n next();\n } catch (error) {\n next(error);\n }\n };\n}\n\n/** Convenience: require a single permission. */\nexport function requirePermission(\n service: IdentityService,\n permission: string,\n): RequestHandler {\n return requireAuthorization(service, { permission });\n}\n\n/**\n * Optional Express error handler that serializes {@link IdentityError} instances to JSON.\n * Mount after your routes. Non-identity errors are forwarded unchanged.\n */\nexport function identityErrorHandler() {\n return (err: unknown, _req: Request, res: Response, next: NextFunction): void => {\n if (err instanceof IdentityError) {\n res.status(err.statusCode).json({ error: { code: err.code, message: err.message } });\n return;\n }\n next(err);\n };\n}\n","import type { NextFunction, Request, RequestHandler, Response } from \"express\";\n\nimport { IdentityError } from \"../errors\";\nimport type { OAuthService } from \"../oauth/oauth-service\";\n\n/**\n * Options for {@link oauthAuthorize} and {@link oauthCallback}.\n */\nexport interface OAuthRouteOptions {\n /** The full redirect URI registered with the provider (must match exactly). */\n redirectUri: string;\n /**\n * Retrieves the stored CSRF state value from the current request context (e.g. from a\n * signed cookie or server session). Return `null` if no state has been stored yet.\n */\n getState(req: Request): string | null | Promise<string | null>;\n /**\n * Persists the generated CSRF state value before redirecting the user to the provider.\n * Use a signed cookie or server session.\n */\n setState(req: Request, res: Response, state: string): void | Promise<void>;\n /**\n * Called on a successful OAuth callback with the auth result. Typically sets a session\n * cookie and redirects to the app.\n */\n onSuccess(req: Request, res: Response, result: import(\"../types\").AuthResult): void | Promise<void>;\n}\n\n/**\n * Returns an Express route handler that redirects the user to the OAuth provider's\n * authorization page. Generates and persists a CSRF state value via `options.setState`.\n *\n * @example\n * ```ts\n * app.get(\"/auth/google\", oauthAuthorize(identity.oauth!, \"google\", {\n * redirectUri: `${BASE_URL}/auth/google/callback`,\n * getState: (req) => req.session?.oauthState ?? null,\n * setState: (req, _res, state) => { req.session!.oauthState = state; },\n * onSuccess: (_req, res, result) => res.json(result),\n * }));\n * ```\n */\nexport function oauthAuthorize(\n oauthService: OAuthService,\n providerName: string,\n options: Pick<OAuthRouteOptions, \"redirectUri\" | \"setState\">,\n): RequestHandler {\n return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const { url, state } = oauthService.buildAuthorizationUrl(providerName, options.redirectUri);\n await options.setState(req, res, state);\n res.redirect(url);\n } catch (error) {\n next(error);\n }\n };\n}\n\n/**\n * Returns an Express route handler that handles the OAuth provider callback. Verifies\n * state, exchanges the code, and calls `options.onSuccess` with the auth result.\n *\n * @example\n * ```ts\n * app.get(\"/auth/google/callback\", oauthCallback(identity.oauth!, \"google\", {\n * redirectUri: `${BASE_URL}/auth/google/callback`,\n * getState: (req) => req.session?.oauthState ?? null,\n * setState: (req, _res, state) => { req.session!.oauthState = state; },\n * onSuccess: (_req, res, result) => res.json(result),\n * }));\n * ```\n */\nexport function oauthCallback(\n oauthService: OAuthService,\n providerName: string,\n options: OAuthRouteOptions,\n): RequestHandler {\n return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const code = typeof req.query[\"code\"] === \"string\" ? req.query[\"code\"] : null;\n const state = typeof req.query[\"state\"] === \"string\" ? req.query[\"state\"] : null;\n const error = typeof req.query[\"error\"] === \"string\" ? req.query[\"error\"] : null;\n\n if (error) {\n const errorDescription =\n typeof req.query[\"error_description\"] === \"string\"\n ? req.query[\"error_description\"]\n : error;\n throw new IdentityError(\"identity/oauth-error\", `Provider error: ${errorDescription}`, 400);\n }\n\n if (!code || !state) {\n throw new IdentityError(\n \"identity/oauth-invalid-callback\",\n \"Missing code or state in OAuth callback.\",\n 400,\n );\n }\n\n const expectedState = await options.getState(req);\n if (!expectedState) {\n throw new IdentityError(\n \"identity/oauth-state-missing\",\n \"No OAuth state found in session. The request may have expired.\",\n 400,\n );\n }\n\n const result = await oauthService.handleCallback(providerName, {\n code,\n state,\n expectedState,\n redirectUri: options.redirectUri,\n });\n\n await options.onSuccess(req, res, result);\n } catch (error) {\n next(error);\n }\n };\n}\n","import { Router, type NextFunction, type Request, type Response } from \"express\";\n\nimport { IdentityError, UnauthenticatedError } from \"../errors\";\nimport type { IdentityService } from \"../identity-service\";\nimport type { IdentityLogger } from \"../logger\";\nimport { resolveLogger } from \"../logger\";\nimport type { AuthResult, AuthTokens, LoginResult } from \"../types\";\nimport { requireAuth } from \"./middleware\";\nimport { oauthAuthorize, oauthCallback } from \"./oauth-routes\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Options for controlling the refresh-token cookie. */\nexport interface CookieRefreshOptions {\n /** Cookie name. Default: `\"azlib_rt\"`. */\n name?: string;\n /** Mark the cookie as `HttpOnly`. Default: `true`. */\n httpOnly?: boolean;\n /**\n * Mark the cookie as `Secure`. Defaults to `true` when `NODE_ENV` is `\"production\"`,\n * `false` otherwise.\n */\n secure?: boolean;\n /** `SameSite` policy. Default: `\"lax\"`. */\n sameSite?: \"strict\" | \"lax\" | \"none\";\n /** Cookie path. Default: `\"/\"`. */\n path?: string;\n /** Cookie domain. Omit to use the current host. */\n domain?: string;\n}\n\n/**\n * Options for {@link createIdentityRouter}.\n */\nexport interface IdentityRouterOptions {\n /**\n * Controls how the refresh token is transported between server and client.\n *\n * - **`\"body\"`** (default) — the refresh token is included in the `tokens` object of\n * every successful `register`/`login`/`refresh` response. The client must store it\n * and send it back via the JSON body on `/refresh` and `/logout`.\n *\n * - **`{ cookie: CookieRefreshOptions }`** — the refresh token is sent as an\n * `HttpOnly` cookie. `/refresh` and `/logout` read it automatically; the response\n * body only includes the access token.\n */\n refreshToken?: \"body\" | { cookie: CookieRefreshOptions };\n\n /**\n * Base URL under which the OAuth callback routes are hosted.\n *\n * Example: `\"https://api.example.com/auth\"`.\n *\n * The callback URI for a provider becomes `{oauthBaseUrl}/{providerName}/callback`.\n * Required when the identity service has OAuth providers configured.\n */\n oauthBaseUrl?: string;\n\n /**\n * URL path prefix prepended to all identity routes.\n *\n * Default: `\"account\"`. Routes are served at `/{prefix}/login`, `/{prefix}/register`, etc.\n *\n * Mount the returned router at the application root:\n * ```ts\n * app.use(createIdentityRouter(service, { prefix: \"auth\" }));\n * // → POST /auth/login, POST /auth/register, …\n * ```\n *\n * Set to `\"\"` to omit the prefix and mount routes directly at the router's mount point.\n */\n prefix?: string;\n\n /**\n * Logger for request/response and error diagnostics.\n *\n * - Omit — defaults to a `console`-based logger with an `[identity]` prefix.\n * - Supply your own `IdentityLogger` — route output to Winston, Pino, etc.\n * - Pass `false` — disable all logging from this router.\n *\n * @example\n * ```ts\n * import pino from \"pino\";\n * app.use(createIdentityRouter(service, { logger: pino() }));\n * ```\n */\n logger?: IdentityLogger | false;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nconst OAUTH_STATE_COOKIE = \"azlib_oauth_state\";\n\nfunction resolveCookieName(opts: CookieRefreshOptions): string {\n return opts.name ?? \"azlib_rt\";\n}\n\n/** Parses cookies from the raw `Cookie` header without a dependency on `cookie-parser`. */\nfunction readCookie(req: Request, name: string): string | undefined {\n const raw = req.headers.cookie ?? \"\";\n for (const part of raw.split(\";\")) {\n const eq = part.indexOf(\"=\");\n if (eq === -1) continue;\n const key = part.slice(0, eq).trim();\n if (key === name) {\n try {\n return decodeURIComponent(part.slice(eq + 1).trim());\n } catch {\n return part.slice(eq + 1).trim();\n }\n }\n }\n return undefined;\n}\n\n/**\n * Writes the refresh token into a `Set-Cookie` header and returns a body-safe tokens\n * object that omits the refresh token.\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\n/**\n * Sends the authentication result as JSON. In cookie mode the refresh token is stored\n * in a `Set-Cookie` header and excluded from the body.\n *\n * When the result is an MFA challenge (`{ kind: \"mfa_required\" }`), it is forwarded as-is\n * with HTTP 200 so the client knows to complete the TOTP step.\n */\nfunction sendLoginResult(\n res: Response,\n result: LoginResult,\n cookieOpts: CookieRefreshOptions | undefined,\n): void {\n if (\"mfaToken\" in result) {\n res.json(result);\n return;\n }\n sendAuthResult(res, result, cookieOpts);\n}\n\nfunction sendAuthResult(\n res: Response,\n result: AuthResult,\n cookieOpts: CookieRefreshOptions | undefined,\n): void {\n if (cookieOpts) {\n const tokens = setCookieAndStripRefreshToken(res, result.tokens, cookieOpts);\n res.json({ user: result.user, tokens });\n } else {\n res.json(result);\n }\n}\n\n/**\n * Reads the refresh token from the request. In cookie mode it is read from the cookie;\n * in body mode it is expected in `req.body.refreshToken`.\n */\nfunction readRefreshToken(req: Request, cookieOpts: CookieRefreshOptions | undefined): string | undefined {\n if (cookieOpts) {\n return readCookie(req, 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// Router factory\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a pre-wired Express `Router` with all standard identity endpoints.\n *\n * Mount it once on your application:\n * ```ts\n * import express from \"express\";\n * import { createIdentityService } from \"@azlib/identity/node\";\n * import { createIdentityRouter, identityErrorHandler } from \"@azlib/identity/express\";\n *\n * const service = createIdentityService(config, store);\n * const app = express();\n *\n * app.use(express.json());\n * // Routes are served at /account/login, /account/register, etc. (default prefix)\n * app.use(createIdentityRouter(service));\n * // Or use a custom prefix:\n * app.use(createIdentityRouter(service, { prefix: \"auth\" }));\n * app.use(identityErrorHandler()); // optional convenience error handler\n * ```\n *\n * Pre-wired routes:\n *\n * | Method | Path | Description |\n * |--------|------|-------------|\n * | POST | `/register` | Create a new account |\n * | POST | `/login` | Email + password login |\n * | POST | `/refresh` | Rotate the refresh token |\n * | POST | `/logout` | Revoke the current session |\n * | GET | `/me` | Return the authenticated principal |\n * | GET | `/:provider` | Start an OAuth 2.0 authorisation flow *(optional)* |\n * | GET | `/:provider/callback` | Handle an OAuth 2.0 callback *(optional)* |\n */\nexport function createIdentityRouter(\n service: IdentityService,\n options: IdentityRouterOptions = {},\n): Router {\n const prefix = options.prefix ?? \"account\";\n const log = resolveLogger(options.logger);\n\n const router = Router();\n const cookieOpts: CookieRefreshOptions | undefined =\n typeof options.refreshToken === \"object\" && \"cookie\" in options.refreshToken\n ? options.refreshToken.cookie\n : undefined;\n\n // Request / response logging middleware\n router.use((_req: Request, res: Response, next: NextFunction): void => {\n const start = Date.now();\n res.on(\"finish\", () => {\n const ms = Date.now() - start;\n log.info(`${_req.method} ${_req.originalUrl} ${res.statusCode}`, { durationMs: ms });\n });\n next();\n });\n\n // POST /register\n router.post(\"/register\", async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const result = await service.register(req.body as { email: string; password: string; displayName?: string });\n sendAuthResult(res, result, cookieOpts);\n } catch (err) {\n next(err);\n }\n });\n\n // POST /login\n router.post(\"/login\", async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const result = await service.login(req.body as { email: string; password: string });\n sendLoginResult(res, result, cookieOpts);\n } catch (err) {\n next(err);\n }\n });\n\n // POST /refresh\n router.post(\"/refresh\", async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const token = readRefreshToken(req, cookieOpts);\n if (!token) {\n throw new UnauthenticatedError(\"Refresh token is missing.\");\n }\n const result = await service.refresh(token);\n sendAuthResult(res, result, cookieOpts);\n } catch (err) {\n next(err);\n }\n });\n\n // POST /logout\n router.post(\"/logout\", async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const token = readRefreshToken(req, cookieOpts);\n if (token) {\n await service.logout(token);\n }\n if (cookieOpts) {\n res.clearCookie(resolveCookieName(cookieOpts), { path: cookieOpts.path ?? \"/\" });\n }\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n });\n\n // GET /me — requires a valid Bearer access token\n router.get(\"/me\", requireAuth(service), (_req: Request, res: Response): void => {\n res.json(_req.identity);\n });\n\n // ---------------------------------------------------------------------------\n // Email verification\n // ---------------------------------------------------------------------------\n\n // POST /request-email-verification — re-send verification link (requires auth)\n router.post(\n \"/request-email-verification\",\n requireAuth(service),\n async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n await service.requestEmailVerification(req.identity!.userId);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n },\n );\n\n // POST /verify-email — consume the token from the verification link\n router.post(\"/verify-email\", async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const { token } = req.body as { token?: string };\n if (!token) {\n throw new UnauthenticatedError(\"token is required.\");\n }\n await service.verifyEmail(token);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n });\n\n // ---------------------------------------------------------------------------\n // Password reset\n // ---------------------------------------------------------------------------\n\n // POST /request-password-reset — send reset link by email\n router.post(\n \"/request-password-reset\",\n async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const { email } = req.body as { email?: string };\n if (!email) {\n throw new UnauthenticatedError(\"email is required.\");\n }\n await service.requestPasswordReset(email);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n },\n );\n\n // POST /reset-password — set new password with token\n router.post(\"/reset-password\", async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const { token, newPassword } = req.body as { token?: string; newPassword?: string };\n if (!token || !newPassword) {\n throw new UnauthenticatedError(\"token and newPassword are required.\");\n }\n await service.resetPassword(token, newPassword);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n });\n\n // ---------------------------------------------------------------------------\n // Two-factor authentication (2FA / TOTP)\n // ---------------------------------------------------------------------------\n\n // POST /mfa/verify — complete an MFA challenge after login\n router.post(\"/mfa/verify\", async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const { mfaToken, code } = req.body as { mfaToken?: string; code?: string };\n if (!mfaToken || !code) {\n throw new UnauthenticatedError(\"mfaToken and code are required.\");\n }\n const result = await service.verifyMfaChallenge(mfaToken, code);\n sendAuthResult(res, result, cookieOpts);\n } catch (err) {\n next(err);\n }\n });\n\n // POST /2fa/setup — begin 2FA setup (requires auth)\n router.post(\n \"/2fa/setup\",\n requireAuth(service),\n async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const result = await service.setup2FA(req.identity!.userId);\n res.json(result);\n } catch (err) {\n next(err);\n }\n },\n );\n\n // POST /2fa/enable — confirm and enable 2FA (requires auth)\n router.post(\n \"/2fa/enable\",\n requireAuth(service),\n async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const { code } = req.body as { code?: string };\n if (!code) {\n throw new UnauthenticatedError(\"code is required.\");\n }\n await service.enable2FA(req.identity!.userId, code);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n },\n );\n\n // POST /2fa/disable — disable 2FA (requires auth)\n router.post(\n \"/2fa/disable\",\n requireAuth(service),\n async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const { code } = req.body as { code?: string };\n if (!code) {\n throw new UnauthenticatedError(\"code is required.\");\n }\n await service.disable2FA(req.identity!.userId, code);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n },\n );\n\n // ---------------------------------------------------------------------------\n // Account management (admin)\n // ---------------------------------------------------------------------------\n\n // POST /admin/lock/:userId — lock an account\n router.post(\n \"/admin/lock/:userId\",\n async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n await service.lockAccount(req.params[\"userId\"]!);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n },\n );\n\n // POST /admin/unlock/:userId — unlock an account\n router.post(\n \"/admin/unlock/:userId\",\n async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n await service.unlockAccount(req.params[\"userId\"]!);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n },\n );\n\n // POST /admin/disable/:userId — disable an account\n router.post(\n \"/admin/disable/:userId\",\n async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n await service.disableAccount(req.params[\"userId\"]!);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n },\n );\n\n // OAuth routes — only when providers are configured on the service\n if (service.oauth) {\n const oauthService = service.oauth;\n const baseUrl = options.oauthBaseUrl ?? \"\";\n\n const stateCookieOptions = {\n httpOnly: true,\n sameSite: \"lax\" as const,\n secure: process.env.NODE_ENV === \"production\",\n maxAge: 10 * 60 * 1000, // 10 minutes\n };\n\n for (const providerName of oauthService.providers) {\n const redirectUri = `${baseUrl}/${providerName}/callback`;\n\n router.get(\n `/${providerName}`,\n oauthAuthorize(oauthService, providerName, {\n redirectUri,\n setState: (_req, oauthRes, state) => {\n oauthRes.cookie(OAUTH_STATE_COOKIE, state, stateCookieOptions);\n },\n }),\n );\n\n router.get(\n `/${providerName}/callback`,\n oauthCallback(oauthService, providerName, {\n redirectUri,\n getState: (oauthReq) => readCookie(oauthReq, OAUTH_STATE_COOKIE) ?? null,\n setState: (_oauthReq, oauthRes, _state) => {\n oauthRes.clearCookie(OAUTH_STATE_COOKIE);\n },\n onSuccess: (_oauthReq, oauthRes, result) => {\n sendAuthResult(oauthRes, result, cookieOpts);\n },\n }),\n );\n }\n }\n\n // Mount the inner router at the configured prefix.\n const outer = Router();\n if (prefix) {\n outer.use(`/${prefix}`, router);\n } else {\n outer.use(router);\n }\n return outer;\n}\n\n// ---------------------------------------------------------------------------\n// Convenience error handler\n// ---------------------------------------------------------------------------\n\n/**\n * Factory that creates an Express error-handling middleware which converts\n * {@link IdentityError} instances to structured JSON responses.\n * Mount it after the identity router:\n *\n * ```ts\n * app.use(createIdentityRouter(service, { prefix: \"auth\" }));\n * app.use(identityErrorHandler()); // default console logger\n * app.use(identityErrorHandler({ logger: false })); // silent\n * ```\n *\n * @param options.logger - Logger for recording serialised error details.\n * Pass `false` to disable. Defaults to the console logger.\n */\nexport function identityErrorHandler(\n options: { logger?: IdentityLogger | false } = {},\n): (err: unknown, req: Request, res: Response, next: NextFunction) => void {\n const log = resolveLogger(options.logger);\n return (err: unknown, _req: Request, res: Response, next: NextFunction): void => {\n if (err instanceof IdentityError) {\n log.debug(\"identity error\", { code: err.code, status: err.statusCode, message: err.message });\n res.status(err.statusCode).json({ code: err.code, message: err.message });\n return;\n }\n log.error(\"unhandled error in identity router\", { error: String(err) });\n next(err);\n };\n}\n"],"mappings":";;;;A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AK,GAAG;EACV;CACF,CACF;CAGA,OAAO,KACL,0BACA,OAAO,KAAc,KAAe,SAAsC;EACxE,IAAI;GACF,MAAM,QAAQ,eAAe,IAAI,OAAO,SAAU;GAClD,IAAI,OAAO,GAAG,EAAE,IAAI;EACtB,SAAS,KAAK;GACZ,KAAK,GAAG;EACV;CACF,CACF;CAGA,IAAI,QAAQ,OAAO;EACjB,MAAM,eAAe,QAAQ;EAC7B,MAAM,UAAU,QAAQ,gBAAgB;EAExC,MAAM,qBAAqB;GACzB,UAAU;GACV,UAAU;GACV,QAAQ,QAAQ,IAAI,aAAa;GACjC,QAAQ,MAAU;EACpB;EAEA,KAAK,MAAM,gBAAgB,aAAa,WAAW;GACjD,MAAM,cAAc,GAAG,QAAQ,GAAG,aAAa;GAE/C,OAAO,IACL,IAAI,gBACJ,eAAe,cAAc,cAAc;IACzC;IACA,WAAW,MAAM,UAAU,UAAU;KACnC,SAAS,OAAO,oBAAoB,OAAO,kBAAkB;IAC/D;GACF,CAAC,CACH;GAEA,OAAO,IACL,IAAI,aAAa,YACjB,cAAc,cAAc,cAAc;IACxC;IACA,WAAW,aAAa,WAAW,UAAU,kBAAkB,KAAK;IACpE,WAAW,WAAW,UAAU,WAAW;KACzC,SAAS,YAAY,kBAAkB;IACzC;IACA,YAAY,WAAW,UAAU,WAAW;KAC1C,eAAe,UAAU,QAAQ,UAAU;IAC7C;GACF,CAAC,CACH;EACF;CACF;CAGA,MAAM,QAAQ,OAAO;CACrB,IAAI,QACF,MAAM,IAAI,IAAI,UAAU,MAAM;MAE9B,MAAM,IAAI,MAAM;CAElB,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"express.mjs","names":[],"sources":["../core/express/middleware.ts","../core/express/oauth-routes.ts","../core/express/identity-router.ts"],"sourcesContent":["import type { NextFunction, Request, RequestHandler, Response } from \"express\";\n\nimport type { AuthorizationRequirement } from \"../authorization\";\nimport { ForbiddenError, IdentityError, UnauthenticatedError } from \"../errors\";\nimport type { IdentityService } from \"../identity-service\";\nimport type { AuthenticatedIdentity } from \"../types\";\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n interface Request {\n /** The authenticated principal, set by {@link requireAuth}. */\n identity?: AuthenticatedIdentity;\n }\n }\n}\n\n/** Loads the resource a policy will be evaluated against. */\nexport type ResourceLoader<TResource> = (req: Request) => TResource | Promise<TResource>;\n\nconst extractBearerToken = (req: Request): string | null => {\n const header = req.headers.authorization;\n if (!header || !header.startsWith(\"Bearer \")) return null;\n const token = header.slice(\"Bearer \".length).trim();\n return token.length > 0 ? token : null;\n};\n\n/**\n * Express middleware that authenticates the request using a Bearer access token and\n * attaches the hydrated principal to `req.identity`. Forwards identity errors to the\n * error-handling middleware.\n */\nexport function requireAuth(service: IdentityService): RequestHandler {\n return async (req: Request, _res: Response, next: NextFunction): Promise<void> => {\n try {\n const token = extractBearerToken(req);\n if (!token) {\n throw new UnauthenticatedError();\n }\n req.identity = await service.authenticate(token);\n next();\n } catch (error) {\n next(error);\n }\n };\n}\n\n/**\n * Express middleware enforcing an authorization requirement (deny-by-default). Must run\n * after {@link requireAuth}. Optionally loads a resource for ownership policies.\n */\nexport function requireAuthorization<TResource = unknown>(\n service: IdentityService,\n requirement: AuthorizationRequirement<TResource>,\n loadResource?: ResourceLoader<TResource>,\n): RequestHandler {\n return async (req: Request, _res: Response, next: NextFunction): Promise<void> => {\n try {\n const principal = req.identity;\n if (!principal) {\n throw new UnauthenticatedError();\n }\n const resource = loadResource ? await loadResource(req) : undefined;\n const decision = await service.authorize(requirement, {\n principal,\n action: requirement.permission ?? \"custom\",\n resource,\n });\n if (!decision.allowed) {\n throw new ForbiddenError();\n }\n next();\n } catch (error) {\n next(error);\n }\n };\n}\n\n/** Convenience: require a single permission. */\nexport function requirePermission(\n service: IdentityService,\n permission: string,\n): RequestHandler {\n return requireAuthorization(service, { permission });\n}\n\n/**\n * Optional Express error handler that serializes {@link IdentityError} instances to JSON.\n * Mount after your routes. Non-identity errors are forwarded unchanged.\n */\nexport function identityErrorHandler() {\n return (err: unknown, _req: Request, res: Response, next: NextFunction): void => {\n if (err instanceof IdentityError) {\n res.status(err.statusCode).json({ error: { code: err.code, message: err.message } });\n return;\n }\n next(err);\n };\n}\n","import type { NextFunction, Request, RequestHandler, Response } from \"express\";\n\nimport { IdentityError } from \"../errors\";\nimport type { OAuthService } from \"../oauth/oauth-service\";\n\n/**\n * Options for {@link oauthAuthorize} and {@link oauthCallback}.\n */\nexport interface OAuthRouteOptions {\n /** The full redirect URI registered with the provider (must match exactly). */\n redirectUri: string;\n /**\n * Retrieves the stored CSRF state value from the current request context (e.g. from a\n * signed cookie or server session). Return `null` if no state has been stored yet.\n */\n getState(req: Request): string | null | Promise<string | null>;\n /**\n * Persists the generated CSRF state value before redirecting the user to the provider.\n * Use a signed cookie or server session.\n */\n setState(req: Request, res: Response, state: string): void | Promise<void>;\n /**\n * Called on a successful OAuth callback with the auth result. Typically sets a session\n * cookie and redirects to the app.\n */\n onSuccess(req: Request, res: Response, result: import(\"../types\").AuthResult): void | Promise<void>;\n}\n\n/**\n * Returns an Express route handler that redirects the user to the OAuth provider's\n * authorization page. Generates and persists a CSRF state value via `options.setState`.\n *\n * @example\n * ```ts\n * app.get(\"/auth/google\", oauthAuthorize(identity.oauth!, \"google\", {\n * redirectUri: `${BASE_URL}/auth/google/callback`,\n * getState: (req) => req.session?.oauthState ?? null,\n * setState: (req, _res, state) => { req.session!.oauthState = state; },\n * onSuccess: (_req, res, result) => res.json(result),\n * }));\n * ```\n */\nexport function oauthAuthorize(\n oauthService: OAuthService,\n providerName: string,\n options: Pick<OAuthRouteOptions, \"redirectUri\" | \"setState\">,\n): RequestHandler {\n return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const { url, state } = oauthService.buildAuthorizationUrl(providerName, options.redirectUri);\n await options.setState(req, res, state);\n res.redirect(url);\n } catch (error) {\n next(error);\n }\n };\n}\n\n/**\n * Returns an Express route handler that handles the OAuth provider callback. Verifies\n * state, exchanges the code, and calls `options.onSuccess` with the auth result.\n *\n * @example\n * ```ts\n * app.get(\"/auth/google/callback\", oauthCallback(identity.oauth!, \"google\", {\n * redirectUri: `${BASE_URL}/auth/google/callback`,\n * getState: (req) => req.session?.oauthState ?? null,\n * setState: (req, _res, state) => { req.session!.oauthState = state; },\n * onSuccess: (_req, res, result) => res.json(result),\n * }));\n * ```\n */\nexport function oauthCallback(\n oauthService: OAuthService,\n providerName: string,\n options: OAuthRouteOptions,\n): RequestHandler {\n return async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const code = typeof req.query[\"code\"] === \"string\" ? req.query[\"code\"] : null;\n const state = typeof req.query[\"state\"] === \"string\" ? req.query[\"state\"] : null;\n const error = typeof req.query[\"error\"] === \"string\" ? req.query[\"error\"] : null;\n\n if (error) {\n const errorDescription =\n typeof req.query[\"error_description\"] === \"string\"\n ? req.query[\"error_description\"]\n : error;\n throw new IdentityError(\"identity/oauth-error\", `Provider error: ${errorDescription}`, 400);\n }\n\n if (!code || !state) {\n throw new IdentityError(\n \"identity/oauth-invalid-callback\",\n \"Missing code or state in OAuth callback.\",\n 400,\n );\n }\n\n const expectedState = await options.getState(req);\n if (!expectedState) {\n throw new IdentityError(\n \"identity/oauth-state-missing\",\n \"No OAuth state found in session. The request may have expired.\",\n 400,\n );\n }\n\n const result = await oauthService.handleCallback(providerName, {\n code,\n state,\n expectedState,\n redirectUri: options.redirectUri,\n });\n\n await options.onSuccess(req, res, result);\n } catch (error) {\n next(error);\n }\n };\n}\n","import { Router, type NextFunction, type Request, type Response } from \"express\";\n\nimport { IdentityError, UnauthenticatedError } from \"../errors\";\nimport type { IdentityService } from \"../identity-service\";\nimport type { IdentityLogger } from \"../logger\";\nimport { resolveLogger } from \"../logger\";\nimport type { AuthResult, AuthTokens, LoginResult } from \"../types\";\nimport { requireAuth } from \"./middleware\";\nimport { oauthAuthorize, oauthCallback } from \"./oauth-routes\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Options for controlling the refresh-token cookie. */\nexport interface CookieRefreshOptions {\n /** Cookie name. Default: `\"azlib_rt\"`. */\n name?: string;\n /** Mark the cookie as `HttpOnly`. Default: `true`. */\n httpOnly?: boolean;\n /**\n * Mark the cookie as `Secure`. Defaults to `true` when `NODE_ENV` is `\"production\"`,\n * `false` otherwise.\n */\n secure?: boolean;\n /** `SameSite` policy. Default: `\"lax\"`. */\n sameSite?: \"strict\" | \"lax\" | \"none\";\n /** Cookie path. Default: `\"/\"`. */\n path?: string;\n /** Cookie domain. Omit to use the current host. */\n domain?: string;\n}\n\n/**\n * Options for {@link createIdentityRouter}.\n */\nexport interface IdentityRouterOptions {\n /**\n * Controls how the refresh token is transported between server and client.\n *\n * - **`\"body\"`** (default) — the refresh token is included in the `tokens` object of\n * every successful `register`/`login`/`refresh` response. The client must store it\n * and send it back via the JSON body on `/refresh` and `/logout`.\n *\n * - **`{ cookie: CookieRefreshOptions }`** — the refresh token is sent as an\n * `HttpOnly` cookie. `/refresh` and `/logout` read it automatically; the response\n * body only includes the access token.\n */\n refreshToken?: \"body\" | { cookie: CookieRefreshOptions };\n\n /**\n * Base URL under which the OAuth callback routes are hosted.\n *\n * Example: `\"https://api.example.com/auth\"`.\n *\n * The callback URI for a provider becomes `{oauthBaseUrl}/{providerName}/callback`.\n * Required when the identity service has OAuth providers configured.\n */\n oauthBaseUrl?: string;\n\n /**\n * URL path prefix prepended to all identity routes.\n *\n * Default: `\"account\"`. Routes are served at `/{prefix}/login`, `/{prefix}/register`, etc.\n *\n * Mount the returned router at the application root:\n * ```ts\n * app.use(createIdentityRouter(service, { prefix: \"auth\" }));\n * // → POST /auth/login, POST /auth/register, …\n * ```\n *\n * Set to `\"\"` to omit the prefix and mount routes directly at the router's mount point.\n */\n prefix?: string;\n\n /**\n * Logger for request/response and error diagnostics.\n *\n * - Omit — defaults to a `console`-based logger with an `[identity]` prefix.\n * - Supply your own `IdentityLogger` — route output to Winston, Pino, etc.\n * - Pass `false` — disable all logging from this router.\n *\n * @example\n * ```ts\n * import pino from \"pino\";\n * app.use(createIdentityRouter(service, { logger: pino() }));\n * ```\n */\n logger?: IdentityLogger | false;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nconst OAUTH_STATE_COOKIE = \"azlib_oauth_state\";\n\nfunction resolveCookieName(opts: CookieRefreshOptions): string {\n return opts.name ?? \"azlib_rt\";\n}\n\n/** Parses cookies from the raw `Cookie` header without a dependency on `cookie-parser`. */\nfunction readCookie(req: Request, name: string): string | undefined {\n const raw = req.headers.cookie ?? \"\";\n for (const part of raw.split(\";\")) {\n const eq = part.indexOf(\"=\");\n if (eq === -1) continue;\n const key = part.slice(0, eq).trim();\n if (key === name) {\n try {\n return decodeURIComponent(part.slice(eq + 1).trim());\n } catch {\n return part.slice(eq + 1).trim();\n }\n }\n }\n return undefined;\n}\n\n/**\n * Writes the refresh token into a `Set-Cookie` header and returns a body-safe tokens\n * object that omits the refresh token.\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\n/**\n * Sends the authentication result as JSON. In cookie mode the refresh token is stored\n * in a `Set-Cookie` header and excluded from the body.\n *\n * When the result is an MFA challenge (`{ kind: \"mfa_required\" }`), it is forwarded as-is\n * with HTTP 200 so the client knows to complete the TOTP step.\n */\nfunction sendLoginResult(\n res: Response,\n result: LoginResult,\n cookieOpts: CookieRefreshOptions | undefined,\n): void {\n if (\"mfaToken\" in result) {\n res.json(result);\n return;\n }\n sendAuthResult(res, result, cookieOpts);\n}\n\nfunction sendAuthResult(\n res: Response,\n result: AuthResult,\n cookieOpts: CookieRefreshOptions | undefined,\n): void {\n if (cookieOpts) {\n const tokens = setCookieAndStripRefreshToken(res, result.tokens, cookieOpts);\n res.json({ user: result.user, tokens });\n } else {\n res.json(result);\n }\n}\n\n/**\n * Reads the refresh token from the request. In cookie mode it is read from the cookie;\n * in body mode it is expected in `req.body.refreshToken`.\n */\nfunction readRefreshToken(req: Request, cookieOpts: CookieRefreshOptions | undefined): string | undefined {\n if (cookieOpts) {\n return readCookie(req, 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// Router factory\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a pre-wired Express `Router` with all standard identity endpoints.\n *\n * Mount it once on your application:\n * ```ts\n * import express from \"express\";\n * import { createIdentityService } from \"@azlib/identity/node\";\n * import { createIdentityRouter, identityErrorHandler } from \"@azlib/identity/express\";\n *\n * const service = createIdentityService(config, store);\n * const app = express();\n *\n * app.use(express.json());\n * // Routes are served at /account/login, /account/register, etc. (default prefix)\n * app.use(createIdentityRouter(service));\n * // Or use a custom prefix:\n * app.use(createIdentityRouter(service, { prefix: \"auth\" }));\n * app.use(identityErrorHandler()); // optional convenience error handler\n * ```\n *\n * Pre-wired routes:\n *\n * | Method | Path | Description |\n * |--------|------|-------------|\n * | POST | `/register` | Create a new account |\n * | POST | `/login` | Email + password login |\n * | POST | `/refresh` | Rotate the refresh token |\n * | POST | `/logout` | Revoke the current session |\n * | GET | `/me` | Return the authenticated principal |\n * | GET | `/:provider` | Start an OAuth 2.0 authorisation flow *(optional)* |\n * | GET | `/:provider/callback` | Handle an OAuth 2.0 callback *(optional)* |\n */\nexport function createIdentityRouter(\n service: IdentityService,\n options: IdentityRouterOptions = {},\n): Router {\n const prefix = options.prefix ?? \"account\";\n const log = resolveLogger(options.logger);\n\n const router = Router();\n const cookieOpts: CookieRefreshOptions | undefined =\n typeof options.refreshToken === \"object\" && \"cookie\" in options.refreshToken\n ? options.refreshToken.cookie\n : undefined;\n\n // Request / response logging middleware\n router.use((_req: Request, res: Response, next: NextFunction): void => {\n const start = Date.now();\n res.on(\"finish\", () => {\n const ms = Date.now() - start;\n log.info(`${_req.method} ${_req.originalUrl} ${res.statusCode}`, { durationMs: ms });\n });\n next();\n });\n\n // POST /register\n router.post(\"/register\", async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const result = await service.register(req.body as { email: string; password: string; displayName?: string });\n sendAuthResult(res, result, cookieOpts);\n } catch (err) {\n next(err);\n }\n });\n\n // POST /login\n router.post(\"/login\", async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const result = await service.login(req.body as { email: string; password: string });\n sendLoginResult(res, result, cookieOpts);\n } catch (err) {\n next(err);\n }\n });\n\n // POST /refresh\n router.post(\"/refresh\", async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const token = readRefreshToken(req, cookieOpts);\n if (!token) {\n throw new UnauthenticatedError(\"Refresh token is missing.\");\n }\n const result = await service.refresh(token);\n sendAuthResult(res, result, cookieOpts);\n } catch (err) {\n next(err);\n }\n });\n\n // POST /logout\n router.post(\"/logout\", async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const token = readRefreshToken(req, cookieOpts);\n if (token) {\n await service.logout(token);\n }\n if (cookieOpts) {\n res.clearCookie(resolveCookieName(cookieOpts), { path: cookieOpts.path ?? \"/\" });\n }\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n });\n\n // GET /me — requires a valid Bearer access token\n router.get(\"/me\", requireAuth(service), (_req: Request, res: Response): void => {\n res.json(_req.identity);\n });\n\n // ---------------------------------------------------------------------------\n // Email verification\n // ---------------------------------------------------------------------------\n\n // POST /request-email-verification — re-send verification link (requires auth)\n router.post(\n \"/request-email-verification\",\n requireAuth(service),\n async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n await service.requestEmailVerification(req.identity!.userId);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n },\n );\n\n // POST /verify-email — consume the token from the verification link\n router.post(\"/verify-email\", async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const { token } = req.body as { token?: string };\n if (!token) {\n throw new UnauthenticatedError(\"token is required.\");\n }\n await service.verifyEmail(token);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n });\n\n // ---------------------------------------------------------------------------\n // Password reset\n // ---------------------------------------------------------------------------\n\n // POST /request-password-reset — send reset link by email\n router.post(\n \"/request-password-reset\",\n async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const { email } = req.body as { email?: string };\n if (!email) {\n throw new UnauthenticatedError(\"email is required.\");\n }\n await service.requestPasswordReset(email);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n },\n );\n\n // POST /reset-password — set new password with token\n router.post(\"/reset-password\", async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const { token, newPassword } = req.body as { token?: string; newPassword?: string };\n if (!token || !newPassword) {\n throw new UnauthenticatedError(\"token and newPassword are required.\");\n }\n await service.resetPassword(token, newPassword);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n });\n\n // ---------------------------------------------------------------------------\n // Two-factor authentication (2FA / TOTP)\n // ---------------------------------------------------------------------------\n\n // POST /mfa/verify — complete an MFA challenge after login\n router.post(\"/mfa/verify\", async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const { mfaToken, code } = req.body as { mfaToken?: string; code?: string };\n if (!mfaToken || !code) {\n throw new UnauthenticatedError(\"mfaToken and code are required.\");\n }\n const result = await service.verifyMfaChallenge(mfaToken, code);\n sendAuthResult(res, result, cookieOpts);\n } catch (err) {\n next(err);\n }\n });\n\n // POST /2fa/setup — begin 2FA setup (requires auth)\n router.post(\n \"/2fa/setup\",\n requireAuth(service),\n async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const result = await service.setup2FA(req.identity!.userId);\n res.json(result);\n } catch (err) {\n next(err);\n }\n },\n );\n\n // POST /2fa/enable — confirm and enable 2FA (requires auth)\n router.post(\n \"/2fa/enable\",\n requireAuth(service),\n async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const { code } = req.body as { code?: string };\n if (!code) {\n throw new UnauthenticatedError(\"code is required.\");\n }\n await service.enable2FA(req.identity!.userId, code);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n },\n );\n\n // POST /2fa/disable — disable 2FA (requires auth)\n router.post(\n \"/2fa/disable\",\n requireAuth(service),\n async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n const { code } = req.body as { code?: string };\n if (!code) {\n throw new UnauthenticatedError(\"code is required.\");\n }\n await service.disable2FA(req.identity!.userId, code);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n },\n );\n\n // ---------------------------------------------------------------------------\n // Account management (admin)\n // ---------------------------------------------------------------------------\n\n // POST /admin/lock/:userId — lock an account\n router.post(\n \"/admin/lock/:userId\",\n async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n await service.lockAccount(req.params[\"userId\"] as string);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n },\n );\n\n // POST /admin/unlock/:userId — unlock an account\n router.post(\n \"/admin/unlock/:userId\",\n async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n await service.unlockAccount(req.params[\"userId\"] as string);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n },\n );\n\n // POST /admin/disable/:userId — disable an account\n router.post(\n \"/admin/disable/:userId\",\n async (req: Request, res: Response, next: NextFunction): Promise<void> => {\n try {\n await service.disableAccount(req.params[\"userId\"] as string);\n res.status(204).end();\n } catch (err) {\n next(err);\n }\n },\n );\n\n // OAuth routes — only when providers are configured on the service\n if (service.oauth) {\n const oauthService = service.oauth;\n const baseUrl = options.oauthBaseUrl ?? \"\";\n\n const stateCookieOptions = {\n httpOnly: true,\n sameSite: \"lax\" as const,\n secure: process.env.NODE_ENV === \"production\",\n maxAge: 10 * 60 * 1000, // 10 minutes\n };\n\n for (const providerName of oauthService.providers) {\n const redirectUri = `${baseUrl}/${providerName}/callback`;\n\n router.get(\n `/${providerName}`,\n oauthAuthorize(oauthService, providerName, {\n redirectUri,\n setState: (_req, oauthRes, state) => {\n oauthRes.cookie(OAUTH_STATE_COOKIE, state, stateCookieOptions);\n },\n }),\n );\n\n router.get(\n `/${providerName}/callback`,\n oauthCallback(oauthService, providerName, {\n redirectUri,\n getState: (oauthReq) => readCookie(oauthReq, OAUTH_STATE_COOKIE) ?? null,\n setState: (_oauthReq, oauthRes, _state) => {\n oauthRes.clearCookie(OAUTH_STATE_COOKIE);\n },\n onSuccess: (_oauthReq, oauthRes, result) => {\n sendAuthResult(oauthRes, result, cookieOpts);\n },\n }),\n );\n }\n }\n\n // Mount the inner router at the configured prefix.\n const outer = Router();\n if (prefix) {\n outer.use(`/${prefix}`, router);\n } else {\n outer.use(router);\n }\n return outer;\n}\n\n// ---------------------------------------------------------------------------\n// Convenience error handler\n// ---------------------------------------------------------------------------\n\n/**\n * Factory that creates an Express error-handling middleware which converts\n * {@link IdentityError} instances to structured JSON responses.\n * Mount it after the identity router:\n *\n * ```ts\n * app.use(createIdentityRouter(service, { prefix: \"auth\" }));\n * app.use(identityErrorHandler()); // default console logger\n * app.use(identityErrorHandler({ logger: false })); // silent\n * ```\n *\n * @param options.logger - Logger for recording serialised error details.\n * Pass `false` to disable. Defaults to the console logger.\n */\nexport function identityErrorHandler(\n options: { logger?: IdentityLogger | false } = {},\n): (err: unknown, req: Request, res: Response, next: NextFunction) => void {\n const log = resolveLogger(options.logger);\n return (err: unknown, _req: Request, res: Response, next: NextFunction): void => {\n if (err instanceof IdentityError) {\n log.debug(\"identity error\", { code: err.code, status: err.statusCode, message: err.message });\n res.status(err.statusCode).json({ code: err.code, message: err.message });\n return;\n }\n log.error(\"unhandled error in identity router\", { error: String(err) });\n next(err);\n };\n}\n"],"mappings":";;;;AAoBA,MAAM,sBAAsB,QAAgC;CAC1D,MAAM,SAAS,IAAI,QAAQ;CAC3B,IAAI,CAAC,UAAU,CAAC,OAAO,WAAW,SAAS,GAAG,OAAO;CACrD,MAAM,QAAQ,OAAO,MAAM,CAAgB,CAAC,CAAC,KAAK;CAClD,OAAO,MAAM,SAAS,IAAI,QAAQ;AACpC;;;;;;AAOA,SAAgB,YAAY,SAA0C;CACpE,OAAO,OAAO,KAAc,MAAgB,SAAsC;EAChF,IAAI;GACF,MAAM,QAAQ,mBAAmB,GAAG;GACpC,IAAI,CAAC,OACH,MAAM,IAAI,qBAAqB;GAEjC,IAAI,WAAW,MAAM,QAAQ,aAAa,KAAK;GAC/C,KAAK;EACP,SAAS,OAAO;GACd,KAAK,KAAK;EACZ;CACF;AACF;;;;;AAMA,SAAgB,qBACd,SACA,aACA,cACgB;CAChB,OAAO,OAAO,KAAc,MAAgB,SAAsC;EAChF,IAAI;GACF,MAAM,YAAY,IAAI;GACtB,IAAI,CAAC,WACH,MAAM,IAAI,qBAAqB;GAEjC,MAAM,WAAW,eAAe,MAAM,aAAa,GAAG,IAAI,KAAA;GAM1D,IAAI,EAAC,MALkB,QAAQ,UAAU,aAAa;IACpD;IACA,QAAQ,YAAY,cAAc;IAClC;GACF,CAAC,EAAA,CACa,SACZ,MAAM,IAAI,eAAe;GAE3B,KAAK;EACP,SAAS,OAAO;GACd,KAAK,KAAK;EACZ;CACF;AACF;;AAGA,SAAgB,kBACd,SACA,YACgB;CAChB,OAAO,qBAAqB,SAAS,EAAE,WAAW,CAAC;AACrD;;;;;;;;;;;;;;;;;AC1CA,SAAgB,eACd,cACA,cACA,SACgB;CAChB,OAAO,OAAO,KAAc,KAAe,SAAsC;EAC/E,IAAI;GACF,MAAM,EAAE,KAAK,UAAU,aAAa,sBAAsB,cAAc,QAAQ,WAAW;GAC3F,MAAM,QAAQ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E,MAAM,MAAM,cAAc,QAAQ,MAAM;CACxC,QAAQ,KAAc,MAAe,KAAe,SAA6B;EAC/E,IAAI,eAAe,eAAe;GAChC,IAAI,MAAM,kBAAkB;IAAE,MAAM,IAAI;IAAM,QAAQ,IAAI;IAAY,SAAS,IAAI;GAAQ,CAAC;GAC5F,IAAI,OAAO,IAAI,UAAU,CAAC,CAAC,KAAK;IAAE,MAAM,IAAI;IAAM,SAAS,IAAI;GAAQ,CAAC;GACxE;EACF;EACA,IAAI,MAAM,sCAAsC,EAAE,OAAO,OAAO,GAAG,EAAE,CAAC;EACtE,KAAK,GAAG;CACV;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"identity-Bz9RDOvT.mjs","names":[],"sources":["../core/config.ts","../core/authorization.ts","../core/session-state.ts","../core/oauth/oauth-service.ts","../schema/model.ts"],"sourcesContent":["import { IdentityConfigError } from \"./errors\";\nimport type { IdentityLogger } from \"./logger\";\nimport { resolveLogger } from \"./logger\";\nimport type { NotificationService } from \"./notification\";\nimport type { IdentityEvent } from \"./types\";\n\n/**\n * Pluggable override points for advanced consumers. All are optional; sensible Node\n * defaults are supplied by the runtime entry (`@azlib/identity/node`).\n */\nexport interface IdentityOverrides {\n /** Returns the current time. Override in tests for deterministic clocks. */\n now?: () => Date;\n /** Generates a unique id (user ids, session ids). Defaults to `crypto.randomUUID`. */\n generateId?: () => string;\n /**\n * Lifecycle hook invoked for every audit event (registration, login, refresh, etc.).\n * Use it to forward events to your own logging/analytics pipeline. It must never throw\n * for normal operation; failures are swallowed so auditing cannot break auth flows.\n */\n onEvent?: (event: IdentityEvent) => void | Promise<void>;\n}\n\n/** Account lockout policy applied after repeated failed logins. */\nexport interface LockoutConfig {\n /**\n * How many consecutive failed login attempts are allowed before the account is\n * temporarily locked. Set to 0 to disable lockout. Default 10.\n */\n maxFailedAttempts: number;\n /**\n * How long (in seconds) a locked account is blocked before automatic unlock.\n * Default 900 (15 minutes). Set to 0 for permanent lock (manual unlock required).\n */\n durationSeconds: number;\n}\n\n/** Raw configuration accepted from consumers. */\nexport interface IdentityConfigInput {\n /**\n * Secret used to sign and verify access tokens (HMAC). Must be at least 32 characters.\n * Provide via environment, never hardcode.\n */\n accessTokenSecret: string;\n /** Access-token lifetime in seconds. Default 900 (15 minutes). */\n accessTokenTtlSeconds?: number;\n /** Refresh-token lifetime in seconds. Default 1209600 (14 days). */\n refreshTokenTtlSeconds?: number;\n /** Token issuer (`iss`). Default `azlib-identity`. */\n issuer?: string;\n /** Token audience (`aud`). Optional. */\n audience?: string;\n /** scrypt cost parameter `N`. Default 16384. */\n passwordScryptCost?: number;\n /**\n * Account lockout policy. Omit or set `maxFailedAttempts: 0` to disable. Default: 10\n * attempts, 15-minute lockout.\n */\n lockout?: Partial<LockoutConfig>;\n /**\n * Pluggable notification service for email verification, password reset, and SMS 2FA.\n * Omit if you do not need these features.\n */\n notifications?: NotificationService;\n /**\n * Logger used throughout the package. Pass your own `IdentityLogger` to route\n * diagnostic output to Winston, Pino, or any other provider. Pass `false` to silence\n * all logging. Defaults to a console-based logger when omitted.\n */\n logger?: IdentityLogger | false;\n /** Override points for clock and id generation. */\n overrides?: IdentityOverrides;\n}\n\n/** Fully resolved, validated configuration used internally. */\nexport interface IdentityConfig {\n accessTokenSecret: string;\n accessTokenTtlSeconds: number;\n refreshTokenTtlSeconds: number;\n issuer: string;\n audience: string | undefined;\n passwordScryptCost: number;\n lockout: LockoutConfig;\n notifications: NotificationService | undefined;\n /** Resolved logger; never `false` — `false` becomes {@link noopLogger}. */\n logger: IdentityLogger;\n now: () => Date;\n generateId: () => string;\n onEvent: ((event: IdentityEvent) => void | Promise<void>) | undefined;\n}\n\nconst MIN_SECRET_LENGTH = 32;\n\nconst defaultGenerateId = (): string => globalThis.crypto.randomUUID();\nconst defaultNow = (): Date => new Date();\n\n/**\n * Validates and applies defaults to consumer-provided configuration.\n * Throws {@link IdentityConfigError} when required values are missing or invalid.\n */\nexport function resolveIdentityConfig(input: IdentityConfigInput): IdentityConfig {\n if (!input.accessTokenSecret || input.accessTokenSecret.length < MIN_SECRET_LENGTH) {\n throw new IdentityConfigError(\n `accessTokenSecret must be at least ${MIN_SECRET_LENGTH} characters.`,\n );\n }\n\n const accessTokenTtlSeconds = input.accessTokenTtlSeconds ?? 900;\n const refreshTokenTtlSeconds = input.refreshTokenTtlSeconds ?? 60 * 60 * 24 * 14;\n const passwordScryptCost = input.passwordScryptCost ?? 16384;\n\n if (accessTokenTtlSeconds <= 0) {\n throw new IdentityConfigError(\"accessTokenTtlSeconds must be positive.\");\n }\n if (refreshTokenTtlSeconds <= accessTokenTtlSeconds) {\n throw new IdentityConfigError(\n \"refreshTokenTtlSeconds must be greater than accessTokenTtlSeconds.\",\n );\n }\n if ((passwordScryptCost & (passwordScryptCost - 1)) !== 0) {\n throw new IdentityConfigError(\"passwordScryptCost must be a power of two.\");\n }\n\n return {\n accessTokenSecret: input.accessTokenSecret,\n accessTokenTtlSeconds,\n refreshTokenTtlSeconds,\n issuer: input.issuer ?? \"azlib-identity\",\n audience: input.audience,\n passwordScryptCost,\n lockout: {\n maxFailedAttempts: input.lockout?.maxFailedAttempts ?? 10,\n durationSeconds: input.lockout?.durationSeconds ?? 900,\n },\n now: input.overrides?.now ?? defaultNow,\n generateId: input.overrides?.generateId ?? defaultGenerateId,\n onEvent: input.overrides?.onEvent,\n notifications: input.notifications,\n logger: resolveLogger(input.logger),\n };\n}\n","import type { AuthenticatedIdentity, Permission } from \"./types\";\n\n/**\n * Context passed to authorization checks. `resource` is an opaque consumer-supplied\n * object (e.g. a loaded document) used by ownership/relationship policies.\n */\nexport interface AuthorizationContext<TResource = unknown> {\n principal: AuthenticatedIdentity;\n /** The action being attempted, typically a permission string. */\n action: string;\n /** The target resource, if any. */\n resource?: TResource;\n}\n\n/**\n * A policy rule returns:\n * - `true` to allow,\n * - `false`/`undefined` to abstain (deny-by-default unless another rule allows),\n * It must never throw for normal \"denied\" outcomes.\n */\nexport type PolicyRule<TResource = unknown> = (\n context: AuthorizationContext<TResource>,\n) => boolean | undefined | Promise<boolean | undefined>;\n\n/** A named requirement combining a required permission and optional ownership policy. */\nexport interface AuthorizationRequirement<TResource = unknown> {\n /** Permission the principal must hold. Omit to rely solely on policies. */\n permission?: Permission;\n /** Optional ownership/relationship rule evaluated against the resource. */\n policy?: PolicyRule<TResource>;\n}\n\n/** Result of an authorization decision. */\nexport interface AuthorizationDecision {\n allowed: boolean;\n /** Non-sensitive reason for diagnostics/audit. */\n reason: string;\n}\n\nconst hasPermission = (\n principal: AuthenticatedIdentity,\n permission: Permission,\n): boolean => principal.permissions.includes(permission);\n\n/**\n * Evaluates a requirement using deny-by-default semantics:\n * 1. If a `permission` is required and the principal lacks it, deny.\n * 2. If a `policy` is provided, it must return `true` to allow.\n * 3. If neither is provided, deny (nothing explicitly granted access).\n */\nexport async function evaluateAuthorization<TResource = unknown>(\n requirement: AuthorizationRequirement<TResource>,\n context: AuthorizationContext<TResource>,\n): Promise<AuthorizationDecision> {\n const { permission, policy } = requirement;\n\n if (permission !== undefined && !hasPermission(context.principal, permission)) {\n return { allowed: false, reason: \"missing-permission\" };\n }\n\n if (policy) {\n const result = await policy(context);\n if (result !== true) {\n return { allowed: false, reason: \"policy-denied\" };\n }\n return { allowed: true, reason: \"policy-allowed\" };\n }\n\n if (permission !== undefined) {\n return { allowed: true, reason: \"permission-granted\" };\n }\n\n return { allowed: false, reason: \"no-grant\" };\n}\n\n/** Convenience boolean form of {@link evaluateAuthorization}. */\nexport async function isAuthorized<TResource = unknown>(\n requirement: AuthorizationRequirement<TResource>,\n context: AuthorizationContext<TResource>,\n): Promise<boolean> {\n return (await evaluateAuthorization(requirement, context)).allowed;\n}\n","import type { IdentityConfig } from \"./config\";\nimport type { IdentityStore } from \"./identity-store\";\nimport type { TokenService } from \"./token-service\";\nimport type { AuthResult, AuthenticatedIdentity, IdentityUser } from \"./types\";\n\n/** Dependencies shared by the register/login/refresh flows. */\nexport interface SessionDeps {\n config: IdentityConfig;\n store: IdentityStore;\n tokenService: TokenService;\n}\n\n/**\n * Builds the runtime principal for a user by reading their roles and permissions from\n * the store. Returns the shape attached to authenticated requests.\n */\nexport async function hydratePrincipal(\n store: IdentityStore,\n user: IdentityUser,\n): Promise<AuthenticatedIdentity> {\n const [roles, permissions] = await Promise.all([\n store.listRolesForUser(user.userId),\n store.listPermissionsForUser(user.userId),\n ]);\n\n return {\n userId: user.userId,\n email: user.email,\n displayName: user.displayName,\n status: user.status,\n emailVerified: user.emailVerifiedAt !== null,\n roles: roles.map((role) => role.name),\n permissions: [...permissions],\n };\n}\n\n/**\n * Issues a fresh token pair for a user and persists a new refresh session\n * (storing only the hash of the refresh token).\n */\nexport async function issueSession(\n deps: SessionDeps,\n user: IdentityUser,\n): Promise<AuthResult> {\n const { config, store, tokenService } = deps;\n const now = config.now();\n\n const principal = await hydratePrincipal(store, user);\n const access = await tokenService.issueAccessToken(user.userId, user.authVersion);\n const sessionId = config.generateId();\n const refresh = tokenService.createRefreshToken(sessionId);\n\n const refreshExpiresAt = new Date(now.getTime() + config.refreshTokenTtlSeconds * 1000);\n await store.createSession({\n sessionId,\n userId: user.userId,\n refreshTokenHash: refresh.hash,\n createdAt: now,\n expiresAt: refreshExpiresAt,\n });\n\n return {\n user: principal,\n tokens: {\n accessToken: access.token,\n refreshToken: refresh.token,\n accessTokenExpiresAt: access.expiresAt,\n refreshTokenExpiresAt: refreshExpiresAt,\n },\n };\n}\n","import type { AuditLogger } from \"../audit\";\nimport type { IdentityConfig } from \"../config\";\nimport type { IdentityStore } from \"../identity-store\";\nimport { issueSession, type SessionDeps } from \"../session-state\";\nimport type { AuthResult, OAuthLinkedAccount } from \"../types\";\nimport type { OAuthProvider } from \"./oauth-provider\";\n\n/** Result of {@link OAuthService.buildAuthorizationUrl}. */\nexport interface OAuthAuthorizationUrl {\n /** The full provider authorization URL to redirect the user to. */\n url: string;\n /**\n * An opaque CSRF-prevention state value. Store this in a signed cookie or server\n * session and pass it as `expectedState` when calling {@link OAuthService.handleCallback}.\n */\n state: string;\n}\n\n/** Parameters for {@link OAuthService.handleCallback}. */\nexport interface OAuthCallbackParams {\n /** The authorization code received from the provider callback query string. */\n code: string;\n /** The `state` value received from the provider callback query string. */\n state: string;\n /**\n * The expected state value previously returned by {@link OAuthService.buildAuthorizationUrl}.\n * The callback will be rejected when they do not match (CSRF protection).\n */\n expectedState: string;\n /** The same redirect URI that was used in the authorization request. */\n redirectUri: string;\n /** Optional scopes to override for this callback's code exchange. */\n scopes?: string[];\n}\n\n/** The OAuth2 / OIDC surface of the identity service. */\nexport interface OAuthService {\n /** Returns the registered provider names, e.g. `[\"google\", \"microsoft\"]`. */\n readonly providers: readonly string[];\n\n /**\n * Builds the authorization URL for the given provider. Redirect the user's browser to\n * the returned `url`, then store `state` for later verification.\n */\n buildAuthorizationUrl(providerName: string, redirectUri: string, scopes?: string[]): OAuthAuthorizationUrl;\n\n /**\n * Handles the provider callback after user consent. Verifies state, exchanges the code\n * for tokens, resolves or provisions a local user, and returns a full auth result.\n *\n * Throws {@link OAuthProviderNotFoundError} for unknown providers.\n * Throws a generic {@link IdentityError} when state mismatches (CSRF guard).\n */\n handleCallback(providerName: string, params: OAuthCallbackParams): Promise<AuthResult>;\n}\n\n/** Thrown when an OAuth operation targets an unregistered provider name. */\nexport class OAuthProviderNotFoundError extends Error {\n constructor(providerName: string) {\n super(`No OAuth provider registered with name \"${providerName}\".`);\n this.name = \"OAuthProviderNotFoundError\";\n }\n}\n\n/** Thrown when the callback state does not match the expected state (CSRF guard). */\nexport class OAuthStateMismatchError extends Error {\n constructor() {\n super(\"OAuth state mismatch. The callback may have been replayed or tampered with.\");\n this.name = \"OAuthStateMismatchError\";\n }\n}\n\n/** Dependencies for {@link createOAuthService}. */\nexport interface OAuthServiceDeps {\n providers: readonly OAuthProvider[];\n config: IdentityConfig;\n store: IdentityStore;\n sessionDeps: SessionDeps;\n audit: AuditLogger;\n}\n\n/**\n * Creates the OAuth2 / OIDC service. Wire into the identity service by passing configured\n * provider instances (e.g. `createGoogleOAuthProvider(...)`) to the `oauth.providers` list\n * in {@link IdentityConfigInput}.\n */\nexport function createOAuthService(deps: OAuthServiceDeps): OAuthService {\n const { providers, config, store, sessionDeps, audit } = deps;\n\n const providerMap = new Map<string, OAuthProvider>();\n for (const p of providers) {\n providerMap.set(p.name, p);\n }\n\n function getProvider(name: string): OAuthProvider {\n const p = providerMap.get(name);\n if (!p) throw new OAuthProviderNotFoundError(name);\n return p;\n }\n\n return {\n get providers() {\n return [...providerMap.keys()];\n },\n\n buildAuthorizationUrl(providerName, redirectUri, scopes) {\n const provider = getProvider(providerName);\n const state = config.generateId();\n const url = provider.buildAuthorizationUrl({ redirectUri, state, scopes });\n return { url, state };\n },\n\n async handleCallback(providerName, params) {\n // CSRF guard — must be the first check.\n if (params.state !== params.expectedState) {\n throw new OAuthStateMismatchError();\n }\n\n const provider = getProvider(providerName);\n\n // Exchange the authorization code for provider tokens.\n const tokens = await provider.exchangeCode({\n code: params.code,\n redirectUri: params.redirectUri,\n });\n\n // Fetch normalized user info from the provider.\n const userInfo = await provider.fetchUserInfo(tokens);\n\n const now = config.now();\n\n // 1. Look up by OAuth link (returning user).\n if (store.findUserByOAuthId) {\n const linkedUser = await store.findUserByOAuthId(providerName, userInfo.providerUserId);\n if (linkedUser) {\n await audit.record(\"user.login.succeeded\", linkedUser.userId, {\n email: linkedUser.email,\n provider: providerName,\n });\n return issueSession(sessionDeps, linkedUser);\n }\n }\n\n // 2. Look up by email (existing local account — link the provider).\n if (userInfo.email) {\n const existingUser = await store.findUserByEmail(userInfo.email);\n if (existingUser) {\n await linkOAuthAccount(store, existingUser.userId, providerName, userInfo, now);\n await audit.record(\"user.oauth.linked\", existingUser.userId, {\n provider: providerName,\n providerUserId: userInfo.providerUserId,\n });\n await audit.record(\"user.login.succeeded\", existingUser.userId, {\n email: existingUser.email,\n provider: providerName,\n });\n return issueSession(sessionDeps, existingUser);\n }\n }\n\n // 3. Provision a new local user and link the provider.\n const newUser = await store.createUser({\n userId: config.generateId(),\n email: userInfo.email ?? `oauth:${providerName}:${userInfo.providerUserId}`,\n displayName: userInfo.displayName,\n status: \"active\",\n authVersion: 0,\n createdAt: now,\n updatedAt: now,\n });\n await linkOAuthAccount(store, newUser.userId, providerName, userInfo, now);\n await audit.record(\"user.registered\", newUser.userId, {\n provider: providerName,\n providerUserId: userInfo.providerUserId,\n });\n await audit.record(\"user.oauth.linked\", newUser.userId, {\n provider: providerName,\n providerUserId: userInfo.providerUserId,\n });\n await audit.record(\"user.login.succeeded\", newUser.userId, {\n email: newUser.email,\n provider: providerName,\n });\n return issueSession(sessionDeps, newUser);\n },\n };\n}\n\nasync function linkOAuthAccount(\n store: IdentityStore,\n userId: string,\n provider: string,\n userInfo: { providerUserId: string; email: string | null; displayName: string | null },\n now: Date,\n): Promise<void> {\n if (!store.createOAuthLink) return; // Store does not support OAuth links — skip silently.\n\n const link: OAuthLinkedAccount = {\n userId,\n provider,\n providerUserId: userInfo.providerUserId,\n email: userInfo.email,\n displayName: userInfo.displayName,\n linkedAt: now,\n };\n await store.createOAuthLink(link);\n}\n","/**\n * Logical description of the relational schema `@azlib/identity` expects.\n *\n * Concrete DDL is shipped alongside this module:\n * - `@azlib/identity/schema/postgres.sql`\n * - `@azlib/identity/schema/mysql.sql`\n * - `@azlib/identity/schema/sqlite.sql`\n * - `@azlib/identity/schema/prisma.schema`\n *\n * This object is documentation-as-data so consumers and tooling can introspect the\n * expected tables without parsing SQL.\n */\nexport interface SchemaColumn {\n name: string;\n description: string;\n nullable: boolean;\n}\n\nexport interface SchemaTable {\n name: string;\n description: string;\n columns: readonly SchemaColumn[];\n}\n\nexport interface SchemaModel {\n tables: readonly SchemaTable[];\n}\n\nexport const identitySchemaModel: SchemaModel = {\n tables: [\n {\n name: \"identity_users\",\n description: \"Core user accounts.\",\n columns: [\n { name: \"user_id\", description: \"Primary key.\", nullable: false },\n { name: \"email\", description: \"Unique, case-insensitive login email.\", nullable: false },\n { name: \"display_name\", description: \"Optional display name.\", nullable: true },\n { name: \"status\", description: \"active | disabled | locked.\", nullable: false },\n { name: \"email_verified_at\", description: \"When email was verified.\", nullable: true },\n { name: \"auth_version\", description: \"Token invalidation counter.\", nullable: false },\n { name: \"created_at\", description: \"Creation timestamp.\", nullable: false },\n { name: \"updated_at\", description: \"Last update timestamp.\", nullable: false },\n ],\n },\n {\n name: \"identity_credentials\",\n description: \"Password hashes, one per user.\",\n columns: [\n { name: \"user_id\", description: \"FK to identity_users.\", nullable: false },\n { name: \"password_hash\", description: \"Algorithm-tagged hash.\", nullable: false },\n { name: \"updated_at\", description: \"Last update timestamp.\", nullable: false },\n ],\n },\n {\n name: \"identity_sessions\",\n description: \"Server-side refresh sessions with hashed tokens.\",\n columns: [\n { name: \"session_id\", description: \"Primary key.\", nullable: false },\n { name: \"user_id\", description: \"FK to identity_users.\", nullable: false },\n { name: \"refresh_token_hash\", description: \"Hash of the active refresh token.\", nullable: false },\n { name: \"created_at\", description: \"Creation timestamp.\", nullable: false },\n { name: \"expires_at\", description: \"Expiry timestamp.\", nullable: false },\n { name: \"revoked_at\", description: \"Set when rotated or revoked.\", nullable: true },\n ],\n },\n {\n name: \"identity_roles\",\n description: \"Named roles.\",\n columns: [\n { name: \"role_id\", description: \"Primary key.\", nullable: false },\n { name: \"name\", description: \"Unique role name.\", nullable: false },\n { name: \"description\", description: \"Optional description.\", nullable: true },\n ],\n },\n {\n name: \"identity_user_roles\",\n description: \"User-to-role assignments.\",\n columns: [\n { name: \"user_id\", description: \"FK to identity_users.\", nullable: false },\n { name: \"role_id\", description: \"FK to identity_roles.\", nullable: false },\n ],\n },\n {\n name: \"identity_role_permissions\",\n description: \"Permissions granted to roles.\",\n columns: [\n { name: \"role_id\", description: \"FK to identity_roles.\", nullable: false },\n { name: \"permission\", description: \"Permission string.\", nullable: false },\n ],\n },\n {\n name: \"identity_user_permissions\",\n description: \"Permissions granted directly to users.\",\n columns: [\n { name: \"user_id\", description: \"FK to identity_users.\", nullable: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,CACP;GAAE,MAAM;GAAW,aAAa;GAAyB,UAAU;EAAM,GACzE;GAAE,MAAM;GAAW,aAAa;GAAyB,UAAU;EAAM,CAC3E;CACF;CACA;EACE,MAAM;EACN,aAAa;EACb,SAAS,CACP;GAAE,MAAM;GAAW,aAAa;GAAyB,UAAU;EAAM,GACzE;GAAE,MAAM;GAAc,aAAa;GAAsB,UAAU;EAAM,CAC3E;CACF;CACA;EACE,MAAM;EACN,aAAa;EACb,SAAS,CACP;GAAE,MAAM;GAAW,aAAa;GAAyB,UAAU;EAAM,GACzE;GAAE,MAAM;GAAc,aAAa;GAAsB,UAAU;EAAM,CAC3E;CACF;AACF,EACF"}
|
|
1
|
+
{"version":3,"file":"identity-Bz9RDOvT.mjs","names":[],"sources":["../core/config.ts","../core/authorization.ts","../core/session-state.ts","../core/oauth/oauth-service.ts","../schema/model.ts"],"sourcesContent":["import { IdentityConfigError } from \"./errors\";\nimport type { IdentityLogger } from \"./logger\";\nimport { resolveLogger } from \"./logger\";\nimport type { NotificationService } from \"./notification\";\nimport type { IdentityEvent } from \"./types\";\n\n/**\n * Pluggable override points for advanced consumers. All are optional; sensible Node\n * defaults are supplied by the runtime entry (`@azlib/identity/node`).\n */\nexport interface IdentityOverrides {\n /** Returns the current time. Override in tests for deterministic clocks. */\n now?: () => Date;\n /** Generates a unique id (user ids, session ids). Defaults to `crypto.randomUUID`. */\n generateId?: () => string;\n /**\n * Lifecycle hook invoked for every audit event (registration, login, refresh, etc.).\n * Use it to forward events to your own logging/analytics pipeline. It must never throw\n * for normal operation; failures are swallowed so auditing cannot break auth flows.\n */\n onEvent?: (event: IdentityEvent) => void | Promise<void>;\n}\n\n/** Account lockout policy applied after repeated failed logins. */\nexport interface LockoutConfig {\n /**\n * How many consecutive failed login attempts are allowed before the account is\n * temporarily locked. Set to 0 to disable lockout. Default 10.\n */\n maxFailedAttempts: number;\n /**\n * How long (in seconds) a locked account is blocked before automatic unlock.\n * Default 900 (15 minutes). Set to 0 for permanent lock (manual unlock required).\n */\n durationSeconds: number;\n}\n\n/** Raw configuration accepted from consumers. */\nexport interface IdentityConfigInput {\n /**\n * Secret used to sign and verify access tokens (HMAC). Must be at least 32 characters.\n * Provide via environment, never hardcode.\n */\n accessTokenSecret: string;\n /** Access-token lifetime in seconds. Default 900 (15 minutes). */\n accessTokenTtlSeconds?: number;\n /** Refresh-token lifetime in seconds. Default 1209600 (14 days). */\n refreshTokenTtlSeconds?: number;\n /** Token issuer (`iss`). Default `azlib-identity`. */\n issuer?: string;\n /** Token audience (`aud`). Optional. */\n audience?: string;\n /** scrypt cost parameter `N`. Default 16384. */\n passwordScryptCost?: number;\n /**\n * Account lockout policy. Omit or set `maxFailedAttempts: 0` to disable. Default: 10\n * attempts, 15-minute lockout.\n */\n lockout?: Partial<LockoutConfig>;\n /**\n * Pluggable notification service for email verification, password reset, and SMS 2FA.\n * Omit if you do not need these features.\n */\n notifications?: NotificationService;\n /**\n * Logger used throughout the package. Pass your own `IdentityLogger` to route\n * diagnostic output to Winston, Pino, or any other provider. Pass `false` to silence\n * all logging. Defaults to a console-based logger when omitted.\n */\n logger?: IdentityLogger | false;\n /** Override points for clock and id generation. */\n overrides?: IdentityOverrides;\n}\n\n/** Fully resolved, validated configuration used internally. */\nexport interface IdentityConfig {\n accessTokenSecret: string;\n accessTokenTtlSeconds: number;\n refreshTokenTtlSeconds: number;\n issuer: string;\n audience: string | undefined;\n passwordScryptCost: number;\n lockout: LockoutConfig;\n notifications: NotificationService | undefined;\n /** Resolved logger; never `false` — `false` becomes {@link noopLogger}. */\n logger: IdentityLogger;\n now: () => Date;\n generateId: () => string;\n onEvent: ((event: IdentityEvent) => void | Promise<void>) | undefined;\n}\n\nconst MIN_SECRET_LENGTH = 32;\n\nconst defaultGenerateId = (): string => globalThis.crypto.randomUUID();\nconst defaultNow = (): Date => new Date();\n\n/**\n * Validates and applies defaults to consumer-provided configuration.\n * Throws {@link IdentityConfigError} when required values are missing or invalid.\n */\nexport function resolveIdentityConfig(input: IdentityConfigInput): IdentityConfig {\n if (!input.accessTokenSecret || input.accessTokenSecret.length < MIN_SECRET_LENGTH) {\n throw new IdentityConfigError(\n `accessTokenSecret must be at least ${MIN_SECRET_LENGTH} characters.`,\n );\n }\n\n const accessTokenTtlSeconds = input.accessTokenTtlSeconds ?? 900;\n const refreshTokenTtlSeconds = input.refreshTokenTtlSeconds ?? 60 * 60 * 24 * 14;\n const passwordScryptCost = input.passwordScryptCost ?? 16384;\n\n if (accessTokenTtlSeconds <= 0) {\n throw new IdentityConfigError(\"accessTokenTtlSeconds must be positive.\");\n }\n if (refreshTokenTtlSeconds <= accessTokenTtlSeconds) {\n throw new IdentityConfigError(\n \"refreshTokenTtlSeconds must be greater than accessTokenTtlSeconds.\",\n );\n }\n if ((passwordScryptCost & (passwordScryptCost - 1)) !== 0) {\n throw new IdentityConfigError(\"passwordScryptCost must be a power of two.\");\n }\n\n return {\n accessTokenSecret: input.accessTokenSecret,\n accessTokenTtlSeconds,\n refreshTokenTtlSeconds,\n issuer: input.issuer ?? \"azlib-identity\",\n audience: input.audience,\n passwordScryptCost,\n lockout: {\n maxFailedAttempts: input.lockout?.maxFailedAttempts ?? 10,\n durationSeconds: input.lockout?.durationSeconds ?? 900,\n },\n now: input.overrides?.now ?? defaultNow,\n generateId: input.overrides?.generateId ?? defaultGenerateId,\n onEvent: input.overrides?.onEvent,\n notifications: input.notifications,\n logger: resolveLogger(input.logger),\n };\n}\n","import type { AuthenticatedIdentity, Permission } from \"./types\";\n\n/**\n * Context passed to authorization checks. `resource` is an opaque consumer-supplied\n * object (e.g. a loaded document) used by ownership/relationship policies.\n */\nexport interface AuthorizationContext<TResource = unknown> {\n principal: AuthenticatedIdentity;\n /** The action being attempted, typically a permission string. */\n action: string;\n /** The target resource, if any. */\n resource?: TResource;\n}\n\n/**\n * A policy rule returns:\n * - `true` to allow,\n * - `false`/`undefined` to abstain (deny-by-default unless another rule allows),\n * It must never throw for normal \"denied\" outcomes.\n */\nexport type PolicyRule<TResource = unknown> = (\n context: AuthorizationContext<TResource>,\n) => boolean | undefined | Promise<boolean | undefined>;\n\n/** A named requirement combining a required permission and optional ownership policy. */\nexport interface AuthorizationRequirement<TResource = unknown> {\n /** Permission the principal must hold. Omit to rely solely on policies. */\n permission?: Permission;\n /** Optional ownership/relationship rule evaluated against the resource. */\n policy?: PolicyRule<TResource>;\n}\n\n/** Result of an authorization decision. */\nexport interface AuthorizationDecision {\n allowed: boolean;\n /** Non-sensitive reason for diagnostics/audit. */\n reason: string;\n}\n\nconst hasPermission = (\n principal: AuthenticatedIdentity,\n permission: Permission,\n): boolean => principal.permissions.includes(permission);\n\n/**\n * Evaluates a requirement using deny-by-default semantics:\n * 1. If a `permission` is required and the principal lacks it, deny.\n * 2. If a `policy` is provided, it must return `true` to allow.\n * 3. If neither is provided, deny (nothing explicitly granted access).\n */\nexport async function evaluateAuthorization<TResource = unknown>(\n requirement: AuthorizationRequirement<TResource>,\n context: AuthorizationContext<TResource>,\n): Promise<AuthorizationDecision> {\n const { permission, policy } = requirement;\n\n if (permission !== undefined && !hasPermission(context.principal, permission)) {\n return { allowed: false, reason: \"missing-permission\" };\n }\n\n if (policy) {\n const result = await policy(context);\n if (result !== true) {\n return { allowed: false, reason: \"policy-denied\" };\n }\n return { allowed: true, reason: \"policy-allowed\" };\n }\n\n if (permission !== undefined) {\n return { allowed: true, reason: \"permission-granted\" };\n }\n\n return { allowed: false, reason: \"no-grant\" };\n}\n\n/** Convenience boolean form of {@link evaluateAuthorization}. */\nexport async function isAuthorized<TResource = unknown>(\n requirement: AuthorizationRequirement<TResource>,\n context: AuthorizationContext<TResource>,\n): Promise<boolean> {\n return (await evaluateAuthorization(requirement, context)).allowed;\n}\n","import type { IdentityConfig } from \"./config\";\nimport type { IdentityStore } from \"./identity-store\";\nimport type { TokenService } from \"./token-service\";\nimport type { AuthResult, AuthenticatedIdentity, IdentityUser } from \"./types\";\n\n/** Dependencies shared by the register/login/refresh flows. */\nexport interface SessionDeps {\n config: IdentityConfig;\n store: IdentityStore;\n tokenService: TokenService;\n}\n\n/**\n * Builds the runtime principal for a user by reading their roles and permissions from\n * the store. Returns the shape attached to authenticated requests.\n */\nexport async function hydratePrincipal(\n store: IdentityStore,\n user: IdentityUser,\n): Promise<AuthenticatedIdentity> {\n const [roles, permissions] = await Promise.all([\n store.listRolesForUser(user.userId),\n store.listPermissionsForUser(user.userId),\n ]);\n\n return {\n userId: user.userId,\n email: user.email,\n displayName: user.displayName,\n status: user.status,\n emailVerified: user.emailVerifiedAt !== null,\n roles: roles.map((role) => role.name),\n permissions: [...permissions],\n };\n}\n\n/**\n * Issues a fresh token pair for a user and persists a new refresh session\n * (storing only the hash of the refresh token).\n */\nexport async function issueSession(\n deps: SessionDeps,\n user: IdentityUser,\n): Promise<AuthResult> {\n const { config, store, tokenService } = deps;\n const now = config.now();\n\n const principal = await hydratePrincipal(store, user);\n const access = await tokenService.issueAccessToken(user.userId, user.authVersion);\n const sessionId = config.generateId();\n const refresh = tokenService.createRefreshToken(sessionId);\n\n const refreshExpiresAt = new Date(now.getTime() + config.refreshTokenTtlSeconds * 1000);\n await store.createSession({\n sessionId,\n userId: user.userId,\n refreshTokenHash: refresh.hash,\n createdAt: now,\n expiresAt: refreshExpiresAt,\n });\n\n return {\n user: principal,\n tokens: {\n accessToken: access.token,\n refreshToken: refresh.token,\n accessTokenExpiresAt: access.expiresAt,\n refreshTokenExpiresAt: refreshExpiresAt,\n },\n };\n}\n","import type { AuditLogger } from \"../audit\";\nimport type { IdentityConfig } from \"../config\";\nimport type { IdentityStore } from \"../identity-store\";\nimport { issueSession, type SessionDeps } from \"../session-state\";\nimport type { AuthResult, OAuthLinkedAccount } from \"../types\";\nimport type { OAuthProvider } from \"./oauth-provider\";\n\n/** Result of {@link OAuthService.buildAuthorizationUrl}. */\nexport interface OAuthAuthorizationUrl {\n /** The full provider authorization URL to redirect the user to. */\n url: string;\n /**\n * An opaque CSRF-prevention state value. Store this in a signed cookie or server\n * session and pass it as `expectedState` when calling {@link OAuthService.handleCallback}.\n */\n state: string;\n}\n\n/** Parameters for {@link OAuthService.handleCallback}. */\nexport interface OAuthCallbackParams {\n /** The authorization code received from the provider callback query string. */\n code: string;\n /** The `state` value received from the provider callback query string. */\n state: string;\n /**\n * The expected state value previously returned by {@link OAuthService.buildAuthorizationUrl}.\n * The callback will be rejected when they do not match (CSRF protection).\n */\n expectedState: string;\n /** The same redirect URI that was used in the authorization request. */\n redirectUri: string;\n /** Optional scopes to override for this callback's code exchange. */\n scopes?: string[];\n}\n\n/** The OAuth2 / OIDC surface of the identity service. */\nexport interface OAuthService {\n /** Returns the registered provider names, e.g. `[\"google\", \"microsoft\"]`. */\n readonly providers: readonly string[];\n\n /**\n * Builds the authorization URL for the given provider. Redirect the user's browser to\n * the returned `url`, then store `state` for later verification.\n */\n buildAuthorizationUrl(providerName: string, redirectUri: string, scopes?: string[]): OAuthAuthorizationUrl;\n\n /**\n * Handles the provider callback after user consent. Verifies state, exchanges the code\n * for tokens, resolves or provisions a local user, and returns a full auth result.\n *\n * Throws {@link OAuthProviderNotFoundError} for unknown providers.\n * Throws a generic {@link IdentityError} when state mismatches (CSRF guard).\n */\n handleCallback(providerName: string, params: OAuthCallbackParams): Promise<AuthResult>;\n}\n\n/** Thrown when an OAuth operation targets an unregistered provider name. */\nexport class OAuthProviderNotFoundError extends Error {\n constructor(providerName: string) {\n super(`No OAuth provider registered with name \"${providerName}\".`);\n this.name = \"OAuthProviderNotFoundError\";\n }\n}\n\n/** Thrown when the callback state does not match the expected state (CSRF guard). */\nexport class OAuthStateMismatchError extends Error {\n constructor() {\n super(\"OAuth state mismatch. The callback may have been replayed or tampered with.\");\n this.name = \"OAuthStateMismatchError\";\n }\n}\n\n/** Dependencies for {@link createOAuthService}. */\nexport interface OAuthServiceDeps {\n providers: readonly OAuthProvider[];\n config: IdentityConfig;\n store: IdentityStore;\n sessionDeps: SessionDeps;\n audit: AuditLogger;\n}\n\n/**\n * Creates the OAuth2 / OIDC service. Wire into the identity service by passing configured\n * provider instances (e.g. `createGoogleOAuthProvider(...)`) to the `oauth.providers` list\n * in {@link IdentityConfigInput}.\n */\nexport function createOAuthService(deps: OAuthServiceDeps): OAuthService {\n const { providers, config, store, sessionDeps, audit } = deps;\n\n const providerMap = new Map<string, OAuthProvider>();\n for (const p of providers) {\n providerMap.set(p.name, p);\n }\n\n function getProvider(name: string): OAuthProvider {\n const p = providerMap.get(name);\n if (!p) throw new OAuthProviderNotFoundError(name);\n return p;\n }\n\n return {\n get providers() {\n return [...providerMap.keys()];\n },\n\n buildAuthorizationUrl(providerName, redirectUri, scopes) {\n const provider = getProvider(providerName);\n const state = config.generateId();\n const url = provider.buildAuthorizationUrl({ redirectUri, state, scopes });\n return { url, state };\n },\n\n async handleCallback(providerName, params) {\n // CSRF guard — must be the first check.\n if (params.state !== params.expectedState) {\n throw new OAuthStateMismatchError();\n }\n\n const provider = getProvider(providerName);\n\n // Exchange the authorization code for provider tokens.\n const tokens = await provider.exchangeCode({\n code: params.code,\n redirectUri: params.redirectUri,\n });\n\n // Fetch normalized user info from the provider.\n const userInfo = await provider.fetchUserInfo(tokens);\n\n const now = config.now();\n\n // 1. Look up by OAuth link (returning user).\n if (store.findUserByOAuthId) {\n const linkedUser = await store.findUserByOAuthId(providerName, userInfo.providerUserId);\n if (linkedUser) {\n await audit.record(\"user.login.succeeded\", linkedUser.userId, {\n email: linkedUser.email,\n provider: providerName,\n });\n return issueSession(sessionDeps, linkedUser);\n }\n }\n\n // 2. Look up by email (existing local account — link the provider).\n if (userInfo.email) {\n const existingUser = await store.findUserByEmail(userInfo.email);\n if (existingUser) {\n await linkOAuthAccount(store, existingUser.userId, providerName, userInfo, now);\n await audit.record(\"user.oauth.linked\", existingUser.userId, {\n provider: providerName,\n providerUserId: userInfo.providerUserId,\n });\n await audit.record(\"user.login.succeeded\", existingUser.userId, {\n email: existingUser.email,\n provider: providerName,\n });\n return issueSession(sessionDeps, existingUser);\n }\n }\n\n // 3. Provision a new local user and link the provider.\n const newUser = await store.createUser({\n userId: config.generateId(),\n email: userInfo.email ?? `oauth:${providerName}:${userInfo.providerUserId}`,\n displayName: userInfo.displayName,\n status: \"active\",\n authVersion: 0,\n createdAt: now,\n updatedAt: now,\n });\n await linkOAuthAccount(store, newUser.userId, providerName, userInfo, now);\n await audit.record(\"user.registered\", newUser.userId, {\n provider: providerName,\n providerUserId: userInfo.providerUserId,\n });\n await audit.record(\"user.oauth.linked\", newUser.userId, {\n provider: providerName,\n providerUserId: userInfo.providerUserId,\n });\n await audit.record(\"user.login.succeeded\", newUser.userId, {\n email: newUser.email,\n provider: providerName,\n });\n return issueSession(sessionDeps, newUser);\n },\n };\n}\n\nasync function linkOAuthAccount(\n store: IdentityStore,\n userId: string,\n provider: string,\n userInfo: { providerUserId: string; email: string | null; displayName: string | null },\n now: Date,\n): Promise<void> {\n if (!store.createOAuthLink) return; // Store does not support OAuth links — skip silently.\n\n const link: OAuthLinkedAccount = {\n userId,\n provider,\n providerUserId: userInfo.providerUserId,\n email: userInfo.email,\n displayName: userInfo.displayName,\n linkedAt: now,\n };\n await store.createOAuthLink(link);\n}\n","/**\n * Logical description of the relational schema `@azlib/identity` expects.\n *\n * Concrete DDL is shipped alongside this module:\n * - `@azlib/identity/schema/postgres.sql`\n * - `@azlib/identity/schema/mysql.sql`\n * - `@azlib/identity/schema/sqlite.sql`\n * - `@azlib/identity/schema/prisma.schema`\n *\n * This object is documentation-as-data so consumers and tooling can introspect the\n * expected tables without parsing SQL.\n */\nexport interface SchemaColumn {\n name: string;\n description: string;\n nullable: boolean;\n}\n\nexport interface SchemaTable {\n name: string;\n description: string;\n columns: readonly SchemaColumn[];\n}\n\nexport interface SchemaModel {\n tables: readonly SchemaTable[];\n}\n\nexport const identitySchemaModel: SchemaModel = {\n tables: [\n {\n name: \"identity_users\",\n description: \"Core user accounts.\",\n columns: [\n { name: \"user_id\", description: \"Primary key.\", nullable: false },\n { name: \"email\", description: \"Unique, case-insensitive login email.\", nullable: false },\n { name: \"display_name\", description: \"Optional display name.\", nullable: true },\n { name: \"status\", description: \"active | disabled | locked.\", nullable: false },\n { name: \"email_verified_at\", description: \"When email was verified.\", nullable: true },\n { name: \"auth_version\", description: \"Token invalidation counter.\", nullable: false },\n { name: \"created_at\", description: \"Creation timestamp.\", nullable: false },\n { name: \"updated_at\", description: \"Last update timestamp.\", nullable: false },\n ],\n },\n {\n name: \"identity_credentials\",\n description: \"Password hashes, one per user.\",\n columns: [\n { name: \"user_id\", description: \"FK to identity_users.\", nullable: false },\n { name: \"password_hash\", description: \"Algorithm-tagged hash.\", nullable: false },\n { name: \"updated_at\", description: \"Last update timestamp.\", nullable: false },\n ],\n },\n {\n name: \"identity_sessions\",\n description: \"Server-side refresh sessions with hashed tokens.\",\n columns: [\n { name: \"session_id\", description: \"Primary key.\", nullable: false },\n { name: \"user_id\", description: \"FK to identity_users.\", nullable: false },\n { name: \"refresh_token_hash\", description: \"Hash of the active refresh token.\", nullable: false },\n { name: \"created_at\", description: \"Creation timestamp.\", nullable: false },\n { name: \"expires_at\", description: \"Expiry timestamp.\", nullable: false },\n { name: \"revoked_at\", description: \"Set when rotated or revoked.\", nullable: true },\n ],\n },\n {\n name: \"identity_roles\",\n description: \"Named roles.\",\n columns: [\n { name: \"role_id\", description: \"Primary key.\", nullable: false },\n { name: \"name\", description: \"Unique role name.\", nullable: false },\n { name: \"description\", description: \"Optional description.\", nullable: true },\n ],\n },\n {\n name: \"identity_user_roles\",\n description: \"User-to-role assignments.\",\n columns: [\n { name: \"user_id\", description: \"FK to identity_users.\", nullable: false },\n { name: \"role_id\", description: \"FK to identity_roles.\", nullable: false },\n ],\n },\n {\n name: \"identity_role_permissions\",\n description: \"Permissions granted to roles.\",\n columns: [\n { name: \"role_id\", description: \"FK to identity_roles.\", nullable: false },\n { name: \"permission\", description: \"Permission string.\", nullable: false },\n ],\n },\n {\n name: \"identity_user_permissions\",\n description: \"Permissions granted directly to users.\",\n columns: [\n { name: \"user_id\", description: \"FK to identity_users.\", nullable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b,SAAS,CACP;GAAE,MAAM;GAAW,aAAa;GAAyB,UAAU;EAAM,GACzE;GAAE,MAAM;GAAW,aAAa;GAAyB,UAAU;EAAM,CAC3E;CACF;CACA;EACE,MAAM;EACN,aAAa;EACb,SAAS,CACP;GAAE,MAAM;GAAW,aAAa;GAAyB,UAAU;EAAM,GACzE;GAAE,MAAM;GAAc,aAAa;GAAsB,UAAU;EAAM,CAC3E;CACF;CACA;EACE,MAAM;EACN,aAAa;EACb,SAAS,CACP;GAAE,MAAM;GAAW,aAAa;GAAyB,UAAU;EAAM,GACzE;GAAE,MAAM;GAAc,aAAa;GAAsB,UAAU;EAAM,CAC3E;CACF;AACF,EACF"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { F as IdentityLogger } from "./errors-
|
|
2
|
-
import { t as IdentityService } from "./identity-service
|
|
3
|
-
import { Request, Response, Router } from "express";
|
|
4
|
-
|
|
1
|
+
import { F as IdentityLogger } from "./errors-CBbiRO2n.cjs";
|
|
2
|
+
import { t as IdentityService } from "./identity-service---OTann1.cjs";
|
|
3
|
+
import { NextFunction, Request, Response, Router } from "express";
|
|
5
4
|
//#region core/express/identity-router.d.ts
|
|
6
5
|
/** Options for controlling the refresh-token cookie. */
|
|
7
6
|
interface CookieRefreshOptions {
|
|
@@ -110,6 +109,23 @@ interface IdentityRouterOptions {
|
|
|
110
109
|
* | GET | `/:provider/callback` | Handle an OAuth 2.0 callback *(optional)* |
|
|
111
110
|
*/
|
|
112
111
|
declare function createIdentityRouter(service: IdentityService, options?: IdentityRouterOptions): Router;
|
|
112
|
+
/**
|
|
113
|
+
* Factory that creates an Express error-handling middleware which converts
|
|
114
|
+
* {@link IdentityError} instances to structured JSON responses.
|
|
115
|
+
* Mount it after the identity router:
|
|
116
|
+
*
|
|
117
|
+
* ```ts
|
|
118
|
+
* app.use(createIdentityRouter(service, { prefix: "auth" }));
|
|
119
|
+
* app.use(identityErrorHandler()); // default console logger
|
|
120
|
+
* app.use(identityErrorHandler({ logger: false })); // silent
|
|
121
|
+
* ```
|
|
122
|
+
*
|
|
123
|
+
* @param options.logger - Logger for recording serialised error details.
|
|
124
|
+
* Pass `false` to disable. Defaults to the console logger.
|
|
125
|
+
*/
|
|
126
|
+
declare function identityErrorHandler(options?: {
|
|
127
|
+
logger?: IdentityLogger | false;
|
|
128
|
+
}): (err: unknown, req: Request, res: Response, next: NextFunction) => void;
|
|
113
129
|
//#endregion
|
|
114
|
-
export { IdentityRouterOptions as n, createIdentityRouter as r, CookieRefreshOptions as t };
|
|
115
|
-
//# sourceMappingURL=identity-router-
|
|
130
|
+
export { identityErrorHandler as i, IdentityRouterOptions as n, createIdentityRouter as r, CookieRefreshOptions as t };
|
|
131
|
+
//# sourceMappingURL=identity-router-D1xJ5H7y.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"identity-router-D1xJ5H7y.d.cts","names":[],"sources":["../core/express/identity-router.ts"],"mappings":";;;;;UAeiB;;EAEf;;EAEA;;;;;EAKA;;EAEA;;EAEA;;EAEA;;;;;UAMe;;;;;;;;;;;;EAYf;IAA0B,QAAQ;;;;;;;;;;EAUlC;;;;;;;;;;;;;;EAeA;;;;;;;;;;;;;;EAeA,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsIK,qBACd,SAAS,iBACT,UAAS,wBACR;;;;;;;;;;;;;;;iBAkUa,qBACd;EAAW,SAAS;KAClB,cAAc,KAAK,SAAS,KAAK,UAAU,MAAM"}
|