@zero-server/auth 0.9.1 → 0.9.3

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 CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Tony Wiedman
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.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tony Wiedman
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/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  // AUTO-GENERATED by .tools/generate-package-stubs.js — edit .tools/scope-manifest.js and re-run `npm run packages:generate`.
2
- export { jwt, jwtSign, jwtVerify, jwtDecode, jwks, tokenPair, createRefreshToken, SUPPORTED_ALGORITHMS, session, Session, MemoryStore, oauth, generatePKCE, generateState, OAUTH_PROVIDERS, authorize, can, canAny, Policy, gate, attachUserHelpers, twoFactor, webauthn, trustedDevice, enrollment } from "@zero-server/sdk";
2
+ export * from './types/auth';
package/index.js CHANGED
@@ -1,31 +1,31 @@
1
1
  // AUTO-GENERATED by .tools/generate-package-stubs.js — edit .tools/scope-manifest.js and re-run `npm run packages:generate`.
2
2
  'use strict';
3
- const sdk = require("@zero-server/sdk");
3
+ const lib = require("./lib/auth");
4
4
 
5
5
  module.exports = {
6
- jwt: sdk.jwt,
7
- jwtSign: sdk.jwtSign,
8
- jwtVerify: sdk.jwtVerify,
9
- jwtDecode: sdk.jwtDecode,
10
- jwks: sdk.jwks,
11
- tokenPair: sdk.tokenPair,
12
- createRefreshToken: sdk.createRefreshToken,
13
- SUPPORTED_ALGORITHMS: sdk.SUPPORTED_ALGORITHMS,
14
- session: sdk.session,
15
- Session: sdk.Session,
16
- MemoryStore: sdk.MemoryStore,
17
- oauth: sdk.oauth,
18
- generatePKCE: sdk.generatePKCE,
19
- generateState: sdk.generateState,
20
- OAUTH_PROVIDERS: sdk.OAUTH_PROVIDERS,
21
- authorize: sdk.authorize,
22
- can: sdk.can,
23
- canAny: sdk.canAny,
24
- Policy: sdk.Policy,
25
- gate: sdk.gate,
26
- attachUserHelpers: sdk.attachUserHelpers,
27
- twoFactor: sdk.twoFactor,
28
- webauthn: sdk.webauthn,
29
- trustedDevice: sdk.trustedDevice,
30
- enrollment: sdk.enrollment,
6
+ jwt: lib.jwt,
7
+ jwtSign: lib.sign,
8
+ jwtVerify: lib.verify,
9
+ jwtDecode: lib.decode,
10
+ jwks: lib.jwks,
11
+ tokenPair: lib.tokenPair,
12
+ createRefreshToken: lib.createRefreshToken,
13
+ SUPPORTED_ALGORITHMS: lib.SUPPORTED_ALGORITHMS,
14
+ session: lib.session,
15
+ Session: lib.Session,
16
+ MemoryStore: lib.MemoryStore,
17
+ oauth: lib.oauth,
18
+ generatePKCE: lib.generatePKCE,
19
+ generateState: lib.generateState,
20
+ OAUTH_PROVIDERS: lib.PROVIDERS,
21
+ authorize: lib.authorize,
22
+ can: lib.can,
23
+ canAny: lib.canAny,
24
+ Policy: lib.Policy,
25
+ gate: lib.gate,
26
+ attachUserHelpers: lib.attachUserHelpers,
27
+ twoFactor: lib.twoFactor,
28
+ webauthn: lib.webauthn,
29
+ trustedDevice: lib.trustedDevice,
30
+ enrollment: lib.enrollment,
31
31
  };
@@ -0,0 +1,399 @@
1
+ /**
2
+ * @module auth/authorize
3
+ * @description Authorization helpers — role-based access control (RBAC),
4
+ * permission-based access, and policy classes.
5
+ *
6
+ * Works with any authentication middleware that sets `req.user`.
7
+ *
8
+ * @example
9
+ * const { createApp, jwt, authorize, can, canAny, Policy, gate,
10
+ * attachUserHelpers, Router } = require('@zero-server/sdk');
11
+ * const app = createApp();
12
+ *
13
+ * app.use(jwt({ secret: process.env.JWT_SECRET }));
14
+ * app.use(attachUserHelpers());
15
+ *
16
+ * // Role-based — only admins and editors can modify posts
17
+ * app.put('/posts/:id', authorize('admin', 'editor'), (req, res) => {
18
+ * res.json({ updated: true });
19
+ * });
20
+ *
21
+ * // Permission-based — require ALL listed permissions
22
+ * app.delete('/users/:id', can('users:read', 'users:delete'), (req, res) => {
23
+ * res.json({ deleted: true });
24
+ * });
25
+ *
26
+ * // ANY permission — useful for overlapping access
27
+ * app.get('/reports', canAny('reports:read', 'admin:read'), (req, res) => {
28
+ * res.json({ reports: [] });
29
+ * });
30
+ *
31
+ * // Policy class — resource-level authorization
32
+ * class PostPolicy extends Policy {
33
+ * before(user) { if (user.role === 'superadmin') return true; }
34
+ * update(user, post) { return user.id === post.authorId || user.role === 'admin'; }
35
+ * delete(user, post) { return user.role === 'admin'; }
36
+ * }
37
+ *
38
+ * app.put('/posts/:id', gate(new PostPolicy(), 'update', async (req) => {
39
+ * return await Post.findById(req.params.id);
40
+ * }), (req, res) => {
41
+ * // req.resource is auto-populated by gate()
42
+ * res.json({ updated: req.resource });
43
+ * });
44
+ *
45
+ * // Inline checks via attachUserHelpers()
46
+ * app.get('/dashboard', (req, res) => {
47
+ * const data = { user: req.user.sub };
48
+ * if (req.user.is('admin')) data.adminPanel = true;
49
+ * if (req.user.can('reports:export')) data.canExport = true;
50
+ * res.json(data);
51
+ * });
52
+ */
53
+ const log = require('../debug')('zero:auth');
54
+
55
+ // -- Role-Based Access Control ------------------------------------
56
+
57
+ /**
58
+ * Role-based authorization middleware.
59
+ * Checks `req.user.role` or `req.user.roles` against allowed roles.
60
+ *
61
+ * Returns 401 if `req.user` is missing (not authenticated).
62
+ * Returns 403 if the user's role is not in the allowed list.
63
+ *
64
+ * @param {...string} roles - Allowed roles.
65
+ * @returns {Function} Middleware `(req, res, next) => void`.
66
+ *
67
+ * @example
68
+ * app.get('/admin', authorize('admin'), (req, res) => {
69
+ * res.json({ message: 'Welcome, admin!' });
70
+ * });
71
+ *
72
+ * @example | Multiple Roles
73
+ * app.put('/posts/:id', authorize('admin', 'editor'), (req, res) => {
74
+ * res.json({ updated: true });
75
+ * });
76
+ */
77
+ function authorize(...roles)
78
+ {
79
+ const allowed = new Set(roles.flat());
80
+
81
+ return function authorizeMiddleware(req, res, next)
82
+ {
83
+ if (!req.user)
84
+ {
85
+ return res.status(401).json({
86
+ error: 'Authentication required',
87
+ code: 'NOT_AUTHENTICATED',
88
+ statusCode: 401,
89
+ });
90
+ }
91
+
92
+ const userRoles = _extractRoles(req.user);
93
+ const hasRole = userRoles.some(r => allowed.has(r));
94
+
95
+ if (!hasRole)
96
+ {
97
+ log.debug('access denied: user roles [%s] not in [%s]', userRoles.join(', '), [...allowed].join(', '));
98
+ return res.status(403).json({
99
+ error: 'Insufficient permissions',
100
+ code: 'FORBIDDEN',
101
+ statusCode: 403,
102
+ });
103
+ }
104
+
105
+ log.debug('authorized: role=%s', userRoles.find(r => allowed.has(r)));
106
+ next();
107
+ };
108
+ }
109
+
110
+ // -- Permission-Based Access Control --------------------------------
111
+
112
+ /**
113
+ * Permission-based authorization middleware.
114
+ * Checks `req.user.permissions` (array or Set) for the required permission(s).
115
+ *
116
+ * Permission strings follow a `resource:action` convention:
117
+ * - `'posts:write'` — write access to posts
118
+ * - `'users:delete'` — delete users
119
+ * - `'*'` — superuser wildcard
120
+ *
121
+ * @param {...string} permissions - Required permissions (ALL must be present unless `opts.any` is true).
122
+ * @returns {Function} Middleware `(req, res, next) => void`.
123
+ *
124
+ * @example | Require Specific Permission
125
+ * app.post('/posts', can('posts:write'), (req, res) => {
126
+ * res.status(201).json(req.body);
127
+ * });
128
+ *
129
+ * @example | Require ALL Permissions
130
+ * app.put('/users/:id', can('users:read', 'users:write'), (req, res) => {
131
+ * res.json({ updated: true });
132
+ * });
133
+ *
134
+ * @example | Require ANY Permission
135
+ * app.get('/dashboard', canAny('admin:read', 'reports:read'), (req, res) => {
136
+ * res.json({ dashboard: true });
137
+ * });
138
+ */
139
+ function can(...permissions)
140
+ {
141
+ return _permissionMiddleware(permissions.flat(), false);
142
+ }
143
+
144
+ /**
145
+ * Like `can()`, but passes if the user has ANY of the listed permissions.
146
+ *
147
+ * @param {...string} permissions - Permissions to check (any one is sufficient).
148
+ * @returns {Function} Middleware.
149
+ *
150
+ * @example
151
+ * app.get('/reports', canAny('reports:read', 'admin:read'), (req, res) => {
152
+ * res.json({ reports: [] });
153
+ * });
154
+ */
155
+ function canAny(...permissions)
156
+ {
157
+ return _permissionMiddleware(permissions.flat(), true);
158
+ }
159
+
160
+ /** @private */
161
+ function _permissionMiddleware(required, anyMode)
162
+ {
163
+ return function permissionMiddleware(req, res, next)
164
+ {
165
+ if (!req.user)
166
+ {
167
+ return res.status(401).json({
168
+ error: 'Authentication required',
169
+ code: 'NOT_AUTHENTICATED',
170
+ statusCode: 401,
171
+ });
172
+ }
173
+
174
+ const userPerms = _extractPermissions(req.user);
175
+
176
+ // Wildcard superuser
177
+ if (userPerms.has('*'))
178
+ {
179
+ log.debug('wildcard permission granted');
180
+ return next();
181
+ }
182
+
183
+ const check = anyMode
184
+ ? required.some(p => userPerms.has(p))
185
+ : required.every(p => userPerms.has(p));
186
+
187
+ if (!check)
188
+ {
189
+ log.debug('permission denied: required [%s] (mode=%s)', required.join(', '), anyMode ? 'any' : 'all');
190
+ return res.status(403).json({
191
+ error: 'Insufficient permissions',
192
+ code: 'FORBIDDEN',
193
+ statusCode: 403,
194
+ });
195
+ }
196
+
197
+ next();
198
+ };
199
+ }
200
+
201
+ // -- Policy Classes -----------------------------------------------
202
+
203
+ /**
204
+ * Base policy class for resource-level authorization.
205
+ * Subclass and define methods matching action names.
206
+ * Each method receives `(user, resource)` and returns `boolean`.
207
+ *
208
+ * @example
209
+ * class PostPolicy extends Policy {
210
+ * view() { return true; } // anyone can view
211
+ * update(user, post) { return user.id === post.authorId; }
212
+ * delete(user, post) { return user.role === 'admin'; }
213
+ * publish(user, post) { return ['admin', 'editor'].includes(user.role); }
214
+ * }
215
+ */
216
+ class Policy
217
+ {
218
+ /**
219
+ * Check if an action is allowed.
220
+ * Falls through to the action method if defined, otherwise denies.
221
+ *
222
+ * @param {string} action - The action name (method name).
223
+ * @param {object} user - The authenticated user.
224
+ * @param {object} [resource] - The resource being accessed.
225
+ * @returns {boolean|Promise<boolean>}
226
+ */
227
+ check(action, user, resource)
228
+ {
229
+ if (typeof this.before === 'function')
230
+ {
231
+ const beforeResult = this.before(user, action, resource);
232
+ if (beforeResult === true) return true;
233
+ if (beforeResult === false) return false;
234
+ // undefined = continue to action method
235
+ }
236
+
237
+ if (typeof this[action] !== 'function') return false;
238
+ return this[action](user, resource);
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Policy gate middleware.
244
+ * Runs a policy check against a resource loaded from the request.
245
+ *
246
+ * @param {Policy} policy - Policy instance.
247
+ * @param {string} action - Action name to check.
248
+ * @param {Function} [getResource] - `async (req) => resource` loader. If omitted, passes `null`.
249
+ * @returns {Function} Middleware `(req, res, next) => void`.
250
+ *
251
+ * @example
252
+ * const postPolicy = new PostPolicy();
253
+ *
254
+ * // With resource loader
255
+ * app.put('/posts/:id', gate(postPolicy, 'update', async (req) => {
256
+ * return await Post.findById(req.params.id);
257
+ * }), (req, res) => {
258
+ * res.json({ updated: req.resource });
259
+ * });
260
+ *
261
+ * // Without resource (for create/list actions)
262
+ * app.post('/posts', gate(postPolicy, 'create'), (req, res) => {
263
+ * res.status(201).json(req.body);
264
+ * });
265
+ */
266
+ function gate(policy, action, getResource)
267
+ {
268
+ return async function gateMiddleware(req, res, next)
269
+ {
270
+ if (!req.user)
271
+ {
272
+ return res.status(401).json({
273
+ error: 'Authentication required',
274
+ code: 'NOT_AUTHENTICATED',
275
+ statusCode: 401,
276
+ });
277
+ }
278
+
279
+ let resource = null;
280
+ if (typeof getResource === 'function')
281
+ {
282
+ resource = await getResource(req);
283
+ }
284
+
285
+ const allowed = await policy.check(action, req.user, resource);
286
+ if (!allowed)
287
+ {
288
+ log.debug('policy denied: action=%s', action);
289
+ return res.status(403).json({
290
+ error: 'Action not allowed',
291
+ code: 'POLICY_DENIED',
292
+ statusCode: 403,
293
+ });
294
+ }
295
+
296
+ // Attach resource if loaded — saves a redundant DB query in the handler
297
+ if (resource && !req.resource) req.resource = resource;
298
+ next();
299
+ };
300
+ }
301
+
302
+ // -- req.user helpers (mixed in by middleware barrel) ----------------
303
+
304
+ /**
305
+ * Attach convenience authorization methods to `req.user`.
306
+ * Call this middleware after JWT/session middleware.
307
+ *
308
+ * Adds:
309
+ * - `req.user.is(...roles)` — check roles
310
+ * - `req.user.can(...perms)` — check permissions
311
+ *
312
+ * @returns {Function} Middleware.
313
+ *
314
+ * @example
315
+ * app.use(jwt({ secret }));
316
+ * app.use(attachUserHelpers());
317
+ *
318
+ * app.get('/dashboard', (req, res) => {
319
+ * if (req.user.is('admin')) {
320
+ * // admin view
321
+ * }
322
+ * if (req.user.can('reports:export')) {
323
+ * // show export button
324
+ * }
325
+ * });
326
+ */
327
+ function attachUserHelpers()
328
+ {
329
+ return function userHelpersMiddleware(req, res, next)
330
+ {
331
+ if (!req.user) return next();
332
+
333
+ if (!req.user.is)
334
+ {
335
+ req.user.is = (...roles) =>
336
+ {
337
+ const userRoles = _extractRoles(req.user);
338
+ return roles.flat().some(r => userRoles.includes(r));
339
+ };
340
+ }
341
+
342
+ if (!req.user.can)
343
+ {
344
+ req.user.can = (...perms) =>
345
+ {
346
+ const userPerms = _extractPermissions(req.user);
347
+ if (userPerms.has('*')) return true;
348
+ return perms.flat().every(p => userPerms.has(p));
349
+ };
350
+ }
351
+
352
+ next();
353
+ };
354
+ }
355
+
356
+ // -- Internal Helpers -----------------------------------------------
357
+
358
+ /**
359
+ * Normalise user roles from various formats.
360
+ * Supports `user.role` (string), `user.roles` (array), and `user.role` (array).
361
+ *
362
+ * @param {object} user
363
+ * @returns {string[]}
364
+ * @private
365
+ */
366
+ function _extractRoles(user)
367
+ {
368
+ if (!user) return [];
369
+ if (Array.isArray(user.roles)) return user.roles;
370
+ if (Array.isArray(user.role)) return user.role;
371
+ if (typeof user.role === 'string') return [user.role];
372
+ return [];
373
+ }
374
+
375
+ /**
376
+ * Normalise user permissions from various formats.
377
+ * Supports `user.permissions` (array or Set), `user.scopes` (array).
378
+ *
379
+ * @param {object} user
380
+ * @returns {Set<string>}
381
+ * @private
382
+ */
383
+ function _extractPermissions(user)
384
+ {
385
+ if (!user) return new Set();
386
+ if (user.permissions instanceof Set) return user.permissions;
387
+ if (Array.isArray(user.permissions)) return new Set(user.permissions);
388
+ if (Array.isArray(user.scopes)) return new Set(user.scopes);
389
+ return new Set();
390
+ }
391
+
392
+ module.exports = {
393
+ authorize,
394
+ can,
395
+ canAny,
396
+ Policy,
397
+ gate,
398
+ attachUserHelpers,
399
+ };