@azlib/identity 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +149 -40
  2. package/dist/cookie-header-DptIxRmW.mjs +76 -0
  3. package/dist/cookie-header-DptIxRmW.mjs.map +1 -0
  4. package/dist/cookie-header-Dqd5k5BU.cjs +115 -0
  5. package/dist/cookie-header-LFWHKQ04.d.cts +86 -0
  6. package/dist/cookie-header-LFWHKQ04.d.cts.map +1 -0
  7. package/dist/cookie-header-LFWHKQ04.d.mts +86 -0
  8. package/dist/cookie-header-LFWHKQ04.d.mts.map +1 -0
  9. package/dist/{errors-C2xZAatu.d.cts → errors-0Zh7EG06.d.cts} +4 -3
  10. package/dist/errors-0Zh7EG06.d.cts.map +1 -0
  11. package/dist/{errors-BGMwaW5s.d.mts → errors-DVDEUk9-.d.mts} +4 -3
  12. package/dist/errors-DVDEUk9-.d.mts.map +1 -0
  13. package/dist/express.cjs +34 -0
  14. package/dist/express.d.cts +5 -6
  15. package/dist/express.d.cts.map +1 -1
  16. package/dist/express.d.mts +5 -6
  17. package/dist/express.d.mts.map +1 -1
  18. package/dist/express.mjs +34 -1
  19. package/dist/express.mjs.map +1 -1
  20. package/dist/{identity-Bz9RDOvT.mjs → identity-D0qyca_c.mjs} +37 -3
  21. package/dist/identity-D0qyca_c.mjs.map +1 -0
  22. package/dist/{identity-4eP45YIP.cjs → identity-Yz1BVkrM.cjs} +46 -0
  23. package/dist/{identity-router-DBL20UWT.d.mts → identity-router-BiratpJR.d.mts} +22 -6
  24. package/dist/identity-router-BiratpJR.d.mts.map +1 -0
  25. package/dist/{identity-router-Dib30Waj.d.cts → identity-router-D4oqYI60.d.cts} +22 -6
  26. package/dist/identity-router-D4oqYI60.d.cts.map +1 -0
  27. package/dist/{identity-service-CLzKx8Z7.d.cts → identity-service-DE0Ffguz.d.cts} +3 -4
  28. package/dist/identity-service-DE0Ffguz.d.cts.map +1 -0
  29. package/dist/{identity-service-B9zrvE9z.d.mts → identity-service-JtsoA6lv.d.mts} +3 -4
  30. package/dist/identity-service-JtsoA6lv.d.mts.map +1 -0
  31. package/dist/identity-store-BRRahxcS.d.cts.map +1 -1
  32. package/dist/identity-store-BRRahxcS.d.mts.map +1 -1
  33. package/dist/index-CsYqHPvK.d.cts +54 -0
  34. package/dist/index-CsYqHPvK.d.cts.map +1 -0
  35. package/dist/index-LhSdoWEP.d.mts +54 -0
  36. package/dist/index-LhSdoWEP.d.mts.map +1 -0
  37. package/dist/index.cjs +11 -1
  38. package/dist/index.d.cts +4 -3
  39. package/dist/index.d.mts +4 -3
  40. package/dist/index.mjs +3 -2
  41. package/dist/logger-CcCHJVVe.mjs.map +1 -1
  42. package/dist/nestjs.cjs +4 -5
  43. package/dist/nestjs.d.cts +3 -4
  44. package/dist/nestjs.d.cts.map +1 -1
  45. package/dist/nestjs.d.mts +3 -4
  46. package/dist/nestjs.d.mts.map +1 -1
  47. package/dist/nestjs.mjs +4 -5
  48. package/dist/nestjs.mjs.map +1 -1
  49. package/dist/next.cjs +285 -0
  50. package/dist/next.d.cts +58 -0
  51. package/dist/next.d.cts.map +1 -0
  52. package/dist/next.d.mts +58 -0
  53. package/dist/next.d.mts.map +1 -0
  54. package/dist/next.mjs +274 -0
  55. package/dist/next.mjs.map +1 -0
  56. package/dist/node.cjs +18 -19
  57. package/dist/node.d.cts +5 -5
  58. package/dist/node.d.cts.map +1 -1
  59. package/dist/node.d.mts +5 -5
  60. package/dist/node.d.mts.map +1 -1
  61. package/dist/node.mjs +10 -20
  62. package/dist/node.mjs.map +1 -1
  63. package/dist/test-utils.d.cts +0 -1
  64. package/dist/test-utils.d.cts.map +1 -1
  65. package/dist/test-utils.d.mts +0 -1
  66. package/dist/test-utils.d.mts.map +1 -1
  67. package/dist/test-utils.mjs.map +1 -1
  68. package/package.json +18 -18
  69. package/schema/model.ts +110 -22
  70. package/dist/errors-BGMwaW5s.d.mts.map +0 -1
  71. package/dist/errors-C2xZAatu.d.cts.map +0 -1
  72. package/dist/identity-Bz9RDOvT.mjs.map +0 -1
  73. package/dist/identity-router-DBL20UWT.d.mts.map +0 -1
  74. package/dist/identity-router-Dib30Waj.d.cts.map +0 -1
  75. package/dist/identity-service-B9zrvE9z.d.mts.map +0 -1
  76. package/dist/identity-service-CLzKx8Z7.d.cts.map +0 -1
  77. package/dist/index-CpufYgyn.d.cts +0 -30
  78. package/dist/index-CpufYgyn.d.cts.map +0 -1
  79. package/dist/index-CpufYgyn.d.mts +0 -30
  80. package/dist/index-CpufYgyn.d.mts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity-D0qyca_c.mjs","names":[],"sources":["../core/config.ts","../core/authorization.ts","../core/session-state.ts","../core/oauth/oauth-service.ts","../core/access-token.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\n/** Default JWT `iss` claim used when `IdentityConfigInput.issuer` is omitted. */\nexport const DEFAULT_ISSUER = \"azlib-identity\";\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(\n input: IdentityConfigInput,\n): IdentityConfig {\n if (\n !input.accessTokenSecret ||\n input.accessTokenSecret.length < MIN_SECRET_LENGTH\n ) {\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 =\n 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 ?? DEFAULT_ISSUER,\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 (\n permission !== undefined &&\n !hasPermission(context.principal, permission)\n ) {\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(\n user.userId,\n user.authVersion,\n );\n const sessionId = config.generateId();\n const refresh = tokenService.createRefreshToken(sessionId);\n\n const refreshExpiresAt = new Date(\n now.getTime() + config.refreshTokenTtlSeconds * 1000,\n );\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(\n providerName: string,\n redirectUri: string,\n scopes?: string[],\n ): 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(\n providerName: string,\n params: OAuthCallbackParams,\n ): 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(\n \"OAuth state mismatch. The callback may have been replayed or tampered with.\",\n );\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({\n redirectUri,\n state,\n scopes,\n });\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(\n providerName,\n userInfo.providerUserId,\n );\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(\n store,\n existingUser.userId,\n providerName,\n userInfo,\n now,\n );\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:\n 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(\n store,\n newUser.userId,\n providerName,\n userInfo,\n now,\n );\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: {\n providerUserId: string;\n email: string | null;\n displayName: string | null;\n },\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","import { jwtVerify } from \"jose\";\n\nimport { DEFAULT_ISSUER } from \"./config\";\nimport { InvalidTokenError } from \"./errors\";\nimport type { AccessTokenClaims } from \"./types\";\n\n/**\n * Options for {@link verifyAccessToken}. Edge-safe: depends only on `jose`.\n */\nexport interface VerifyAccessTokenOptions {\n /** HMAC secret used to sign access tokens. Must match `accessTokenSecret`. */\n secret: string;\n /** Expected JWT issuer. Default {@link DEFAULT_ISSUER}. */\n issuer?: string;\n /** Expected JWT audience. Omit when tokens are minted without `aud`. */\n audience?: string;\n}\n\n/**\n * Verifies an HS256 access token and returns its claims.\n *\n * This helper is framework-agnostic and safe to run on the Edge (no `node:crypto`).\n * Hydrating the principal still requires {@link IdentityService.authenticate} in Node.\n *\n * Throws {@link InvalidTokenError} when the token is missing, malformed, expired,\n * signed with the wrong secret, or missing required claims.\n */\nexport async function verifyAccessToken(\n token: string,\n options: VerifyAccessTokenOptions,\n): Promise<AccessTokenClaims> {\n if (typeof token !== \"string\" || token.trim().length === 0) {\n throw new InvalidTokenError();\n }\n\n try {\n const secret = new TextEncoder().encode(options.secret);\n const { payload } = await jwtVerify(token.trim(), secret, {\n issuer: options.issuer ?? DEFAULT_ISSUER,\n audience: options.audience,\n });\n if (\n typeof payload.sub !== \"string\" ||\n payload.sub.length === 0 ||\n typeof payload.authVersion !== \"number\" ||\n !Number.isFinite(payload.authVersion)\n ) {\n throw new InvalidTokenError();\n }\n return {\n sub: payload.sub,\n authVersion: payload.authVersion,\n iat: payload.iat ?? 0,\n exp: payload.exp ?? 0,\n };\n } catch (error) {\n if (error instanceof InvalidTokenError) throw error;\n throw new InvalidTokenError();\n }\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 {\n name: \"email\",\n description: \"Unique, case-insensitive login email.\",\n nullable: false,\n },\n {\n name: \"display_name\",\n description: \"Optional display name.\",\n nullable: true,\n },\n {\n name: \"status\",\n description: \"active | disabled | locked.\",\n nullable: false,\n },\n {\n name: \"email_verified_at\",\n description: \"When email was verified.\",\n nullable: true,\n },\n {\n name: \"auth_version\",\n description: \"Token invalidation counter.\",\n nullable: false,\n },\n {\n name: \"created_at\",\n description: \"Creation timestamp.\",\n nullable: false,\n },\n {\n name: \"updated_at\",\n description: \"Last update timestamp.\",\n nullable: false,\n },\n ],\n },\n {\n name: \"identity_credentials\",\n description: \"Password hashes, one per user.\",\n columns: [\n {\n name: \"user_id\",\n description: \"FK to identity_users.\",\n nullable: false,\n },\n {\n name: \"password_hash\",\n description: \"Algorithm-tagged hash.\",\n nullable: false,\n },\n {\n name: \"updated_at\",\n description: \"Last update timestamp.\",\n nullable: false,\n },\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 {\n name: \"user_id\",\n description: \"FK to identity_users.\",\n nullable: false,\n },\n {\n name: \"refresh_token_hash\",\n description: \"Hash of the active refresh token.\",\n nullable: false,\n },\n {\n name: \"created_at\",\n description: \"Creation timestamp.\",\n nullable: false,\n },\n {\n name: \"expires_at\",\n description: \"Expiry timestamp.\",\n nullable: false,\n },\n {\n name: \"revoked_at\",\n description: \"Set when rotated or revoked.\",\n nullable: true,\n },\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 {\n name: \"description\",\n description: \"Optional description.\",\n nullable: true,\n },\n ],\n },\n {\n name: \"identity_user_roles\",\n description: \"User-to-role assignments.\",\n columns: [\n {\n name: \"user_id\",\n description: \"FK to identity_users.\",\n nullable: false,\n },\n {\n name: \"role_id\",\n description: \"FK to identity_roles.\",\n nullable: false,\n },\n ],\n },\n {\n name: \"identity_role_permissions\",\n description: \"Permissions granted to roles.\",\n columns: [\n {\n name: \"role_id\",\n description: \"FK to identity_roles.\",\n nullable: false,\n },\n {\n name: \"permission\",\n description: \"Permission string.\",\n nullable: false,\n },\n ],\n },\n {\n name: \"identity_user_permissions\",\n description: \"Permissions granted directly to users.\",\n columns: [\n {\n name: \"user_id\",\n description: \"FK to identity_users.\",\n nullable: false,\n },\n {\n name: \"permission\",\n description: \"Permission string.\",\n nullable: false,\n },\n ],\n },\n ],\n};\n"],"mappings":";;;;AA2FA,MAAM,oBAAoB;;AAG1B,MAAa,iBAAiB;AAE9B,MAAM,0BAAkC,WAAW,OAAO,WAAW;AACrE,MAAM,mCAAyB,IAAI,KAAK;;;;;AAMxC,SAAgB,sBACd,OACgB;CAChB,IACE,CAAC,MAAM,qBACP,MAAM,kBAAkB,SAAS,mBAEjC,MAAM,IAAI,oBACR,sCAAsC,kBAAkB,aAC1D;CAGF,MAAM,wBAAwB,MAAM,yBAAyB;CAC7D,MAAM,yBACJ,MAAM,0BAA0B,OAAU,KAAK;CACjD,MAAM,qBAAqB,MAAM,sBAAsB;CAEvD,IAAI,yBAAyB,GAC3B,MAAM,IAAI,oBAAoB,yCAAyC;CAEzE,IAAI,0BAA0B,uBAC5B,MAAM,IAAI,oBACR,oEACF;CAEF,KAAK,qBAAsB,qBAAqB,OAAQ,GACtD,MAAM,IAAI,oBAAoB,4CAA4C;CAG5E,OAAO;EACL,mBAAmB,MAAM;EACzB;EACA;EACA,QAAQ,MAAM,UAAA;EACd,UAAU,MAAM;EAChB;EACA,SAAS;GACP,mBAAmB,MAAM,SAAS,qBAAqB;GACvD,iBAAiB,MAAM,SAAS,mBAAmB;EACrD;EACA,KAAK,MAAM,WAAW,OAAO;EAC7B,YAAY,MAAM,WAAW,cAAc;EAC3C,SAAS,MAAM,WAAW;EAC1B,eAAe,MAAM;EACrB,QAAQ,cAAc,MAAM,MAAM;CACpC;AACF;;;AC9GA,MAAM,iBACJ,WACA,eACY,UAAU,YAAY,SAAS,UAAU;;;;;;;AAQvD,eA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AAM;IACN,aAAa;IACb,UAAU;GACZ;EACF;CACF;CACA;EACE,MAAM;EACN,aAAa;EACb,SAAS;GACP;IACE,MAAM;IACN,aAAa;IACb,UAAU;GACZ;GACA;IACE,MAAM;IACN,aAAa;IACb,UAAU;GACZ;GACA;IACE,MAAM;IACN,aAAa;IACb,UAAU;GACZ;EACF;CACF;CACA;EACE,MAAM;EACN,aAAa;EACb,SAAS;GACP;IAAE,MAAM;IAAc,aAAa;IAAgB,UAAU;GAAM;GACnE;IACE,MAAM;IACN,aAAa;IACb,UAAU;GACZ;GACA;IACE,MAAM;IACN,aAAa;IACb,UAAU;GACZ;GACA;IACE,MAAM;IACN,aAAa;IACb,UAAU;GACZ;GACA;IACE,MAAM;IACN,aAAa;IACb,UAAU;GACZ;GACA;IACE,MAAM;IACN,aAAa;IACb,UAAU;GACZ;EACF;CACF;CACA;EACE,MAAM;EACN,aAAa;EACb,SAAS;GACP;IAAE,MAAM;IAAW,aAAa;IAAgB,UAAU;GAAM;GAChE;IAAE,MAAM;IAAQ,aAAa;IAAqB,UAAU;GAAM;GAClE;IACE,MAAM;IACN,aAAa;IACb,UAAU;GACZ;EACF;CACF;CACA;EACE,MAAM;EACN,aAAa;EACb,SAAS,CACP;GACE,MAAM;GACN,aAAa;GACb,UAAU;EACZ,GACA;GACE,MAAM;GACN,aAAa;GACb,UAAU;EACZ,CACF;CACF;CACA;EACE,MAAM;EACN,aAAa;EACb,SAAS,CACP;GACE,MAAM;GACN,aAAa;GACb,UAAU;EACZ,GACA;GACE,MAAM;GACN,aAAa;GACb,UAAU;EACZ,CACF;CACF;CACA;EACE,MAAM;EACN,aAAa;EACb,SAAS,CACP;GACE,MAAM;GACN,aAAa;GACb,UAAU;EACZ,GACA;GACE,MAAM;GACN,aAAa;GACb,UAAU;EACZ,CACF;CACF;AACF,EACF"}
@@ -1,7 +1,10 @@
1
1
  const require_errors = require("./errors-Bcjx9o6g.cjs");
2
2
  const require_logger = require("./logger-Be1wDzBC.cjs");
3
+ let jose = require("jose");
3
4
  //#region core/config.ts
4
5
  const MIN_SECRET_LENGTH = 32;
6
+ /** Default JWT `iss` claim used when `IdentityConfigInput.issuer` is omitted. */
7
+ const DEFAULT_ISSUER = "azlib-identity";
5
8
  const defaultGenerateId = () => globalThis.crypto.randomUUID();
6
9
  const defaultNow = () => /* @__PURE__ */ new Date();
7
10
  /**
@@ -238,6 +241,37 @@ async function linkOAuthAccount(store, userId, provider, userInfo, now) {
238
241
  await store.createOAuthLink(link);
239
242
  }
240
243
  //#endregion
244
+ //#region core/access-token.ts
245
+ /**
246
+ * Verifies an HS256 access token and returns its claims.
247
+ *
248
+ * This helper is framework-agnostic and safe to run on the Edge (no `node:crypto`).
249
+ * Hydrating the principal still requires {@link IdentityService.authenticate} in Node.
250
+ *
251
+ * Throws {@link InvalidTokenError} when the token is missing, malformed, expired,
252
+ * signed with the wrong secret, or missing required claims.
253
+ */
254
+ async function verifyAccessToken(token, options) {
255
+ if (typeof token !== "string" || token.trim().length === 0) throw new require_errors.InvalidTokenError();
256
+ try {
257
+ const secret = new TextEncoder().encode(options.secret);
258
+ const { payload } = await (0, jose.jwtVerify)(token.trim(), secret, {
259
+ issuer: options.issuer ?? "azlib-identity",
260
+ audience: options.audience
261
+ });
262
+ if (typeof payload.sub !== "string" || payload.sub.length === 0 || typeof payload.authVersion !== "number" || !Number.isFinite(payload.authVersion)) throw new require_errors.InvalidTokenError();
263
+ return {
264
+ sub: payload.sub,
265
+ authVersion: payload.authVersion,
266
+ iat: payload.iat ?? 0,
267
+ exp: payload.exp ?? 0
268
+ };
269
+ } catch (error) {
270
+ if (error instanceof require_errors.InvalidTokenError) throw error;
271
+ throw new require_errors.InvalidTokenError();
272
+ }
273
+ }
274
+ //#endregion
241
275
  //#region schema/model.ts
242
276
  const identitySchemaModel = { tables: [
243
277
  {
@@ -405,6 +439,12 @@ const identitySchemaModel = { tables: [
405
439
  }
406
440
  ] };
407
441
  //#endregion
442
+ Object.defineProperty(exports, "DEFAULT_ISSUER", {
443
+ enumerable: true,
444
+ get: function() {
445
+ return DEFAULT_ISSUER;
446
+ }
447
+ });
408
448
  Object.defineProperty(exports, "OAuthProviderNotFoundError", {
409
449
  enumerable: true,
410
450
  get: function() {
@@ -459,3 +499,9 @@ Object.defineProperty(exports, "resolveIdentityConfig", {
459
499
  return resolveIdentityConfig;
460
500
  }
461
501
  });
502
+ Object.defineProperty(exports, "verifyAccessToken", {
503
+ enumerable: true,
504
+ get: function() {
505
+ return verifyAccessToken;
506
+ }
507
+ });
@@ -1,7 +1,6 @@
1
- import { F as IdentityLogger } from "./errors-BGMwaW5s.mjs";
2
- import { t as IdentityService } from "./identity-service-B9zrvE9z.mjs";
3
- import { Request, Response, Router } from "express";
4
-
1
+ import { I as IdentityLogger } from "./errors-DVDEUk9-.mjs";
2
+ import { t as IdentityService } from "./identity-service-JtsoA6lv.mjs";
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-DBL20UWT.d.mts.map
130
+ export { identityErrorHandler as i, IdentityRouterOptions as n, createIdentityRouter as r, CookieRefreshOptions as t };
131
+ //# sourceMappingURL=identity-router-BiratpJR.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity-router-BiratpJR.d.mts","names":[],"sources":["../core/express/identity-router.ts"],"mappings":";;;;;UAoBiB;;EAEf;;EAEA;;;;;EAKA;;EAEA;;EAEA;;EAEA;;;;;UAMe;;;;;;;;;;;;EAYf;IAA0B,QAAQ;;;;;;;;;;EAUlC;;;;;;;;;;;;;;EAeA;;;;;;;;;;;;;;EAeA,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiJK,qBACd,SAAS,iBACT,UAAS,wBACR;;;;;;;;;;;;;;;iBA0Wa,qBACd;EAAW,SAAS;KAClB,cAAc,KAAK,SAAS,KAAK,UAAU,MAAM"}
@@ -1,7 +1,6 @@
1
- import { F as IdentityLogger } from "./errors-C2xZAatu.cjs";
2
- import { t as IdentityService } from "./identity-service-CLzKx8Z7.cjs";
3
- import { Request, Response, Router } from "express";
4
-
1
+ import { I as IdentityLogger } from "./errors-0Zh7EG06.cjs";
2
+ import { t as IdentityService } from "./identity-service-DE0Ffguz.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-Dib30Waj.d.cts.map
130
+ export { identityErrorHandler as i, IdentityRouterOptions as n, createIdentityRouter as r, CookieRefreshOptions as t };
131
+ //# sourceMappingURL=identity-router-D4oqYI60.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity-router-D4oqYI60.d.cts","names":[],"sources":["../core/express/identity-router.ts"],"mappings":";;;;;UAoBiB;;EAEf;;EAEA;;;;;EAKA;;EAEA;;EAEA;;EAEA;;;;;UAMe;;;;;;;;;;;;EAYf;IAA0B,QAAQ;;;;;;;;;;EAUlC;;;;;;;;;;;;;;EAeA;;;;;;;;;;;;;;EAeA,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiJK,qBACd,SAAS,iBACT,UAAS,wBACR;;;;;;;;;;;;;;;iBA0Wa,qBACd;EAAW,SAAS;KAClB,cAAc,KAAK,SAAS,KAAK,UAAU,MAAM"}
@@ -1,6 +1,5 @@
1
1
  import { T as TotpSetupResult, c as AuthResult, d as AuthenticatedIdentity, r as IdentityStore, v as LoginResult } from "./identity-store-BRRahxcS.cjs";
2
- import { B as AuthorizationDecision, D as IdentityConfigInput, V as AuthorizationRequirement, a as IdentityError, f as OAuthService, v as OAuthProvider, w as AuditLogger, x as SessionDeps, z as AuthorizationContext } from "./errors-C2xZAatu.cjs";
3
-
2
+ import { B as AuthorizationContext, H as AuthorizationRequirement, O as IdentityConfigInput, V as AuthorizationDecision, a as IdentityError, f as OAuthService, v as OAuthProvider, w as AuditLogger, x as SessionDeps } from "./errors-0Zh7EG06.cjs";
4
3
  //#region core/password-hasher.d.ts
5
4
  interface PasswordHasher {
6
5
  hash(password: string): Promise<string>;
@@ -120,9 +119,9 @@ interface IdentityServiceConfig extends IdentityConfigInput {
120
119
  }
121
120
  /**
122
121
  * Wires the framework-agnostic identity runtime with Node defaults (scrypt hashing,
123
- * `jose` HS256 tokens). Express and NestJS adapters build on top of this service.
122
+ * `jose` HS256 tokens). Express, NestJS, and Next.js adapters build on top of this service.
124
123
  */
125
124
  declare function createIdentityService(configInput: IdentityServiceConfig, store: IdentityStore): IdentityService;
126
125
  //#endregion
127
126
  export { RegisterInput as a, registerUser as c, loginUser as d, PasswordHasher as f, RegisterDeps as i, LoginDeps as l, IdentityServiceConfig as n, RegistrationValidationError as o, createPasswordHasher as p, createIdentityService as r, normalizeEmail as s, IdentityService as t, LoginInput as u };
128
- //# sourceMappingURL=identity-service-CLzKx8Z7.d.cts.map
127
+ //# sourceMappingURL=identity-service-DE0Ffguz.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity-service-DE0Ffguz.d.cts","names":[],"sources":["../core/password-hasher.ts","../core/login.ts","../core/register.ts","../core/identity-service.ts"],"mappings":";;;UA6BiB;EACf,KAAK,mBAAmB;EACxB,OAAO,kBAAkB,qBAAqB;;;iBAIhC,qBAAqB,eAAe;;;;UCzBnC,kBAAkB;EACjC,QAAQ;EACR,OAAO;;;UAIQ;EACf;EACA;;;;;;;;;;iBAWoB,UACpB,MAAM,WACN,OAAO,aACN,QAAQ;;;;UCzBM,qBAAqB;EACpC,QAAQ;EACR,OAAO;;;UAIQ;EACf;EACA;EACA;;;cAIW,oCAAoC;EAC/C,YAAY;;;iBASE,eAAe;;;;;iBAQT,aACpB,MAAM,cACN,OAAO,gBACN,QAAQ;;;;UCDM;EACf,SAAS,OAAO,gBAAgB,QAAQ;;;;;;EAMxC,MAAM,OAAO,aAAa,QAAQ;EAClC,QAAQ,uBAAuB,QAAQ;EACvC,OAAO,uBAAuB;;;;;EAK9B,aAAa,sBAAsB,QAAQ;EAC3C,UAAU,qBACR,aAAa,yBAAyB,YACtC,SAAS,qBAAqB,aAC7B,QAAQ;;EAIX,yBAAyB,iBAAiB;;EAE1C,YAAY,gBAAgB;;EAI5B,qBAAqB,gBAAgB;;EAErC,cAAc,eAAe,sBAAsB;;;;;EAOnD,SAAS,iBAAiB,QAAQ;;EAElC,UAAU,gBAAgB,mBAAmB;;EAE7C,WAAW,gBAAgB,mBAAmB;;;;;EAK9C,mBAAmB,kBAAkB,mBAAmB,QAAQ;;EAIhE,YAAY,iBAAiB;;EAE7B,cAAc,iBAAiB;;EAE/B,eAAe,iBAAiB;;;;;EAMhC,QAAQ;;;UAIO,8BAA8B;;EAE7C;;;;;;IAME,WAAW;;;;;;;iBAQC,sBACd,aAAa,uBACb,OAAO,gBACN"}
@@ -1,6 +1,5 @@
1
1
  import { T as TotpSetupResult, c as AuthResult, d as AuthenticatedIdentity, r as IdentityStore, v as LoginResult } from "./identity-store-BRRahxcS.mjs";
2
- import { B as AuthorizationDecision, D as IdentityConfigInput, V as AuthorizationRequirement, a as IdentityError, f as OAuthService, v as OAuthProvider, w as AuditLogger, x as SessionDeps, z as AuthorizationContext } from "./errors-BGMwaW5s.mjs";
3
-
2
+ import { B as AuthorizationContext, H as AuthorizationRequirement, O as IdentityConfigInput, V as AuthorizationDecision, a as IdentityError, f as OAuthService, v as OAuthProvider, w as AuditLogger, x as SessionDeps } from "./errors-DVDEUk9-.mjs";
4
3
  //#region core/password-hasher.d.ts
5
4
  interface PasswordHasher {
6
5
  hash(password: string): Promise<string>;
@@ -120,9 +119,9 @@ interface IdentityServiceConfig extends IdentityConfigInput {
120
119
  }
121
120
  /**
122
121
  * Wires the framework-agnostic identity runtime with Node defaults (scrypt hashing,
123
- * `jose` HS256 tokens). Express and NestJS adapters build on top of this service.
122
+ * `jose` HS256 tokens). Express, NestJS, and Next.js adapters build on top of this service.
124
123
  */
125
124
  declare function createIdentityService(configInput: IdentityServiceConfig, store: IdentityStore): IdentityService;
126
125
  //#endregion
127
126
  export { RegisterInput as a, registerUser as c, loginUser as d, PasswordHasher as f, RegisterDeps as i, LoginDeps as l, IdentityServiceConfig as n, RegistrationValidationError as o, createPasswordHasher as p, createIdentityService as r, normalizeEmail as s, IdentityService as t, LoginInput as u };
128
- //# sourceMappingURL=identity-service-B9zrvE9z.d.mts.map
127
+ //# sourceMappingURL=identity-service-JtsoA6lv.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity-service-JtsoA6lv.d.mts","names":[],"sources":["../core/password-hasher.ts","../core/login.ts","../core/register.ts","../core/identity-service.ts"],"mappings":";;;UA6BiB;EACf,KAAK,mBAAmB;EACxB,OAAO,kBAAkB,qBAAqB;;;iBAIhC,qBAAqB,eAAe;;;;UCzBnC,kBAAkB;EACjC,QAAQ;EACR,OAAO;;;UAIQ;EACf;EACA;;;;;;;;;;iBAWoB,UACpB,MAAM,WACN,OAAO,aACN,QAAQ;;;;UCzBM,qBAAqB;EACpC,QAAQ;EACR,OAAO;;;UAIQ;EACf;EACA;EACA;;;cAIW,oCAAoC;EAC/C,YAAY;;;iBASE,eAAe;;;;;iBAQT,aACpB,MAAM,cACN,OAAO,gBACN,QAAQ;;;;UCDM;EACf,SAAS,OAAO,gBAAgB,QAAQ;;;;;;EAMxC,MAAM,OAAO,aAAa,QAAQ;EAClC,QAAQ,uBAAuB,QAAQ;EACvC,OAAO,uBAAuB;;;;;EAK9B,aAAa,sBAAsB,QAAQ;EAC3C,UAAU,qBACR,aAAa,yBAAyB,YACtC,SAAS,qBAAqB,aAC7B,QAAQ;;EAIX,yBAAyB,iBAAiB;;EAE1C,YAAY,gBAAgB;;EAI5B,qBAAqB,gBAAgB;;EAErC,cAAc,eAAe,sBAAsB;;;;;EAOnD,SAAS,iBAAiB,QAAQ;;EAElC,UAAU,gBAAgB,mBAAmB;;EAE7C,WAAW,gBAAgB,mBAAmB;;;;;EAK9C,mBAAmB,kBAAkB,mBAAmB,QAAQ;;EAIhE,YAAY,iBAAiB;;EAE7B,cAAc,iBAAiB;;EAE/B,eAAe,iBAAiB;;;;;EAMhC,QAAQ;;;UAIO,8BAA8B;;EAE7C;;;;;;IAME,WAAW;;;;;;;iBAQC,sBACd,aAAa,uBACb,OAAO,gBACN"}
@@ -1 +1 @@
1
- {"version":3,"file":"identity-store-BRRahxcS.d.cts","names":[],"sources":["../core/types.ts","../core/verification-token.ts","../core/identity-store.ts"],"mappings":";;AAQA;;;;AAA8B;AAG9B;AAAA,KAHY,kBAAA;;UAGK,YAAA;EACf,MAAA;EACA,KAAA;EACA,WAAA;EACA,MAAA,EAAQ,kBAAA;EACR,eAAA,EAAiB,IAAA;EAqBF;;;EAjBf,gBAAA;EALA;;;;EAUA,WAAA;EAAA;;;;EAKA,mBAAA;EAMW;;;;EADX,WAAA,EAAa,IAAA;EACb,SAAA,EAAW,IAAA;EACX,SAAA,EAAW,IAAA;AAAA;;UAII,gBAAA;EACf,MAAA;EAGA;EADA,YAAA;EACA,SAAA,EAAW,IAAI;AAAA;AAOjB;;;;AAAA,UAAiB,WAAA;EACf,SAAA;EACA,MAAA;EAMe;EAJf,gBAAA;EACA,SAAA,EAAW,IAAA;EACX,SAAA,EAAW,IAAA;EADX;EAGA,SAAA,EAAW,IAAA;AAAA;;KAID,UAAA;;UAGK,IAAA;EACf,MAAA;EACA,IAAA;EACA,WAAA;AAAA;;UAIe,kBAAA;EACf,MAAA;EACA,MAAM;AAAA;;UAIS,mBAAA;EACf,MAAA;EACA,UAAA,EAAY,UAAU;AAAA;AAZX;AAAA,UAgBI,qBAAA;EACf,MAAA;EACA,UAAA,EAAY,UAAU;AAAA;AAZhB;AAAA,KAgBI,iBAAA;;UAoBK,kBAAA;EACf,MAAA;EAhCA;EAkCA,QAAA;EAjCY;EAmCZ,cAAA;EACA,KAAA;EACA,WAAA;EACA,QAAA,EAAU,IAAI;AAAA;;UAIC,aAAA;EACf,IAAA,EAAM,iBAAA;EACN,M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CA,yBAAA,EAA2B,SAAA,UAAmB,MAAA,EAAQ,IAAA,GAAO,OAAA;EFnC7D;EEuCA,cAAA,EAAgB,MAAA,WAAiB,OAAA,CAAQ,UAAA;EFtC9B;EEwCX,gBAAA,EAAkB,MAAA,EAAQ,UAAA,GAAa,OAAA;EFvC5B;EEyCX,gBAAA,EAAkB,MAAA,WAAiB,OAAA;EAGnC,WAAA,EAAa,KAAA,EAAO,aAAA,GAAgB,OAAA;EF1CrB;AAAA;AAIjB;;EE6CE,iBAAA,EAAmB,QAAA,UAAkB,cAAA,WAAyB,OAAA,CAAQ,YAAA;EF7ClD;EE+CpB,eAAA,EAAiB,IAAA,EAAM,kBAAA,GAAqB,OAAA;EF5C7B;EE8Cf,cAAA,EAAgB,MAAA,WAAiB,OAAA,UAAiB,kBAAA;AAAA"}
1
+ {"version":3,"file":"identity-store-BRRahxcS.d.cts","names":[],"sources":["../core/types.ts","../core/verification-token.ts","../core/identity-store.ts"],"mappings":";;;;;;;;KAQY;;UAGK;EACf;EACA;EACA;EACA,QAAQ;EACR,iBAAiB;;;;EAIjB;;;;;EAKA;;;;;EAKA;;;;;EAKA,aAAa;EACb,WAAW;EACX,WAAW;;;UAII;EACf;;EAEA;EACA,WAAW;;;;;;UAOI;EACf;EACA;;EAEA;EACA,WAAW;EACX,WAAW;;EAEX,WAAW;;;KAID;;UAGK;EACf;EACA;EACA;;;UAIe;EACf;EACA;;;UAIe;EACf;EACA,YAAY;;;UAIG;EACf;EACA,YAAY;;;KAIF;;UAoBK;EACf;;EAEA;;EAEA;EACA;EACA;EACA,UAAU;;;UAIK;EACf,MAAM;EACN;;EAEA,UAAU;EACV,YAAY;;;;;;UAOG;EACf;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA,sBAAsB;;;UAIP;EACf;EACA;EACA,sBAAsB;EACtB,uBAAuB;;;UAIR;EACf,MAAM;EACN,QAAQ;;;;;;UAOO;EACf;;EAEA;;;KAIU,cAAc,aAAa;;KAG3B;;UAGK;;EA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-BRRahxcS.d.mts","names":[],"sources":["../core/types.ts","../core/verification-token.ts","../core/identity-store.ts"],"mappings":";;AAQA;;;;AAA8B;AAG9B;AAAA,KAHY,kBAAA;;UAGK,YAAA;EACf,MAAA;EACA,KAAA;EACA,WAAA;EACA,MAAA,EAAQ,kBAAA;EACR,eAAA,EAAiB,IAAA;EAqBF;;;EAjBf,gBAAA;EALA;;;;EAUA,WAAA;EAAA;;;;EAKA,mBAAA;EAMW;;;;EADX,WAAA,EAAa,IAAA;EACb,SAAA,EAAW,IAAA;EACX,SAAA,EAAW,IAAA;AAAA;;UAII,gBAAA;EACf,MAAA;EAGA;EADA,YAAA;EACA,SAAA,EAAW,IAAI;AAAA;AAOjB;;;;AAAA,UAAiB,WAAA;EACf,SAAA;EACA,MAAA;EAMe;EAJf,gBAAA;EACA,SAAA,EAAW,IAAA;EACX,SAAA,EAAW,IAAA;EADX;EAGA,SAAA,EAAW,IAAA;AAAA;;KAID,UAAA;;UAGK,IAAA;EACf,MAAA;EACA,IAAA;EACA,WAAA;AAAA;;UAIe,kBAAA;EACf,MAAA;EACA,MAAM;AAAA;;UAIS,mBAAA;EACf,MAAA;EACA,UAAA,EAAY,UAAU;AAAA;AAZX;AAAA,UAgBI,qBAAA;EACf,MAAA;EACA,UAAA,EAAY,UAAU;AAAA;AAZhB;AAAA,KAgBI,iBAAA;;UAoBK,kBAAA;EACf,MAAA;EAhCA;EAkCA,QAAA;EAjCY;EAmCZ,cAAA;EACA,KAAA;EACA,WAAA;EACA,QAAA,EAAU,IAAI;AAAA;;UAIC,aAAA;EACf,IAAA,EAAM,iBAAA;EACN,MAAA;EAtCsB;EAwCtB,QAAA,EAAU,MAAA;EACV,UAAA,EAAY,IAAA;AAAA;;;AArCe;AAoB7B;UAwBiB,qBAAA;EACf,MAAA;EACA,KAAA;EACA,WAAA;EACA,MAAA,EAAQ,kBAAA;EACR,aAAA;EACA,KAAA;EACA,WAAA,WAAsB,UAAU;AAAA;;UAIjB,UAAA;EACf,W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AA;EAGnC,WAAA,EAAa,KAAA,EAAO,aAAA,GAAgB,OAAA;EF1CrB;AAAA;AAIjB;;EE6CE,iBAAA,EAAmB,QAAA,UAAkB,cAAA,WAAyB,OAAA,CAAQ,YAAA;EF7ClD;EE+CpB,eAAA,EAAiB,IAAA,EAAM,kBAAA,GAAqB,OAAA;EF5C7B;EE8Cf,cAAA,EAAgB,MAAA,WAAiB,OAAA,UAAiB,kBAAA;AAAA"}
1
+ {"version":3,"file":"identity-store-BRRahxcS.d.mts","names":[],"sources":["../core/types.ts","../core/verification-token.ts","../core/identity-store.ts"],"mappings":";;;;;;;;KAQY;;UAGK;EACf;EACA;EACA;EACA,QAAQ;EACR,iBAAiB;;;;EAIjB;;;;;EAKA;;;;;EAKA;;;;;EAKA,aAAa;EACb,WAAW;EACX,WAAW;;;UAII;EACf;;EAEA;EACA,WAAW;;;;;;UAOI;EACf;EACA;;EAEA;EACA,WAAW;EACX,WAAW;;EAEX,WAAW;;;KAID;;UAGK;EACf;EACA;EACA;;;UAIe;EACf;EACA;;;UAIe;EACf;EACA,YAAY;;;UAIG;EACf;EACA,YAAY;;;KAIF;;UAoBK;EACf;;EAEA;;EAEA;EACA;EACA;EACA,UAAU;;;UAIK;EACf,MAAM;EACN;;EAEA,UAAU;EACV,YAAY;;;;;;UAOG;EACf;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA,sBAAsB;;;UAIP;EACf;EACA;EACA,sBAAsB;EACtB,uBAAuB;;;UAIR;EACf,MAAM;EACN,QAAQ;;;;;;UAOO;EACf;;EAEA;;;KAIU,cAAc,aAAa;;KAG3B;;UAGK;;EAEf;EACA;EACA,MAAM;EACN,WAAW;;EAEX,QAAQ;;;UAIO;EACf;;EAEA;;EAEA,WAAW;EACX,WAAW;;;UAII;;EAEf;;EAEA;;;UAIe;;EAEf;;EAEA;;EAEA;;EAEA;;;;;UC/Me;;EAEf;EACA;EACA,MAAM;EACN,WAAW;;;;;;iBAOG;EACd;EACA;;;iBAQc,sBAAsB;;;;UCZrB;EACf;EACA;EACA;EACA,QAAQ;EACR;EACA,WAAW;EACX,WAAW;;;UAII;EACf;EACA;EACA;EACA,WAAW;EACX,WAAW;;;;;;;;;;UAWI;EAEf,gBAAgB,gBAAgB,QAAQ;EACxC,aAAa,iBAAiB,QAAQ;EACtC,WAAW,OAAO,0BAA0B,QAAQ;EACpD,WACE,gBACA,OAAO,QACL,KACE,4IAUH,QAAQ;EAEX,eAAe,iBAAiB,QAAQ;EACxC,iBAAiB,QAAQ,mBAAmB;EAG5C,cAAc,OAAO,yBAAyB,QAAQ;EACtD,gBAAgB,oBAAoB,QAAQ;;EAE5C,cAAc,mBAAmB,WAAW,OAAO;;EAEnD,cACE,mBACA,0BACA,WAAW,OACV;;EAEH,kBAAkB,gBAAgB,WAAW,OAAO;EAGpD,iBAAiB,iBAAiB,iBAAiB;EACnD,uBAAuB,iBAAiB,iBAAiB;EACzD,WAAW,YAAY,qBAAqB;EAC5C,oBAAoB,OAAO,sBAAsB;EACjD,sBAAsB,OAAO,wBAAwB;;EAIrD,yBAAyB,OAAO,+BAA+B;;EAE/D,uBAAuB,oBAAoB,QAAQ;;EAEnD,2BAA2B,mBAAmB,QAAQ,OAAO;;EAI7D,gBAAgB,iBAAiB,QAAQ;;EAEzC,kBAAkB,QAAQ,aAAa;;EAEvC,kBAAkB,iBAAiB;EAGnC,aAAa,OAAO,gBAAgB;;;;;EAOpC,mBACE,kBACA,yBACC,QAAQ;;EAEX,iBAAiB,MAAM,qBAAqB;;EAE5C,gBAAgB,iBAAiB,iBAAiB"}
@@ -0,0 +1,54 @@
1
+ import { s as AccessTokenClaims } from "./identity-store-BRRahxcS.cjs";
2
+ //#region core/access-token.d.ts
3
+ /**
4
+ * Options for {@link verifyAccessToken}. Edge-safe: depends only on `jose`.
5
+ */
6
+ interface VerifyAccessTokenOptions {
7
+ /** HMAC secret used to sign access tokens. Must match `accessTokenSecret`. */
8
+ secret: string;
9
+ /** Expected JWT issuer. Default {@link DEFAULT_ISSUER}. */
10
+ issuer?: string;
11
+ /** Expected JWT audience. Omit when tokens are minted without `aud`. */
12
+ audience?: string;
13
+ }
14
+ /**
15
+ * Verifies an HS256 access token and returns its claims.
16
+ *
17
+ * This helper is framework-agnostic and safe to run on the Edge (no `node:crypto`).
18
+ * Hydrating the principal still requires {@link IdentityService.authenticate} in Node.
19
+ *
20
+ * Throws {@link InvalidTokenError} when the token is missing, malformed, expired,
21
+ * signed with the wrong secret, or missing required claims.
22
+ */
23
+ declare function verifyAccessToken(token: string, options: VerifyAccessTokenOptions): Promise<AccessTokenClaims>;
24
+ //#endregion
25
+ //#region schema/model.d.ts
26
+ /**
27
+ * Logical description of the relational schema `@azlib/identity` expects.
28
+ *
29
+ * Concrete DDL is shipped alongside this module:
30
+ * - `@azlib/identity/schema/postgres.sql`
31
+ * - `@azlib/identity/schema/mysql.sql`
32
+ * - `@azlib/identity/schema/sqlite.sql`
33
+ * - `@azlib/identity/schema/prisma.schema`
34
+ *
35
+ * This object is documentation-as-data so consumers and tooling can introspect the
36
+ * expected tables without parsing SQL.
37
+ */
38
+ interface SchemaColumn {
39
+ name: string;
40
+ description: string;
41
+ nullable: boolean;
42
+ }
43
+ interface SchemaTable {
44
+ name: string;
45
+ description: string;
46
+ columns: readonly SchemaColumn[];
47
+ }
48
+ interface SchemaModel {
49
+ tables: readonly SchemaTable[];
50
+ }
51
+ declare const identitySchemaModel: SchemaModel;
52
+ //#endregion
53
+ export { VerifyAccessTokenOptions as n, verifyAccessToken as r, identitySchemaModel as t };
54
+ //# sourceMappingURL=index-CsYqHPvK.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-CsYqHPvK.d.cts","names":[],"sources":["../core/access-token.ts","../schema/model.ts"],"mappings":";;;;;UASiB;;EAEf;;EAEA;;EAEA;;;;;;;;;;;iBAYoB,kBACpB,eACA,SAAS,2BACR,QAAQ;;;;;;;;;;;;;;;UClBM;EACf;EACA;EACA;;UAGe;EACf;EACA;EACA,kBAAkB;;UAGH;EACf,iBAAiB;;cAGN,qBAAqB"}
@@ -0,0 +1,54 @@
1
+ import { s as AccessTokenClaims } from "./identity-store-BRRahxcS.mjs";
2
+ //#region core/access-token.d.ts
3
+ /**
4
+ * Options for {@link verifyAccessToken}. Edge-safe: depends only on `jose`.
5
+ */
6
+ interface VerifyAccessTokenOptions {
7
+ /** HMAC secret used to sign access tokens. Must match `accessTokenSecret`. */
8
+ secret: string;
9
+ /** Expected JWT issuer. Default {@link DEFAULT_ISSUER}. */
10
+ issuer?: string;
11
+ /** Expected JWT audience. Omit when tokens are minted without `aud`. */
12
+ audience?: string;
13
+ }
14
+ /**
15
+ * Verifies an HS256 access token and returns its claims.
16
+ *
17
+ * This helper is framework-agnostic and safe to run on the Edge (no `node:crypto`).
18
+ * Hydrating the principal still requires {@link IdentityService.authenticate} in Node.
19
+ *
20
+ * Throws {@link InvalidTokenError} when the token is missing, malformed, expired,
21
+ * signed with the wrong secret, or missing required claims.
22
+ */
23
+ declare function verifyAccessToken(token: string, options: VerifyAccessTokenOptions): Promise<AccessTokenClaims>;
24
+ //#endregion
25
+ //#region schema/model.d.ts
26
+ /**
27
+ * Logical description of the relational schema `@azlib/identity` expects.
28
+ *
29
+ * Concrete DDL is shipped alongside this module:
30
+ * - `@azlib/identity/schema/postgres.sql`
31
+ * - `@azlib/identity/schema/mysql.sql`
32
+ * - `@azlib/identity/schema/sqlite.sql`
33
+ * - `@azlib/identity/schema/prisma.schema`
34
+ *
35
+ * This object is documentation-as-data so consumers and tooling can introspect the
36
+ * expected tables without parsing SQL.
37
+ */
38
+ interface SchemaColumn {
39
+ name: string;
40
+ description: string;
41
+ nullable: boolean;
42
+ }
43
+ interface SchemaTable {
44
+ name: string;
45
+ description: string;
46
+ columns: readonly SchemaColumn[];
47
+ }
48
+ interface SchemaModel {
49
+ tables: readonly SchemaTable[];
50
+ }
51
+ declare const identitySchemaModel: SchemaModel;
52
+ //#endregion
53
+ export { VerifyAccessTokenOptions as n, verifyAccessToken as r, identitySchemaModel as t };
54
+ //# sourceMappingURL=index-LhSdoWEP.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-LhSdoWEP.d.mts","names":[],"sources":["../core/access-token.ts","../schema/model.ts"],"mappings":";;;;;UASiB;;EAEf;;EAEA;;EAEA;;;;;;;;;;;iBAYoB,kBACpB,eACA,SAAS,2BACR,QAAQ;;;;;;;;;;;;;;;UClBM;EACf;EACA;EACA;;UAGe;EACf;EACA;EACA,kBAAkB;;UAGH;EACf,iBAAiB;;cAGN,qBAAqB"}
package/dist/index.cjs CHANGED
@@ -1,7 +1,11 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_errors = require("./errors-Bcjx9o6g.cjs");
3
- const require_identity = require("./identity-4eP45YIP.cjs");
3
+ const require_identity = require("./identity-Yz1BVkrM.cjs");
4
+ const require_cookie_header = require("./cookie-header-Dqd5k5BU.cjs");
4
5
  exports.AccountUnavailableError = require_errors.AccountUnavailableError;
6
+ exports.DEFAULT_ACCESS_COOKIE = require_cookie_header.DEFAULT_ACCESS_COOKIE;
7
+ exports.DEFAULT_ISSUER = require_identity.DEFAULT_ISSUER;
8
+ exports.DEFAULT_REFRESH_COOKIE = require_cookie_header.DEFAULT_REFRESH_COOKIE;
5
9
  exports.EmailAlreadyRegisteredError = require_errors.EmailAlreadyRegisteredError;
6
10
  exports.ForbiddenError = require_errors.ForbiddenError;
7
11
  exports.IdentityConfigError = require_errors.IdentityConfigError;
@@ -13,6 +17,12 @@ exports.OAuthStateMismatchError = require_identity.OAuthStateMismatchError;
13
17
  exports.UnauthenticatedError = require_errors.UnauthenticatedError;
14
18
  exports.createOAuthService = require_identity.createOAuthService;
15
19
  exports.evaluateAuthorization = require_identity.evaluateAuthorization;
20
+ exports.hasIdentityCookies = require_cookie_header.hasIdentityCookies;
16
21
  exports.identitySchemaModel = require_identity.identitySchemaModel;
17
22
  exports.isAuthorized = require_identity.isAuthorized;
23
+ exports.parseCookieHeader = require_cookie_header.parseCookieHeader;
24
+ exports.readCookieValue = require_cookie_header.readCookieValue;
25
+ exports.resolveCookieAttributes = require_cookie_header.resolveCookieAttributes;
26
+ exports.resolveCookieNames = require_cookie_header.resolveCookieNames;
18
27
  exports.resolveIdentityConfig = require_identity.resolveIdentityConfig;
28
+ exports.verifyAccessToken = require_identity.verifyAccessToken;
package/dist/index.d.cts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { C as RolePermissionGrant, D as VerificationToken, E as UserRoleAssignment, O as VerificationTokenType, S as Role, T as TotpSetupResult, _ as IdentityUserStatus, b as OAuthLinkedAccount, c as AuthResult, d as AuthenticatedIdentity, f as CredentialRecord, g as IdentityUser, h as IdentityEventType, l as AuthSession, m as IdentityEvent, n as CreateIdentityUserInput, p as DirectPermissionGrant, r as IdentityStore, s as AccessTokenClaims, t as CreateAuthSessionInput, u as AuthTokens, v as LoginResult, w as TotpSecret, x as Permission, y as MfaRequiredResult } from "./identity-store-BRRahxcS.cjs";
2
- import { A as resolveIdentityConfig, B as AuthorizationDecision, D as IdentityConfigInput, E as IdentityConfig, H as PolicyRule, O as IdentityOverrides, U as evaluateAuthorization, V as AuthorizationRequirement, W as isAuthorized, _ as ExchangeCodeParams, a as IdentityError, b as OAuthUserInfo, c as UnauthenticatedError, d as OAuthProviderNotFoundError, f as OAuthService, g as BuildAuthUrlParams, h as createOAuthService, i as IdentityConfigError, k as LockoutConfig, l as OAuthAuthorizationUrl, m as OAuthStateMismatchError, n as EmailAlreadyRegisteredError, o as InvalidCredentialsError, p as OAuthServiceDeps, r as ForbiddenError, s as InvalidTokenError, t as AccountUnavailableError, u as OAuthCallbackParams, v as OAuthProvider, y as OAuthTokens, z as AuthorizationContext } from "./errors-C2xZAatu.cjs";
3
- import { t as identitySchemaModel } from "./index-CpufYgyn.cjs";
4
- export { AccessTokenClaims, AccountUnavailableError, AuthResult, AuthSession, AuthTokens, AuthenticatedIdentity, AuthorizationContext, AuthorizationDecision, AuthorizationRequirement, BuildAuthUrlParams, CreateAuthSessionInput, CreateIdentityUserInput, CredentialRecord, DirectPermissionGrant, EmailAlreadyRegisteredError, ExchangeCodeParams, ForbiddenError, IdentityConfig, IdentityConfigError, IdentityConfigInput, IdentityError, IdentityEvent, IdentityEventType, IdentityOverrides, IdentityStore, IdentityUser, IdentityUserStatus, InvalidCredentialsError, InvalidTokenError, LockoutConfig, LoginResult, MfaRequiredResult, OAuthAuthorizationUrl, OAuthCallbackParams, OAuthLinkedAccount, OAuthProvider, OAuthProviderNotFoundError, OAuthService, OAuthServiceDeps, OAuthStateMismatchError, OAuthTokens, OAuthUserInfo, Permission, PolicyRule, Role, RolePermissionGrant, TotpSecret, TotpSetupResult, UnauthenticatedError, UserRoleAssignment, VerificationToken, VerificationTokenType, createOAuthService, evaluateAuthorization, identitySchemaModel, isAuthorized, resolveIdentityConfig };
2
+ import { A as LockoutConfig, B as AuthorizationContext, D as IdentityConfig, E as DEFAULT_ISSUER, G as isAuthorized, H as AuthorizationRequirement, O as IdentityConfigInput, U as PolicyRule, V as AuthorizationDecision, W as evaluateAuthorization, _ as ExchangeCodeParams, a as IdentityError, b as OAuthUserInfo, c as UnauthenticatedError, d as OAuthProviderNotFoundError, f as OAuthService, g as BuildAuthUrlParams, h as createOAuthService, i as IdentityConfigError, j as resolveIdentityConfig, k as IdentityOverrides, l as OAuthAuthorizationUrl, m as OAuthStateMismatchError, n as EmailAlreadyRegisteredError, o as InvalidCredentialsError, p as OAuthServiceDeps, r as ForbiddenError, s as InvalidTokenError, t as AccountUnavailableError, u as OAuthCallbackParams, v as OAuthProvider, y as OAuthTokens } from "./errors-0Zh7EG06.cjs";
3
+ import { n as VerifyAccessTokenOptions, r as verifyAccessToken, t as identitySchemaModel } from "./index-CsYqHPvK.cjs";
4
+ import { a as DEFAULT_ACCESS_COOKIE, c as IdentityCookieNames, d as parseCookieHeader, f as readCookieValue, i as CookieWriter, l as IdentityCookieOptions, m as resolveCookieNames, n as CookieSource, o as DEFAULT_REFRESH_COOKIE, p as resolveCookieAttributes, r as CookieStore, s as IdentityCookieAttributes, t as CookieReader, u as hasIdentityCookies } from "./cookie-header-LFWHKQ04.cjs";
5
+ export { AccessTokenClaims, AccountUnavailableError, AuthResult, AuthSession, AuthTokens, AuthenticatedIdentity, AuthorizationContext, AuthorizationDecision, AuthorizationRequirement, BuildAuthUrlParams, type CookieReader, type CookieSource, type CookieStore, type CookieWriter, CreateAuthSessionInput, CreateIdentityUserInput, CredentialRecord, DEFAULT_ACCESS_COOKIE, DEFAULT_ISSUER, DEFAULT_REFRESH_COOKIE, DirectPermissionGrant, EmailAlreadyRegisteredError, ExchangeCodeParams, ForbiddenError, IdentityConfig, IdentityConfigError, IdentityConfigInput, type IdentityCookieAttributes, type IdentityCookieNames, type IdentityCookieOptions, IdentityError, IdentityEvent, IdentityEventType, IdentityOverrides, IdentityStore, IdentityUser, IdentityUserStatus, InvalidCredentialsError, InvalidTokenError, LockoutConfig, LoginResult, MfaRequiredResult, OAuthAuthorizationUrl, OAuthCallbackParams, OAuthLinkedAccount, OAuthProvider, OAuthProviderNotFoundError, OAuthService, OAuthServiceDeps, OAuthStateMismatchError, OAuthTokens, OAuthUserInfo, Permission, PolicyRule, Role, RolePermissionGrant, TotpSecret, TotpSetupResult, UnauthenticatedError, UserRoleAssignment, VerificationToken, VerificationTokenType, type VerifyAccessTokenOptions, createOAuthService, evaluateAuthorization, hasIdentityCookies, identitySchemaModel, isAuthorized, parseCookieHeader, readCookieValue, resolveCookieAttributes, resolveCookieNames, resolveIdentityConfig, verifyAccessToken };
package/dist/index.d.mts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { C as RolePermissionGrant, D as VerificationToken, E as UserRoleAssignment, O as VerificationTokenType, S as Role, T as TotpSetupResult, _ as IdentityUserStatus, b as OAuthLinkedAccount, c as AuthResult, d as AuthenticatedIdentity, f as CredentialRecord, g as IdentityUser, h as IdentityEventType, l as AuthSession, m as IdentityEvent, n as CreateIdentityUserInput, p as DirectPermissionGrant, r as IdentityStore, s as AccessTokenClaims, t as CreateAuthSessionInput, u as AuthTokens, v as LoginResult, w as TotpSecret, x as Permission, y as MfaRequiredResult } from "./identity-store-BRRahxcS.mjs";
2
- import { A as resolveIdentityConfig, B as AuthorizationDecision, D as IdentityConfigInput, E as IdentityConfig, H as PolicyRule, O as IdentityOverrides, U as evaluateAuthorization, V as AuthorizationRequirement, W as isAuthorized, _ as ExchangeCodeParams, a as IdentityError, b as OAuthUserInfo, c as UnauthenticatedError, d as OAuthProviderNotFoundError, f as OAuthService, g as BuildAuthUrlParams, h as createOAuthService, i as IdentityConfigError, k as LockoutConfig, l as OAuthAuthorizationUrl, m as OAuthStateMismatchError, n as EmailAlreadyRegisteredError, o as InvalidCredentialsError, p as OAuthServiceDeps, r as ForbiddenError, s as InvalidTokenError, t as AccountUnavailableError, u as OAuthCallbackParams, v as OAuthProvider, y as OAuthTokens, z as AuthorizationContext } from "./errors-BGMwaW5s.mjs";
3
- import { t as identitySchemaModel } from "./index-CpufYgyn.mjs";
4
- export { AccessTokenClaims, AccountUnavailableError, AuthResult, AuthSession, AuthTokens, AuthenticatedIdentity, AuthorizationContext, AuthorizationDecision, AuthorizationRequirement, BuildAuthUrlParams, CreateAuthSessionInput, CreateIdentityUserInput, CredentialRecord, DirectPermissionGrant, EmailAlreadyRegisteredError, ExchangeCodeParams, ForbiddenError, IdentityConfig, IdentityConfigError, IdentityConfigInput, IdentityError, IdentityEvent, IdentityEventType, IdentityOverrides, IdentityStore, IdentityUser, IdentityUserStatus, InvalidCredentialsError, InvalidTokenError, LockoutConfig, LoginResult, MfaRequiredResult, OAuthAuthorizationUrl, OAuthCallbackParams, OAuthLinkedAccount, OAuthProvider, OAuthProviderNotFoundError, OAuthService, OAuthServiceDeps, OAuthStateMismatchError, OAuthTokens, OAuthUserInfo, Permission, PolicyRule, Role, RolePermissionGrant, TotpSecret, TotpSetupResult, UnauthenticatedError, UserRoleAssignment, VerificationToken, VerificationTokenType, createOAuthService, evaluateAuthorization, identitySchemaModel, isAuthorized, resolveIdentityConfig };
2
+ import { A as LockoutConfig, B as AuthorizationContext, D as IdentityConfig, E as DEFAULT_ISSUER, G as isAuthorized, H as AuthorizationRequirement, O as IdentityConfigInput, U as PolicyRule, V as AuthorizationDecision, W as evaluateAuthorization, _ as ExchangeCodeParams, a as IdentityError, b as OAuthUserInfo, c as UnauthenticatedError, d as OAuthProviderNotFoundError, f as OAuthService, g as BuildAuthUrlParams, h as createOAuthService, i as IdentityConfigError, j as resolveIdentityConfig, k as IdentityOverrides, l as OAuthAuthorizationUrl, m as OAuthStateMismatchError, n as EmailAlreadyRegisteredError, o as InvalidCredentialsError, p as OAuthServiceDeps, r as ForbiddenError, s as InvalidTokenError, t as AccountUnavailableError, u as OAuthCallbackParams, v as OAuthProvider, y as OAuthTokens } from "./errors-DVDEUk9-.mjs";
3
+ import { n as VerifyAccessTokenOptions, r as verifyAccessToken, t as identitySchemaModel } from "./index-LhSdoWEP.mjs";
4
+ import { a as DEFAULT_ACCESS_COOKIE, c as IdentityCookieNames, d as parseCookieHeader, f as readCookieValue, i as CookieWriter, l as IdentityCookieOptions, m as resolveCookieNames, n as CookieSource, o as DEFAULT_REFRESH_COOKIE, p as resolveCookieAttributes, r as CookieStore, s as IdentityCookieAttributes, t as CookieReader, u as hasIdentityCookies } from "./cookie-header-LFWHKQ04.mjs";
5
+ export { AccessTokenClaims, AccountUnavailableError, AuthResult, AuthSession, AuthTokens, AuthenticatedIdentity, AuthorizationContext, AuthorizationDecision, AuthorizationRequirement, BuildAuthUrlParams, type CookieReader, type CookieSource, type CookieStore, type CookieWriter, CreateAuthSessionInput, CreateIdentityUserInput, CredentialRecord, DEFAULT_ACCESS_COOKIE, DEFAULT_ISSUER, DEFAULT_REFRESH_COOKIE, DirectPermissionGrant, EmailAlreadyRegisteredError, ExchangeCodeParams, ForbiddenError, IdentityConfig, IdentityConfigError, IdentityConfigInput, type IdentityCookieAttributes, type IdentityCookieNames, type IdentityCookieOptions, IdentityError, IdentityEvent, IdentityEventType, IdentityOverrides, IdentityStore, IdentityUser, IdentityUserStatus, InvalidCredentialsError, InvalidTokenError, LockoutConfig, LoginResult, MfaRequiredResult, OAuthAuthorizationUrl, OAuthCallbackParams, OAuthLinkedAccount, OAuthProvider, OAuthProviderNotFoundError, OAuthService, OAuthServiceDeps, OAuthStateMismatchError, OAuthTokens, OAuthUserInfo, Permission, PolicyRule, Role, RolePermissionGrant, TotpSecret, TotpSetupResult, UnauthenticatedError, UserRoleAssignment, VerificationToken, VerificationTokenType, type VerifyAccessTokenOptions, createOAuthService, evaluateAuthorization, hasIdentityCookies, identitySchemaModel, isAuthorized, parseCookieHeader, readCookieValue, resolveCookieAttributes, resolveCookieNames, resolveIdentityConfig, verifyAccessToken };
package/dist/index.mjs CHANGED
@@ -1,3 +1,4 @@
1
1
  import { a as IdentityError, c as UnauthenticatedError, i as IdentityConfigError, n as EmailAlreadyRegisteredError, o as InvalidCredentialsError, r as ForbiddenError, s as InvalidTokenError, t as AccountUnavailableError } from "./errors-CEmnZxIn.mjs";
2
- import { c as isAuthorized, i as createOAuthService, l as resolveIdentityConfig, n as OAuthProviderNotFoundError, r as OAuthStateMismatchError, s as evaluateAuthorization, t as identitySchemaModel } from "./identity-Bz9RDOvT.mjs";
3
- export { AccountUnavailableError, EmailAlreadyRegisteredError, ForbiddenError, IdentityConfigError, IdentityError, InvalidCredentialsError, InvalidTokenError, OAuthProviderNotFoundError, OAuthStateMismatchError, UnauthenticatedError, createOAuthService, evaluateAuthorization, identitySchemaModel, isAuthorized, resolveIdentityConfig };
2
+ import { a as createOAuthService, c as evaluateAuthorization, d as resolveIdentityConfig, i as OAuthStateMismatchError, l as isAuthorized, n as verifyAccessToken, r as OAuthProviderNotFoundError, t as identitySchemaModel, u as DEFAULT_ISSUER } from "./identity-D0qyca_c.mjs";
3
+ import { a as readCookieValue, i as parseCookieHeader, n as DEFAULT_REFRESH_COOKIE, o as resolveCookieAttributes, r as hasIdentityCookies, s as resolveCookieNames, t as DEFAULT_ACCESS_COOKIE } from "./cookie-header-DptIxRmW.mjs";
4
+ export { AccountUnavailableError, DEFAULT_ACCESS_COOKIE, DEFAULT_ISSUER, DEFAULT_REFRESH_COOKIE, EmailAlreadyRegisteredError, ForbiddenError, IdentityConfigError, IdentityError, InvalidCredentialsError, InvalidTokenError, OAuthProviderNotFoundError, OAuthStateMismatchError, UnauthenticatedError, createOAuthService, evaluateAuthorization, hasIdentityCookies, identitySchemaModel, isAuthorized, parseCookieHeader, readCookieValue, resolveCookieAttributes, resolveCookieNames, resolveIdentityConfig, verifyAccessToken };
@@ -1 +1 @@
1
- {"version":3,"file":"logger-CcCHJVVe.mjs","names":[],"sources":["../core/logger.ts"],"sourcesContent":["/**\n * Pluggable logger interface for `@azlib/identity`.\n *\n * The package uses this interface for request/response logging in the Express router and\n * for operational messages throughout the module. Consumers can hook any structured\n * logging library (Winston, Pino, Bunyan, etc.) by implementing this interface.\n *\n * @example\n * ```ts\n * import pino from \"pino\";\n *\n * const logger = pino();\n * createIdentityRouter(service, { logger });\n * ```\n */\nexport interface IdentityLogger {\n debug(message: string, meta?: Record<string, unknown>): void;\n info(message: string, meta?: Record<string, unknown>): void;\n warn(message: string, meta?: Record<string, unknown>): void;\n error(message: string, meta?: Record<string, unknown>): void;\n}\n\n/**\n * Default logger that writes to the Node.js console with an `[identity]` prefix.\n * Used when no custom logger is provided.\n */\nexport const consoleLogger: IdentityLogger = {\n debug: (msg, meta) => console.debug(`[identity] ${msg}`, ...(meta !== undefined ? [meta] : [])),\n info: (msg, meta) => console.info(`[identity] ${msg}`, ...(meta !== undefined ? [meta] : [])),\n warn: (msg, meta) => console.warn(`[identity] ${msg}`, ...(meta !== undefined ? [meta] : [])),\n error: (msg, meta) => console.error(`[identity] ${msg}`, ...(meta !== undefined ? [meta] : [])),\n};\n\n/** No-op logger. Pass `false` or `noopLogger` to disable all identity logging. */\nexport const noopLogger: IdentityLogger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\n/**\n * Resolves an `IdentityLogger | false | undefined` to a concrete `IdentityLogger`.\n *\n * - `false` → {@link noopLogger}\n * - `undefined` → {@link consoleLogger}\n * - anything else → returned as-is\n */\nexport function resolveLogger(logger?: IdentityLogger | false): IdentityLogger {\n if (logger === false) return noopLogger;\n return logger ?? consoleLogger;\n}\n"],"mappings":";;;;;AA0BA,MAAa,gBAAgC;CAC3C,QAAQ,KAAK,SAAS,QAAQ,MAAM,cAAc,OAAO,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,IAAI,CAAC,CAAE;CAC9F,OAAO,KAAK,SAAS,QAAQ,KAAK,cAAc,OAAO,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,IAAI,CAAC,CAAE;CAC5F,OAAO,KAAK,SAAS,QAAQ,KAAK,cAAc,OAAO,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,IAAI,CAAC,CAAE;CAC5F,QAAQ,KAAK,SAAS,QAAQ,MAAM,cAAc,OAAO,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,IAAI,CAAC,CAAE;AAChG;;AAGA,MAAa,aAA6B;CACxC,aAAa,CAAC;CACd,YAAY,CAAC;CACb,YAAY,CAAC;CACb,aAAa,CAAC;AAChB;;;;;;;;AASA,SAAgB,cAAc,QAAiD;CAC7E,IAAI,WAAW,OAAO,OAAO;CAC7B,OAAO,UAAU;AACnB"}
1
+ {"version":3,"file":"logger-CcCHJVVe.mjs","names":[],"sources":["../core/logger.ts"],"sourcesContent":["/**\n * Pluggable logger interface for `@azlib/identity`.\n *\n * The package uses this interface for request/response logging in the Express router and\n * for operational messages throughout the module. Consumers can hook any structured\n * logging library (Winston, Pino, Bunyan, etc.) by implementing this interface.\n *\n * @example\n * ```ts\n * import pino from \"pino\";\n *\n * const logger = pino();\n * createIdentityRouter(service, { logger });\n * ```\n */\nexport interface IdentityLogger {\n debug(message: string, meta?: Record<string, unknown>): void;\n info(message: string, meta?: Record<string, unknown>): void;\n warn(message: string, meta?: Record<string, unknown>): void;\n error(message: string, meta?: Record<string, unknown>): void;\n}\n\n/**\n * Default logger that writes to the Node.js console with an `[identity]` prefix.\n * Used when no custom logger is provided.\n */\nexport const consoleLogger: IdentityLogger = {\n debug: (msg, meta) =>\n console.debug(`[identity] ${msg}`, ...(meta !== undefined ? [meta] : [])),\n info: (msg, meta) =>\n console.info(`[identity] ${msg}`, ...(meta !== undefined ? [meta] : [])),\n warn: (msg, meta) =>\n console.warn(`[identity] ${msg}`, ...(meta !== undefined ? [meta] : [])),\n error: (msg, meta) =>\n console.error(`[identity] ${msg}`, ...(meta !== undefined ? [meta] : [])),\n};\n\n/** No-op logger. Pass `false` or `noopLogger` to disable all identity logging. */\nexport const noopLogger: IdentityLogger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n\n/**\n * Resolves an `IdentityLogger | false | undefined` to a concrete `IdentityLogger`.\n *\n * - `false` → {@link noopLogger}\n * - `undefined` → {@link consoleLogger}\n * - anything else → returned as-is\n */\nexport function resolveLogger(logger?: IdentityLogger | false): IdentityLogger {\n if (logger === false) return noopLogger;\n return logger ?? consoleLogger;\n}\n"],"mappings":";;;;;AA0BA,MAAa,gBAAgC;CAC3C,QAAQ,KAAK,SACX,QAAQ,MAAM,cAAc,OAAO,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,IAAI,CAAC,CAAE;CAC1E,OAAO,KAAK,SACV,QAAQ,KAAK,cAAc,OAAO,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,IAAI,CAAC,CAAE;CACzE,OAAO,KAAK,SACV,QAAQ,KAAK,cAAc,OAAO,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,IAAI,CAAC,CAAE;CACzE,QAAQ,KAAK,SACX,QAAQ,MAAM,cAAc,OAAO,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,IAAI,CAAC,CAAE;AAC5E;;AAGA,MAAa,aAA6B;CACxC,aAAa,CAAC;CACd,YAAY,CAAC;CACb,YAAY,CAAC;CACb,aAAa,CAAC;AAChB;;;;;;;;AASA,SAAgB,cAAc,QAAiD;CAC7E,IAAI,WAAW,OAAO,OAAO;CAC7B,OAAO,UAAU;AACnB"}
package/dist/nestjs.cjs CHANGED
@@ -2,19 +2,19 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_errors = require("./errors-Bcjx9o6g.cjs");
3
3
  let _nestjs_common = require("@nestjs/common");
4
4
  let _nestjs_core = require("@nestjs/core");
5
- //#region \0@oxc-project+runtime@0.132.0/helpers/decorateMetadata.js
5
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorateMetadata.js
6
6
  function __decorateMetadata(k, v) {
7
7
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
8
8
  }
9
9
  //#endregion
10
- //#region \0@oxc-project+runtime@0.132.0/helpers/decorateParam.js
10
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorateParam.js
11
11
  function __decorateParam(paramIndex, decorator) {
12
12
  return function(target, key) {
13
13
  decorator(target, key, paramIndex);
14
14
  };
15
15
  }
16
16
  //#endregion
17
- //#region \0@oxc-project+runtime@0.132.0/helpers/decorate.js
17
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorate.js
18
18
  function __decorate(decorators, target, key, desc) {
19
19
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
20
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -373,7 +373,6 @@ function createIdentityController(prefix, controllerOptions = {}) {
373
373
  * by metadata decorators, and a `@CurrentUser()` param decorator. `@nestjs/common` and
374
374
  * `reflect-metadata` are optional peer dependencies — only required when this entry is used.
375
375
  */
376
- var _ref;
377
376
  /** Token used to inject the configured {@link IdentityService} in Nest providers. */
378
377
  const IDENTITY_SERVICE = Symbol.for("azlib.identity.service");
379
378
  /** Metadata key holding the authorization requirement for a route. */
@@ -429,7 +428,7 @@ let IdentityAuthorizationGuard = class IdentityAuthorizationGuard {
429
428
  IdentityAuthorizationGuard = __decorate([
430
429
  (0, _nestjs_common.Injectable)(),
431
430
  __decorateParam(0, (0, _nestjs_common.Inject)(IDENTITY_SERVICE)),
432
- __decorateMetadata("design:paramtypes", [Object, typeof (_ref = typeof _nestjs_core.Reflector !== "undefined" && _nestjs_core.Reflector) === "function" ? _ref : Object])
431
+ __decorateMetadata("design:paramtypes", [Object, typeof _nestjs_core.Reflector === "undefined" ? Object : _nestjs_core.Reflector])
433
432
  ], IdentityAuthorizationGuard);
434
433
  /** Declares the authorization requirement for a route or controller. */
435
434
  const RequireAuthorization = (requirement) => (0, _nestjs_common.SetMetadata)(IDENTITY_REQUIREMENT, requirement);
package/dist/nestjs.d.cts CHANGED
@@ -1,10 +1,9 @@
1
- import { V as AuthorizationRequirement } from "./errors-C2xZAatu.cjs";
2
- import { t as IdentityService } from "./identity-service-CLzKx8Z7.cjs";
3
- import { t as CookieRefreshOptions } from "./identity-router-Dib30Waj.cjs";
1
+ import { H as AuthorizationRequirement } from "./errors-0Zh7EG06.cjs";
2
+ import { t as IdentityService } from "./identity-service-DE0Ffguz.cjs";
3
+ import { t as CookieRefreshOptions } from "./identity-router-D4oqYI60.cjs";
4
4
  import { Request, Response } from "express";
5
5
  import { CanActivate, DynamicModule, ExecutionContext } from "@nestjs/common";
6
6
  import { Reflector } from "@nestjs/core";
7
-
8
7
  //#region core/nestjs/identity-controller.d.ts
9
8
  /** Options accepted by {@link createIdentityController}. */
10
9
  interface IdentityControllerOptions {