@omnitron-dev/titan-auth 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 LuxQuant
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,27 @@
1
+ # @omnitron-dev/titan-auth
2
+
3
+ > JWT authentication module for the Titan framework
4
+
5
+ Part of the [Omni](../../README.md) monorepo — Fullstack Type-Safe RPC Framework.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pnpm add @omnitron-dev/titan-auth
11
+ ```
12
+
13
+ ## Overview
14
+
15
+ Provides JWT-based authentication for Titan applications. Handles token issuance (HS256, via `jose`), validation in HTTP middleware, and bridges auth context into Titan's async-local-storage RLS layer so every RPC call has access to the authenticated user.
16
+
17
+ ### Key Features
18
+
19
+ - JWT issuance and validation
20
+ - `AuthenticationManager` for HTTP middleware
21
+ - `AuthenticationClient` with pluggable token storage
22
+ - Auth context propagation via `AsyncLocalStorage`
23
+ - Method-level authorization via `@Public({ auth: { roles, permissions, policies } })`
24
+
25
+ ## License
26
+
27
+ MIT
@@ -0,0 +1,15 @@
1
+ import type { IAuthContext, IRequireAuthOptions, IAuthMiddleware } from './auth.types.js';
2
+ export declare const AUTH_METADATA_KEY: unique symbol;
3
+ export declare const PUBLIC_METADATA_KEY: unique symbol;
4
+ export interface IAuthDecoratorContext {
5
+ __authMiddleware__?: IAuthMiddleware;
6
+ __authContext__?: IAuthContext;
7
+ }
8
+ export declare function RequireAuth(options?: IRequireAuthOptions): MethodDecorator;
9
+ export declare function RequireServiceAuth(): MethodDecorator;
10
+ export declare function RequireAdminAuth(): MethodDecorator;
11
+ export declare function getAuthRequirements(target: object, propertyKey: string | symbol): IRequireAuthOptions | undefined;
12
+ export declare function Public(): ClassDecorator & MethodDecorator;
13
+ export declare function isPublic(target: object, propertyKey?: string | symbol): boolean;
14
+ export declare function RequireRole(roles: string[], message?: string): MethodDecorator;
15
+ //# sourceMappingURL=auth.decorators.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.decorators.d.ts","sourceRoot":"","sources":["../src/auth.decorators.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAO1F,eAAO,MAAM,iBAAiB,eAAwC,CAAC;AAKvE,eAAO,MAAM,mBAAmB,eAAkC,CAAC;AAKnE,MAAM,WAAW,qBAAqB;IAEpC,kBAAkB,CAAC,EAAE,eAAe,CAAC;IAErC,eAAe,CAAC,EAAE,YAAY,CAAC;CAChC;AAoCD,wBAAgB,WAAW,CAAC,OAAO,GAAE,mBAAwB,GAAG,eAAe,CAqD9E;AAeD,wBAAgB,kBAAkB,IAAI,eAAe,CAKpD;AAeD,wBAAgB,gBAAgB,IAAI,eAAe,CAKlD;AASD,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,GAAG,mBAAmB,GAAG,SAAS,CAEjH;AAoCD,wBAAgB,MAAM,IAAI,cAAc,GAAG,eAAe,CAgBzD;AASD,wBAAgB,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAU/E;AAgCD,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,eAAe,CAK9E"}
@@ -0,0 +1,77 @@
1
+ import { hasRole, isAnonymous } from './auth.utils.js';
2
+ export const AUTH_METADATA_KEY = Symbol.for('titan:auth:requirements');
3
+ export const PUBLIC_METADATA_KEY = Symbol.for('titan:auth:public');
4
+ export function RequireAuth(options = {}) {
5
+ return function (target, propertyKey, descriptor) {
6
+ const originalMethod = descriptor.value;
7
+ descriptor.value = async function (...args) {
8
+ const middleware = this.__authMiddleware__;
9
+ if (!middleware) {
10
+ throw new Error(`@RequireAuth: __authMiddleware__ not injected. ` +
11
+ `Inject AUTH_MIDDLEWARE_TOKEN as __authMiddleware__ in the class constructor.`);
12
+ }
13
+ const request = args.find((arg) => typeof arg === 'object' && arg !== null && 'headers' in arg);
14
+ if (!request) {
15
+ throw new Error(`@RequireAuth: No request object found in method arguments. ` +
16
+ `The first argument should be a request-like object with headers.`);
17
+ }
18
+ const authContext = options.allowAnonymous
19
+ ? await middleware.authenticate(request)
20
+ : await middleware.authenticateRequired(request);
21
+ if (options.roles && options.roles.length > 0 && !isAnonymous(authContext)) {
22
+ if (!hasRole(authContext.role, options.roles)) {
23
+ const error = new Error(options.message ?? 'Insufficient permissions');
24
+ error.name = 'ForbiddenError';
25
+ throw error;
26
+ }
27
+ }
28
+ this.__authContext__ = authContext;
29
+ return originalMethod.apply(this, args);
30
+ };
31
+ Reflect.defineMetadata(AUTH_METADATA_KEY, options, target, propertyKey);
32
+ return descriptor;
33
+ };
34
+ }
35
+ export function RequireServiceAuth() {
36
+ return RequireAuth({
37
+ roles: ['service_role'],
38
+ message: 'Service authentication required',
39
+ });
40
+ }
41
+ export function RequireAdminAuth() {
42
+ return RequireAuth({
43
+ roles: ['admin', 'service_role'],
44
+ message: 'Admin authentication required',
45
+ });
46
+ }
47
+ export function getAuthRequirements(target, propertyKey) {
48
+ return Reflect.getMetadata(AUTH_METADATA_KEY, target, propertyKey);
49
+ }
50
+ export function Public() {
51
+ return function (target, propertyKey, descriptor) {
52
+ if (propertyKey !== undefined && descriptor !== undefined) {
53
+ Reflect.defineMetadata(PUBLIC_METADATA_KEY, true, target, propertyKey);
54
+ return descriptor;
55
+ }
56
+ else {
57
+ Reflect.defineMetadata(PUBLIC_METADATA_KEY, true, target);
58
+ return undefined;
59
+ }
60
+ };
61
+ }
62
+ export function isPublic(target, propertyKey) {
63
+ if (propertyKey !== undefined) {
64
+ const methodPublic = Reflect.getMetadata(PUBLIC_METADATA_KEY, target, propertyKey);
65
+ if (methodPublic === true)
66
+ return true;
67
+ }
68
+ const classTarget = typeof target === 'function' ? target : target.constructor;
69
+ return Reflect.getMetadata(PUBLIC_METADATA_KEY, classTarget) === true;
70
+ }
71
+ export function RequireRole(roles, message) {
72
+ return RequireAuth({
73
+ roles,
74
+ message: message ?? `Required roles: ${roles.join(', ')}`,
75
+ });
76
+ }
77
+ //# sourceMappingURL=auth.decorators.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.decorators.js","sourceRoot":"","sources":["../src/auth.decorators.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAKvD,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;AAKvE,MAAM,CAAC,MAAM,mBAAmB,GAAG,MAAM,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC;AA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,YAAY,GAAG,OAAO,CAAC,WAAW,CAAC,mBAAmB,EAAE,MAAM,EAAE,WAAW,CAAC,CAAC;QACnF,IAAI,YAAY,KAAK,IAAI;YAAE,OAAO,IAAI,CAAC;IACzC,CAAC;IAGD,MAAM,WAAW,GAAG,OAAO,MAAM,KAAK,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC;IAC/E,OAAO,OAAO,CAAC,WAAW,CAAC,mBAAmB,EAAE,WAAW,CAAC,KAAK,IAAI,CAAC;AACxE,CAAC;AAgCD,MAAM,UAAU,WAAW,CAAC,KAAe,EAAE,OAAgB;IAC3D,OAAO,WAAW,CAAC;QACjB,KAAK;QACL,OAAO,EAAE,OAAO,IAAI,mBAAmB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;KAC1D,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,48 @@
1
+ import type { IAuthContext, IAuthMiddleware, IRequestLike } from './auth.types.js';
2
+ export interface IGuardContext {
3
+ request: IRequestLike;
4
+ handler?: object;
5
+ methodName?: string | symbol;
6
+ data?: Record<string, unknown>;
7
+ }
8
+ export interface IGuard {
9
+ canActivate(context: IGuardContext): Promise<boolean>;
10
+ }
11
+ export interface IGuardResult {
12
+ allowed: boolean;
13
+ authContext?: IAuthContext;
14
+ reason?: string;
15
+ }
16
+ export declare class AuthGuard implements IGuard {
17
+ private readonly authMiddleware;
18
+ constructor(authMiddleware: IAuthMiddleware);
19
+ canActivate(context: IGuardContext): Promise<boolean>;
20
+ execute(context: IGuardContext): Promise<IGuardResult>;
21
+ }
22
+ export declare class RoleGuard implements IGuard {
23
+ private readonly authMiddleware;
24
+ private readonly requiredRoles;
25
+ constructor(authMiddleware: IAuthMiddleware, requiredRoles: string[]);
26
+ canActivate(context: IGuardContext): Promise<boolean>;
27
+ execute(context: IGuardContext): Promise<IGuardResult>;
28
+ }
29
+ export declare class ApiKeyGuard implements IGuard {
30
+ private readonly headerName;
31
+ private readonly validateKey;
32
+ constructor(options: {
33
+ headerName?: string;
34
+ validateKey: (key: string) => Promise<{
35
+ userId?: string;
36
+ scopes?: string[];
37
+ } | null>;
38
+ });
39
+ canActivate(context: IGuardContext): Promise<boolean>;
40
+ execute(context: IGuardContext): Promise<IGuardResult>;
41
+ }
42
+ export declare class CompositeGuard implements IGuard {
43
+ private readonly guards;
44
+ private readonly mode;
45
+ constructor(guards: IGuard[], mode?: 'all' | 'any');
46
+ canActivate(context: IGuardContext): Promise<boolean>;
47
+ }
48
+ //# sourceMappingURL=auth.guards.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.guards.d.ts","sourceRoot":"","sources":["../src/auth.guards.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAOnF,MAAM,WAAW,aAAa;IAE5B,OAAO,EAAE,YAAY,CAAC;IAEtB,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAE7B,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAChC;AAKD,MAAM,WAAW,MAAM;IAOrB,WAAW,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACvD;AAKD,MAAM,WAAW,YAAY;IAE3B,OAAO,EAAE,OAAO,CAAC;IAEjB,WAAW,CAAC,EAAE,YAAY,CAAC;IAE3B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAkBD,qBAAa,SAAU,YAAW,MAAM;IAC1B,OAAO,CAAC,QAAQ,CAAC,cAAc;gBAAd,cAAc,EAAE,eAAe;IAKtD,WAAW,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,OAAO,CAAC;IAQrD,OAAO,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,YAAY,CAAC;CAuB7D;AAkBD,qBAAa,SAAU,YAAW,MAAM;IAEpC,OAAO,CAAC,QAAQ,CAAC,cAAc;IAC/B,OAAO,CAAC,QAAQ,CAAC,aAAa;gBADb,cAAc,EAAE,eAAe,EAC/B,aAAa,EAAE,MAAM,EAAE;IAMpC,WAAW,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,OAAO,CAAC;IAQrD,OAAO,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,YAAY,CAAC;CAwD7D;AAyBD,qBAAa,WAAY,YAAW,MAAM;IACxC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAA0E;gBAE1F,OAAO,EAAE;QAEnB,UAAU,CAAC,EAAE,MAAM,CAAC;QAEpB,WAAW,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC;YAAE,MAAM,CAAC,EAAE,MAAM,CAAC;YAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAA;SAAE,GAAG,IAAI,CAAC,CAAC;KACtF;IAQK,WAAW,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,OAAO,CAAC;IAQrD,OAAO,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,YAAY,CAAC;CAsD7D;AAcD,qBAAa,cAAe,YAAW,MAAM;IAEzC,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,IAAI;gBADJ,MAAM,EAAE,MAAM,EAAE,EAChB,IAAI,GAAE,KAAK,GAAG,KAAa;IAMxC,WAAW,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,OAAO,CAAC;CAiB5D"}
@@ -0,0 +1,162 @@
1
+ import { isPublic, getAuthRequirements } from './auth.decorators.js';
2
+ import { hasRole, isAnonymous } from './auth.utils.js';
3
+ export class AuthGuard {
4
+ constructor(authMiddleware) {
5
+ this.authMiddleware = authMiddleware;
6
+ }
7
+ async canActivate(context) {
8
+ const result = await this.execute(context);
9
+ return result.allowed;
10
+ }
11
+ async execute(context) {
12
+ const { request, handler, methodName } = context;
13
+ if (handler && methodName && isPublic(handler, methodName)) {
14
+ return { allowed: true };
15
+ }
16
+ if (handler && isPublic(handler)) {
17
+ return { allowed: true };
18
+ }
19
+ try {
20
+ const authContext = await this.authMiddleware.authenticateRequired(request);
21
+ return { allowed: true, authContext };
22
+ }
23
+ catch (error) {
24
+ return {
25
+ allowed: false,
26
+ reason: error instanceof Error ? error.message : 'Authentication required',
27
+ };
28
+ }
29
+ }
30
+ }
31
+ export class RoleGuard {
32
+ constructor(authMiddleware, requiredRoles) {
33
+ this.authMiddleware = authMiddleware;
34
+ this.requiredRoles = requiredRoles;
35
+ }
36
+ async canActivate(context) {
37
+ const result = await this.execute(context);
38
+ return result.allowed;
39
+ }
40
+ async execute(context) {
41
+ const { request, handler, methodName } = context;
42
+ if (handler && methodName && isPublic(handler, methodName)) {
43
+ return { allowed: true };
44
+ }
45
+ let authContext;
46
+ try {
47
+ authContext = await this.authMiddleware.authenticateRequired(request);
48
+ }
49
+ catch (error) {
50
+ return {
51
+ allowed: false,
52
+ reason: error instanceof Error ? error.message : 'Authentication required',
53
+ };
54
+ }
55
+ if (isAnonymous(authContext)) {
56
+ return {
57
+ allowed: false,
58
+ authContext,
59
+ reason: 'Authentication required for role check',
60
+ };
61
+ }
62
+ if (handler && methodName) {
63
+ const requirements = getAuthRequirements(handler, methodName);
64
+ if (requirements?.roles && requirements.roles.length > 0) {
65
+ if (!hasRole(authContext.role, requirements.roles)) {
66
+ return {
67
+ allowed: false,
68
+ authContext,
69
+ reason: `Required roles: ${requirements.roles.join(', ')}`,
70
+ };
71
+ }
72
+ return { allowed: true, authContext };
73
+ }
74
+ }
75
+ if (this.requiredRoles.length > 0) {
76
+ if (!hasRole(authContext.role, this.requiredRoles)) {
77
+ return {
78
+ allowed: false,
79
+ authContext,
80
+ reason: `Required roles: ${this.requiredRoles.join(', ')}`,
81
+ };
82
+ }
83
+ }
84
+ return { allowed: true, authContext };
85
+ }
86
+ }
87
+ export class ApiKeyGuard {
88
+ constructor(options) {
89
+ this.headerName = options.headerName ?? 'X-API-Key';
90
+ this.validateKey = options.validateKey;
91
+ }
92
+ async canActivate(context) {
93
+ const result = await this.execute(context);
94
+ return result.allowed;
95
+ }
96
+ async execute(context) {
97
+ const { request, handler, methodName } = context;
98
+ if (handler && methodName && isPublic(handler, methodName)) {
99
+ return { allowed: true };
100
+ }
101
+ const headers = request.headers;
102
+ let headerValue;
103
+ if ('get' in headers && typeof headers.get === 'function') {
104
+ headerValue = headers.get(this.headerName.toLowerCase());
105
+ }
106
+ else {
107
+ const nodeHeaders = headers;
108
+ headerValue = nodeHeaders[this.headerName.toLowerCase()];
109
+ }
110
+ const apiKey = Array.isArray(headerValue) ? headerValue[0] : headerValue;
111
+ if (!apiKey) {
112
+ return {
113
+ allowed: false,
114
+ reason: `Missing API key in ${this.headerName} header`,
115
+ };
116
+ }
117
+ const keyInfo = await this.validateKey(apiKey);
118
+ if (!keyInfo) {
119
+ return {
120
+ allowed: false,
121
+ reason: 'Invalid API key',
122
+ };
123
+ }
124
+ const authContext = {
125
+ userId: keyInfo.userId ?? 'api_key_user',
126
+ role: 'api_key',
127
+ tenantId: 'default',
128
+ isServiceRole: false,
129
+ claims: {
130
+ sub: keyInfo.userId ?? 'api_key_user',
131
+ role: 'api_key',
132
+ scopes: keyInfo.scopes,
133
+ },
134
+ };
135
+ return { allowed: true, authContext };
136
+ }
137
+ }
138
+ export class CompositeGuard {
139
+ constructor(guards, mode = 'all') {
140
+ this.guards = guards;
141
+ this.mode = mode;
142
+ }
143
+ async canActivate(context) {
144
+ if (this.mode === 'all') {
145
+ for (const guard of this.guards) {
146
+ if (!(await guard.canActivate(context))) {
147
+ return false;
148
+ }
149
+ }
150
+ return true;
151
+ }
152
+ else {
153
+ for (const guard of this.guards) {
154
+ if (await guard.canActivate(context)) {
155
+ return true;
156
+ }
157
+ }
158
+ return false;
159
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BACrC,IAAI,EAAE,SAAS;gBACf,MAAM,EAAE,OAAO,CAAC,MAAM;aACvB;SACF,CAAC;QAEF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC;IACxC,CAAC;CACF;AAcD,MAAM,OAAO,cAAc;IACzB,YACmB,MAAgB,EAChB,OAAsB,KAAK;QAD3B,WAAM,GAAN,MAAM,CAAU;QAChB,SAAI,GAAJ,IAAI,CAAuB;IAC3C,CAAC;IAKJ,KAAK,CAAC,WAAW,CAAC,OAAsB;QACtC,IAAI,IAAI,CAAC,IAAI,KAAK,KAAK,EAAE,CAAC;YACxB,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;gBAChC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;oBACxC,OAAO,KAAK,CAAC;gBACf,CAAC;YACH,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;aAAM,CAAC;YACN,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;gBAChC,IAAI,MAAM,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE,CAAC;oBACrC,OAAO,IAAI,CAAC;gBACd,CAAC;YACH,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,33 @@
1
+ import type { ILogger } from '@omnitron-dev/titan/types';
2
+ import type { IJWTService, ISignedUrlService, IJWTPayload, IAuthContext, ITokenCacheStats, ISignedTokenPayload, IAuthModuleOptions } from './auth.types.js';
3
+ export declare class InvalidTokenError extends Error {
4
+ readonly code: string;
5
+ constructor(message?: string, code?: string);
6
+ }
7
+ export declare class TokenExpiredError extends InvalidTokenError {
8
+ constructor();
9
+ }
10
+ export declare class JWTService implements IJWTService, ISignedUrlService {
11
+ private readonly logger;
12
+ private readonly options;
13
+ private jwks;
14
+ private secret;
15
+ private urlSigningSecret;
16
+ private readonly tokenCache;
17
+ private cacheHits;
18
+ private cacheMisses;
19
+ constructor(options: IAuthModuleOptions, logger: ILogger);
20
+ private initializeKeys;
21
+ verify(token: string): Promise<IJWTPayload>;
22
+ private verifyWithKey;
23
+ private validateAndMapPayload;
24
+ private getCachedToken;
25
+ private cacheToken;
26
+ private evictExpiredEntries;
27
+ createContext(token: string): Promise<IAuthContext>;
28
+ clearCache(): void;
29
+ getCacheStats(): ITokenCacheStats;
30
+ createSignedToken(payload: ISignedTokenPayload, expiresIn: number): Promise<string>;
31
+ verifySignedToken(token: string): Promise<ISignedTokenPayload>;
32
+ }
33
+ //# sourceMappingURL=auth.jwt.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.jwt.service.d.ts","sourceRoot":"","sources":["../src/auth.jwt.service.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,2BAA2B,CAAC;AAEzD,OAAO,KAAK,EACV,WAAW,EACX,iBAAiB,EACjB,WAAW,EACX,YAAY,EACZ,gBAAgB,EAEhB,mBAAmB,EACnB,kBAAkB,EACnB,MAAM,iBAAiB,CAAC;AAMzB,qBAAa,iBAAkB,SAAQ,KAAK;IAE1C,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;gBAEV,OAAO,GAAE,MAAmC,EAAE,IAAI,GAAE,MAAwB;CAKzF;AAMD,qBAAa,iBAAkB,SAAQ,iBAAiB;;CAKvD;AAuCD,qBACa,UAAW,YAAW,WAAW,EAAE,iBAAiB;IAavC,OAAO,CAAC,QAAQ,CAAC,MAAM;IAZ/C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA8C;IACtE,OAAO,CAAC,IAAI,CAAsD;IAClE,OAAO,CAAC,MAAM,CAA2B;IACzC,OAAO,CAAC,gBAAgB,CAA2B;IAGnD,OAAO,CAAC,QAAQ,CAAC,UAAU,CAA4C;IACvE,OAAO,CAAC,SAAS,CAAK;IACtB,OAAO,CAAC,WAAW,CAAK;gBAGM,OAAO,EAAE,kBAAkB,EAChB,MAAM,EAAE,OAAO;IASxD,OAAO,CAAC,cAAc;IAkChB,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;YAwCnC,aAAa;IA6B3B,OAAO,CAAC,qBAAqB;IAkC7B,OAAO,CAAC,cAAc;IAoBtB,OAAO,CAAC,UAAU;IA4BlB,OAAO,CAAC,mBAAmB;IAYrB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IAQzD,UAAU,IAAI,IAAI;IASlB,aAAa,IAAI,gBAAgB;IAgB3B,iBAAiB,CAAC,OAAO,EAAE,mBAAmB,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAoBnF,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC;CAiBrE"}
@@ -0,0 +1,245 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { jwtVerify, createRemoteJWKSet, SignJWT } from 'jose';
14
+ import { JWTExpired } from 'jose/errors';
15
+ import { Injectable, Inject } from '@omnitron-dev/titan/decorators';
16
+ import { LOGGER_TOKEN } from '@omnitron-dev/titan/module/logger';
17
+ import { AUTH_OPTIONS_TOKEN } from './auth.tokens.js';
18
+ import { createContextFromPayload } from './auth.utils.js';
19
+ export class InvalidTokenError extends Error {
20
+ constructor(message = 'Invalid or expired token', code = 'INVALID_TOKEN') {
21
+ super(message);
22
+ this.name = 'InvalidTokenError';
23
+ this.code = code;
24
+ }
25
+ }
26
+ export class TokenExpiredError extends InvalidTokenError {
27
+ constructor() {
28
+ super('Access token has expired', 'TOKEN_EXPIRED');
29
+ this.name = 'TokenExpiredError';
30
+ }
31
+ }
32
+ const DEFAULT_OPTIONS = {
33
+ algorithm: 'HS256',
34
+ defaultTenantId: 'default',
35
+ cacheEnabled: true,
36
+ cacheMaxSize: 1000,
37
+ cacheTTL: 300000,
38
+ isGlobal: false,
39
+ };
40
+ let JWTService = class JWTService {
41
+ constructor(options, logger) {
42
+ this.logger = logger;
43
+ this.jwks = null;
44
+ this.secret = null;
45
+ this.urlSigningSecret = null;
46
+ this.tokenCache = new Map();
47
+ this.cacheHits = 0;
48
+ this.cacheMisses = 0;
49
+ this.options = { ...DEFAULT_OPTIONS, ...options };
50
+ this.initializeKeys();
51
+ }
52
+ initializeKeys() {
53
+ const { algorithm, jwtSecret, jwksUrl, urlSigningKey } = this.options;
54
+ if (algorithm === 'HS256' && jwtSecret) {
55
+ this.secret = new TextEncoder().encode(jwtSecret);
56
+ }
57
+ if ((algorithm === 'RS256' || algorithm === 'ES256') && jwksUrl) {
58
+ try {
59
+ this.jwks = createRemoteJWKSet(new URL(jwksUrl));
60
+ this.logger.debug({ algorithm, jwksUrl }, 'Initialized JWKS for JWT verification');
61
+ }
62
+ catch (error) {
63
+ this.logger.error({ error, jwksUrl }, 'Failed to initialize JWKS');
64
+ throw new Error(`Failed to initialize JWKS: ${jwksUrl}`, { cause: error });
65
+ }
66
+ }
67
+ const signingKey = urlSigningKey ?? jwtSecret;
68
+ if (signingKey) {
69
+ this.urlSigningSecret = new TextEncoder().encode(signingKey);
70
+ }
71
+ if (!this.secret && !this.jwks) {
72
+ this.logger.warn('No JWT verification key configured. JWT verification will fail.');
73
+ }
74
+ }
75
+ async verify(token) {
76
+ if (this.options.cacheEnabled) {
77
+ const cached = this.getCachedToken(token);
78
+ if (cached) {
79
+ this.cacheHits++;
80
+ return cached;
81
+ }
82
+ this.cacheMisses++;
83
+ }
84
+ try {
85
+ const result = await this.verifyWithKey(token);
86
+ const payload = this.validateAndMapPayload(result.payload);
87
+ if (this.options.cacheEnabled) {
88
+ this.cacheToken(token, payload);
89
+ }
90
+ return payload;
91
+ }
92
+ catch (error) {
93
+ if (error instanceof InvalidTokenError) {
94
+ throw error;
95
+ }
96
+ if (error instanceof JWTExpired) {
97
+ this.logger.debug({ error }, 'JWT expired');
98
+ throw new TokenExpiredError();
99
+ }
100
+ this.logger.debug({ error }, 'JWT verification failed');
101
+ throw new InvalidTokenError();
102
+ }
103
+ }
104
+ async verifyWithKey(token) {
105
+ const { algorithm, issuer, audience } = this.options;
106
+ const verifyOptions = {
107
+ algorithms: [algorithm],
108
+ };
109
+ if (issuer) {
110
+ verifyOptions.issuer = issuer;
111
+ }
112
+ if (audience) {
113
+ verifyOptions.audience = audience;
114
+ }
115
+ if (this.jwks) {
116
+ return jwtVerify(token, this.jwks, verifyOptions);
117
+ }
118
+ if (this.secret) {
119
+ return jwtVerify(token, this.secret, verifyOptions);
120
+ }
121
+ throw new InvalidTokenError('JWT verification not configured');
122
+ }
123
+ validateAndMapPayload(josePayload) {
124
+ if (!josePayload.sub) {
125
+ throw new InvalidTokenError('Missing required claim: sub');
126
+ }
127
+ const payload = {
128
+ sub: josePayload.sub,
129
+ role: josePayload['role'] ?? 'user',
130
+ aud: josePayload.aud,
131
+ iss: josePayload.iss,
132
+ tenant_id: josePayload['tenant_id'],
133
+ exp: josePayload.exp,
134
+ iat: josePayload.iat,
135
+ email: josePayload['email'],
136
+ username: josePayload['username'],
137
+ display_name: josePayload['display_name'],
138
+ avatar_url: josePayload['avatar_url'],
139
+ app_metadata: josePayload['app_metadata'],
140
+ user_metadata: josePayload['user_metadata'],
141
+ };
142
+ for (const [key, value] of Object.entries(josePayload)) {
143
+ if (!(key in payload)) {
144
+ payload[key] = value;
145
+ }
146
+ }
147
+ return payload;
148
+ }
149
+ getCachedToken(token) {
150
+ const entry = this.tokenCache.get(token);
151
+ if (entry && entry.expiresAt > Date.now()) {
152
+ this.tokenCache.delete(token);
153
+ this.tokenCache.set(token, entry);
154
+ return entry.payload;
155
+ }
156
+ if (entry) {
157
+ this.tokenCache.delete(token);
158
+ }
159
+ return null;
160
+ }
161
+ cacheToken(token, payload) {
162
+ const { cacheMaxSize, cacheTTL } = this.options;
163
+ if (this.tokenCache.size >= cacheMaxSize) {
164
+ this.evictExpiredEntries();
165
+ }
166
+ if (this.tokenCache.size >= cacheMaxSize) {
167
+ const toEvict = Math.ceil(cacheMaxSize * 0.1);
168
+ const keys = Array.from(this.tokenCache.keys()).slice(0, toEvict);
169
+ for (const key of keys) {
170
+ this.tokenCache.delete(key);
171
+ }
172
+ }
173
+ const tokenExp = payload.exp ? payload.exp * 1000 : Date.now() + cacheTTL;
174
+ const cacheExp = Date.now() + cacheTTL;
175
+ const expiresAt = Math.min(tokenExp, cacheExp);
176
+ this.tokenCache.set(token, { payload, expiresAt });
177
+ }
178
+ evictExpiredEntries() {
179
+ const now = Date.now();
180
+ for (const [key, entry] of this.tokenCache) {
181
+ if (entry.expiresAt <= now) {
182
+ this.tokenCache.delete(key);
183
+ }
184
+ }
185
+ }
186
+ async createContext(token) {
187
+ const payload = await this.verify(token);
188
+ return createContextFromPayload(payload, this.options.defaultTenantId);
189
+ }
190
+ clearCache() {
191
+ this.tokenCache.clear();
192
+ this.cacheHits = 0;
193
+ this.cacheMisses = 0;
194
+ }
195
+ getCacheStats() {
196
+ const total = this.cacheHits + this.cacheMisses;
197
+ return {
198
+ size: this.tokenCache.size,
199
+ maxSize: this.options.cacheMaxSize,
200
+ hits: this.cacheHits,
201
+ misses: this.cacheMisses,
202
+ hitRate: total > 0 ? this.cacheHits / total : 0,
203
+ };
204
+ }
205
+ async createSignedToken(payload, expiresIn) {
206
+ if (!this.urlSigningSecret) {
207
+ throw new Error('URL signing key not configured');
208
+ }
209
+ return new SignJWT({
210
+ resource_id: payload.resourceId,
211
+ resource_path: payload.resourcePath,
212
+ operation: payload.operation,
213
+ transform: payload.transform,
214
+ })
215
+ .setProtectedHeader({ alg: 'HS256' })
216
+ .setExpirationTime(`${expiresIn}s`)
217
+ .setIssuedAt()
218
+ .sign(this.urlSigningSecret);
219
+ }
220
+ async verifySignedToken(token) {
221
+ if (!this.urlSigningSecret) {
222
+ throw new Error('URL signing key not configured');
223
+ }
224
+ try {
225
+ const result = await jwtVerify(token, this.urlSigningSecret);
226
+ return {
227
+ resourceId: result.payload['resource_id'],
228
+ resourcePath: result.payload['resource_path'],
229
+ operation: result.payload['operation'],
230
+ transform: result.payload['transform'],
231
+ };
232
+ }
233
+ catch {
234
+ throw new InvalidTokenError('Invalid or expired signed URL token');
235
+ }
236
+ }
237
+ };
238
+ JWTService = __decorate([
239
+ Injectable(),
240
+ __param(0, Inject(AUTH_OPTIONS_TOKEN)),
241
+ __param(1, Inject(LOGGER_TOKEN)),
242
+ __metadata("design:paramtypes", [Object, Object])
243
+ ], JWTService);
244
+ export { JWTService };
245
+ //# sourceMappingURL=auth.jwt.service.js.map