@c9up/warden 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +35 -0
  3. package/index.darwin-arm64.node +0 -0
  4. package/index.darwin-x64.node +0 -0
  5. package/index.linux-arm64-gnu.node +0 -0
  6. package/index.linux-x64-gnu.node +0 -0
  7. package/index.win32-x64-msvc.node +0 -0
  8. package/package.json +81 -0
  9. package/scripts/copy-napi.mjs +67 -0
  10. package/src/AuthManager.ts +228 -0
  11. package/src/AuthRateLimiter.ts +105 -0
  12. package/src/Guard.ts +68 -0
  13. package/src/RefreshTokenStore.ts +67 -0
  14. package/src/TokenBlacklist.ts +58 -0
  15. package/src/WardenProvider.ts +84 -0
  16. package/src/bouncer/AuthorizationResponse.ts +38 -0
  17. package/src/bouncer/BasePolicy.ts +66 -0
  18. package/src/bouncer/Bouncer.ts +236 -0
  19. package/src/bouncer/PolicyAuthorizer.ts +125 -0
  20. package/src/bouncer/decorators.ts +44 -0
  21. package/src/bouncer/evaluate.ts +104 -0
  22. package/src/bouncer/policyContext.ts +53 -0
  23. package/src/bouncer/types.ts +67 -0
  24. package/src/config.ts +48 -0
  25. package/src/configure.ts +59 -0
  26. package/src/errors.ts +25 -0
  27. package/src/firstcontact/FirstContactManager.ts +54 -0
  28. package/src/firstcontact/drivers/GitHubDriver.ts +78 -0
  29. package/src/firstcontact/drivers/GoogleDriver.ts +81 -0
  30. package/src/firstcontact/types.ts +38 -0
  31. package/src/index.ts +77 -0
  32. package/src/middleware.ts +283 -0
  33. package/src/native.ts +53 -0
  34. package/src/rights/MemoryRightsStore.ts +92 -0
  35. package/src/rights/RightsResolver.ts +84 -0
  36. package/src/rights/types.ts +58 -0
  37. package/src/services/main.ts +40 -0
  38. package/src/standalone.ts +128 -0
  39. package/src/strategies/ApiKeyStrategy.ts +54 -0
  40. package/src/strategies/JwtStrategy.ts +217 -0
  41. package/src/strategies/SessionStrategy.ts +105 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 C9up
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,35 @@
1
+ # @c9up/warden
2
+
3
+ Authentication & authorization for Node.js. Multi-strategy auth, RBAC, decorators.
4
+
5
+ ## Usage
6
+
7
+ ```typescript
8
+ import { AuthManager, Guard, Permission, Role } from '@c9up/warden'
9
+
10
+ const auth = new AuthManager({
11
+ defaultStrategy: 'jwt',
12
+ strategies: { jwt: myJwtStrategy },
13
+ })
14
+
15
+ const result = await auth.authenticate({ email: 'admin@c9up.com', password: 'secret' })
16
+ auth.hasRole(result.user!, 'admin') // true
17
+
18
+ class OrderController {
19
+ @Guard('jwt')
20
+ @Permission('orders.create')
21
+ async create() { /* protected */ }
22
+ }
23
+ ```
24
+
25
+ ## Features
26
+
27
+ - Multi-strategy AuthManager (JWT, session, API key, OAuth)
28
+ - `@Guard()`, `@Permission()`, `@Role()` decorators
29
+ - RBAC: `hasRole`, `hasPermission`, `hasAllPermissions`
30
+ - Strategy exception safety (catch → AuthResult)
31
+ - Runtime strategy registration
32
+
33
+ ## License
34
+
35
+ MIT
Binary file
Binary file
Binary file
Binary file
Binary file
package/package.json ADDED
@@ -0,0 +1,81 @@
1
+ {
2
+ "name": "@c9up/warden",
3
+ "version": "0.1.0",
4
+ "description": "Warden — Authentication for the Ream framework",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "files": [
10
+ "LICENSE",
11
+ "README.md",
12
+ "dist",
13
+ "index.*.node",
14
+ "scripts",
15
+ "src"
16
+ ],
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ },
22
+ "./provider": {
23
+ "types": "./dist/WardenProvider.d.ts",
24
+ "import": "./dist/WardenProvider.js"
25
+ },
26
+ "./services/main": {
27
+ "types": "./dist/services/main.d.ts",
28
+ "import": "./dist/services/main.js"
29
+ },
30
+ "./middleware": {
31
+ "types": "./dist/middleware.d.ts",
32
+ "import": "./dist/middleware.js"
33
+ },
34
+ "./config": {
35
+ "types": "./dist/config.d.ts",
36
+ "import": "./dist/config.js"
37
+ },
38
+ "./standalone": {
39
+ "types": "./dist/standalone.d.ts",
40
+ "import": "./dist/standalone.js"
41
+ },
42
+ "./configure": {
43
+ "types": "./dist/configure.d.ts",
44
+ "import": "./dist/configure.js"
45
+ }
46
+ },
47
+ "peerDependencies": {
48
+ "@c9up/ream": "^0.1.0"
49
+ },
50
+ "peerDependenciesMeta": {
51
+ "@c9up/ream": {
52
+ "optional": true
53
+ }
54
+ },
55
+ "devDependencies": {
56
+ "@types/node": "^22.19.15",
57
+ "reflect-metadata": "^0.2.2",
58
+ "typescript": "^6.0.2",
59
+ "vitest": "^4.1.2"
60
+ },
61
+ "engines": {
62
+ "node": ">=22.0.0"
63
+ },
64
+ "publishConfig": {
65
+ "access": "public"
66
+ },
67
+ "repository": {
68
+ "type": "git",
69
+ "url": "git+https://github.com/C9up/warden.git"
70
+ },
71
+ "scripts": {
72
+ "build": "tsc -p tsconfig.build.json",
73
+ "build:rust": "cargo build --release -p warden-engine-napi",
74
+ "build:napi": "pnpm build:rust && node scripts/copy-napi.mjs",
75
+ "test": "vitest run",
76
+ "test:rust": "cargo test -p warden-engine",
77
+ "lint": "biome check src/",
78
+ "test:coverage": "vitest run --coverage",
79
+ "typecheck": "tsc --noEmit"
80
+ }
81
+ }
@@ -0,0 +1,67 @@
1
+ import { copyFileSync, existsSync } from 'node:fs'
2
+ import { dirname, join } from 'node:path'
3
+ import { arch, env, platform } from 'node:process'
4
+ import { fileURLToPath } from 'node:url'
5
+
6
+ const here = dirname(fileURLToPath(import.meta.url))
7
+ const root = join(here, '..')
8
+ const CRATE = 'warden_engine_napi'
9
+ const TAG = '[warden:napi]'
10
+
11
+ // Rust target triple -> { suffix, os }. Set CARGO_BUILD_TARGET to cross-compile
12
+ // (e.g. build the x86_64-apple-darwin binary on an arm64 macOS runner). When
13
+ // unset we fall back to the host platform/arch and the default target/release.
14
+ const tripleMap = {
15
+ 'x86_64-unknown-linux-gnu': { suffix: 'linux-x64-gnu', os: 'linux' },
16
+ 'aarch64-unknown-linux-gnu': { suffix: 'linux-arm64-gnu', os: 'linux' },
17
+ 'x86_64-apple-darwin': { suffix: 'darwin-x64', os: 'darwin' },
18
+ 'aarch64-apple-darwin': { suffix: 'darwin-arm64', os: 'darwin' },
19
+ 'x86_64-pc-windows-msvc': { suffix: 'win32-x64-msvc', os: 'win32' },
20
+ }
21
+
22
+ const hostSuffixMap = {
23
+ 'linux-x64': 'linux-x64-gnu',
24
+ 'linux-arm64': 'linux-arm64-gnu',
25
+ 'darwin-x64': 'darwin-x64',
26
+ 'darwin-arm64': 'darwin-arm64',
27
+ 'win32-x64': 'win32-x64-msvc',
28
+ }
29
+
30
+ const triple = env.CARGO_BUILD_TARGET ?? ''
31
+ let suffix
32
+ let os
33
+ let releaseDir
34
+ if (triple) {
35
+ const entry = tripleMap[triple]
36
+ if (!entry) {
37
+ throw new Error(`${TAG} unsupported CARGO_BUILD_TARGET: ${triple}`)
38
+ }
39
+ suffix = entry.suffix
40
+ os = entry.os
41
+ releaseDir = join(root, 'target', triple, 'release')
42
+ } else {
43
+ suffix = hostSuffixMap[`${platform}-${arch}`]
44
+ os = platform
45
+ releaseDir = join(root, 'target', 'release')
46
+ if (!suffix) {
47
+ throw new Error(`${TAG} unsupported platform/arch: ${platform}-${arch}`)
48
+ }
49
+ }
50
+
51
+ const candidates =
52
+ os === 'win32'
53
+ ? [join(releaseDir, `${CRATE}.dll`), join(releaseDir, `lib${CRATE}.dll`)]
54
+ : os === 'darwin'
55
+ ? [join(releaseDir, `lib${CRATE}.dylib`)]
56
+ : [join(releaseDir, `lib${CRATE}.so`)]
57
+
58
+ const source = candidates.find((candidate) => existsSync(candidate))
59
+ if (!source) {
60
+ throw new Error(
61
+ `${TAG} native library not found. Looked for:\n${candidates.map((p) => `- ${p}`).join('\n')}`,
62
+ )
63
+ }
64
+
65
+ const target = join(root, `index.${suffix}.node`)
66
+ copyFileSync(source, target)
67
+ console.log(`${TAG} copied ${source} -> ${target}`)
@@ -0,0 +1,228 @@
1
+ /**
2
+ * AuthManager — manages multiple authentication strategies.
3
+ *
4
+ * @implements FR48, FR50, FR51
5
+ */
6
+
7
+ import { WardenError } from "./errors.js";
8
+ import { MemoryRightsStore } from "./rights/MemoryRightsStore.js";
9
+ import { RightsResolver } from "./rights/RightsResolver.js";
10
+ import type { EffectivePermissions, Scope } from "./rights/types.js";
11
+
12
+ export interface UserPayload {
13
+ id: string;
14
+ roles?: string[];
15
+ permissions?: string[];
16
+ [key: string]: unknown;
17
+ }
18
+
19
+ export interface AuthResult {
20
+ authenticated: boolean;
21
+ user?: UserPayload;
22
+ error?: string;
23
+ /**
24
+ * @internal Set when the strategy's `verify()` / `authenticate()` THREW
25
+ * a generic error (vs returned a deliberate `{ authenticated: false }`
26
+ * rejection). The middleware uses this to distinguish credential
27
+ * failures (→ 401) from strategy crashes (→ 500). Not part of the
28
+ * public consumer-facing API.
29
+ */
30
+ strategyCrash?: true;
31
+ }
32
+
33
+ export interface AuthStrategy {
34
+ name: string;
35
+ authenticate(credentials: Record<string, unknown>): Promise<AuthResult>;
36
+ verify(token: string, context?: Record<string, unknown>): Promise<AuthResult>;
37
+ }
38
+
39
+ export interface AuthConfig {
40
+ defaultStrategy: string;
41
+ strategies: Record<string, AuthStrategy>;
42
+ /**
43
+ * The rights resolver backing the coarse RBAC helpers (Epic 56). When
44
+ * absent, a default `RightsResolver(new MemoryRightsStore())` is used so
45
+ * `new AuthManager({ defaultStrategy, strategies })` keeps working — with
46
+ * an empty store, payload roles still fold in (D2) and permissions are
47
+ * empty (token `user.permissions` is not an input — D1).
48
+ */
49
+ rights?: RightsResolver;
50
+ }
51
+
52
+ /**
53
+ * Manages authentication strategies and provides guard/permission checks.
54
+ */
55
+ export class AuthManager {
56
+ private strategies: Map<string, AuthStrategy> = new Map();
57
+ private defaultStrategy: string;
58
+ private readonly rights: RightsResolver;
59
+
60
+ constructor(config: AuthConfig) {
61
+ this.defaultStrategy = config.defaultStrategy;
62
+ this.rights = config.rights ?? new RightsResolver(new MemoryRightsStore());
63
+ for (const [name, strategy] of Object.entries(config.strategies)) {
64
+ this.strategies.set(name, strategy);
65
+ }
66
+ // Fail-fast at construction: an AuthManager with zero strategies
67
+ // is a configuration bug. Previously, an empty `strategies: {}`
68
+ // passed the constructor cleanly and the first protected request
69
+ // crashed at runtime when `getStrategy('jwt')` threw — opaque 401
70
+ // or 500 instead of a boot-time INVALID_CONFIG that points the
71
+ // operator at the missing `config.auth.jwt` (or other strategy).
72
+ if (Object.keys(config.strategies).length === 0) {
73
+ throw new WardenError(
74
+ "INVALID_CONFIG",
75
+ `AuthManager: no authentication strategies registered. Configure at least one strategy (e.g. config.warden.auth.jwt) before booting WardenProvider.`,
76
+ );
77
+ }
78
+ if (!this.strategies.has(config.defaultStrategy)) {
79
+ throw new WardenError(
80
+ "INVALID_CONFIG",
81
+ `defaultStrategy '${config.defaultStrategy}' is not present in strategies`,
82
+ );
83
+ }
84
+ }
85
+
86
+ /** Authenticate with credentials using a specific or default strategy. */
87
+ async authenticate(
88
+ credentials: Record<string, unknown>,
89
+ strategyName?: string,
90
+ ): Promise<AuthResult> {
91
+ const strategy = this.getStrategy(strategyName);
92
+ try {
93
+ const result = await strategy.authenticate(credentials);
94
+ if (result.user) sanitizePayload(result.user);
95
+ return result;
96
+ } catch (err) {
97
+ // Re-throw structured WardenError sentinels (e.g. SessionStrategy's
98
+ // USE_LOGIN throw) so callers see the design-boundary signal instead
99
+ // of a soft `{ authenticated: false }`. Generic errors stay soft.
100
+ if (err instanceof WardenError) throw err;
101
+ return {
102
+ authenticated: false,
103
+ error:
104
+ err instanceof Error ? err.message : "Unknown authentication error",
105
+ };
106
+ }
107
+ }
108
+
109
+ /** Verify a token (JWT, session, API key). */
110
+ async verify(
111
+ token: string,
112
+ strategyName?: string,
113
+ context?: Record<string, unknown>,
114
+ ): Promise<AuthResult> {
115
+ const strategy = this.getStrategy(strategyName);
116
+ try {
117
+ const result = await strategy.verify(token, context);
118
+ if (result.user) sanitizePayload(result.user);
119
+ return result;
120
+ } catch (err) {
121
+ // Mirror authenticate(): rethrow structured WardenError sentinels;
122
+ // soft-fail generic throws but TAG them as strategy crashes so the
123
+ // middleware can flip 401 → 500 when every attempted strategy bombed.
124
+ if (err instanceof WardenError) throw err;
125
+ return {
126
+ authenticated: false,
127
+ error:
128
+ err instanceof Error ? err.message : "Unknown verification error",
129
+ strategyCrash: true,
130
+ };
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Resolve a user's effective permissions for a scope (Epic 56). The single
136
+ * resolution entry the coarse helpers wrap — `hasRole`/`hasPermission`/
137
+ * `hasAllPermissions` read this set, never the token payload directly. The
138
+ * Bouncer policy path (`this.permissions`, 56.3) consults the SAME resolver,
139
+ * so a coarse question and a policy question return the same answer for the
140
+ * same `(user, scope)` (the single unification point — AC-E3).
141
+ */
142
+ resolvePermissions(
143
+ user: UserPayload,
144
+ scope: Scope = "global",
145
+ ): Promise<EffectivePermissions> {
146
+ return this.rights.resolve(user, scope);
147
+ }
148
+
149
+ /**
150
+ * Check if a user has a specific role within a scope (default `"global"`).
151
+ * Reflects payload roles ∪ store roles (D2) — a token-carried role still
152
+ * satisfies it with no store config.
153
+ */
154
+ async hasRole(
155
+ user: UserPayload,
156
+ role: string,
157
+ scope: Scope = "global",
158
+ ): Promise<boolean> {
159
+ return (await this.resolvePermissions(user, scope)).roles.has(role);
160
+ }
161
+
162
+ /**
163
+ * Check if a user has a specific permission within a scope (default
164
+ * `"global"`). Derived from roles + store grants ONLY — token
165
+ * `user.permissions` is NOT read (D1, cerebrum 459).
166
+ */
167
+ async hasPermission(
168
+ user: UserPayload,
169
+ permission: string,
170
+ scope: Scope = "global",
171
+ ): Promise<boolean> {
172
+ return (await this.resolvePermissions(user, scope)).has(permission);
173
+ }
174
+
175
+ /**
176
+ * Check if a user has ALL required permissions within a scope (default
177
+ * `"global"`). Empty list ⇒ vacuously true.
178
+ */
179
+ async hasAllPermissions(
180
+ user: UserPayload,
181
+ permissions: string[],
182
+ scope: Scope = "global",
183
+ ): Promise<boolean> {
184
+ return (await this.resolvePermissions(user, scope)).hasAll(permissions);
185
+ }
186
+
187
+ /** Get a registered strategy by name. */
188
+ getStrategy(name?: string): AuthStrategy {
189
+ const strategyName = name ?? this.defaultStrategy;
190
+ const strategy = this.strategies.get(strategyName);
191
+ if (!strategy) {
192
+ throw new WardenError(
193
+ "STRATEGY_NOT_FOUND",
194
+ `Auth strategy '${strategyName}' not registered`,
195
+ {
196
+ hint: "Call registerStrategy() before using this strategy name.",
197
+ },
198
+ );
199
+ }
200
+ return strategy;
201
+ }
202
+
203
+ /** Register a new strategy at runtime. */
204
+ registerStrategy(name: string, strategy: AuthStrategy): void {
205
+ this.strategies.set(name, strategy);
206
+ }
207
+
208
+ /** Get all registered strategy names. */
209
+ getStrategyNames(): string[] {
210
+ return [...this.strategies.keys()];
211
+ }
212
+ }
213
+
214
+ /** Strip dangerous prototype-pollution keys from user payload. */
215
+ /**
216
+ * Strip prototype-pollution keys from a user payload before it's
217
+ * attached to the request. Exported so the middleware can apply it to
218
+ * the session path too — session auth goes through `verifyWithContext`
219
+ * directly (not `AuthManager.verify`), so without this it would skip
220
+ * the guard JWT / api-key users get.
221
+ */
222
+ export function sanitizePayload(user: UserPayload): void {
223
+ for (const key of ["__proto__", "constructor", "prototype"]) {
224
+ if (key in user) {
225
+ delete (user as Record<string, unknown>)[key];
226
+ }
227
+ }
228
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * AuthRateLimiter — brute force protection for login endpoints.
3
+ *
4
+ * Dual-key rate limiting: IP + email to prevent distributed attacks.
5
+ *
6
+ * @implements MISS-26
7
+ */
8
+
9
+ export interface AuthRateLimiterConfig {
10
+ maxAttempts?: number; // default 5
11
+ windowSeconds?: number; // default 900 (15 min)
12
+ }
13
+
14
+ interface AttemptEntry {
15
+ count: number;
16
+ resetAt: number;
17
+ }
18
+
19
+ export class AuthRateLimiter {
20
+ private maxAttempts: number;
21
+ private window: number;
22
+ private store: Map<string, AttemptEntry> = new Map();
23
+ private maxStoreSize = 100_000;
24
+
25
+ constructor(config?: AuthRateLimiterConfig) {
26
+ this.maxAttempts = config?.maxAttempts ?? 5;
27
+ if (this.maxAttempts <= 0) this.maxAttempts = 1;
28
+ this.window = (config?.windowSeconds ?? 900) * 1000;
29
+ if (this.window <= 0) this.window = 900_000; // prevent bypass via 0/negative
30
+ }
31
+
32
+ /** Check if an attempt is allowed. Returns false if rate limited. */
33
+ check(ip: string, identifier: string): boolean {
34
+ const now = Date.now();
35
+ const ipNorm = normalizeIp(ip);
36
+ const identifierNorm = normalizeIdentifier(identifier);
37
+ // Dual key: limit both by IP and by identifier (email)
38
+ const ipKey = `ip:${ipNorm}`;
39
+ const idKey = `id:${identifierNorm}`;
40
+
41
+ return this.checkKey(ipKey, now) && this.checkKey(idKey, now);
42
+ }
43
+
44
+ /** Record a failed attempt. */
45
+ recordFailure(ip: string, identifier: string): void {
46
+ const now = Date.now();
47
+ const ipNorm = normalizeIp(ip);
48
+ const identifierNorm = normalizeIdentifier(identifier);
49
+ this.increment(`ip:${ipNorm}`, now);
50
+ this.increment(`id:${identifierNorm}`, now);
51
+ }
52
+
53
+ /** Reset counters on successful login. */
54
+ recordSuccess(ip: string, identifier: string): void {
55
+ const ipNorm = normalizeIp(ip);
56
+ const identifierNorm = normalizeIdentifier(identifier);
57
+ this.store.delete(`ip:${ipNorm}`);
58
+ this.store.delete(`id:${identifierNorm}`);
59
+ }
60
+
61
+ /** Get remaining attempts for an identifier. */
62
+ remaining(ip: string, identifier: string): number {
63
+ const ipNorm = normalizeIp(ip);
64
+ const identifierNorm = normalizeIdentifier(identifier);
65
+ const ipEntry = this.store.get(`ip:${ipNorm}`);
66
+ const idEntry = this.store.get(`id:${identifierNorm}`);
67
+ const ipRemaining = ipEntry
68
+ ? Math.max(0, this.maxAttempts - ipEntry.count)
69
+ : this.maxAttempts;
70
+ const idRemaining = idEntry
71
+ ? Math.max(0, this.maxAttempts - idEntry.count)
72
+ : this.maxAttempts;
73
+ return Math.min(ipRemaining, idRemaining);
74
+ }
75
+
76
+ private checkKey(key: string, now: number): boolean {
77
+ const entry = this.store.get(key);
78
+ if (!entry || entry.resetAt < now) return true;
79
+ return entry.count < this.maxAttempts;
80
+ }
81
+
82
+ private increment(key: string, now: number): void {
83
+ // Evict expired entries when store grows too large (prevent OOM)
84
+ if (this.store.size > this.maxStoreSize) {
85
+ for (const [k, v] of this.store) {
86
+ if (v.resetAt < now) this.store.delete(k);
87
+ }
88
+ }
89
+
90
+ let entry = this.store.get(key);
91
+ if (!entry || entry.resetAt < now) {
92
+ entry = { count: 0, resetAt: now + this.window };
93
+ this.store.set(key, entry);
94
+ }
95
+ entry.count++;
96
+ }
97
+ }
98
+
99
+ function normalizeIdentifier(identifier: string): string {
100
+ return identifier.trim().toLowerCase();
101
+ }
102
+
103
+ function normalizeIp(ip: string): string {
104
+ return ip.trim();
105
+ }
package/src/Guard.ts ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * @Guard() decorator — protects route handlers with authentication.
3
+ *
4
+ * @implements FR50, FR51
5
+ */
6
+
7
+ // Side-effect import: registers the `Reflect.defineMetadata` / `getOwnMetadata`
8
+ // methods used below. Pulled in here (not transitively via the framework)
9
+ // so warden remains self-sufficient when published / consumed standalone.
10
+ import "reflect-metadata";
11
+
12
+ /** Guard decorator metadata key — Symbol.for ensures cross-module accessibility. */
13
+ const GUARD_KEY = Symbol.for("warden:guard");
14
+ const PERMISSION_KEY = Symbol.for("warden:permission");
15
+ const ROLE_KEY = Symbol.for("warden:role");
16
+
17
+ /**
18
+ * @Guard('jwt') — require authentication via the named strategy.
19
+ * At least one strategy name is required.
20
+ */
21
+ export function Guard(first: string, ...rest: string[]): MethodDecorator {
22
+ const strategies = [first, ...rest];
23
+ return (target, propertyKey) => {
24
+ Reflect.defineMetadata(GUARD_KEY, strategies, target, propertyKey);
25
+ };
26
+ }
27
+
28
+ /**
29
+ * @Permission('orders.create') — require specific permissions.
30
+ */
31
+ export function Permission(...permissions: string[]): MethodDecorator {
32
+ return (target, propertyKey) => {
33
+ Reflect.defineMetadata(PERMISSION_KEY, permissions, target, propertyKey);
34
+ };
35
+ }
36
+
37
+ /**
38
+ * @Role('admin') — require specific roles.
39
+ */
40
+ export function Role(...roles: string[]): MethodDecorator {
41
+ return (target, propertyKey) => {
42
+ Reflect.defineMetadata(ROLE_KEY, roles, target, propertyKey);
43
+ };
44
+ }
45
+
46
+ /** Get guard metadata. */
47
+ export function getGuardMetadata(
48
+ target: object,
49
+ propertyKey: string | symbol,
50
+ ): string[] {
51
+ return Reflect.getOwnMetadata(GUARD_KEY, target, propertyKey) ?? [];
52
+ }
53
+
54
+ /** Get permission metadata. */
55
+ export function getPermissionMetadata(
56
+ target: object,
57
+ propertyKey: string | symbol,
58
+ ): string[] {
59
+ return Reflect.getOwnMetadata(PERMISSION_KEY, target, propertyKey) ?? [];
60
+ }
61
+
62
+ /** Get role metadata. */
63
+ export function getRoleMetadata(
64
+ target: object,
65
+ propertyKey: string | symbol,
66
+ ): string[] {
67
+ return Reflect.getOwnMetadata(ROLE_KEY, target, propertyKey) ?? [];
68
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * RefreshTokenStore — server-side opaque refresh token management.
3
+ *
4
+ * AdonisJS opaque token pattern:
5
+ * { accessToken, refreshToken, expiresIn }
6
+ * POST /auth/refresh → new pair, old token invalidated
7
+ *
8
+ * @implements MISS-5
9
+ */
10
+
11
+ import { randomBytes } from "node:crypto";
12
+
13
+ export interface StoredRefreshToken {
14
+ token: string;
15
+ userId: string | number;
16
+ expiresAt: number;
17
+ createdAt: number;
18
+ }
19
+
20
+ export interface RefreshTokenDriver {
21
+ store(token: StoredRefreshToken): Promise<void>;
22
+ find(token: string): Promise<StoredRefreshToken | null>;
23
+ revoke(token: string): Promise<void>;
24
+ revokeAllForUser(userId: string | number): Promise<void>;
25
+ cleanup(): Promise<void>;
26
+ }
27
+
28
+ /** In-memory driver for development. */
29
+ export class MemoryRefreshTokenDriver implements RefreshTokenDriver {
30
+ private tokens: Map<string, StoredRefreshToken> = new Map();
31
+
32
+ async store(token: StoredRefreshToken): Promise<void> {
33
+ this.tokens.set(token.token, token);
34
+ }
35
+
36
+ async find(token: string): Promise<StoredRefreshToken | null> {
37
+ const stored = this.tokens.get(token);
38
+ if (!stored) return null;
39
+ if (stored.expiresAt < Date.now()) {
40
+ this.tokens.delete(token);
41
+ return null;
42
+ }
43
+ return stored;
44
+ }
45
+
46
+ async revoke(token: string): Promise<void> {
47
+ this.tokens.delete(token);
48
+ }
49
+
50
+ async revokeAllForUser(userId: string | number): Promise<void> {
51
+ for (const [key, val] of this.tokens) {
52
+ if (val.userId === userId) this.tokens.delete(key);
53
+ }
54
+ }
55
+
56
+ async cleanup(): Promise<void> {
57
+ const now = Date.now();
58
+ for (const [key, val] of this.tokens) {
59
+ if (val.expiresAt < now) this.tokens.delete(key);
60
+ }
61
+ }
62
+ }
63
+
64
+ /** Generate an opaque refresh token. */
65
+ export function generateRefreshToken(): string {
66
+ return randomBytes(48).toString("base64url");
67
+ }