@aponiajs/auth 0.0.0-stage → 1.0.0-beta.64

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/dist/index.mjs ADDED
@@ -0,0 +1,837 @@
1
+ import { APP_GUARD, AponiaError, ConfigurableModuleBuilder, Inject, Injectable, Module, Reflector, RolesGuard, RolesGuard as RolesGuard$1, SetMetadata, createParamDecorator, createToken, httpErrors, provideClass, provideValue } from "@aponiajs/common";
2
+ import { RequestContextModule, RequestContextService } from "@aponiajs/core";
3
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
4
+ import { SignJWT, createRemoteJWKSet, customFetch, decodeProtectedHeader, jwtVerify } from "jose";
5
+ // src/auth.constants.ts
6
+ /** The request-context token the authenticated user is stored under. */
7
+ const AUTH_USER = createToken("aponia.auth.user");
8
+ /** The verifier `AuthGuard` uses; `JwtService` or `OidcService` behind one token. */
9
+ const AUTH_VERIFIER = createToken("aponia.auth.verifier");
10
+ /** The header/cookie policy `AuthGuard` reads. */
11
+ const AUTH_TOKEN_OPTIONS = createToken("aponia.auth.token-options");
12
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/decorateMetadata.js
13
+ function __decorateMetadata(k, v) {
14
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
15
+ }
16
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/decorateParam.js
17
+ function __decorateParam(paramIndex, decorator) {
18
+ return function(target, key) {
19
+ decorator(target, key, paramIndex);
20
+ };
21
+ }
22
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/decorate.js
23
+ function __decorate(decorators, target, key, desc) {
24
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
25
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
26
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
27
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
28
+ }
29
+ // src/auth.service.ts
30
+ let AuthService = class AuthService {
31
+ #requestContext;
32
+ /** @internal Construct through `AuthModule.register`. */
33
+ constructor(requestContext) {
34
+ this.#requestContext = requestContext;
35
+ }
36
+ /** The user the current request authenticated, if any. */
37
+ current() {
38
+ return this.#requestContext.current()?.get(AUTH_USER);
39
+ }
40
+ /** @internal Enters the authenticated user into the request context. */
41
+ enter(user) {
42
+ this.#requestContext.current()?.set(AUTH_USER, user);
43
+ }
44
+ };
45
+ AuthService = __decorate([
46
+ Injectable(),
47
+ __decorateParam(0, Inject(RequestContextService)),
48
+ __decorateMetadata("design:paramtypes", [typeof RequestContextService === "undefined" ? Object : RequestContextService])
49
+ ], AuthService);
50
+ // src/revocation.service.ts
51
+ /** Checks whether an access token's `jti` was revoked. */
52
+ var RevocationService = class {
53
+ #store;
54
+ /** @internal Construct through `AuthModule.register`. */
55
+ constructor(store) {
56
+ this.#store = store;
57
+ }
58
+ /** Revokes one `jti` until its token expiry. */
59
+ async revoke(jti, expiresAt) {
60
+ await this.#store.revoke(jti, expiresAt);
61
+ }
62
+ /** Whether the token's `jti` is currently revoked. */
63
+ async isRevoked(jti) {
64
+ return await this.#store.isRevoked(jti);
65
+ }
66
+ /** Clears the revocation set. */
67
+ async clear() {
68
+ await this.#store.clear();
69
+ }
70
+ };
71
+ // src/auth.guard.ts
72
+ let AuthGuard = class AuthGuard {
73
+ #verifier;
74
+ #auth;
75
+ #reflector;
76
+ #revocation;
77
+ #tokenOptions;
78
+ constructor(verifier, tokenOptions, auth, reflector, revocation) {
79
+ this.#verifier = verifier;
80
+ this.#tokenOptions = tokenOptions;
81
+ this.#auth = auth;
82
+ this.#reflector = reflector;
83
+ this.#revocation = revocation;
84
+ }
85
+ async canActivate(context) {
86
+ const request = context.switchToHttp().getRequest();
87
+ if (this.#reflector.getAllAndOverride("isPublic", [context.getHandler(), context.getClass()])) return true;
88
+ const token = readToken(request.request, this.#tokenOptions);
89
+ if (token === void 0) throw httpErrors.unauthorized("Authentication token is missing.");
90
+ let user;
91
+ try {
92
+ user = await this.#verifier.verify(token);
93
+ } catch {
94
+ throw httpErrors.unauthorized("Invalid or expired authentication token.");
95
+ }
96
+ const jti = typeof user.jti === "string" ? user.jti : void 0;
97
+ if (jti !== void 0 && await this.#revocation.isRevoked(jti)) throw httpErrors.unauthorized("Authentication token has been revoked.");
98
+ this.#auth.enter(user);
99
+ const authenticated = request;
100
+ authenticated.user = user;
101
+ authenticated.session = Object.freeze({
102
+ user,
103
+ token,
104
+ claims: user
105
+ });
106
+ return true;
107
+ }
108
+ };
109
+ AuthGuard = __decorate([
110
+ Injectable(),
111
+ __decorateParam(0, Inject(AUTH_VERIFIER)),
112
+ __decorateParam(1, Inject(AUTH_TOKEN_OPTIONS)),
113
+ __decorateParam(2, Inject(AuthService)),
114
+ __decorateParam(3, Inject(Reflector)),
115
+ __decorateParam(4, Inject(RevocationService)),
116
+ __decorateMetadata("design:paramtypes", [
117
+ Object,
118
+ Object,
119
+ typeof AuthService === "undefined" ? Object : AuthService,
120
+ typeof Reflector === "undefined" ? Object : Reflector,
121
+ typeof RevocationService === "undefined" ? Object : RevocationService
122
+ ])
123
+ ], AuthGuard);
124
+ function readToken(request, options) {
125
+ const authorization = request.headers.get("authorization");
126
+ if (authorization !== null) {
127
+ const [scheme, token] = authorization.split(" ");
128
+ if (scheme?.toLowerCase() === options.scheme.toLowerCase() && token) return token;
129
+ }
130
+ if (options.cookieName === void 0) return;
131
+ const cookie = request.headers.get("cookie");
132
+ if (cookie === null) return;
133
+ for (const entry of cookie.split(";")) {
134
+ const [name, ...rest] = entry.trim().split("=");
135
+ if (name === options.cookieName) {
136
+ const value = rest.join("=");
137
+ if (value === "") return;
138
+ try {
139
+ return decodeURIComponent(value);
140
+ } catch {
141
+ return;
142
+ }
143
+ }
144
+ }
145
+ }
146
+ // src/permissions.guard.ts
147
+ let PermissionsGuard = class PermissionsGuard {
148
+ #reflector;
149
+ constructor(reflector) {
150
+ this.#reflector = reflector;
151
+ }
152
+ canActivate(context) {
153
+ if (this.#reflector.getAllAndOverride("isPublic", [context.getHandler(), context.getClass()])) return true;
154
+ const required = this.#reflector.getAllAndOverride("permissions", [context.getHandler(), context.getClass()]);
155
+ if (required === void 0 || required.length === 0) return true;
156
+ const granted = context.switchToHttp().getRequest().user?.permissions;
157
+ if (!Array.isArray(granted) || !required.every((permission) => granted.includes(permission))) throw httpErrors.forbidden("User does not possess the required permissions.");
158
+ return true;
159
+ }
160
+ };
161
+ PermissionsGuard = __decorate([
162
+ Injectable(),
163
+ __decorateParam(0, Inject(Reflector)),
164
+ __decorateMetadata("design:paramtypes", [typeof Reflector === "undefined" ? Object : Reflector])
165
+ ], PermissionsGuard);
166
+ // src/claims.ts
167
+ /** Lowers verified JWT claims into the frozen user a request carries. */
168
+ function mapVerifiedClaims(payload) {
169
+ const id = typeof payload.sub === "string" || typeof payload.sub === "number" ? payload.sub : typeof payload.id === "string" || typeof payload.id === "number" ? payload.id : void 0;
170
+ const roles = stringArray(payload.roles);
171
+ const permissions = stringArray(payload.permissions);
172
+ return Object.freeze({
173
+ ...payload,
174
+ ...id === void 0 ? {} : { id },
175
+ ...roles === void 0 ? {} : { roles },
176
+ ...permissions === void 0 ? {} : { permissions }
177
+ });
178
+ }
179
+ function stringArray(value) {
180
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string") ? Object.freeze([...value]) : void 0;
181
+ }
182
+ // src/jwt.service.ts
183
+ /** The JWT verifier and signer an application injects. */
184
+ var JwtService = class {
185
+ #key;
186
+ #rotation;
187
+ #active;
188
+ #options;
189
+ /** @internal Construct through `AuthModule.register`. */
190
+ constructor(options) {
191
+ const encoder = new TextEncoder();
192
+ this.#key = encoder.encode(options.secret);
193
+ this.#rotation = new Map((options.keys ?? []).map((key) => [key.kid, encoder.encode(key.secret)]));
194
+ const activeKid = options.activeKid ?? options.keys?.[0]?.kid;
195
+ this.#active = activeKid === void 0 ? void 0 : {
196
+ kid: activeKid,
197
+ key: this.#rotation.get(activeKid)
198
+ };
199
+ this.#options = options;
200
+ }
201
+ /**
202
+ * Signs one claims object.
203
+ *
204
+ * An access token needs a `jti` for revocation to reach it, so one is minted
205
+ * when the caller did not supply a non-empty string. A caller-supplied `jti`
206
+ * is preserved, which keeps deterministic test tokens and application-owned
207
+ * identifiers working.
208
+ */
209
+ async sign(claims, expiresIn) {
210
+ const jti = typeof claims.jti === "string" && claims.jti !== "" ? claims.jti : randomUUID();
211
+ const token = new SignJWT({
212
+ ...claims,
213
+ jti
214
+ }).setProtectedHeader(this.#active === void 0 ? { alg: "HS256" } : {
215
+ alg: "HS256",
216
+ kid: this.#active.kid
217
+ }).setJti(jti).setIssuedAt().setExpirationTime(expiresIn ?? this.#options.expiresIn);
218
+ if (this.#options.issuer !== void 0) token.setIssuer(this.#options.issuer);
219
+ if (this.#options.audience !== void 0) token.setAudience(this.#options.audience);
220
+ return await token.sign(this.#active?.key ?? this.#key);
221
+ }
222
+ /** Verifies one token and answers its user claims. */
223
+ async verify(token) {
224
+ try {
225
+ const options = {
226
+ ...this.#options.issuer === void 0 ? {} : { issuer: this.#options.issuer },
227
+ ...this.#options.audience === void 0 ? {} : { audience: this.#options.audience },
228
+ algorithms: [...this.#options.algorithms]
229
+ };
230
+ const kid = readKeyId(token);
231
+ if (kid !== void 0) {
232
+ const key = this.#rotation.get(kid);
233
+ if (key === void 0) throw new AponiaError("INVALID_AUTH_TOKEN", "The authentication token is invalid or expired.");
234
+ const { payload } = await jwtVerify(token, key, options);
235
+ return mapVerifiedClaims(payload);
236
+ }
237
+ const keys = [this.#key, ...this.#rotation.values()];
238
+ let lastError;
239
+ for (const key of keys) try {
240
+ const { payload } = await jwtVerify(token, key, options);
241
+ return mapVerifiedClaims(payload);
242
+ } catch (error) {
243
+ lastError = error;
244
+ }
245
+ throw lastError ?? /* @__PURE__ */ new Error("No key accepted the token.");
246
+ } catch {
247
+ throw new AponiaError("INVALID_AUTH_TOKEN", "The authentication token is invalid or expired.");
248
+ }
249
+ }
250
+ };
251
+ function readKeyId(token) {
252
+ try {
253
+ const header = decodeProtectedHeader(token);
254
+ return typeof header.kid === "string" && header.kid !== "" ? header.kid : void 0;
255
+ } catch {
256
+ return;
257
+ }
258
+ }
259
+ // src/oidc.service.ts
260
+ const defaultAlgorithms = Object.freeze([
261
+ "RS256",
262
+ "PS256",
263
+ "ES256"
264
+ ]);
265
+ /** Verifies access tokens against an OpenID Connect provider's published keys. */
266
+ var OidcService = class {
267
+ #options;
268
+ #metadata;
269
+ #keys;
270
+ /** @internal Construct through `AuthModule.register`. */
271
+ constructor(options) {
272
+ this.#options = resolveOptions$1(options);
273
+ }
274
+ /** Reads and validates the provider's discovery document. */
275
+ async discover() {
276
+ this.#metadata ??= this.#readMetadata();
277
+ try {
278
+ return await this.#metadata;
279
+ } catch (error) {
280
+ this.#metadata = void 0;
281
+ throw error;
282
+ }
283
+ }
284
+ /** Verifies one token against the provider's key set. */
285
+ async verify(token) {
286
+ const metadata = await this.discover();
287
+ const keys = this.#keys ??= createRemoteJWKSet(new URL(metadata.jwks_uri), {
288
+ timeoutDuration: this.#options.timeoutMs,
289
+ [customFetch]: this.#options.fetch
290
+ });
291
+ let payload;
292
+ try {
293
+ ({payload} = await jwtVerify(token, keys, {
294
+ issuer: this.#options.issuer,
295
+ ...this.#options.audience === void 0 ? {} : { audience: this.#options.audience },
296
+ algorithms: [...this.#options.algorithms],
297
+ clockTolerance: this.#options.clockTolerance
298
+ }));
299
+ } catch {
300
+ throw new AponiaError("INVALID_AUTH_TOKEN", "The authentication token is invalid or expired.");
301
+ }
302
+ return mapVerifiedClaims(payload);
303
+ }
304
+ /** Drops the cached discovery document and key set. */
305
+ clear() {
306
+ this.#metadata = void 0;
307
+ this.#keys = void 0;
308
+ }
309
+ async #readMetadata() {
310
+ const { discoveryUrl, timeoutMs, fetch } = this.#options;
311
+ let response;
312
+ try {
313
+ response = await fetch(discoveryUrl, {
314
+ redirect: "manual",
315
+ signal: AbortSignal.timeout(timeoutMs)
316
+ });
317
+ } catch {
318
+ throw discoveryFailed(discoveryUrl, "the request failed");
319
+ }
320
+ if (!response.ok) throw discoveryFailed(discoveryUrl, `it answered ${response.status}`);
321
+ let document;
322
+ try {
323
+ document = await response.json();
324
+ } catch {
325
+ throw discoveryFailed(discoveryUrl, "the body is not JSON");
326
+ }
327
+ return Object.freeze(validateMetadata(document, this.#options.issuer, discoveryUrl));
328
+ }
329
+ };
330
+ function resolveOptions$1(options) {
331
+ if (typeof options.issuer !== "string" || options.issuer.trim() === "") throw invalid$1("oidc.issuer must be a non-empty string");
332
+ if (options.audience !== void 0 && options.audience.trim() === "") throw invalid$1("oidc.audience must be a non-empty string when present");
333
+ const algorithms = options.algorithms ?? defaultAlgorithms;
334
+ if (!Array.isArray(algorithms) || algorithms.length === 0 || algorithms.some((algorithm) => typeof algorithm !== "string" || algorithm.trim() === "")) throw invalid$1("oidc.algorithms must be a non-empty array of strings");
335
+ const timeoutMs = options.timeoutMs ?? 5e3;
336
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1) throw invalid$1("oidc.timeoutMs must be a positive integer");
337
+ const clockTolerance = options.clockTolerance ?? 30;
338
+ if (!Number.isFinite(clockTolerance) || clockTolerance < 0) throw invalid$1("oidc.clockTolerance must be a non-negative number");
339
+ const discoveryUrl = options.discoveryUrl ?? `${trimTrailingSlashes(options.issuer)}/.well-known/openid-configuration`;
340
+ if (!isHttpUrl(discoveryUrl)) throw invalid$1("oidc.discoveryUrl must be https, or http on a loopback host");
341
+ return Object.freeze({
342
+ issuer: options.issuer,
343
+ audience: options.audience,
344
+ algorithms: Object.freeze([...algorithms]),
345
+ discoveryUrl,
346
+ timeoutMs,
347
+ clockTolerance,
348
+ fetch: options.fetch ?? globalThis.fetch
349
+ });
350
+ }
351
+ function trimTrailingSlashes(value) {
352
+ let end = value.length;
353
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
354
+ return end === value.length ? value : value.slice(0, end);
355
+ }
356
+ function validateMetadata(document, issuer, discoveryUrl) {
357
+ if (typeof document !== "object" || document === null || Array.isArray(document)) throw discoveryFailed(discoveryUrl, "the body is not an object");
358
+ const record = document;
359
+ if (record.issuer !== issuer) throw discoveryFailed(discoveryUrl, "it names a different issuer");
360
+ if (typeof record.jwks_uri !== "string" || !isHttpUrl(record.jwks_uri)) throw discoveryFailed(discoveryUrl, "it states no usable jwks_uri");
361
+ return record;
362
+ }
363
+ function isHttpUrl(value) {
364
+ try {
365
+ const url = new URL(value);
366
+ if (url.protocol === "https:") return true;
367
+ return url.protocol === "http:" && isLoopbackHost(url.hostname);
368
+ } catch {
369
+ return false;
370
+ }
371
+ }
372
+ function isLoopbackHost(hostname) {
373
+ return hostname === "localhost" || hostname === "::1" || hostname === "[::1]" || hostname.startsWith("127.");
374
+ }
375
+ function discoveryFailed(url, reason) {
376
+ return new AponiaError("OIDC_DISCOVERY_FAILED", `The OIDC discovery document could not be read: ${reason}.`, Object.freeze({ url }));
377
+ }
378
+ function invalid$1(issue) {
379
+ return new AponiaError("INVALID_AUTH_OPTIONS", `The auth registration is invalid: ${issue}.`, { issues: Object.freeze([issue]) });
380
+ }
381
+ // src/password/password-hasher.service.ts
382
+ /** Bun-native password hashing and verification. */
383
+ var PasswordService = class {
384
+ /** Hashes a password with Bun's default password algorithm. */
385
+ async hash(password) {
386
+ assertPassword(password);
387
+ return await Bun.password.hash(password);
388
+ }
389
+ /** Verifies a password against a stored hash. */
390
+ async verify(password, hash) {
391
+ assertPassword(password);
392
+ return await Bun.password.verify(password, hash);
393
+ }
394
+ };
395
+ function assertPassword(password) {
396
+ if (typeof password !== "string" || password.length === 0) throw new AponiaError("INVALID_AUTH_OPTIONS", "A password must be a non-empty string.");
397
+ }
398
+ // src/memory-refresh-token.store.ts
399
+ /** A bounded, process-local refresh-token store. */
400
+ var MemoryRefreshTokenStore = class {
401
+ #records = /* @__PURE__ */ new Map();
402
+ #used = /* @__PURE__ */ new Map();
403
+ #maxTokens;
404
+ #now;
405
+ constructor(options = {}) {
406
+ const maxTokens = options.maxTokens ?? 1e4;
407
+ if (!Number.isInteger(maxTokens) || maxTokens < 1) throw new AponiaError("INVALID_AUTH_OPTIONS", "RefreshTokenStore maxTokens must be a positive integer.");
408
+ this.#maxTokens = maxTokens;
409
+ this.#now = options.now ?? Date.now;
410
+ }
411
+ create(record) {
412
+ this.#prune();
413
+ if (!this.#records.has(record.idHash) && this.#records.size >= this.#maxTokens) {
414
+ const oldest = this.#records.keys().next().value;
415
+ if (oldest !== void 0) this.#records.delete(oldest);
416
+ }
417
+ this.#records.set(record.idHash, record);
418
+ }
419
+ find(idHash) {
420
+ const record = this.#records.get(idHash);
421
+ if (record === void 0) return;
422
+ if (record.expiresAt <= this.#now()) {
423
+ this.#records.delete(idHash);
424
+ return;
425
+ }
426
+ return record;
427
+ }
428
+ delete(idHash) {
429
+ return this.#records.delete(idHash);
430
+ }
431
+ consume(idHash) {
432
+ this.#prune();
433
+ const record = this.#records.get(idHash);
434
+ if (record !== void 0) {
435
+ this.#records.delete(idHash);
436
+ this.#rememberUsed(idHash, record);
437
+ return { record };
438
+ }
439
+ const used = this.#used.get(idHash);
440
+ if (used !== void 0) return { familyId: used.familyId };
441
+ }
442
+ /**
443
+ * Records a consumed token without letting the tombstones outgrow the store.
444
+ *
445
+ * They share the record cap: a tombstone retained forever would make every
446
+ * `create` and `consume` scan an unbounded map, which one client rotating a
447
+ * token in a loop could turn into a memory and CPU denial of service. When
448
+ * the cap is reached the oldest tombstone is dropped, so reuse of a very old
449
+ * consumed token is answered as unknown rather than as family reuse; the
450
+ * token itself is already gone and cannot be rotated either way.
451
+ */
452
+ #rememberUsed(idHash, record) {
453
+ if (!this.#used.has(idHash) && this.#used.size >= this.#maxTokens) {
454
+ const oldest = this.#used.keys().next().value;
455
+ if (oldest !== void 0) this.#used.delete(oldest);
456
+ }
457
+ this.#used.set(idHash, {
458
+ familyId: record.familyId,
459
+ expiresAt: record.expiresAt
460
+ });
461
+ }
462
+ deleteFamily(familyId) {
463
+ let deleted = 0;
464
+ for (const [key, record] of this.#records) if (record.familyId === familyId) {
465
+ this.#records.delete(key);
466
+ deleted += 1;
467
+ }
468
+ return deleted;
469
+ }
470
+ clear() {
471
+ this.#records.clear();
472
+ this.#used.clear();
473
+ }
474
+ #prune() {
475
+ const now = this.#now();
476
+ for (const [key, record] of this.#records) if (record.expiresAt <= now) this.#records.delete(key);
477
+ for (const [key, used] of this.#used) if (used.expiresAt <= now) this.#used.delete(key);
478
+ }
479
+ };
480
+ // src/refresh-token.service.ts
481
+ const defaultTtlMs = 2592e6;
482
+ /** Issues, rotates, and revokes opaque refresh tokens. */
483
+ var RefreshTokenService = class {
484
+ #store;
485
+ #ttlMs;
486
+ #now;
487
+ /** @internal Construct through `AuthModule.register`. */
488
+ constructor(store, options = {}) {
489
+ const ttlMs = options.ttlMs ?? defaultTtlMs;
490
+ if (!Number.isInteger(ttlMs) || ttlMs < 1) throw new AponiaError("INVALID_AUTH_OPTIONS", "refresh.ttlMs must be a positive integer.");
491
+ this.#store = store;
492
+ this.#ttlMs = ttlMs;
493
+ this.#now = options.now ?? Date.now;
494
+ }
495
+ /** Issues one token, optionally in an existing rotation family. */
496
+ async issue(userId, familyId = randomUUID()) {
497
+ const token = randomBytes(32).toString("base64url");
498
+ const now = this.#now();
499
+ const record = Object.freeze({
500
+ idHash: hashToken(token),
501
+ userId,
502
+ familyId,
503
+ createdAt: now,
504
+ expiresAt: now + this.#ttlMs
505
+ });
506
+ await this.#store.create(record);
507
+ return Object.freeze({
508
+ token,
509
+ userId,
510
+ familyId,
511
+ expiresAt: record.expiresAt
512
+ });
513
+ }
514
+ /**
515
+ * Rotates one token; the old token is consumed before the new one is issued.
516
+ *
517
+ * An already-consumed token revokes its whole family (OAuth reuse detection).
518
+ * A store without `consume` falls back to `find` + `delete`, which still lets
519
+ * exactly one concurrent rotation win.
520
+ */
521
+ async rotate(token) {
522
+ const consumed = await this.#consume(hashToken(token));
523
+ if (consumed === void 0) throw invalidRefreshToken();
524
+ if ("familyId" in consumed) {
525
+ await this.#store.deleteFamily(consumed.familyId);
526
+ throw invalidRefreshToken();
527
+ }
528
+ const record = consumed.record;
529
+ if (record.expiresAt <= this.#now()) throw invalidRefreshToken();
530
+ return await this.issue(record.userId, record.familyId);
531
+ }
532
+ /** Revokes one token. */
533
+ async revoke(token) {
534
+ return await this.#store.delete(hashToken(token));
535
+ }
536
+ /** Revokes every token in a rotation family. */
537
+ async revokeFamily(familyId) {
538
+ return await this.#store.deleteFamily(familyId);
539
+ }
540
+ /** Clears the store. */
541
+ async clear() {
542
+ await this.#store.clear();
543
+ }
544
+ async #consume(idHash) {
545
+ if (this.#store.consume !== void 0) return await this.#store.consume(idHash);
546
+ const record = await this.#store.find(idHash);
547
+ if (record === void 0) return;
548
+ return await this.#store.delete(idHash) ? { record } : void 0;
549
+ }
550
+ };
551
+ function hashToken(token) {
552
+ return createHash("sha256").update(token).digest("hex");
553
+ }
554
+ function invalidRefreshToken() {
555
+ return new AponiaError("INVALID_REFRESH_TOKEN", "The refresh token is invalid, expired, or already used.");
556
+ }
557
+ // src/memory-revocation.store.ts
558
+ /** A bounded, process-local revocation set. */
559
+ var MemoryRevocationStore = class {
560
+ #entries = /* @__PURE__ */ new Map();
561
+ #maxEntries;
562
+ #now;
563
+ constructor(options = {}) {
564
+ const maxEntries = options.maxEntries ?? 1e4;
565
+ if (!Number.isInteger(maxEntries) || maxEntries < 1) throw new AponiaError("INVALID_AUTH_OPTIONS", "RevocationStore maxEntries must be a positive integer.");
566
+ this.#maxEntries = maxEntries;
567
+ this.#now = options.now ?? Date.now;
568
+ }
569
+ revoke(jti, expiresAt) {
570
+ if (!Number.isFinite(expiresAt) || expiresAt <= this.#now()) throw new AponiaError("INVALID_AUTH_OPTIONS", "Revocation expiresAt must be epoch milliseconds in the future.");
571
+ this.#prune();
572
+ if (!this.#entries.has(jti) && this.#entries.size >= this.#maxEntries) {
573
+ const oldest = this.#entries.keys().next().value;
574
+ if (oldest !== void 0) this.#entries.delete(oldest);
575
+ }
576
+ this.#entries.set(jti, expiresAt);
577
+ }
578
+ isRevoked(jti) {
579
+ this.#prune();
580
+ return this.#entries.has(jti);
581
+ }
582
+ clear() {
583
+ this.#entries.clear();
584
+ }
585
+ #prune() {
586
+ const now = this.#now();
587
+ for (const [jti, expiresAt] of this.#entries) if (expiresAt <= now) this.#entries.delete(jti);
588
+ }
589
+ };
590
+ // src/auth.module-definition.ts
591
+ const builder = new ConfigurableModuleBuilder({ moduleName: "Auth" }).setExtras({
592
+ isGlobal: true,
593
+ globalGuard: true
594
+ }, (definition, extras) => ({
595
+ ...definition,
596
+ global: extras.isGlobal ?? true,
597
+ providers: [...definition.providers ?? [], ...extras.globalGuard === false ? [] : [provideValue(APP_GUARD, AuthGuard)]]
598
+ })).build();
599
+ /**
600
+ * The generated registration class, options token, and type markers.
601
+ *
602
+ * `MODULE_OPTIONS_TOKEN` is the `AUTH_MODULE_OPTIONS` token; `OPTIONS_TYPE` and
603
+ * `ASYNC_OPTIONS_TYPE` are type markers that throw when read as values.
604
+ *
605
+ * This package's registration is shaped by its options: the verification arm
606
+ * decides which verifier provider exists, which a container factory cannot
607
+ * change. `forRoot` is therefore the only registration, and the generated
608
+ * `registerAsync` is not exposed as a public surface.
609
+ */
610
+ const { ConfigurableModuleClass, OPTIONS_TYPE, ASYNC_OPTIONS_TYPE } = builder;
611
+ /** The options token, narrowed to the explicit token the builder mints. */
612
+ const MODULE_OPTIONS_TOKEN = builder.MODULE_OPTIONS_TOKEN;
613
+ // src/auth.module.ts
614
+ var _AuthModule;
615
+ let AuthModule = _AuthModule = class AuthModule extends ConfigurableModuleClass {
616
+ /**
617
+ * Builds one authentication module.
618
+ *
619
+ * The registration has no `forRootAsync`: which providers exist — a JWT
620
+ * verifier or an OIDC one — is decided by the options arm, and a container
621
+ * factory cannot change a provider list. A configuration that must be built
622
+ * asynchronously is resolved before the module is registered.
623
+ *
624
+ * @param options - The verifier arm, token policy, refresh, revocation, and extras.
625
+ * @returns A frozen dynamic module an application imports.
626
+ * @throws An `AponiaError` with `INVALID_AUTH_OPTIONS` when an option is invalid.
627
+ */
628
+ static forRoot(options) {
629
+ assertExtras(options);
630
+ return complete(super.register(options), resolveRegistration(options));
631
+ }
632
+ /**
633
+ * Builds one authentication module.
634
+ *
635
+ * @deprecated Use {@link AuthModule.forRoot}; retained for the beta line.
636
+ */
637
+ static register(options) {
638
+ return _AuthModule.forRoot(options);
639
+ }
640
+ /**
641
+ * Refuses the asynchronous form, which this package's registration cannot serve.
642
+ *
643
+ * @throws An `AponiaError` with `INVALID_AUTH_OPTIONS`; a provider list that
644
+ * the options arm decides cannot be built from a factory result.
645
+ */
646
+ static registerAsync(_options) {
647
+ throw new AponiaError("INVALID_AUTH_OPTIONS", "AuthModule does not support an asynchronous registration: resolve the options before registering.", { issues: Object.freeze(["registerAsync is not supported"]) });
648
+ }
649
+ };
650
+ AuthModule = _AuthModule = __decorate([Module({})], AuthModule);
651
+ function complete(definition, parts) {
652
+ return Object.freeze({
653
+ ...definition,
654
+ module: AuthModule,
655
+ imports: Object.freeze([RequestContextModule.forRoot(), ...definition.imports ?? []]),
656
+ controllers: Object.freeze([...definition.controllers ?? []]),
657
+ providers: Object.freeze([
658
+ ...definition.providers ?? [],
659
+ ...parts.verification.providers,
660
+ provideValue(AUTH_VERIFIER, parts.verification.verifier),
661
+ provideValue(AUTH_TOKEN_OPTIONS, parts.tokenOptions),
662
+ provideClass(AuthService, [RequestContextService]),
663
+ provideValue(PasswordService, parts.password),
664
+ provideValue(RefreshTokenService, parts.refresh),
665
+ provideValue(RevocationService, parts.revocation),
666
+ provideClass(Reflector, []),
667
+ provideClass(AuthGuard, [
668
+ AUTH_VERIFIER,
669
+ AUTH_TOKEN_OPTIONS,
670
+ AuthService,
671
+ Reflector,
672
+ RevocationService
673
+ ]),
674
+ provideClass(RolesGuard$1, [Reflector]),
675
+ provideClass(PermissionsGuard, [Reflector])
676
+ ]),
677
+ exports: Object.freeze([
678
+ MODULE_OPTIONS_TOKEN,
679
+ AUTH_VERIFIER,
680
+ ...parts.verification.exports,
681
+ AuthService,
682
+ PasswordService,
683
+ RefreshTokenService,
684
+ RevocationService,
685
+ AuthGuard,
686
+ RolesGuard$1,
687
+ PermissionsGuard
688
+ ])
689
+ });
690
+ }
691
+ function assertExtras(options) {
692
+ if (options.isGlobal !== void 0 && typeof options.isGlobal !== "boolean") throw invalid("isGlobal must be a boolean");
693
+ if (options.globalGuard !== void 0 && typeof options.globalGuard !== "boolean") throw invalid("globalGuard must be a boolean");
694
+ }
695
+ function resolveRegistration(options) {
696
+ const verification = resolveVerification(options);
697
+ const tokenOptions = resolveTokenOptions(options.token);
698
+ const password = new PasswordService();
699
+ const refreshStore = options.refresh?.store === void 0 ? new MemoryRefreshTokenStore({
700
+ maxTokens: options.refresh?.maxTokens,
701
+ now: options.refresh?.now
702
+ }) : options.refresh.store;
703
+ assertRefreshStore(refreshStore);
704
+ const revocationStore = options.revocation?.store === void 0 ? new MemoryRevocationStore(options.revocation) : options.revocation.store;
705
+ assertRevocationStore(revocationStore);
706
+ const refresh = new RefreshTokenService(refreshStore, options.refresh);
707
+ const revocation = new RevocationService(revocationStore);
708
+ return Object.freeze({
709
+ verification,
710
+ tokenOptions,
711
+ password,
712
+ refresh,
713
+ revocation
714
+ });
715
+ }
716
+ function resolveTokenOptions(options) {
717
+ const cookies = options?.cookieName;
718
+ if (cookies !== void 0 && (typeof cookies !== "string" || cookies.trim() === "")) throw invalid("token.cookieName must be a non-empty string when present");
719
+ const scheme = options?.scheme ?? "Bearer";
720
+ if (typeof scheme !== "string" || scheme.trim() === "") throw invalid("token.scheme must be a non-empty string");
721
+ return Object.freeze({
722
+ cookieName: cookies,
723
+ scheme
724
+ });
725
+ }
726
+ function assertRefreshStore(store) {
727
+ if (typeof store !== "object" || store === null) throw invalid("refresh.store must implement RefreshTokenStore");
728
+ const missing = [
729
+ "create",
730
+ "find",
731
+ "delete",
732
+ "deleteFamily",
733
+ "clear"
734
+ ].filter((method) => typeof store[method] !== "function");
735
+ if (missing.length > 0) throw invalid(`refresh.store is missing ${missing.join(", ")}`);
736
+ }
737
+ function assertRevocationStore(store) {
738
+ if (typeof store !== "object" || store === null) throw invalid("revocation.store must implement RevocationStore");
739
+ const missing = [
740
+ "revoke",
741
+ "isRevoked",
742
+ "clear"
743
+ ].filter((method) => typeof store[method] !== "function");
744
+ if (missing.length > 0) throw invalid(`revocation.store is missing ${missing.join(", ")}`);
745
+ }
746
+ function resolveVerification(options) {
747
+ if (options.jwt !== void 0 === (options.oidc !== void 0)) throw invalid("exactly one of jwt or oidc must be present");
748
+ if (options.jwt !== void 0) {
749
+ const jwt = new JwtService(resolveOptions({ jwt: options.jwt }));
750
+ return Object.freeze({
751
+ verifier: jwt,
752
+ providers: Object.freeze([provideValue(JwtService, jwt)]),
753
+ exports: Object.freeze([JwtService])
754
+ });
755
+ }
756
+ const oidc = new OidcService(options.oidc);
757
+ return Object.freeze({
758
+ verifier: oidc,
759
+ providers: Object.freeze([provideValue(OidcService, oidc)]),
760
+ exports: Object.freeze([OidcService])
761
+ });
762
+ }
763
+ function resolveOptions(options) {
764
+ const jwt = options.jwt;
765
+ if (typeof jwt.secret !== "string" || jwt.secret.length < 32) throw invalid("jwt.secret must be a string of at least 32 characters");
766
+ if (jwt.issuer !== void 0 && (typeof jwt.issuer !== "string" || jwt.issuer.trim() === "")) throw invalid("jwt.issuer must be a non-empty string when present");
767
+ if (jwt.audience !== void 0 && (typeof jwt.audience !== "string" || jwt.audience.trim() === "")) throw invalid("jwt.audience must be a non-empty string when present");
768
+ const algorithms = jwt.algorithms ?? ["HS256"];
769
+ if (!Array.isArray(algorithms) || algorithms.length === 0 || algorithms.some((algorithm) => typeof algorithm !== "string" || algorithm.trim() === "")) throw invalid("jwt.algorithms must be a non-empty array of strings");
770
+ const expiresIn = jwt.expiresIn ?? "1h";
771
+ if (typeof expiresIn !== "string" && typeof expiresIn !== "number" || typeof expiresIn === "string" && expiresIn.trim() === "") throw invalid("jwt.expiresIn must be a non-empty string or a number");
772
+ const keys = jwt.keys ?? [];
773
+ if (!Array.isArray(keys)) throw invalid("jwt.keys must be an array when present");
774
+ const kids = /* @__PURE__ */ new Set();
775
+ for (const key of keys) {
776
+ if (typeof key !== "object" || key === null) throw invalid("jwt.keys must contain key objects");
777
+ if (typeof key.kid !== "string" || key.kid.trim() === "") throw invalid("jwt.keys entries need a non-empty kid");
778
+ if (kids.has(key.kid)) throw invalid(`jwt.keys declares the kid "${key.kid}" twice`);
779
+ kids.add(key.kid);
780
+ if (typeof key.secret !== "string" || key.secret.length < 32) throw invalid(`jwt.keys entry "${key.kid}" needs a secret of at least 32 characters`);
781
+ }
782
+ const activeKid = jwt.activeKid;
783
+ if (activeKid !== void 0 && !kids.has(activeKid)) throw invalid("jwt.activeKid must name one of jwt.keys");
784
+ return Object.freeze({
785
+ secret: jwt.secret,
786
+ issuer: jwt.issuer,
787
+ audience: jwt.audience,
788
+ algorithms: Object.freeze([...algorithms]),
789
+ expiresIn,
790
+ keys: Object.freeze(keys.map((key) => Object.freeze({
791
+ kid: key.kid,
792
+ secret: key.secret
793
+ }))),
794
+ activeKid
795
+ });
796
+ }
797
+ function invalid(issue) {
798
+ return new AponiaError("INVALID_AUTH_OPTIONS", `The auth registration is invalid: ${issue}.`, { issues: Object.freeze([issue]) });
799
+ }
800
+ // src/current-user.decorator.ts
801
+ /**
802
+ * The authenticated user for the current request, or `null`.
803
+ *
804
+ * Mirrors `@nestjs/authentication`'s `@CurrentUser()`: the optional key picks
805
+ * one claim. `AuthGuard` writes the value onto the route context, so a handler
806
+ * decorated with `@Public()` reads `null` rather than throwing.
807
+ *
808
+ * @param key - One claim to read; omitted means the whole user.
809
+ * @returns The parameter decorator.
810
+ */
811
+ const CurrentUser = createParamDecorator((key, context) => {
812
+ const user = context.user ?? null;
813
+ return key !== void 0 && user !== null ? user[key] : user;
814
+ });
815
+ /**
816
+ * The session the current request authenticated with, or `null`.
817
+ *
818
+ * Mirrors `@nestjs/authentication`'s `@CurrentSession()`: the value carries the
819
+ * user, the opaque token, and its verified claims.
820
+ *
821
+ * @returns The parameter decorator.
822
+ */
823
+ const CurrentSession = createParamDecorator((_data, context) => context.session ?? null);
824
+ // src/authorization.decorator.ts
825
+ /** Requires at least one of the named roles. */
826
+ function Roles(...roles) {
827
+ return SetMetadata("roles", Object.freeze([...roles]));
828
+ }
829
+ /** Requires every named permission. */
830
+ function Permissions(...permissions) {
831
+ return SetMetadata("permissions", Object.freeze([...permissions]));
832
+ }
833
+ /** Allows a route without authentication. */
834
+ function Public() {
835
+ return SetMetadata("isPublic", true);
836
+ }
837
+ export { AUTH_TOKEN_OPTIONS, AUTH_USER, AUTH_VERIFIER, AuthGuard, AuthModule, AuthService, CurrentSession, CurrentUser, JwtService, MODULE_OPTIONS_TOKEN, MemoryRefreshTokenStore, MemoryRevocationStore, OidcService, PasswordService, Permissions, PermissionsGuard, Public, RefreshTokenService, RevocationService, Roles, RolesGuard };