@my-nestjs-kit/auth 0.1.0-dev.20261129020438 → 0.1.0-dev.20261129030513
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/README.md +19 -0
- package/dist/strategies/attempt-limiter.d.ts +23 -0
- package/dist/strategies/attempt-limiter.js +26 -0
- package/dist/strategies/auth-strategies.guard.d.ts +21 -0
- package/dist/strategies/auth-strategies.guard.js +78 -0
- package/dist/strategies/auth-strategy.types.d.ts +41 -0
- package/dist/strategies/auth-strategy.types.js +2 -0
- package/dist/strategies/constants.d.ts +2 -0
- package/dist/strategies/constants.js +5 -0
- package/dist/strategies/index.d.ts +8 -0
- package/dist/strategies/index.js +29 -0
- package/dist/strategies/secrets.d.ts +18 -0
- package/dist/strategies/secrets.js +42 -0
- package/dist/strategies/session-cookie.d.ts +18 -0
- package/dist/strategies/session-cookie.js +29 -0
- package/dist/strategies/session-token.d.ts +10 -0
- package/dist/strategies/session-token.js +38 -0
- package/package.json +37 -3
package/README.md
CHANGED
|
@@ -20,6 +20,25 @@ Peers: `@nestjs/common`, `@nestjs/core`, `@nestjs/swagger`, `typeorm`, `jsonwebt
|
|
|
20
20
|
- **Guards:** `AbstractAuthGuard`, `AbstractRefreshJwtTokenGuard`. Route config wins over controller config;
|
|
21
21
|
`@Public()` / `SetAuthConfig({ isPublic: true })` opens a route (guards with `ignorePublic` still run); a guarded
|
|
22
22
|
route with no auth config is denied; `isServerAction` routes pass only with their own server-token guard.
|
|
23
|
+
- **`@my-nestjs-kit/auth/strategies`** (its own entry, loads no JWT / OAuth code): `AuthStrategy` +
|
|
24
|
+
`AuthStrategiesGuard`, a global guard where `@Public()` (the same marker as above) passes, the first strategy that
|
|
25
|
+
proves the caller wins and sets `req.auth = { via, details }`, else 401 (`unauthorizedError` overrides the error),
|
|
26
|
+
with an optional dev-only `bypass`. Registered by `provideAuthStrategies({ inject, useFactory })` (options +
|
|
27
|
+
`APP_GUARD`) or `AuthStrategiesGuard.registerOptions(...)`. Building blocks: stateless signed session token
|
|
28
|
+
`<expiresAt>.<hmac>` (`createSessionToken` / `verifySessionToken`) and its httpOnly cookie (`setSessionCookie` /
|
|
29
|
+
`clearSessionCookie` / `readCookie`, needs `cookie-parser`); `AttemptLimiter`, a Redis fixed-window failure counter
|
|
30
|
+
over `RedisService`; `sameSecret` / `sameHash` (constant time), `readBearer`, `parseOpaqueToken(value, prefix)`,
|
|
31
|
+
`shouldStampLastUsed`. The app keeps key derivation, cookie name, password rule and token storage.
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
providers: [
|
|
35
|
+
SessionStrategy, CliTokenStrategy,
|
|
36
|
+
...provideAuthStrategies({
|
|
37
|
+
inject: [SessionStrategy, CliTokenStrategy, AppConfigService],
|
|
38
|
+
useFactory: (session, cli, config) => ({ strategies: [session, cli], bypass: () => config.authDisabled }),
|
|
39
|
+
}),
|
|
40
|
+
]
|
|
41
|
+
```
|
|
23
42
|
- **Request auth context:** `SetAuthConfig`, `Public`, `AuthConfigsMetaStorage`, `GetUser`, `GetSession`,
|
|
24
43
|
`GetAuthParams`, `AuthParams`, `ErpRequestTarget`, `AuthConfigs`, `AuthTokenType`, `AppWs`.
|
|
25
44
|
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { RedisService } from '@my-nestjs-kit/core';
|
|
2
|
+
/** The part of `RedisService` the limiter uses (a fake in tests). */
|
|
3
|
+
export type AttemptLimiterStore = Pick<RedisService, 'incrInWindow' | 'getCount' | 'del'>;
|
|
4
|
+
export interface AttemptLimiterOptions {
|
|
5
|
+
/** Key of one subject's counter, without the app prefix (the Redis client adds it), e.g. `(ip) => \`login-fail:\${ip}\``. */
|
|
6
|
+
key: (subject: string) => string;
|
|
7
|
+
max: number;
|
|
8
|
+
windowS: number;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Fixed-window failure counter (password guessing): blocked once `max` failures fall in one window; the window
|
|
12
|
+
* starts at the first failure. Check `isBlocked` before verifying the credential, so a right password can't be
|
|
13
|
+
* found by guessing past the limit. Plain class, not a provider: an app extends or builds one per purpose.
|
|
14
|
+
*/
|
|
15
|
+
export declare class AttemptLimiter {
|
|
16
|
+
private readonly store;
|
|
17
|
+
private readonly options;
|
|
18
|
+
constructor(store: AttemptLimiterStore, options: AttemptLimiterOptions);
|
|
19
|
+
isBlocked(subject: string): Promise<boolean>;
|
|
20
|
+
/** Returns the failures in the current window. */
|
|
21
|
+
recordFailure(subject: string): Promise<number>;
|
|
22
|
+
clear(subject: string): Promise<void>;
|
|
23
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AttemptLimiter = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Fixed-window failure counter (password guessing): blocked once `max` failures fall in one window; the window
|
|
6
|
+
* starts at the first failure. Check `isBlocked` before verifying the credential, so a right password can't be
|
|
7
|
+
* found by guessing past the limit. Plain class, not a provider: an app extends or builds one per purpose.
|
|
8
|
+
*/
|
|
9
|
+
class AttemptLimiter {
|
|
10
|
+
constructor(store, options) {
|
|
11
|
+
this.store = store;
|
|
12
|
+
this.options = options;
|
|
13
|
+
}
|
|
14
|
+
async isBlocked(subject) {
|
|
15
|
+
return ((await this.store.getCount(this.options.key(subject))) >=
|
|
16
|
+
this.options.max);
|
|
17
|
+
}
|
|
18
|
+
/** Returns the failures in the current window. */
|
|
19
|
+
recordFailure(subject) {
|
|
20
|
+
return this.store.incrInWindow(this.options.key(subject), this.options.windowS);
|
|
21
|
+
}
|
|
22
|
+
async clear(subject) {
|
|
23
|
+
await this.store.del(this.options.key(subject));
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
exports.AttemptLimiter = AttemptLimiter;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { CanActivate, ExecutionContext, Provider } from '@nestjs/common';
|
|
2
|
+
import { Reflector } from '@nestjs/core';
|
|
3
|
+
import type { AuthStrategiesOptions, AuthStrategiesOptionsProvider, AuthStrategiesRegistration } from './auth-strategy.types';
|
|
4
|
+
/**
|
|
5
|
+
* Global guard over a list of `AuthStrategy`: `@Public()` passes (the same marker `AbstractAuthGuard` honours);
|
|
6
|
+
* else the first strategy that proves the caller wins and sets `req.auth`; else 401. HTTP only: other contexts are
|
|
7
|
+
* denied (a WS / SSE ticket guard on a `@Public()` route covers those).
|
|
8
|
+
*/
|
|
9
|
+
export declare class AuthStrategiesGuard implements CanActivate {
|
|
10
|
+
private readonly reflector;
|
|
11
|
+
private readonly options;
|
|
12
|
+
constructor(reflector: Reflector, options: AuthStrategiesOptions);
|
|
13
|
+
/** The options provider alone; register the guard yourself (or use `provideAuthStrategies`). */
|
|
14
|
+
static registerOptions(registration: AuthStrategiesRegistration): AuthStrategiesOptionsProvider;
|
|
15
|
+
canActivate(ctx: ExecutionContext): Promise<boolean>;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Providers for the app's own auth module: the options and the guard as `APP_GUARD`. A provider list rather than
|
|
19
|
+
* `forRootAsync`, because strategies usually need services of the very module that registers the guard.
|
|
20
|
+
*/
|
|
21
|
+
export declare function provideAuthStrategies(registration: AuthStrategiesRegistration): Provider[];
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
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;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.provideAuthStrategies = exports.AuthStrategiesGuard = void 0;
|
|
16
|
+
const common_1 = require("@nestjs/common");
|
|
17
|
+
const core_1 = require("@nestjs/core");
|
|
18
|
+
const core_2 = require("@my-nestjs-kit/core");
|
|
19
|
+
const Public_decorator_1 = require("../decorators/Public.decorator");
|
|
20
|
+
const constants_1 = require("./constants");
|
|
21
|
+
/**
|
|
22
|
+
* Global guard over a list of `AuthStrategy`: `@Public()` passes (the same marker `AbstractAuthGuard` honours);
|
|
23
|
+
* else the first strategy that proves the caller wins and sets `req.auth`; else 401. HTTP only: other contexts are
|
|
24
|
+
* denied (a WS / SSE ticket guard on a `@Public()` route covers those).
|
|
25
|
+
*/
|
|
26
|
+
let AuthStrategiesGuard = class AuthStrategiesGuard {
|
|
27
|
+
constructor(reflector, options) {
|
|
28
|
+
this.reflector = reflector;
|
|
29
|
+
this.options = options;
|
|
30
|
+
}
|
|
31
|
+
/** The options provider alone; register the guard yourself (or use `provideAuthStrategies`). */
|
|
32
|
+
static registerOptions(registration) {
|
|
33
|
+
return {
|
|
34
|
+
provide: constants_1.AUTH_STRATEGIES_OPTIONS,
|
|
35
|
+
inject: registration.inject ?? [],
|
|
36
|
+
useFactory: registration.useFactory,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
async canActivate(ctx) {
|
|
40
|
+
if ((0, Public_decorator_1.isPublicRoute)(this.reflector, ctx.getHandler(), ctx.getClass())) {
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
if (ctx.getType() !== 'http')
|
|
44
|
+
return false;
|
|
45
|
+
const req = ctx.switchToHttp().getRequest();
|
|
46
|
+
if (this.options.bypass?.()) {
|
|
47
|
+
req.auth = { via: 'bypass' };
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
for (const strategy of this.options.strategies) {
|
|
51
|
+
const identity = await strategy.authenticate(req);
|
|
52
|
+
if (identity) {
|
|
53
|
+
req.auth = identity;
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
throw this.options.unauthorizedError
|
|
58
|
+
? this.options.unauthorizedError()
|
|
59
|
+
: new core_2.AppHttpException({ statusCode: common_1.HttpStatus.UNAUTHORIZED });
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
exports.AuthStrategiesGuard = AuthStrategiesGuard;
|
|
63
|
+
exports.AuthStrategiesGuard = AuthStrategiesGuard = __decorate([
|
|
64
|
+
(0, common_1.Injectable)(),
|
|
65
|
+
__param(1, (0, common_1.Inject)(constants_1.AUTH_STRATEGIES_OPTIONS)),
|
|
66
|
+
__metadata("design:paramtypes", [core_1.Reflector, Object])
|
|
67
|
+
], AuthStrategiesGuard);
|
|
68
|
+
/**
|
|
69
|
+
* Providers for the app's own auth module: the options and the guard as `APP_GUARD`. A provider list rather than
|
|
70
|
+
* `forRootAsync`, because strategies usually need services of the very module that registers the guard.
|
|
71
|
+
*/
|
|
72
|
+
function provideAuthStrategies(registration) {
|
|
73
|
+
return [
|
|
74
|
+
AuthStrategiesGuard.registerOptions(registration),
|
|
75
|
+
{ provide: core_1.APP_GUARD, useClass: AuthStrategiesGuard },
|
|
76
|
+
];
|
|
77
|
+
}
|
|
78
|
+
exports.provideAuthStrategies = provideAuthStrategies;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { FactoryProvider, InjectionToken } from '@nestjs/common';
|
|
2
|
+
import type { Request } from 'express';
|
|
3
|
+
/** What a strategy proved about the caller; the guard puts it on `req.auth`. */
|
|
4
|
+
export interface AuthIdentity {
|
|
5
|
+
/** Which strategy matched (`session`, `cli`, …), or `bypass`. */
|
|
6
|
+
via: string;
|
|
7
|
+
/** Strategy-specific details (token public view, scope…). Never a secret: it is readable by every handler. */
|
|
8
|
+
details?: unknown;
|
|
9
|
+
}
|
|
10
|
+
export type AuthStrategyResult = AuthIdentity | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* One way in. Returns the identity or undefined; never throws for "not mine / wrong": only the guard answers 401,
|
|
13
|
+
* so strategies stay composable and a failing one can't mask the next.
|
|
14
|
+
*/
|
|
15
|
+
export interface AuthStrategy {
|
|
16
|
+
readonly name: string;
|
|
17
|
+
authenticate(req: Request): Promise<AuthStrategyResult> | AuthStrategyResult;
|
|
18
|
+
}
|
|
19
|
+
export interface AuthStrategiesOptions {
|
|
20
|
+
/** Tried in order; the first match wins. */
|
|
21
|
+
strategies: AuthStrategy[];
|
|
22
|
+
/** Dev-only switch that lets every request in as `{ via: 'bypass' }`. The app must return false in production. */
|
|
23
|
+
bypass?: () => boolean;
|
|
24
|
+
/** The error thrown when no strategy matches. Default: a 401 `AppHttpException`. */
|
|
25
|
+
unauthorizedError?: () => Error;
|
|
26
|
+
}
|
|
27
|
+
export type AuthStrategiesOptionsFactory = (...deps: any[]) => AuthStrategiesOptions | Promise<AuthStrategiesOptions>;
|
|
28
|
+
/** `inject` + `useFactory`, like a `forRootAsync`: strategies are usually providers of the module that registers this. */
|
|
29
|
+
export interface AuthStrategiesRegistration {
|
|
30
|
+
inject?: InjectionToken[];
|
|
31
|
+
useFactory: AuthStrategiesOptionsFactory;
|
|
32
|
+
}
|
|
33
|
+
export type AuthStrategiesOptionsProvider = FactoryProvider<AuthStrategiesOptions>;
|
|
34
|
+
declare global {
|
|
35
|
+
namespace Express {
|
|
36
|
+
interface Request {
|
|
37
|
+
/** Set by `AuthStrategiesGuard` on a guarded route. */
|
|
38
|
+
auth?: AuthIdentity;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AUTH_STRATEGIES_OPTIONS = void 0;
|
|
4
|
+
/** Injection token of the `AuthStrategiesOptions` the `AuthStrategiesGuard` reads. */
|
|
5
|
+
exports.AUTH_STRATEGIES_OPTIONS = Symbol('my-nestjs-kit:auth:strategiesOptions');
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { Public, isPublicRoute } from '../decorators/Public.decorator';
|
|
2
|
+
export * from './auth-strategy.types';
|
|
3
|
+
export * from './auth-strategies.guard';
|
|
4
|
+
export * from './constants';
|
|
5
|
+
export * from './session-token';
|
|
6
|
+
export * from './session-cookie';
|
|
7
|
+
export * from './secrets';
|
|
8
|
+
export * from './attempt-limiter';
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.isPublicRoute = exports.Public = void 0;
|
|
18
|
+
// @my-nestjs-kit/auth/strategies — strategy guard, stateless signed session token + cookie, attempt limiter,
|
|
19
|
+
// constant-time secret helpers. Loads no JWT / OAuth code: an app that only needs this imports only this entry.
|
|
20
|
+
var Public_decorator_1 = require("../decorators/Public.decorator");
|
|
21
|
+
Object.defineProperty(exports, "Public", { enumerable: true, get: function () { return Public_decorator_1.Public; } });
|
|
22
|
+
Object.defineProperty(exports, "isPublicRoute", { enumerable: true, get: function () { return Public_decorator_1.isPublicRoute; } });
|
|
23
|
+
__exportStar(require("./auth-strategy.types"), exports);
|
|
24
|
+
__exportStar(require("./auth-strategies.guard"), exports);
|
|
25
|
+
__exportStar(require("./constants"), exports);
|
|
26
|
+
__exportStar(require("./session-token"), exports);
|
|
27
|
+
__exportStar(require("./session-cookie"), exports);
|
|
28
|
+
__exportStar(require("./secrets"), exports);
|
|
29
|
+
__exportStar(require("./attempt-limiter"), exports);
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Request } from 'express';
|
|
2
|
+
/** Constant-time compare of two secrets of any length (fixed-length digests: no length leak, no throw). */
|
|
3
|
+
export declare function sameSecret(candidate: string, expected: string): boolean;
|
|
4
|
+
/** Constant-time compare of two encoded hashes of the same scheme; false on length mismatch. */
|
|
5
|
+
export declare function sameHash(given: string, expected: string): boolean;
|
|
6
|
+
/** The token of `Authorization: Bearer <token>`, or undefined. */
|
|
7
|
+
export declare function readBearer(req: Request): string | undefined;
|
|
8
|
+
export interface OpaqueTokenParts {
|
|
9
|
+
id: string;
|
|
10
|
+
secret: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Splits an opaque token `<prefix><id><sep><secret>` (e.g. `app_<id>.<secret>`); undefined when the shape is wrong.
|
|
14
|
+
* The app looks the id up and compares the secret's hash with `sameHash`.
|
|
15
|
+
*/
|
|
16
|
+
export declare function parseOpaqueToken(value: string | undefined, prefix: string, sep?: string): OpaqueTokenParts | undefined;
|
|
17
|
+
/** `lastUsedAt` is a hint, not an audit log: stamp it at most once per resolution window. */
|
|
18
|
+
export declare function shouldStampLastUsed(lastUsedAt: Date | number | null | undefined, now: number, resolutionMs: number): boolean;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.shouldStampLastUsed = exports.parseOpaqueToken = exports.readBearer = exports.sameHash = exports.sameSecret = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
/** Constant-time compare of two secrets of any length (fixed-length digests: no length leak, no throw). */
|
|
6
|
+
function sameSecret(candidate, expected) {
|
|
7
|
+
const a = (0, node_crypto_1.createHash)('sha256').update(candidate).digest();
|
|
8
|
+
const b = (0, node_crypto_1.createHash)('sha256').update(expected).digest();
|
|
9
|
+
return (0, node_crypto_1.timingSafeEqual)(a, b);
|
|
10
|
+
}
|
|
11
|
+
exports.sameSecret = sameSecret;
|
|
12
|
+
/** Constant-time compare of two encoded hashes of the same scheme; false on length mismatch. */
|
|
13
|
+
function sameHash(given, expected) {
|
|
14
|
+
const a = Buffer.from(given);
|
|
15
|
+
const b = Buffer.from(expected);
|
|
16
|
+
return a.length === b.length && (0, node_crypto_1.timingSafeEqual)(a, b);
|
|
17
|
+
}
|
|
18
|
+
exports.sameHash = sameHash;
|
|
19
|
+
/** The token of `Authorization: Bearer <token>`, or undefined. */
|
|
20
|
+
function readBearer(req) {
|
|
21
|
+
return /^Bearer\s+(\S+)$/i.exec(req.headers.authorization ?? '')?.[1];
|
|
22
|
+
}
|
|
23
|
+
exports.readBearer = readBearer;
|
|
24
|
+
/**
|
|
25
|
+
* Splits an opaque token `<prefix><id><sep><secret>` (e.g. `app_<id>.<secret>`); undefined when the shape is wrong.
|
|
26
|
+
* The app looks the id up and compares the secret's hash with `sameHash`.
|
|
27
|
+
*/
|
|
28
|
+
function parseOpaqueToken(value, prefix, sep = '.') {
|
|
29
|
+
if (!value?.startsWith(prefix))
|
|
30
|
+
return undefined;
|
|
31
|
+
const parts = value.slice(prefix.length).split(sep);
|
|
32
|
+
if (parts.length !== 2 || !parts[0] || !parts[1])
|
|
33
|
+
return undefined;
|
|
34
|
+
return { id: parts[0], secret: parts[1] };
|
|
35
|
+
}
|
|
36
|
+
exports.parseOpaqueToken = parseOpaqueToken;
|
|
37
|
+
/** `lastUsedAt` is a hint, not an audit log: stamp it at most once per resolution window. */
|
|
38
|
+
function shouldStampLastUsed(lastUsedAt, now, resolutionMs) {
|
|
39
|
+
const last = lastUsedAt instanceof Date ? lastUsedAt.getTime() : (lastUsedAt ?? 0);
|
|
40
|
+
return now - last > resolutionMs;
|
|
41
|
+
}
|
|
42
|
+
exports.shouldStampLastUsed = shouldStampLastUsed;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Request, Response } from 'express';
|
|
2
|
+
export type SessionCookieSameSite = 'strict' | 'lax';
|
|
3
|
+
export interface SessionCookieOptions {
|
|
4
|
+
name: string;
|
|
5
|
+
ttlMs: number;
|
|
6
|
+
/** true behind HTTPS (production runtime). */
|
|
7
|
+
secure: boolean;
|
|
8
|
+
/** Default `strict`; `lax` when the cookie must survive a top-level redirect from another site. */
|
|
9
|
+
sameSite?: SessionCookieSameSite;
|
|
10
|
+
/** Default `/`. */
|
|
11
|
+
path?: string;
|
|
12
|
+
}
|
|
13
|
+
/** A string cookie, or undefined. Needs `cookie-parser`. */
|
|
14
|
+
export declare function readCookie(req: Request, name: string): string | undefined;
|
|
15
|
+
/** httpOnly session cookie. */
|
|
16
|
+
export declare function setSessionCookie(res: Response, o: SessionCookieOptions, value: string): void;
|
|
17
|
+
/** Clears it with the same attributes it was set with (else the browser keeps it). */
|
|
18
|
+
export declare function clearSessionCookie(res: Response, o: SessionCookieOptions): void;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.clearSessionCookie = exports.setSessionCookie = exports.readCookie = void 0;
|
|
4
|
+
function cookieOptions(o) {
|
|
5
|
+
return {
|
|
6
|
+
httpOnly: true,
|
|
7
|
+
sameSite: o.sameSite ?? 'strict',
|
|
8
|
+
secure: o.secure,
|
|
9
|
+
path: o.path ?? '/',
|
|
10
|
+
maxAge: o.ttlMs,
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
/** A string cookie, or undefined. Needs `cookie-parser`. */
|
|
14
|
+
function readCookie(req, name) {
|
|
15
|
+
const value = req.cookies?.[name];
|
|
16
|
+
return typeof value === 'string' ? value : undefined;
|
|
17
|
+
}
|
|
18
|
+
exports.readCookie = readCookie;
|
|
19
|
+
/** httpOnly session cookie. */
|
|
20
|
+
function setSessionCookie(res, o, value) {
|
|
21
|
+
res.cookie(o.name, value, cookieOptions(o));
|
|
22
|
+
}
|
|
23
|
+
exports.setSessionCookie = setSessionCookie;
|
|
24
|
+
/** Clears it with the same attributes it was set with (else the browser keeps it). */
|
|
25
|
+
function clearSessionCookie(res, o) {
|
|
26
|
+
const { maxAge: _maxAge, ...rest } = cookieOptions(o);
|
|
27
|
+
res.clearCookie(o.name, rest);
|
|
28
|
+
}
|
|
29
|
+
exports.clearSessionCookie = clearSessionCookie;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
/** base64url HMAC-SHA256 of `payload`. */
|
|
3
|
+
export declare function signPayload(key: Buffer, payload: string): string;
|
|
4
|
+
/**
|
|
5
|
+
* Stateless session token `<expiresAt>.<hmac(expiresAt)>`: no user row, no session row, any instance with the same
|
|
6
|
+
* key verifies it. Revocation = rotating the key. The app owns the key (derivation, rotation, storage).
|
|
7
|
+
*/
|
|
8
|
+
export declare function createSessionToken(key: Buffer, ttlMs: number, now?: number): string;
|
|
9
|
+
/** True for a token signed with `key` and not expired. A null key (none configured) accepts nothing. */
|
|
10
|
+
export declare function verifySessionToken(key: Buffer | null, token: string | undefined, now?: number): boolean;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.verifySessionToken = exports.createSessionToken = exports.signPayload = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
/** Longer tokens are rejected before any HMAC work (an epoch-ms + a base64url SHA-256 is ~57 chars). */
|
|
6
|
+
const SESSION_TOKEN_MAX_LENGTH = 256;
|
|
7
|
+
/** base64url HMAC-SHA256 of `payload`. */
|
|
8
|
+
function signPayload(key, payload) {
|
|
9
|
+
return (0, node_crypto_1.createHmac)('sha256', key).update(payload).digest('base64url');
|
|
10
|
+
}
|
|
11
|
+
exports.signPayload = signPayload;
|
|
12
|
+
/**
|
|
13
|
+
* Stateless session token `<expiresAt>.<hmac(expiresAt)>`: no user row, no session row, any instance with the same
|
|
14
|
+
* key verifies it. Revocation = rotating the key. The app owns the key (derivation, rotation, storage).
|
|
15
|
+
*/
|
|
16
|
+
function createSessionToken(key, ttlMs, now = Date.now()) {
|
|
17
|
+
const expiresAt = String(now + ttlMs);
|
|
18
|
+
return `${expiresAt}.${signPayload(key, expiresAt)}`;
|
|
19
|
+
}
|
|
20
|
+
exports.createSessionToken = createSessionToken;
|
|
21
|
+
/** True for a token signed with `key` and not expired. A null key (none configured) accepts nothing. */
|
|
22
|
+
function verifySessionToken(key, token, now = Date.now()) {
|
|
23
|
+
if (!key || !token || token.length > SESSION_TOKEN_MAX_LENGTH)
|
|
24
|
+
return false;
|
|
25
|
+
const dot = token.indexOf('.');
|
|
26
|
+
if (dot === -1)
|
|
27
|
+
return false;
|
|
28
|
+
const expiresAt = token.slice(0, dot);
|
|
29
|
+
if (!/^\d{1,16}$/.test(expiresAt))
|
|
30
|
+
return false;
|
|
31
|
+
const given = Buffer.from(token.slice(dot + 1));
|
|
32
|
+
const expected = Buffer.from(signPayload(key, expiresAt));
|
|
33
|
+
if (given.length !== expected.length || !(0, node_crypto_1.timingSafeEqual)(given, expected)) {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
return Number(expiresAt) > now;
|
|
37
|
+
}
|
|
38
|
+
exports.verifySessionToken = verifySessionToken;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@my-nestjs-kit/auth",
|
|
3
|
-
"version": "0.1.0-dev.
|
|
3
|
+
"version": "0.1.0-dev.20261129030513",
|
|
4
4
|
"description": "NestJS auth bases: JWT engine with key rotation, auth and session service bases, OAuth bases, guard bases, route auth config and request auth decorators, access tokens.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"nestjs",
|
|
@@ -34,8 +34,20 @@
|
|
|
34
34
|
"require": "./dist/index.js",
|
|
35
35
|
"default": "./dist/index.js"
|
|
36
36
|
},
|
|
37
|
+
"./strategies": {
|
|
38
|
+
"types": "./dist/strategies/index.d.ts",
|
|
39
|
+
"require": "./dist/strategies/index.js",
|
|
40
|
+
"default": "./dist/strategies/index.js"
|
|
41
|
+
},
|
|
37
42
|
"./package.json": "./package.json"
|
|
38
43
|
},
|
|
44
|
+
"typesVersions": {
|
|
45
|
+
"*": {
|
|
46
|
+
"strategies": [
|
|
47
|
+
"dist/strategies/index.d.ts"
|
|
48
|
+
]
|
|
49
|
+
}
|
|
50
|
+
},
|
|
39
51
|
"files": [
|
|
40
52
|
"dist",
|
|
41
53
|
"!dist/**/*.spec.*",
|
|
@@ -44,7 +56,7 @@
|
|
|
44
56
|
"LICENSE"
|
|
45
57
|
],
|
|
46
58
|
"dependencies": {
|
|
47
|
-
"@my-nestjs-kit/core": "^0.1.0-dev.
|
|
59
|
+
"@my-nestjs-kit/core": "^0.1.0-dev.20261129030513",
|
|
48
60
|
"nanoid": "^3.3.7"
|
|
49
61
|
},
|
|
50
62
|
"peerDependencies": {
|
|
@@ -73,6 +85,7 @@
|
|
|
73
85
|
"@nestjs/websockets": "10.4.1",
|
|
74
86
|
"@types/bcryptjs": "2.4.6",
|
|
75
87
|
"@types/express": "4.17.21",
|
|
88
|
+
"@types/jest": "29.5.12",
|
|
76
89
|
"@types/jsonwebtoken": "9.0.5",
|
|
77
90
|
"@types/lodash": "4.17.0",
|
|
78
91
|
"@types/node": "20.11.28",
|
|
@@ -83,16 +96,37 @@
|
|
|
83
96
|
"date-fns": "3.5.0",
|
|
84
97
|
"decimal.js": "10.4.3",
|
|
85
98
|
"ioredis": "5.8.2",
|
|
99
|
+
"jest": "29.7.0",
|
|
86
100
|
"jsonwebtoken": "9.0.2",
|
|
87
101
|
"lodash": "4.17.21",
|
|
88
102
|
"reflect-metadata": "0.2.2",
|
|
89
103
|
"rxjs": "7.8.1",
|
|
104
|
+
"ts-jest": "29.1.2",
|
|
90
105
|
"typeorm": "0.3.28",
|
|
91
106
|
"typescript": "5.4.2"
|
|
92
107
|
},
|
|
108
|
+
"jest": {
|
|
109
|
+
"moduleFileExtensions": [
|
|
110
|
+
"js",
|
|
111
|
+
"json",
|
|
112
|
+
"ts"
|
|
113
|
+
],
|
|
114
|
+
"rootDir": "src",
|
|
115
|
+
"testRegex": ".*\\.spec\\.ts$",
|
|
116
|
+
"transform": {
|
|
117
|
+
"^.+\\.ts$": [
|
|
118
|
+
"ts-jest",
|
|
119
|
+
{
|
|
120
|
+
"tsconfig": "<rootDir>/../tsconfig.spec.json"
|
|
121
|
+
}
|
|
122
|
+
]
|
|
123
|
+
},
|
|
124
|
+
"testEnvironment": "node"
|
|
125
|
+
},
|
|
93
126
|
"scripts": {
|
|
94
127
|
"build": "rm -rf dist && tsc -p tsconfig.json",
|
|
95
128
|
"build:watch": "tsc -p tsconfig.json --watch",
|
|
96
|
-
"typecheck": "tsc -p tsconfig.json
|
|
129
|
+
"typecheck": "tsc -p tsconfig.spec.json",
|
|
130
|
+
"test": "jest"
|
|
97
131
|
}
|
|
98
132
|
}
|