@hazeljs/auth 0.2.0-alpha.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 (39) hide show
  1. package/LICENSE +192 -0
  2. package/README.md +499 -0
  3. package/dist/auth.guard.d.ts +15 -0
  4. package/dist/auth.guard.d.ts.map +1 -0
  5. package/dist/auth.guard.js +96 -0
  6. package/dist/auth.service.d.ts +13 -0
  7. package/dist/auth.service.d.ts.map +1 -0
  8. package/dist/auth.service.js +38 -0
  9. package/dist/auth.test.d.ts +2 -0
  10. package/dist/auth.test.d.ts.map +1 -0
  11. package/dist/auth.test.js +682 -0
  12. package/dist/decorators/current-user.decorator.d.ts +26 -0
  13. package/dist/decorators/current-user.decorator.d.ts.map +1 -0
  14. package/dist/decorators/current-user.decorator.js +39 -0
  15. package/dist/guards/jwt-auth.guard.d.ts +24 -0
  16. package/dist/guards/jwt-auth.guard.d.ts.map +1 -0
  17. package/dist/guards/jwt-auth.guard.js +61 -0
  18. package/dist/guards/role.guard.d.ts +36 -0
  19. package/dist/guards/role.guard.d.ts.map +1 -0
  20. package/dist/guards/role.guard.js +66 -0
  21. package/dist/guards/tenant.guard.d.ts +54 -0
  22. package/dist/guards/tenant.guard.d.ts.map +1 -0
  23. package/dist/guards/tenant.guard.js +96 -0
  24. package/dist/index.d.ts +18 -0
  25. package/dist/index.d.ts.map +1 -0
  26. package/dist/index.js +28 -0
  27. package/dist/jwt/jwt.module.d.ts +5 -0
  28. package/dist/jwt/jwt.module.d.ts.map +1 -0
  29. package/dist/jwt/jwt.module.js +27 -0
  30. package/dist/jwt/jwt.service.d.ts +25 -0
  31. package/dist/jwt/jwt.service.d.ts.map +1 -0
  32. package/dist/jwt/jwt.service.js +61 -0
  33. package/dist/tenant/tenant-context.d.ts +81 -0
  34. package/dist/tenant/tenant-context.d.ts.map +1 -0
  35. package/dist/tenant/tenant-context.js +108 -0
  36. package/dist/utils/role-hierarchy.d.ts +42 -0
  37. package/dist/utils/role-hierarchy.d.ts.map +1 -0
  38. package/dist/utils/role-hierarchy.js +57 -0
  39. package/package.json +55 -0
package/LICENSE ADDED
@@ -0,0 +1,192 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Copyright 2024 HazelJS Team
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
18
+
19
+ ---
20
+
21
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
22
+
23
+ 1. Definitions.
24
+
25
+ "License" shall mean the terms and conditions for use, reproduction,
26
+ and distribution as defined by Sections 1 through 9 of this document.
27
+
28
+ "Licensor" shall mean the copyright owner or entity authorized by
29
+ the copyright owner that is granting the License.
30
+
31
+ "Legal Entity" shall mean the union of the acting entity and all
32
+ other entities that control, are controlled by, or are under common
33
+ control with that entity. For the purposes of this definition,
34
+ "control" means (i) the power, direct or indirect, to cause the
35
+ direction or management of such entity, whether by contract or
36
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
37
+ outstanding shares, or (iii) beneficial ownership of such entity.
38
+
39
+ "You" (or "Your") shall mean an individual or Legal Entity
40
+ exercising permissions granted by this License.
41
+
42
+ "Source" form shall mean the preferred form for making modifications,
43
+ including but not limited to software source code, documentation
44
+ source, and configuration files.
45
+
46
+ "Object" form shall mean any form resulting from mechanical
47
+ transformation or translation of a Source form, including but
48
+ not limited to compiled object code, generated documentation,
49
+ and conversions to other media types.
50
+
51
+ "Work" shall mean the work of authorship, whether in Source or
52
+ Object form, made available under the License, as indicated by a
53
+ copyright notice that is included in or attached to the work
54
+ (an example is provided in the Appendix below).
55
+
56
+ "Derivative Works" shall mean any work, whether in Source or Object
57
+ form, that is based on (or derived from) the Work and for which the
58
+ editorial revisions, annotations, elaborations, or other modifications
59
+ represent, as a whole, an original work of authorship. For the purposes
60
+ of this License, Derivative Works shall not include works that remain
61
+ separable from, or merely link (or bind by name) to the interfaces of,
62
+ the Work and Derivative Works thereof.
63
+
64
+ "Contribution" shall mean any work of authorship, including
65
+ the original version of the Work and any modifications or additions
66
+ to that Work or Derivative Works thereof, that is intentionally
67
+ submitted to Licensor for inclusion in the Work by the copyright owner
68
+ or by an individual or Legal Entity authorized to submit on behalf of
69
+ the copyright owner. For the purposes of this definition, "submitted"
70
+ means any form of electronic, verbal, or written communication sent
71
+ to the Licensor or its representatives, including but not limited to
72
+ communication on electronic mailing lists, source code control systems,
73
+ and issue tracking systems that are managed by, or on behalf of, the
74
+ Licensor for the purpose of discussing and improving the Work, but
75
+ excluding communication that is conspicuously marked or otherwise
76
+ designated in writing by the copyright owner as "Not a Contribution."
77
+
78
+ "Contributor" shall mean Licensor and any individual or Legal Entity
79
+ on behalf of whom a Contribution has been received by Licensor and
80
+ subsequently incorporated within the Work.
81
+
82
+ 2. Grant of Copyright License. Subject to the terms and conditions of
83
+ this License, each Contributor hereby grants to You a perpetual,
84
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
85
+ copyright license to reproduce, prepare Derivative Works of,
86
+ publicly display, publicly perform, sublicense, and distribute the
87
+ Work and such Derivative Works in Source or Object form.
88
+
89
+ 3. Grant of Patent License. Subject to the terms and conditions of
90
+ this License, each Contributor hereby grants to You a perpetual,
91
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
92
+ (except as stated in this section) patent license to make, have made,
93
+ use, offer to sell, sell, import, and otherwise transfer the Work,
94
+ where such license applies only to those patent claims licensable
95
+ by such Contributor that are necessarily infringed by their
96
+ Contribution(s) alone or by combination of their Contribution(s)
97
+ with the Work to which such Contribution(s) was submitted. If You
98
+ institute patent litigation against any entity (including a
99
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
100
+ or a Contribution incorporated within the Work constitutes direct
101
+ or contributory patent infringement, then any patent licenses
102
+ granted to You under this License for that Work shall terminate
103
+ as of the date such litigation is filed.
104
+
105
+ 4. Redistribution. You may reproduce and distribute copies of the
106
+ Work or Derivative Works thereof in any medium, with or without
107
+ modifications, and in Source or Object form, provided that You
108
+ meet the following conditions:
109
+
110
+ (a) You must give any other recipients of the Work or
111
+ Derivative Works a copy of this License; and
112
+
113
+ (b) You must cause any modified files to carry prominent notices
114
+ stating that You changed the files; and
115
+
116
+ (c) You must retain, in the Source form of any Derivative Works
117
+ that You distribute, all copyright, patent, trademark, and
118
+ attribution notices from the Source form of the Work,
119
+ excluding those notices that do not pertain to any part of
120
+ the Derivative Works; and
121
+
122
+ (d) If the Work includes a "NOTICE" text file as part of its
123
+ distribution, then any Derivative Works that You distribute must
124
+ include a readable copy of the attribution notices contained
125
+ within such NOTICE file, excluding those notices that do not
126
+ pertain to any part of the Derivative Works, in at least one
127
+ of the following places: within a NOTICE text file distributed
128
+ as part of the Derivative Works; within the Source form or
129
+ documentation, if provided along with the Derivative Works; or,
130
+ within a display generated by the Derivative Works, if and
131
+ wherever such third-party notices normally appear. The contents
132
+ of the NOTICE file are for informational purposes only and
133
+ do not modify the License. You may add Your own attribution
134
+ notices within Derivative Works that You distribute, alongside
135
+ or as an addendum to the NOTICE text from the Work, provided
136
+ that such additional attribution notices cannot be construed
137
+ as modifying the License.
138
+
139
+ You may add Your own copyright statement to Your modifications and
140
+ may provide additional or different license terms and conditions
141
+ for use, reproduction, or distribution of Your modifications, or
142
+ for any such Derivative Works as a whole, provided Your use,
143
+ reproduction, and distribution of the Work otherwise complies with
144
+ the conditions stated in this License.
145
+
146
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
147
+ any Contribution intentionally submitted for inclusion in the Work
148
+ by You to the Licensor shall be under the terms and conditions of
149
+ this License, without any additional terms or conditions.
150
+ Notwithstanding the above, nothing herein shall supersede or modify
151
+ the terms of any separate license agreement you may have executed
152
+ with Licensor regarding such Contributions.
153
+
154
+ 6. Trademarks. This License does not grant permission to use the trade
155
+ names, trademarks, service marks, or product names of the Licensor,
156
+ except as required for reasonable and customary use in describing the
157
+ origin of the Work and reproducing the content of the NOTICE file.
158
+
159
+ 7. Disclaimer of Warranty. Unless required by applicable law or
160
+ agreed to in writing, Licensor provides the Work (and each
161
+ Contributor provides its Contributions) on an "AS IS" BASIS,
162
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
163
+ implied, including, without limitation, any warranties or conditions
164
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
165
+ PARTICULAR PURPOSE. You are solely responsible for determining the
166
+ appropriateness of using or redistributing the Work and assume any
167
+ risks associated with Your exercise of permissions under this License.
168
+
169
+ 8. Limitation of Liability. In no event and under no legal theory,
170
+ whether in tort (including negligence), contract, or otherwise,
171
+ unless required by applicable law (such as deliberate and grossly
172
+ negligent acts) or agreed to in writing, shall any Contributor be
173
+ liable to You for damages, including any direct, indirect, special,
174
+ incidental, or consequential damages of any character arising as a
175
+ result of this License or out of the use or inability to use the
176
+ Work (including but not limited to damages for loss of goodwill,
177
+ work stoppage, computer failure or malfunction, or any and all
178
+ other commercial damages or losses), even if such Contributor
179
+ has been advised of the possibility of such damages.
180
+
181
+ 9. Accepting Warranty or Additional Liability. While redistributing
182
+ the Work or Derivative Works thereof, You may choose to offer,
183
+ and charge a fee for, acceptance of support, warranty, indemnity,
184
+ or other liability obligations and/or rights consistent with this
185
+ License. However, in accepting such obligations, You may act only
186
+ on Your own behalf and on Your sole responsibility, not on behalf
187
+ of any other Contributor, and only if You agree to indemnify,
188
+ defend, and hold each Contributor harmless for any liability
189
+ incurred by, or claims asserted against, such Contributor by reason
190
+ of your accepting any such warranty or additional liability.
191
+
192
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,499 @@
1
+ # @hazeljs/auth
2
+
3
+ **JWT authentication, role-based access control, and tenant isolation — in one line of decorators.**
4
+
5
+ No Passport config, no middleware soup. `@UseGuards(JwtAuthGuard)` on a controller and you're done.
6
+
7
+ [![npm version](https://img.shields.io/npm/v/@hazeljs/auth.svg)](https://www.npmjs.com/package/@hazeljs/auth)
8
+ [![npm downloads](https://img.shields.io/npm/dm/@hazeljs/auth)](https://www.npmjs.com/package/@hazeljs/auth)
9
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
10
+
11
+ ## Features
12
+
13
+ - **JWT signing & verification** via `JwtService` (backed by `jsonwebtoken`)
14
+ - **`JwtAuthGuard`** — `@UseGuards`-compatible guard that verifies Bearer tokens and attaches `req.user`
15
+ - **`RoleGuard`** — configurable role check with **inherited role hierarchy** (admin satisfies manager checks automatically)
16
+ - **`TenantGuard`** — tenant-level isolation; compares the tenant ID on the JWT against a URL param, header, or query string
17
+ - **`@CurrentUser()`** — parameter decorator that injects the authenticated user into controller methods
18
+ - **`@Auth()`** — all-in-one method decorator for JWT + optional role check without `@UseGuards`
19
+
20
+ ---
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ npm install @hazeljs/auth
26
+ ```
27
+
28
+ ---
29
+
30
+ ## Setup
31
+
32
+ ### 1. Register `JwtModule`
33
+
34
+ Configure the JWT secret once in your root module. Picks up `JWT_SECRET` and `JWT_EXPIRES_IN` env vars automatically when no options are passed.
35
+
36
+ ```typescript
37
+ import { HazelModule } from '@hazeljs/core';
38
+ import { JwtModule } from '@hazeljs/auth';
39
+
40
+ @HazelModule({
41
+ imports: [
42
+ JwtModule.forRoot({
43
+ secret: process.env.JWT_SECRET, // or set JWT_SECRET env var
44
+ expiresIn: '1h', // or set JWT_EXPIRES_IN env var
45
+ issuer: 'my-app', // optional
46
+ audience: 'my-users', // optional
47
+ }),
48
+ ],
49
+ })
50
+ export class AppModule {}
51
+ ```
52
+
53
+ ```env
54
+ JWT_SECRET=change-me-in-production
55
+ JWT_EXPIRES_IN=1h
56
+ ```
57
+
58
+ ### 2. Issue tokens at login
59
+
60
+ ```typescript
61
+ import { Service } from '@hazeljs/core';
62
+ import { JwtService } from '@hazeljs/auth';
63
+
64
+ @Service()
65
+ export class AuthLoginService {
66
+ constructor(private readonly jwt: JwtService) {}
67
+
68
+ async login(userId: string, role: string, tenantId?: string) {
69
+ const token = this.jwt.sign({
70
+ sub: userId,
71
+ role,
72
+ tenantId, // include for TenantGuard
73
+ });
74
+
75
+ return { accessToken: token };
76
+ }
77
+ }
78
+ ```
79
+
80
+ ---
81
+
82
+ ## Guards
83
+
84
+ All guards are resolved from the DI container, so they can inject services.
85
+
86
+ ### `JwtAuthGuard`
87
+
88
+ Verifies the `Authorization: Bearer <token>` header. On success it attaches the decoded payload to `req.user` so downstream guards and `@CurrentUser()` can read it.
89
+
90
+ ```typescript
91
+ import { Controller, Get } from '@hazeljs/core';
92
+ import { UseGuards } from '@hazeljs/core';
93
+ import { JwtAuthGuard, CurrentUser, AuthUser } from '@hazeljs/auth';
94
+
95
+ @UseGuards(JwtAuthGuard) // protects every route in this controller
96
+ @Controller('/profile')
97
+ export class ProfileController {
98
+ @Get('/')
99
+ getProfile(@CurrentUser() user: AuthUser) {
100
+ return user;
101
+ }
102
+ }
103
+ ```
104
+
105
+ Errors thrown:
106
+
107
+ | Condition | Status |
108
+ |---|---|
109
+ | No `Authorization` header | 400 |
110
+ | Header not in `Bearer <token>` format | 400 |
111
+ | Token invalid or expired | 401 |
112
+
113
+ ---
114
+
115
+ ### `RoleGuard`
116
+
117
+ Checks the authenticated user's `role` against a list of allowed roles. Uses the **role hierarchy** so higher roles automatically satisfy lower-level checks.
118
+
119
+ ```typescript
120
+ import { UseGuards } from '@hazeljs/core';
121
+ import { JwtAuthGuard, RoleGuard } from '@hazeljs/auth';
122
+
123
+ @UseGuards(JwtAuthGuard, RoleGuard('manager')) // manager, admin, superadmin can access
124
+ @Controller('/reports')
125
+ export class ReportsController {}
126
+ ```
127
+
128
+ #### Role hierarchy
129
+
130
+ The default hierarchy is `superadmin → admin → manager → user`.
131
+
132
+ ```
133
+ superadmin
134
+ └─ admin
135
+ └─ manager
136
+ └─ user
137
+ ```
138
+
139
+ So `RoleGuard('user')` passes for **every** role, and `RoleGuard('admin')` only passes for `admin` and `superadmin`.
140
+
141
+ ```typescript
142
+ // Only superadmin and admin can call this:
143
+ @UseGuards(JwtAuthGuard, RoleGuard('admin'))
144
+
145
+ // Everyone authenticated can call this:
146
+ @UseGuards(JwtAuthGuard, RoleGuard('user'))
147
+
148
+ // Either role (admin OR moderator, each with their inherited roles):
149
+ @UseGuards(JwtAuthGuard, RoleGuard('admin', 'moderator'))
150
+ ```
151
+
152
+ #### Custom hierarchy
153
+
154
+ ```typescript
155
+ import { RoleGuard, RoleHierarchy } from '@hazeljs/auth';
156
+
157
+ const hierarchy = new RoleHierarchy({
158
+ owner: ['editor'],
159
+ editor: ['viewer'],
160
+ viewer: [],
161
+ });
162
+
163
+ @UseGuards(JwtAuthGuard, RoleGuard('editor', { hierarchy }))
164
+ // owner and editor pass; viewer does not
165
+ ```
166
+
167
+ #### Disable hierarchy
168
+
169
+ ```typescript
170
+ @UseGuards(JwtAuthGuard, RoleGuard('admin', { hierarchy: {} }))
171
+ // Only exact 'admin' role passes — no inheritance
172
+ ```
173
+
174
+ Errors thrown:
175
+
176
+ | Condition | Status |
177
+ |---|---|
178
+ | No `req.user` (guard order wrong) | 401 |
179
+ | User role not in allowed set | 403 |
180
+
181
+ ---
182
+
183
+ ### `TenantGuard`
184
+
185
+ Enforces tenant-level isolation. Compares `req.user.tenantId` (from the JWT) against the tenant ID found in the request.
186
+
187
+ **Requires `JwtAuthGuard` to run first** so `req.user` is populated.
188
+
189
+ #### URL param (default)
190
+
191
+ ```typescript
192
+ import { JwtAuthGuard, TenantGuard } from '@hazeljs/auth';
193
+
194
+ // Route: GET /orgs/:tenantId/invoices
195
+ @UseGuards(JwtAuthGuard, TenantGuard())
196
+ @Controller('/orgs/:tenantId/invoices')
197
+ export class InvoicesController {}
198
+ ```
199
+
200
+ #### HTTP header
201
+
202
+ ```typescript
203
+ // Client sends: X-Org-ID: acme
204
+ @UseGuards(JwtAuthGuard, TenantGuard({ source: 'header', key: 'x-org-id' }))
205
+ @Controller('/invoices')
206
+ export class InvoicesController {}
207
+ ```
208
+
209
+ #### Query string
210
+
211
+ ```typescript
212
+ // Client sends: GET /invoices?org=acme
213
+ @UseGuards(JwtAuthGuard, TenantGuard({ source: 'query', key: 'org' }))
214
+ @Controller('/invoices')
215
+ export class InvoicesController {}
216
+ ```
217
+
218
+ #### Bypass for privileged roles
219
+
220
+ Superadmins often need to manage any tenant. Use `bypassRoles` to skip the check for them:
221
+
222
+ ```typescript
223
+ @UseGuards(
224
+ JwtAuthGuard,
225
+ TenantGuard({ bypassRoles: ['superadmin'] })
226
+ )
227
+ @Controller('/orgs/:tenantId/settings')
228
+ export class OrgSettingsController {}
229
+ ```
230
+
231
+ #### Custom user field
232
+
233
+ ```typescript
234
+ // JWT payload uses 'orgId' instead of 'tenantId'
235
+ @UseGuards(JwtAuthGuard, TenantGuard({ userField: 'orgId' }))
236
+ ```
237
+
238
+ All options:
239
+
240
+ | Option | Type | Default | Description |
241
+ |---|---|---|---|
242
+ | `source` | `'param' \| 'header' \| 'query'` | `'param'` | Where to read the tenant ID from the request |
243
+ | `key` | `string` | `'tenantId'` | Param name / header name / query key |
244
+ | `userField` | `string` | `'tenantId'` | Field on `req.user` holding the user's tenant |
245
+ | `bypassRoles` | `string[]` | `[]` | Roles that skip the check entirely |
246
+
247
+ Errors thrown:
248
+
249
+ | Condition | Status |
250
+ |---|---|
251
+ | No `req.user` | 401 |
252
+ | `req.user` has no tenant field | 403 |
253
+ | Tenant ID absent from request | 400 |
254
+ | Tenant IDs do not match | 403 |
255
+
256
+ ---
257
+
258
+ ### Database-level tenant isolation
259
+
260
+ `TenantGuard` blocks cross-tenant HTTP requests, but that alone isn't enough — a bug in service code could still return another tenant's rows. `TenantContext` closes that gap by enforcing isolation at the **query level** using Node.js `AsyncLocalStorage`.
261
+
262
+ After `TenantGuard` validates the request it calls `TenantContext.enterWith(tenantId)`, which seeds the tenant ID into the current async execution chain. Every service and repository downstream can then call `tenantCtx.requireId()` to get the current tenant without it being passed through every function signature.
263
+
264
+ ```typescript
265
+ // src/orders/orders.repository.ts
266
+ import { Service } from '@hazeljs/core';
267
+ import { TenantContext } from '@hazeljs/auth';
268
+
269
+ @Service()
270
+ export class OrdersRepository {
271
+ constructor(private readonly tenantCtx: TenantContext) {}
272
+
273
+ findAll() {
274
+ const tenantId = this.tenantCtx.requireId();
275
+ // Scoped automatically — no tenantId parameter needed
276
+ return db.query('SELECT * FROM orders WHERE tenant_id = $1', [tenantId]);
277
+ }
278
+
279
+ findById(id: string) {
280
+ const tenantId = this.tenantCtx.requireId();
281
+ // Even direct ID lookup is tenant-scoped — prevents IDOR attacks
282
+ return db.query(
283
+ 'SELECT * FROM orders WHERE id = $1 AND tenant_id = $2',
284
+ [id, tenantId]
285
+ );
286
+ }
287
+ }
288
+ ```
289
+
290
+ The route setup:
291
+
292
+ ```typescript
293
+ @UseGuards(JwtAuthGuard, TenantGuard())
294
+ @Controller('/orgs/:tenantId/orders')
295
+ export class OrdersController {
296
+ constructor(private readonly repo: OrdersRepository) {}
297
+
298
+ @Get('/')
299
+ list() {
300
+ // TenantContext is already seeded by TenantGuard — no need to pass tenantId
301
+ return this.repo.findAll();
302
+ }
303
+ }
304
+ ```
305
+
306
+ The two layers together:
307
+
308
+ | Layer | What it does | What it catches |
309
+ |---|---|---|
310
+ | `TenantGuard` | Rejects requests where `req.user.tenantId !== :tenantId` | Unauthenticated cross-tenant requests |
311
+ | `TenantContext` | Scopes every DB query via AsyncLocalStorage | Bugs, missing guard on a route, IDOR attempts |
312
+
313
+ For background jobs or tests, you can run code in a specific tenant context explicitly:
314
+
315
+ ```typescript
316
+ // Background job — no HTTP request involved
317
+ await TenantContext.run('acme', async () => {
318
+ await ordersService.processPendingOrders();
319
+ });
320
+ ```
321
+
322
+ `requireId()` throws with a 500 if called outside any tenant context (guard missing), giving you a clear error instead of silently querying all tenants.
323
+
324
+ ---
325
+
326
+ ### Combining guards
327
+
328
+ Guards run left-to-right. Always put `JwtAuthGuard` first.
329
+
330
+ ```typescript
331
+ @UseGuards(JwtAuthGuard, RoleGuard('manager'), TenantGuard())
332
+ @Controller('/orgs/:tenantId/orders')
333
+ export class OrdersController {
334
+
335
+ @Get('/')
336
+ listOrders(@CurrentUser() user: AuthUser) {
337
+ return this.ordersService.findAll(user.tenantId!);
338
+ }
339
+
340
+ // Stricter restriction on a single route — only admin (and above) can delete:
341
+ @UseGuards(RoleGuard('admin'))
342
+ @Delete('/:id')
343
+ deleteOrder(@Param('id') id: string) {
344
+ return this.ordersService.remove(id);
345
+ }
346
+ }
347
+ ```
348
+
349
+ ---
350
+
351
+ ## `@CurrentUser()` decorator
352
+
353
+ Injects the authenticated user (or a specific field from it) directly into the controller parameter.
354
+
355
+ ```typescript
356
+ import { CurrentUser, AuthUser } from '@hazeljs/auth';
357
+
358
+ @UseGuards(JwtAuthGuard)
359
+ @Get('/me')
360
+ getMe(@CurrentUser() user: AuthUser) {
361
+ return user;
362
+ // { id: 'u1', username: 'alice', role: 'admin', tenantId: 'acme' }
363
+ }
364
+
365
+ @Get('/role')
366
+ getRole(@CurrentUser('role') role: string) {
367
+ return { role };
368
+ }
369
+
370
+ @Get('/tenant')
371
+ getTenant(@CurrentUser('tenantId') tenantId: string) {
372
+ return { tenantId };
373
+ }
374
+ ```
375
+
376
+ ---
377
+
378
+ ## `@Auth()` decorator (method-level shorthand)
379
+
380
+ A lower-level alternative that wraps the handler directly instead of using the `@UseGuards` metadata system. Useful for one-off routes or when you prefer explicit colocation.
381
+
382
+ ```typescript
383
+ import { Auth } from '@hazeljs/auth';
384
+
385
+ @Controller('/admin')
386
+ export class AdminController {
387
+ @Auth() // JWT check only
388
+ @Get('/dashboard')
389
+ getDashboard() { ... }
390
+
391
+ @Auth({ roles: ['admin'] }) // JWT + role check (no hierarchy)
392
+ @Delete('/user/:id')
393
+ deleteUser(@Param('id') id: string) { ... }
394
+ }
395
+ ```
396
+
397
+ > **Note:** `@Auth()` does not use the role hierarchy. Use `@UseGuards(JwtAuthGuard, RoleGuard('admin'))` when hierarchy matters.
398
+
399
+ ---
400
+
401
+ ## `JwtService` API
402
+
403
+ ```typescript
404
+ import { JwtService } from '@hazeljs/auth';
405
+
406
+ // Sign a token
407
+ const token = jwtService.sign({ sub: userId, role: 'admin', tenantId: 'acme' });
408
+ const token = jwtService.sign({ sub: userId }, { expiresIn: '15m' }); // custom expiry
409
+
410
+ // Verify and decode
411
+ const payload = jwtService.verify(token); // throws on invalid/expired
412
+ payload.sub // string
413
+ payload.role // string
414
+ payload.tenantId // string | undefined
415
+
416
+ // Decode without verification (e.g. to read exp before refreshing)
417
+ const payload = jwtService.decode(token); // returns null on malformed
418
+ ```
419
+
420
+ ---
421
+
422
+ ## `AuthService` API
423
+
424
+ `AuthService` wraps `JwtService` and returns a typed `AuthUser` object:
425
+
426
+ ```typescript
427
+ interface AuthUser {
428
+ id: string;
429
+ username?: string;
430
+ role: string;
431
+ [key: string]: unknown; // all other JWT claims pass through
432
+ }
433
+
434
+ const user = await authService.verifyToken(token);
435
+ // Returns AuthUser | null (null when token is invalid — never throws)
436
+ ```
437
+
438
+ ---
439
+
440
+ ## `RoleHierarchy` API
441
+
442
+ ```typescript
443
+ import { RoleHierarchy, DEFAULT_ROLE_HIERARCHY } from '@hazeljs/auth';
444
+
445
+ const h = new RoleHierarchy(DEFAULT_ROLE_HIERARCHY);
446
+
447
+ h.satisfies('superadmin', 'user') // true — full chain
448
+ h.satisfies('manager', 'admin') // false — no upward inheritance
449
+ h.resolve('admin') // Set { 'admin', 'manager', 'user' }
450
+ ```
451
+
452
+ ---
453
+
454
+ ## Custom guards
455
+
456
+ Implement `CanActivate` from `@hazeljs/core` for fully custom logic:
457
+
458
+ ```typescript
459
+ import { Injectable, CanActivate, ExecutionContext } from '@hazeljs/core';
460
+
461
+ @Injectable()
462
+ export class ApiKeyGuard implements CanActivate {
463
+ canActivate(context: ExecutionContext): boolean {
464
+ const req = context.switchToHttp().getRequest() as { headers: Record<string, string> };
465
+ return req.headers['x-api-key'] === process.env.API_KEY;
466
+ }
467
+ }
468
+ ```
469
+
470
+ The `ExecutionContext` also exposes the fully parsed `RequestContext` (params, query, headers, body, user):
471
+
472
+ ```typescript
473
+ canActivate(context: ExecutionContext): boolean {
474
+ const ctx = context.switchToHttp().getContext();
475
+ const orgId = ctx.params['orgId'];
476
+ const user = ctx.user;
477
+ // ...
478
+ }
479
+ ```
480
+
481
+ ---
482
+
483
+ ## Environment variables
484
+
485
+ | Variable | Default | Description |
486
+ |---|---|---|
487
+ | `JWT_SECRET` | *(required)* | Secret used to sign and verify tokens |
488
+ | `JWT_EXPIRES_IN` | `1h` | Default token lifetime |
489
+ | `JWT_ISSUER` | — | Optional `iss` claim |
490
+ | `JWT_AUDIENCE` | — | Optional `aud` claim |
491
+
492
+ ---
493
+
494
+ ## Links
495
+
496
+ - [Documentation](https://hazeljs.com/docs/packages/auth)
497
+ - [GitHub](https://github.com/hazel-js/hazeljs)
498
+ - [Issues](https://github.com/hazel-js/hazeljs/issues)
499
+ - [Discord](https://discord.com/channels/1448263814238965833/1448263814859456575)
@@ -0,0 +1,15 @@
1
+ import { RequestContext } from '@hazeljs/core';
2
+ import { AuthService } from './auth.service';
3
+ export interface AuthGuardOptions {
4
+ roles?: string[];
5
+ }
6
+ export interface IAuthGuard {
7
+ canActivate(context: RequestContext, options?: AuthGuardOptions): Promise<boolean>;
8
+ }
9
+ export declare class AuthGuard implements IAuthGuard {
10
+ private authService;
11
+ constructor(authService: AuthService);
12
+ canActivate(context: RequestContext, options?: AuthGuardOptions): Promise<boolean>;
13
+ }
14
+ export declare function Auth(options?: AuthGuardOptions): (target: unknown, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
15
+ //# sourceMappingURL=auth.guard.d.ts.map