glasswork 0.8.0 → 0.8.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.
Files changed (49) hide show
  1. package/dist/openapi/openapi-transformer.d.ts +5 -0
  2. package/dist/openapi/openapi-transformer.d.ts.map +1 -1
  3. package/dist/openapi/openapi-transformer.js +5 -0
  4. package/dist/openapi/openapi-transformer.js.map +1 -1
  5. package/dist/utils/serialize-prisma-types.d.ts +1 -1
  6. package/dist/utils/serialize-prisma-types.d.ts.map +1 -1
  7. package/dist/utils/serialize-prisma-types.js +12 -10
  8. package/dist/utils/serialize-prisma-types.js.map +1 -1
  9. package/package.json +2 -2
  10. package/dist/authorization/ability-middleware.d.ts +0 -61
  11. package/dist/authorization/ability-middleware.d.ts.map +0 -1
  12. package/dist/authorization/ability-middleware.js +0 -74
  13. package/dist/authorization/ability-middleware.js.map +0 -1
  14. package/dist/authorization/index.d.ts +0 -46
  15. package/dist/authorization/index.d.ts.map +0 -1
  16. package/dist/authorization/index.js +0 -46
  17. package/dist/authorization/index.js.map +0 -1
  18. package/dist/authorization/route-helpers.d.ts +0 -106
  19. package/dist/authorization/route-helpers.d.ts.map +0 -1
  20. package/dist/authorization/route-helpers.js +0 -136
  21. package/dist/authorization/route-helpers.js.map +0 -1
  22. package/dist/authorization/service-proxy.d.ts +0 -59
  23. package/dist/authorization/service-proxy.d.ts.map +0 -1
  24. package/dist/authorization/service-proxy.js +0 -110
  25. package/dist/authorization/service-proxy.js.map +0 -1
  26. package/dist/authorization/types.d.ts +0 -58
  27. package/dist/authorization/types.d.ts.map +0 -1
  28. package/dist/authorization/types.js +0 -7
  29. package/dist/authorization/types.js.map +0 -1
  30. package/dist/hooks/authorization-hook.d.ts +0 -100
  31. package/dist/hooks/authorization-hook.d.ts.map +0 -1
  32. package/dist/hooks/authorization-hook.js +0 -93
  33. package/dist/hooks/authorization-hook.js.map +0 -1
  34. package/dist/hooks/index.d.ts +0 -54
  35. package/dist/hooks/index.d.ts.map +0 -1
  36. package/dist/hooks/index.js +0 -55
  37. package/dist/hooks/index.js.map +0 -1
  38. package/dist/hooks/service-hooks.d.ts +0 -82
  39. package/dist/hooks/service-hooks.d.ts.map +0 -1
  40. package/dist/hooks/service-hooks.js +0 -158
  41. package/dist/hooks/service-hooks.js.map +0 -1
  42. package/dist/hooks/types.d.ts +0 -151
  43. package/dist/hooks/types.d.ts.map +0 -1
  44. package/dist/hooks/types.js +0 -2
  45. package/dist/hooks/types.js.map +0 -1
  46. package/dist/utils/pagination.d.ts +0 -48
  47. package/dist/utils/pagination.d.ts.map +0 -1
  48. package/dist/utils/pagination.js +0 -42
  49. package/dist/utils/pagination.js.map +0 -1
@@ -1,59 +0,0 @@
1
- import type { AuthorizedServiceOptions, BaseAbility, ServiceAuthMetadata } from './types.js';
2
- /**
3
- * Creates a transparent proxy around a service that automatically
4
- * checks CASL permissions before executing methods.
5
- *
6
- * **⚠️ DEPRECATED: Use the hooks system instead!**
7
- *
8
- * This function is deprecated in favor of the more flexible hooks system.
9
- * Instead of manually wrapping services, configure authorization globally:
10
- *
11
- * ```typescript
12
- * // NEW APPROACH (Recommended):
13
- * import { authorizationHook, defineServiceMetadata, defineAuthorize } from 'glasswork';
14
- *
15
- * const authServiceMeta = defineServiceMetadata({
16
- * deleteSession: {
17
- * authorize: defineAuthorize('delete', 'Session')
18
- * }
19
- * });
20
- *
21
- * bootstrap(AppModule, {
22
- * serviceHooks: [authorizationHook],
23
- * serviceMetadata: { authService: authServiceMeta }
24
- * });
25
- *
26
- * // In routes - services are automatically authorized!
27
- * await services.authService.deleteSession(token);
28
- * ```
29
- *
30
- * @deprecated Use hooks system with authorizationHook instead
31
- * @see {@link https://github.com/rolandboon/glasswork/blob/main/HOOKS_SYSTEM.md}
32
- *
33
- * @param service - The service instance to wrap
34
- * @param options - Authorization configuration
35
- * @returns Proxied service with automatic authorization
36
- */
37
- export declare function withAuthorization<T extends object>(service: T, options: AuthorizedServiceOptions): T;
38
- /**
39
- * Helper to define service authorization metadata.
40
- *
41
- * **⚠️ DEPRECATED: Use `defineServiceMetadata` and `defineAuthorize` from hooks system instead!**
42
- *
43
- * @deprecated Use `defineServiceMetadata` with `defineAuthorize` from hooks module
44
- * @param metadata - Service authorization metadata
45
- * @returns The same metadata (identity function)
46
- */
47
- export declare function defineServiceAuth(metadata: ServiceAuthMetadata): ServiceAuthMetadata;
48
- /**
49
- * Creates a factory function that wraps services with authorization.
50
- *
51
- * **⚠️ DEPRECATED: Use hooks system configured in bootstrap instead!**
52
- *
53
- * @deprecated Configure authorization globally with serviceHooks in bootstrap
54
- * @param ability - The CASL ability to use
55
- * @param metadataMap - Map of service names to their authorization metadata
56
- * @returns Function that wraps services with authorization
57
- */
58
- export declare function createServiceWrapper<T extends BaseAbility = BaseAbility>(ability: T, metadataMap: Record<string, ServiceAuthMetadata>): <S extends object>(serviceName: string, service: S) => S;
59
- //# sourceMappingURL=service-proxy.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"service-proxy.d.ts","sourceRoot":"","sources":["../../src/authorization/service-proxy.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,wBAAwB,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAE7F;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,MAAM,EAChD,OAAO,EAAE,CAAC,EACV,OAAO,EAAE,wBAAwB,GAChC,CAAC,CAmDH;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,mBAAmB,GAAG,mBAAmB,CAEpF;AAED;;;;;;;;;GASG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,SAAS,WAAW,GAAG,WAAW,EACtE,OAAO,EAAE,CAAC,EACV,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,mBAAmB,CAAC,GAC/C,CAAC,CAAC,SAAS,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,KAAK,CAAC,CAW1D"}
@@ -1,110 +0,0 @@
1
- import { ForbiddenError, subject } from '@casl/ability';
2
- /**
3
- * Creates a transparent proxy around a service that automatically
4
- * checks CASL permissions before executing methods.
5
- *
6
- * **⚠️ DEPRECATED: Use the hooks system instead!**
7
- *
8
- * This function is deprecated in favor of the more flexible hooks system.
9
- * Instead of manually wrapping services, configure authorization globally:
10
- *
11
- * ```typescript
12
- * // NEW APPROACH (Recommended):
13
- * import { authorizationHook, defineServiceMetadata, defineAuthorize } from 'glasswork';
14
- *
15
- * const authServiceMeta = defineServiceMetadata({
16
- * deleteSession: {
17
- * authorize: defineAuthorize('delete', 'Session')
18
- * }
19
- * });
20
- *
21
- * bootstrap(AppModule, {
22
- * serviceHooks: [authorizationHook],
23
- * serviceMetadata: { authService: authServiceMeta }
24
- * });
25
- *
26
- * // In routes - services are automatically authorized!
27
- * await services.authService.deleteSession(token);
28
- * ```
29
- *
30
- * @deprecated Use hooks system with authorizationHook instead
31
- * @see {@link https://github.com/rolandboon/glasswork/blob/main/HOOKS_SYSTEM.md}
32
- *
33
- * @param service - The service instance to wrap
34
- * @param options - Authorization configuration
35
- * @returns Proxied service with automatic authorization
36
- */
37
- export function withAuthorization(service, options) {
38
- const { ability, metadata, onUnauthorized } = options;
39
- return new Proxy(service, {
40
- get(target, prop) {
41
- // Only intercept function calls
42
- if (typeof prop !== 'string') {
43
- return Reflect.get(target, prop);
44
- }
45
- const originalMethod = Reflect.get(target, prop);
46
- // If it's not a function, return as-is
47
- if (typeof originalMethod !== 'function') {
48
- return originalMethod;
49
- }
50
- // Check if this method has authorization metadata
51
- const authMeta = metadata[prop];
52
- // If no metadata, return original method (no authorization)
53
- if (!authMeta) {
54
- return originalMethod.bind(target);
55
- }
56
- // Return wrapped method with authorization
57
- return function (...args) {
58
- const { action, subject: subjectType, getSubject } = authMeta;
59
- // Get subject data if extractor provided
60
- const subjectData = getSubject ? getSubject(...args) : undefined;
61
- // Check authorization using CASL
62
- try {
63
- ForbiddenError.from(ability).throwUnlessCan(action, subject(subjectType, subjectData || {}));
64
- }
65
- catch (error) {
66
- if (onUnauthorized) {
67
- onUnauthorized(prop, args);
68
- throw error; // Still throw after custom handler
69
- }
70
- throw error;
71
- }
72
- // Authorization passed - execute original method
73
- return originalMethod.apply(target, args);
74
- };
75
- },
76
- });
77
- }
78
- /**
79
- * Helper to define service authorization metadata.
80
- *
81
- * **⚠️ DEPRECATED: Use `defineServiceMetadata` and `defineAuthorize` from hooks system instead!**
82
- *
83
- * @deprecated Use `defineServiceMetadata` with `defineAuthorize` from hooks module
84
- * @param metadata - Service authorization metadata
85
- * @returns The same metadata (identity function)
86
- */
87
- export function defineServiceAuth(metadata) {
88
- return metadata;
89
- }
90
- /**
91
- * Creates a factory function that wraps services with authorization.
92
- *
93
- * **⚠️ DEPRECATED: Use hooks system configured in bootstrap instead!**
94
- *
95
- * @deprecated Configure authorization globally with serviceHooks in bootstrap
96
- * @param ability - The CASL ability to use
97
- * @param metadataMap - Map of service names to their authorization metadata
98
- * @returns Function that wraps services with authorization
99
- */
100
- export function createServiceWrapper(ability, metadataMap) {
101
- return (serviceName, service) => {
102
- const metadata = metadataMap[serviceName];
103
- if (!metadata) {
104
- // No metadata, return unwrapped service
105
- return service;
106
- }
107
- return withAuthorization(service, { ability, metadata });
108
- };
109
- }
110
- //# sourceMappingURL=service-proxy.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"service-proxy.js","sourceRoot":"","sources":["../../src/authorization/service-proxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAGxD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAM,UAAU,iBAAiB,CAC/B,OAAU,EACV,OAAiC;IAEjC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC;IAEtD,OAAO,IAAI,KAAK,CAAC,OAAO,EAAE;QACxB,GAAG,CAAC,MAAM,EAAE,IAAqB;YAC/B,gCAAgC;YAChC,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC7B,OAAO,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;YACnC,CAAC;YAED,MAAM,cAAc,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;YAEjD,uCAAuC;YACvC,IAAI,OAAO,cAAc,KAAK,UAAU,EAAE,CAAC;gBACzC,OAAO,cAAc,CAAC;YACxB,CAAC;YAED,kDAAkD;YAClD,MAAM,QAAQ,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;YAEhC,4DAA4D;YAC5D,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACd,OAAO,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACrC,CAAC;YAED,2CAA2C;YAC3C,OAAO,UAAyB,GAAG,IAAe;gBAChD,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,GAAG,QAAQ,CAAC;gBAE9D,yCAAyC;gBACzC,MAAM,WAAW,GAAG,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;gBAEjE,iCAAiC;gBACjC,IAAI,CAAC;oBACH,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,cAAc,CACzC,MAAM,EACN,OAAO,CAAC,WAAW,EAAE,WAAW,IAAI,EAAE,CAAC,CACxC,CAAC;gBACJ,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,IAAI,cAAc,EAAE,CAAC;wBACnB,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;wBAC3B,MAAM,KAAK,CAAC,CAAC,mCAAmC;oBAClD,CAAC;oBACD,MAAM,KAAK,CAAC;gBACd,CAAC;gBAED,iDAAiD;gBACjD,OAAO,cAAc,CAAC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;YAC5C,CAAC,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,iBAAiB,CAAC,QAA6B;IAC7D,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,oBAAoB,CAClC,OAAU,EACV,WAAgD;IAEhD,OAAO,CAAmB,WAAmB,EAAE,OAAU,EAAK,EAAE;QAC9D,MAAM,QAAQ,GAAG,WAAW,CAAC,WAAW,CAAC,CAAC;QAE1C,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,wCAAwC;YACxC,OAAO,OAAO,CAAC;QACjB,CAAC;QAED,OAAO,iBAAiB,CAAC,OAAO,EAAE,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;IAC3D,CAAC,CAAC;AACJ,CAAC"}
@@ -1,58 +0,0 @@
1
- /**
2
- * Authorization types for CASL integration.
3
- *
4
- * This file contains core types for ability configuration and middleware.
5
- */
6
- import type { PureAbility } from '@casl/ability';
7
- import type { Context } from 'hono';
8
- /**
9
- * Base CASL ability type that applications can extend.
10
- * This type is re-exported from @casl/ability to maintain transparency.
11
- *
12
- * @example
13
- * ```typescript
14
- * import { createPrismaAbility } from '@casl/prisma';
15
- * import { AbilityBuilder } from '@casl/ability';
16
- *
17
- * type AppAbility = PureAbility<[Action, Subject]>;
18
- *
19
- * function defineAbility() {
20
- * const { can, build } = new AbilityBuilder<AppAbility>(createPrismaAbility);
21
- * can('read', 'User');
22
- * return build();
23
- * }
24
- * ```
25
- */
26
- export type BaseAbility = PureAbility<[string, string | object]>;
27
- /**
28
- * Factory function that creates an ability based on user context.
29
- * This function receives the full Hono context, allowing access to
30
- * user data, request information, etc.
31
- *
32
- * @example
33
- * ```typescript
34
- * const abilityFactory: AbilityFactory<AppAbility> = (c) => {
35
- * const user = c.get('user');
36
- * if (user.role === 'admin') {
37
- * return new AdminAbility();
38
- * }
39
- * return new UserAbility(user);
40
- * };
41
- * ```
42
- */
43
- export type AbilityFactory<T extends BaseAbility = BaseAbility> = (context: Context) => T | Promise<T>;
44
- /**
45
- * Configuration for ability-based authorization in routes.
46
- */
47
- export interface AbilityConfig<T extends BaseAbility = BaseAbility> {
48
- /**
49
- * Factory function to create the ability from request context.
50
- */
51
- factory: AbilityFactory<T>;
52
- /**
53
- * Optional key to store the ability in context variables.
54
- * @default 'ability'
55
- */
56
- contextKey?: string;
57
- }
58
- //# sourceMappingURL=types.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/authorization/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAEpC;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,MAAM,WAAW,GAAG,WAAW,CAAC,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC;AAEjE;;;;;;;;;;;;;;;GAeG;AACH,MAAM,MAAM,cAAc,CAAC,CAAC,SAAS,WAAW,GAAG,WAAW,IAAI,CAChE,OAAO,EAAE,OAAO,KACb,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAEpB;;GAEG;AACH,MAAM,WAAW,aAAa,CAAC,CAAC,SAAS,WAAW,GAAG,WAAW;IAChE;;OAEG;IACH,OAAO,EAAE,cAAc,CAAC,CAAC,CAAC,CAAC;IAE3B;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB"}
@@ -1,7 +0,0 @@
1
- /**
2
- * Authorization types for CASL integration.
3
- *
4
- * This file contains core types for ability configuration and middleware.
5
- */
6
- export {};
7
- //# sourceMappingURL=types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/authorization/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG"}
@@ -1,100 +0,0 @@
1
- import type { ServiceHook } from './types.js';
2
- /**
3
- * Authorization metadata for a service method.
4
- * Defines what CASL action/subject to check before the method executes.
5
- */
6
- export interface AuthorizationMetadata {
7
- /**
8
- * CASL action (e.g., 'create', 'read', 'update', 'delete')
9
- */
10
- action: string;
11
- /**
12
- * CASL subject type (e.g., 'User', 'Post', 'Session')
13
- */
14
- subject: string;
15
- /**
16
- * Optional function to extract subject data from method arguments.
17
- * Used for field-level and instance-level authorization.
18
- *
19
- * @param args - The arguments passed to the service method
20
- * @returns The subject data to check against CASL rules
21
- *
22
- * @example
23
- * ```typescript
24
- * getSubjectData: (userId, updates) => ({ id: userId, ...updates })
25
- * ```
26
- */
27
- getSubjectData?: (...args: unknown[]) => object | undefined;
28
- }
29
- /**
30
- * Service hook that performs CASL authorization before method execution.
31
- *
32
- * This hook checks for `authorize` metadata on service methods and calls
33
- * the CASL `authorize()` function before allowing the method to execute.
34
- *
35
- * **Usage:**
36
- * 1. Define authorization metadata for your service methods
37
- * 2. Include this hook when wrapping services
38
- * 3. Ensure ability middleware is configured in your routes
39
- *
40
- * @example
41
- * ```typescript
42
- * import { authorizationHook, defineServiceMetadata } from 'glasswork';
43
- *
44
- * // Define metadata
45
- * export const authServiceMetadata = defineServiceMetadata({
46
- * deleteSession: {
47
- * authorize: {
48
- * action: 'delete',
49
- * subject: 'Session'
50
- * }
51
- * },
52
- * updateUser: {
53
- * authorize: {
54
- * action: 'update',
55
- * subject: 'User',
56
- * getSubjectData: (userId, data) => ({ id: userId, ...data })
57
- * }
58
- * }
59
- * });
60
- *
61
- * // Use in routes
62
- * router.delete('/session', async (c) => {
63
- * const services = withServiceHooks(
64
- * { authService },
65
- * {
66
- * hooks: [authorizationHook],
67
- * metadata: authServiceMetadata
68
- * },
69
- * c
70
- * );
71
- *
72
- * // This automatically checks authorization before executing
73
- * await services.authService.deleteSession(token);
74
- * });
75
- * ```
76
- */
77
- export declare const authorizationHook: ServiceHook;
78
- /**
79
- * Helper to define authorization metadata for service methods.
80
- * Provides better type inference for the authorize property.
81
- *
82
- * @param action - CASL action
83
- * @param subject - CASL subject type
84
- * @param getSubjectData - Optional function to extract subject data
85
- * @returns Authorization metadata object
86
- *
87
- * @example
88
- * ```typescript
89
- * export const userServiceMetadata = defineServiceMetadata({
90
- * update: {
91
- * authorize: defineAuthorize('update', 'User', (id, data) => ({ id, ...data }))
92
- * },
93
- * delete: {
94
- * authorize: defineAuthorize('delete', 'User', (id) => ({ id }))
95
- * }
96
- * });
97
- * ```
98
- */
99
- export declare function defineAuthorize(action: string, subject: string, getSubjectData?: (...args: unknown[]) => object | undefined): AuthorizationMetadata;
100
- //# sourceMappingURL=authorization-hook.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"authorization-hook.d.ts","sourceRoot":"","sources":["../../src/hooks/authorization-hook.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C;;;GAGG;AACH,MAAM,WAAW,qBAAqB;IACpC;;OAEG;IACH,MAAM,EAAE,MAAM,CAAC;IAEf;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;;;;;;;;;;OAWG;IACH,cAAc,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,MAAM,GAAG,SAAS,CAAC;CAC7D;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,eAAO,MAAM,iBAAiB,EAAE,WAkB/B,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,EACf,cAAc,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,MAAM,GAAG,SAAS,GAC1D,qBAAqB,CAMvB"}
@@ -1,93 +0,0 @@
1
- import { authorize } from '../authorization/route-helpers.js';
2
- /**
3
- * Service hook that performs CASL authorization before method execution.
4
- *
5
- * This hook checks for `authorize` metadata on service methods and calls
6
- * the CASL `authorize()` function before allowing the method to execute.
7
- *
8
- * **Usage:**
9
- * 1. Define authorization metadata for your service methods
10
- * 2. Include this hook when wrapping services
11
- * 3. Ensure ability middleware is configured in your routes
12
- *
13
- * @example
14
- * ```typescript
15
- * import { authorizationHook, defineServiceMetadata } from 'glasswork';
16
- *
17
- * // Define metadata
18
- * export const authServiceMetadata = defineServiceMetadata({
19
- * deleteSession: {
20
- * authorize: {
21
- * action: 'delete',
22
- * subject: 'Session'
23
- * }
24
- * },
25
- * updateUser: {
26
- * authorize: {
27
- * action: 'update',
28
- * subject: 'User',
29
- * getSubjectData: (userId, data) => ({ id: userId, ...data })
30
- * }
31
- * }
32
- * });
33
- *
34
- * // Use in routes
35
- * router.delete('/session', async (c) => {
36
- * const services = withServiceHooks(
37
- * { authService },
38
- * {
39
- * hooks: [authorizationHook],
40
- * metadata: authServiceMetadata
41
- * },
42
- * c
43
- * );
44
- *
45
- * // This automatically checks authorization before executing
46
- * await services.authService.deleteSession(token);
47
- * });
48
- * ```
49
- */
50
- export const authorizationHook = {
51
- before: async (context, args) => {
52
- // Check if this method has authorization metadata
53
- const metadata = context.metadata;
54
- if (!metadata?.authorize) {
55
- // No authorization required for this method
56
- return;
57
- }
58
- const { action, subject, getSubjectData } = metadata.authorize;
59
- // Extract subject data if function provided
60
- const subjectData = getSubjectData ? getSubjectData(...args) : undefined;
61
- // Call CASL authorize - this will throw ForbiddenError if not allowed
62
- authorize(context.honoContext, action, subject, subjectData);
63
- },
64
- };
65
- /**
66
- * Helper to define authorization metadata for service methods.
67
- * Provides better type inference for the authorize property.
68
- *
69
- * @param action - CASL action
70
- * @param subject - CASL subject type
71
- * @param getSubjectData - Optional function to extract subject data
72
- * @returns Authorization metadata object
73
- *
74
- * @example
75
- * ```typescript
76
- * export const userServiceMetadata = defineServiceMetadata({
77
- * update: {
78
- * authorize: defineAuthorize('update', 'User', (id, data) => ({ id, ...data }))
79
- * },
80
- * delete: {
81
- * authorize: defineAuthorize('delete', 'User', (id) => ({ id }))
82
- * }
83
- * });
84
- * ```
85
- */
86
- export function defineAuthorize(action, subject, getSubjectData) {
87
- return {
88
- action,
89
- subject,
90
- getSubjectData,
91
- };
92
- }
93
- //# sourceMappingURL=authorization-hook.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"authorization-hook.js","sourceRoot":"","sources":["../../src/hooks/authorization-hook.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,mCAAmC,CAAC;AAiC9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAgB;IAC5C,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE;QAC9B,kDAAkD;QAClD,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAiD,CAAC;QAE3E,IAAI,CAAC,QAAQ,EAAE,SAAS,EAAE,CAAC;YACzB,4CAA4C;YAC5C,OAAO;QACT,CAAC;QAED,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,QAAQ,CAAC,SAAS,CAAC;QAE/D,4CAA4C;QAC5C,MAAM,WAAW,GAAG,cAAc,CAAC,CAAC,CAAC,cAAc,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAEzE,sEAAsE;QACtE,SAAS,CAAC,OAAO,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,CAAC,CAAC;IAC/D,CAAC;CACF,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,eAAe,CAC7B,MAAc,EACd,OAAe,EACf,cAA2D;IAE3D,OAAO;QACL,MAAM;QACN,OAAO;QACP,cAAc;KACf,CAAC;AACJ,CAAC"}
@@ -1,54 +0,0 @@
1
- /**
2
- * Service hooks system for wrapping service method calls with before/after/error hooks.
3
- *
4
- * This module provides a flexible hook system that can be used for:
5
- * - Authorization (using CASL)
6
- * - Audit logging
7
- * - Metrics and tracing
8
- * - Error handling
9
- * - Retry logic
10
- * - Timeouts
11
- * - Response transformation
12
- *
13
- * Hooks are transparent - they wrap service methods without modifying the service
14
- * implementation, keeping business logic clean and framework-agnostic.
15
- *
16
- * @module hooks
17
- *
18
- * @example Basic Usage
19
- * ```typescript
20
- * import { authorizationHook, defineServiceMetadata } from 'glasswork';
21
- *
22
- * // Define metadata for service methods
23
- * export const authServiceMetadata = defineServiceMetadata({
24
- * deleteSession: {
25
- * authorize: {
26
- * action: 'delete',
27
- * subject: 'Session'
28
- * }
29
- * }
30
- * });
31
- *
32
- * // Configure hooks globally in bootstrap
33
- * bootstrap({
34
- * serviceHooks: [authorizationHook],
35
- * serviceMetadata: {
36
- * authService: authServiceMetadata
37
- * }
38
- * });
39
- *
40
- * // In routes, service calls are automatically wrapped
41
- * export const authRoutes = createRoutes((router, { authService }) => {
42
- * router.delete('/session', ...route({
43
- * handler: async ({ context }) => {
44
- * // This automatically checks authorization before executing!
45
- * await authService.deleteSession(token);
46
- * }
47
- * }));
48
- * });
49
- * ```
50
- */
51
- export { type AuthorizationMetadata, authorizationHook, defineAuthorize, } from './authorization-hook.js';
52
- export { defineServiceMetadata, withServiceHooks, withServiceHooksMany, } from './service-hooks.js';
53
- export type { ServiceAfterHook, ServiceBeforeHook, ServiceErrorHook, ServiceHook, ServiceHookContext, ServiceHooksConfig, ServiceMethodMetadata, ServicesRegistry, } from './types.js';
54
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/hooks/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AAGH,OAAO,EACL,KAAK,qBAAqB,EAC1B,iBAAiB,EACjB,eAAe,GAChB,MAAM,yBAAyB,CAAC;AAGjC,OAAO,EACL,qBAAqB,EACrB,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,oBAAoB,CAAC;AAE5B,YAAY,EACV,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,WAAW,EACX,kBAAkB,EAClB,kBAAkB,EAClB,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,YAAY,CAAC"}
@@ -1,55 +0,0 @@
1
- /**
2
- * Service hooks system for wrapping service method calls with before/after/error hooks.
3
- *
4
- * This module provides a flexible hook system that can be used for:
5
- * - Authorization (using CASL)
6
- * - Audit logging
7
- * - Metrics and tracing
8
- * - Error handling
9
- * - Retry logic
10
- * - Timeouts
11
- * - Response transformation
12
- *
13
- * Hooks are transparent - they wrap service methods without modifying the service
14
- * implementation, keeping business logic clean and framework-agnostic.
15
- *
16
- * @module hooks
17
- *
18
- * @example Basic Usage
19
- * ```typescript
20
- * import { authorizationHook, defineServiceMetadata } from 'glasswork';
21
- *
22
- * // Define metadata for service methods
23
- * export const authServiceMetadata = defineServiceMetadata({
24
- * deleteSession: {
25
- * authorize: {
26
- * action: 'delete',
27
- * subject: 'Session'
28
- * }
29
- * }
30
- * });
31
- *
32
- * // Configure hooks globally in bootstrap
33
- * bootstrap({
34
- * serviceHooks: [authorizationHook],
35
- * serviceMetadata: {
36
- * authService: authServiceMetadata
37
- * }
38
- * });
39
- *
40
- * // In routes, service calls are automatically wrapped
41
- * export const authRoutes = createRoutes((router, { authService }) => {
42
- * router.delete('/session', ...route({
43
- * handler: async ({ context }) => {
44
- * // This automatically checks authorization before executing!
45
- * await authService.deleteSession(token);
46
- * }
47
- * }));
48
- * });
49
- * ```
50
- */
51
- // Built-in hooks
52
- export { authorizationHook, defineAuthorize, } from './authorization-hook.js';
53
- // Hook system
54
- export { defineServiceMetadata, withServiceHooks, withServiceHooksMany, } from './service-hooks.js';
55
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/hooks/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AAEH,iBAAiB;AACjB,OAAO,EAEL,iBAAiB,EACjB,eAAe,GAChB,MAAM,yBAAyB,CAAC;AAEjC,cAAc;AACd,OAAO,EACL,qBAAqB,EACrB,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,oBAAoB,CAAC"}
@@ -1,82 +0,0 @@
1
- import type { Context } from 'hono';
2
- import type { ServiceHooksConfig, ServiceMethodMetadata } from './types.js';
3
- /**
4
- * Wraps a service with hooks that run before/after/on-error for method calls.
5
- * This creates a transparent proxy that intercepts method calls and runs hooks
6
- * while preserving all service functionality.
7
- *
8
- * **Note:** Hooks only run for method calls, not property access.
9
- *
10
- * @param service - The service instance to wrap
11
- * @param config - Hook configuration
12
- * @param honoContext - The current Hono request context
13
- * @returns Proxied service with hooks
14
- *
15
- * @example
16
- * ```typescript
17
- * const authHook: ServiceHook = {
18
- * before: async (context) => {
19
- * if (context.metadata?.authorize) {
20
- * authorize(context.honoContext, ...);
21
- * }
22
- * }
23
- * };
24
- *
25
- * const wrappedService = withServiceHooks(authService, {
26
- * hooks: [authHook],
27
- * metadata: {
28
- * deleteSession: {
29
- * authorize: { action: 'delete', subject: 'Session' }
30
- * }
31
- * }
32
- * }, honoContext);
33
- *
34
- * // Hooks automatically run when calling methods
35
- * await wrappedService.deleteSession(token);
36
- * ```
37
- */
38
- export declare function withServiceHooks<T extends object>(service: T, config: ServiceHooksConfig, honoContext: Context): T;
39
- /**
40
- * Wraps multiple services with the same hooks configuration.
41
- * Useful when you want to apply the same hooks to all services in a container.
42
- *
43
- * @param services - Object containing service instances
44
- * @param config - Hook configuration (can be a function for per-service config)
45
- * @param honoContext - The current Hono request context
46
- * @returns Object with all services wrapped with hooks
47
- *
48
- * @example
49
- * ```typescript
50
- * const wrappedServices = withServiceHooksMany(
51
- * { authService, userService },
52
- * (serviceName) => ({
53
- * hooks: [authHook, auditHook],
54
- * metadata: serviceMetadataRegistry[serviceName],
55
- * serviceName,
56
- * }),
57
- * honoContext
58
- * );
59
- * ```
60
- */
61
- export declare function withServiceHooksMany<T extends Record<string, object>>(services: T, config: ServiceHooksConfig | ((serviceName: string, service: unknown) => ServiceHooksConfig), honoContext: Context): T;
62
- /**
63
- * Helper to define service method metadata with better type inference.
64
- * This is just an identity function that helps TypeScript understand the structure.
65
- *
66
- * @param metadata - Service method metadata mapping
67
- * @returns The same metadata (identity function)
68
- *
69
- * @example
70
- * ```typescript
71
- * export const authServiceMetadata = defineServiceMetadata({
72
- * deleteSession: {
73
- * authorize: { action: 'delete', subject: 'Session' }
74
- * },
75
- * findById: {
76
- * authorize: { action: 'read', subject: 'User' }
77
- * }
78
- * });
79
- * ```
80
- */
81
- export declare function defineServiceMetadata(metadata: Record<string, ServiceMethodMetadata>): Record<string, ServiceMethodMetadata>;
82
- //# sourceMappingURL=service-hooks.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"service-hooks.d.ts","sourceRoot":"","sources":["../../src/hooks/service-hooks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAGV,kBAAkB,EAClB,qBAAqB,EACtB,MAAM,YAAY,CAAC;AAkDpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,MAAM,EAC/C,OAAO,EAAE,CAAC,EACV,MAAM,EAAE,kBAAkB,EAC1B,WAAW,EAAE,OAAO,GACnB,CAAC,CAqCH;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EACnE,QAAQ,EAAE,CAAC,EACX,MAAM,EAAE,kBAAkB,GAAG,CAAC,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,KAAK,kBAAkB,CAAC,EAC5F,WAAW,EAAE,OAAO,GACnB,CAAC,CAcH;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,qBAAqB,CACnC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,qBAAqB,CAAC,GAC9C,MAAM,CAAC,MAAM,EAAE,qBAAqB,CAAC,CAEvC"}