barejs 0.1.51 → 0.1.54
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 +50 -29
- package/dist/index.js +95 -86
- package/dist/types/core/bare.d.ts +10 -2
- package/dist/types/core/context.d.ts +2 -1
- package/dist/types/core/router.d.ts +61 -10
- package/dist/types/index.d.ts +5 -4
- package/dist/types/security/auth.d.ts +17 -4
- package/dist/types/security/idempotency.d.ts +3 -0
- package/dist/types/security/rateLimit.d.ts +3 -0
- package/dist/types/security/store.d.ts +36 -0
- package/dist/types/utils/compress.d.ts +6 -3
- package/dist/types/utils/static.d.ts +8 -0
- package/llms.txt +19 -20
- package/package.json +1 -1
- package/src/client/index.ts +4 -3
- package/src/core/bare.ts +110 -58
- package/src/core/context.ts +67 -33
- package/src/core/radix.ts +3 -1
- package/src/core/router.ts +94 -16
- package/src/index.ts +13 -4
- package/src/security/auth.ts +282 -49
- package/src/security/cors.ts +25 -1
- package/src/security/csrf.ts +8 -1
- package/src/security/idempotency.ts +127 -26
- package/src/security/rateLimit.ts +40 -22
- package/src/security/store.ts +159 -0
- package/src/security/validators.ts +10 -4
- package/src/utils/compress.ts +50 -7
- package/src/utils/static.ts +69 -16
package/src/core/router.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
|
+
type Context,
|
|
2
3
|
type Middleware,
|
|
3
4
|
type Handler,
|
|
4
5
|
type GroupCallback
|
|
5
6
|
} from '../core/context';
|
|
6
7
|
import { schemaValidator, type RouteSchemas } from '../security/validators';
|
|
7
8
|
|
|
8
|
-
import type { RouteSchema } from '../client/index';
|
|
9
|
+
import type { RouteEndpoint, RouteSchema } from '../client/index';
|
|
9
10
|
|
|
10
11
|
type HandlersChain = (Middleware | Handler | RouteSchemas)[];
|
|
11
12
|
|
|
@@ -14,6 +15,59 @@ export type InferSchema<S> =
|
|
|
14
15
|
: S extends { _output: infer T } ? T
|
|
15
16
|
: any;
|
|
16
17
|
|
|
18
|
+
type StripLeadingSlash<S extends string> = S extends `/${infer Rest}` ? StripLeadingSlash<Rest> : S;
|
|
19
|
+
type StripTrailingSlash<S extends string> = S extends `${infer Rest}/` ? StripTrailingSlash<Rest> : S;
|
|
20
|
+
type NormalizePrefix<P extends string> = StripTrailingSlash<StripLeadingSlash<P>> extends ''
|
|
21
|
+
? ''
|
|
22
|
+
: `/${StripTrailingSlash<StripLeadingSlash<P>>}`;
|
|
23
|
+
|
|
24
|
+
type JoinPath<P extends string, Sub extends string> =
|
|
25
|
+
NormalizePrefix<P> extends ''
|
|
26
|
+
? (Sub extends '' ? '/' : (Sub extends `/${string}` ? Sub : `/${Sub}`))
|
|
27
|
+
: (StripLeadingSlash<Sub> extends ''
|
|
28
|
+
? NormalizePrefix<P>
|
|
29
|
+
: `${NormalizePrefix<P>}/${StripLeadingSlash<Sub>}`);
|
|
30
|
+
|
|
31
|
+
export type PrefixRoutes<P extends string, R extends RouteSchema> = {
|
|
32
|
+
[K in keyof R as K extends `${infer M} ${infer Sub}`
|
|
33
|
+
? `${M} ${JoinPath<P, Sub>}`
|
|
34
|
+
: K]: R[K] extends infer E extends RouteEndpoint
|
|
35
|
+
? Omit<E, 'path'> & {
|
|
36
|
+
path: E['path'] extends string
|
|
37
|
+
? JoinPath<P, E['path']>
|
|
38
|
+
: JoinPath<P, K extends `${string} ${infer Sub}` ? Sub : (K & string)>;
|
|
39
|
+
}
|
|
40
|
+
: R[K];
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
type TypedRouterHandler<S extends RouteSchemas, Res> = (
|
|
44
|
+
ctx: Context & {
|
|
45
|
+
body: S extends { body: infer B } ? InferSchema<B> : any;
|
|
46
|
+
query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, string>;
|
|
47
|
+
params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
|
|
48
|
+
}
|
|
49
|
+
) => Res | Promise<Res>;
|
|
50
|
+
|
|
51
|
+
type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
|
|
52
|
+
<P extends string, S extends RouteSchemas, Res = S extends { response: infer R } ? InferSchema<R> : any>(
|
|
53
|
+
path: P,
|
|
54
|
+
schemas: S,
|
|
55
|
+
handler: TypedRouterHandler<S, Res>
|
|
56
|
+
): BareRouter<Routes & Record<`${M} ${P}`, {
|
|
57
|
+
method: M;
|
|
58
|
+
path: P;
|
|
59
|
+
params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
|
|
60
|
+
query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, any>;
|
|
61
|
+
headers: S extends { headers: infer H } ? InferSchema<H> : Record<string, string>;
|
|
62
|
+
body: S extends { body: infer B } ? InferSchema<B> : any;
|
|
63
|
+
response: S extends { response: infer R } ? InferSchema<R> : Awaited<Res>;
|
|
64
|
+
}>>;
|
|
65
|
+
<P extends string, Res = any>(
|
|
66
|
+
path: P,
|
|
67
|
+
...handlers: any[]
|
|
68
|
+
): BareRouter<Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res> }>>;
|
|
69
|
+
};
|
|
70
|
+
|
|
17
71
|
export class BareRouter<Routes extends RouteSchema = {}> {
|
|
18
72
|
declare readonly __routes: Routes;
|
|
19
73
|
public routes: any[] = [];
|
|
@@ -47,19 +101,19 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
47
101
|
return this;
|
|
48
102
|
}
|
|
49
103
|
|
|
50
|
-
public get:
|
|
51
|
-
public post:
|
|
52
|
-
public put:
|
|
53
|
-
public patch:
|
|
54
|
-
public delete:
|
|
55
|
-
public options:
|
|
56
|
-
public head:
|
|
57
|
-
public all:
|
|
104
|
+
public get: AddRouterRoute<Routes, 'GET'> = ((path: string, ...h: HandlersChain) => this._add("GET", path, h)) as any;
|
|
105
|
+
public post: AddRouterRoute<Routes, 'POST'> = ((path: string, ...h: HandlersChain) => this._add("POST", path, h)) as any;
|
|
106
|
+
public put: AddRouterRoute<Routes, 'PUT'> = ((path: string, ...h: HandlersChain) => this._add("PUT", path, h)) as any;
|
|
107
|
+
public patch: AddRouterRoute<Routes, 'PATCH'> = ((path: string, ...h: HandlersChain) => this._add("PATCH", path, h)) as any;
|
|
108
|
+
public delete: AddRouterRoute<Routes, 'DELETE'> = ((path: string, ...h: HandlersChain) => this._add("DELETE", path, h)) as any;
|
|
109
|
+
public options: AddRouterRoute<Routes, 'OPTIONS'> = ((path: string, ...h: HandlersChain) => this._add("OPTIONS", path, h)) as any;
|
|
110
|
+
public head: AddRouterRoute<Routes, 'HEAD'> = ((path: string, ...h: HandlersChain) => this._add("HEAD", path, h)) as any;
|
|
111
|
+
public all: AddRouterRoute<Routes, 'ALL'> = ((path: string, ...h: HandlersChain) => {
|
|
58
112
|
for (const m of ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]) {
|
|
59
113
|
this._add(m, path, h);
|
|
60
114
|
}
|
|
61
115
|
return this;
|
|
62
|
-
};
|
|
116
|
+
}) as any;
|
|
63
117
|
|
|
64
118
|
public group = (path: string, ...args: any[]) => {
|
|
65
119
|
const callback = args.pop();
|
|
@@ -73,15 +127,39 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
73
127
|
return this;
|
|
74
128
|
};
|
|
75
129
|
|
|
130
|
+
private _mountRouter(prefix: string, router: BareRouter<any>) {
|
|
131
|
+
const base = (this.prefix + "/" + prefix).replace(/\/+/g, "/").replace(/\/$/, "");
|
|
132
|
+
for (const r of router.routes) {
|
|
133
|
+
let fullPath = (base + "/" + r.path).replace(/\/+/g, "/");
|
|
134
|
+
if (fullPath.endsWith("/")) fullPath = fullPath.slice(0, -1);
|
|
135
|
+
this.routes.push({
|
|
136
|
+
method: r.method,
|
|
137
|
+
path: fullPath || "",
|
|
138
|
+
handlers: [...this.groupMiddleware, ...r.handlers]
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
public route<P extends string, R2 extends RouteSchema = {}>(
|
|
144
|
+
prefix: P,
|
|
145
|
+
router: BareRouter<R2>
|
|
146
|
+
): BareRouter<Routes & PrefixRoutes<P, R2>> {
|
|
147
|
+
this._mountRouter(prefix, router);
|
|
148
|
+
return this as any;
|
|
149
|
+
}
|
|
150
|
+
|
|
76
151
|
public use<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareRouter<Routes & R2>;
|
|
152
|
+
public use<P extends string, R2 extends RouteSchema = {}>(prefix: P, mw: BareRouter<R2>): BareRouter<Routes & PrefixRoutes<P, R2>>;
|
|
77
153
|
public use(mw: any): BareRouter<Routes>;
|
|
78
|
-
public use(
|
|
79
|
-
if (
|
|
80
|
-
this.
|
|
81
|
-
} else if (
|
|
82
|
-
|
|
154
|
+
public use(prefixOrMw: any, maybeMw?: any): any {
|
|
155
|
+
if (typeof prefixOrMw === 'string' && (maybeMw instanceof BareRouter || (maybeMw && maybeMw.routes))) {
|
|
156
|
+
this._mountRouter(prefixOrMw, maybeMw);
|
|
157
|
+
} else if (prefixOrMw instanceof BareRouter || (prefixOrMw && prefixOrMw.routes)) {
|
|
158
|
+
this._mountRouter("", prefixOrMw);
|
|
159
|
+
} else if (prefixOrMw && typeof prefixOrMw.install === 'function') {
|
|
160
|
+
prefixOrMw.install(this);
|
|
83
161
|
} else {
|
|
84
|
-
this.groupMiddleware.push(
|
|
162
|
+
this.groupMiddleware.push(prefixOrMw);
|
|
85
163
|
}
|
|
86
164
|
return this;
|
|
87
165
|
}
|
package/src/index.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
// --- 1. Core Engine ---
|
|
9
9
|
export { BareJS, type WebSocketRouteHandler, type CronOptions } from './core/bare';
|
|
10
|
-
export { BareRouter, type InferSchema } from './core/router';
|
|
10
|
+
export { BareRouter, type InferSchema, type PrefixRoutes } from './core/router';
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* Plugin Interface for BareJS
|
|
@@ -66,15 +66,24 @@ export { csrf, type CsrfOptions } from './security/csrf';
|
|
|
66
66
|
export { timeout, type TimeoutOptions } from './security/timeout';
|
|
67
67
|
export { rateLimit, type RateLimitOptions } from './security/rateLimit';
|
|
68
68
|
export { idempotency, createSingleflight, type IdempotencyOptions } from './security/idempotency';
|
|
69
|
+
export {
|
|
70
|
+
redisStore,
|
|
71
|
+
type BareStore,
|
|
72
|
+
type RateLimitStore,
|
|
73
|
+
type IdempotencyStore,
|
|
74
|
+
type CachedIdempotentEntry,
|
|
75
|
+
type RevocationStore,
|
|
76
|
+
type RedisStoreOptions,
|
|
77
|
+
} from './security/store';
|
|
69
78
|
export { circuitBreaker, type CircuitBreakerOptions, type CircuitState } from './security/resilience';
|
|
70
79
|
export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
|
|
71
|
-
export { staticFile, type StaticOptions } from './utils/static';
|
|
72
|
-
export { compress, type CompressOptions } from './utils/compress';
|
|
80
|
+
export { staticFile, type StaticOptions, type StaticMetadataCacheOptions } from './utils/static';
|
|
81
|
+
export { compress, type CompressOptions, type CompressionEncoding } from './utils/compress';
|
|
73
82
|
export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
|
|
74
83
|
|
|
75
84
|
// --- 6. Authentication (Bun Native) ---
|
|
76
85
|
// Always deploy using process.env [2026-01-06]
|
|
77
|
-
export { bareAuth, createToken, basicAuth, hasRole, revokeToken, isTokenRevoked, type BareAuthOptions } from './security/auth';
|
|
86
|
+
export { bareAuth, createToken, basicAuth, hasRole, revokeToken, isTokenRevoked, type BareAuthOptions, type JwtAlgorithm } from './security/auth';
|
|
78
87
|
// --- 7. Hashing ---
|
|
79
88
|
export { Hash as Password, Hash } from './security/hash';
|
|
80
89
|
|
package/src/security/auth.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Next } from '../core/context';
|
|
2
|
+
import type { RevocationStore } from './store';
|
|
2
3
|
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
|
|
3
4
|
|
|
4
5
|
/**
|
|
@@ -9,9 +10,7 @@ const encoder = new TextEncoder();
|
|
|
9
10
|
|
|
10
11
|
// Base64Url Helpers (RFC 4648) using native C++ Buffer encoding
|
|
11
12
|
const base64Url = (input: Uint8Array | string): string => {
|
|
12
|
-
return
|
|
13
|
-
? Buffer.from(input).toString('base64url')
|
|
14
|
-
: Buffer.from(input).toString('base64url');
|
|
13
|
+
return Buffer.from(input).toString('base64url');
|
|
15
14
|
};
|
|
16
15
|
|
|
17
16
|
const fromBase64Url = (str: string): string => {
|
|
@@ -58,8 +57,14 @@ const revokedTokens = new Map<string, number>();
|
|
|
58
57
|
|
|
59
58
|
/**
|
|
60
59
|
* Revoke a JWT token or JTI for ttlMs (default: 1 hour).
|
|
60
|
+
* Optionally delegates to an external RevocationStore (e.g. redisStore).
|
|
61
61
|
*/
|
|
62
|
-
export
|
|
62
|
+
export function revokeToken(tokenOrJti: string, ttlMs?: number): void;
|
|
63
|
+
export function revokeToken(tokenOrJti: string, ttlMs: number, store: RevocationStore): Promise<void>;
|
|
64
|
+
export function revokeToken(tokenOrJti: string, ttlMs: number = 3600_000, store?: RevocationStore): void | Promise<void> {
|
|
65
|
+
if (store) {
|
|
66
|
+
return store.revoke(tokenOrJti, ttlMs);
|
|
67
|
+
}
|
|
63
68
|
if (revokedTokens.size >= 10_000) {
|
|
64
69
|
const now = Date.now();
|
|
65
70
|
for (const [k, exp] of revokedTokens) {
|
|
@@ -71,9 +76,14 @@ export const revokeToken = (tokenOrJti: string, ttlMs: number = 3600_000): void
|
|
|
71
76
|
}
|
|
72
77
|
}
|
|
73
78
|
revokedTokens.set(tokenOrJti, Date.now() + ttlMs);
|
|
74
|
-
}
|
|
79
|
+
}
|
|
75
80
|
|
|
76
|
-
export
|
|
81
|
+
export function isTokenRevoked(tokenOrJti: string): boolean;
|
|
82
|
+
export function isTokenRevoked(tokenOrJti: string, store: RevocationStore): Promise<boolean>;
|
|
83
|
+
export function isTokenRevoked(tokenOrJti: string, store?: RevocationStore): boolean | Promise<boolean> {
|
|
84
|
+
if (store) {
|
|
85
|
+
return store.isRevoked(tokenOrJti);
|
|
86
|
+
}
|
|
77
87
|
const exp = revokedTokens.get(tokenOrJti);
|
|
78
88
|
if (exp === undefined) return false;
|
|
79
89
|
if (Date.now() >= exp) {
|
|
@@ -81,20 +91,75 @@ export const isTokenRevoked = (tokenOrJti: string): boolean => {
|
|
|
81
91
|
return false;
|
|
82
92
|
}
|
|
83
93
|
return true;
|
|
84
|
-
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export type JwtAlgorithm = 'HS256' | 'RS256' | 'ES256';
|
|
85
97
|
|
|
86
98
|
export interface BareAuthOptions {
|
|
87
|
-
secret
|
|
99
|
+
secret?: string;
|
|
100
|
+
algorithms?: JwtAlgorithm[];
|
|
101
|
+
publicKey?: string | CryptoKey;
|
|
102
|
+
jwksUri?: string;
|
|
103
|
+
jwksCacheTtlMs?: number;
|
|
104
|
+
issuer?: string | string[];
|
|
105
|
+
audience?: string | string[];
|
|
106
|
+
revocationStore?: RevocationStore;
|
|
88
107
|
isRevoked?: (payload: any, token: string) => boolean | Promise<boolean>;
|
|
89
108
|
}
|
|
90
109
|
|
|
110
|
+
const pemKeyCache = new Map<string, CryptoKey>();
|
|
111
|
+
|
|
112
|
+
const getAsymmetricAlgParams = (alg: 'RS256' | 'ES256') =>
|
|
113
|
+
alg === 'RS256'
|
|
114
|
+
? ({ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' } as const)
|
|
115
|
+
: ({ name: 'ECDSA', namedCurve: 'P-256' } as const);
|
|
116
|
+
|
|
117
|
+
const getVerifyParams = (alg: 'RS256' | 'ES256') =>
|
|
118
|
+
alg === 'RS256'
|
|
119
|
+
? ({ name: 'RSASSA-PKCS1-v1_5' } as const)
|
|
120
|
+
: ({ name: 'ECDSA', hash: 'SHA-256' } as const);
|
|
121
|
+
|
|
122
|
+
const pemToDer = (pem: string): ArrayBuffer => {
|
|
123
|
+
const b64 = pem
|
|
124
|
+
.replace(/-----BEGIN [A-Z0-9 ]+-----/g, '')
|
|
125
|
+
.replace(/-----END [A-Z0-9 ]+-----/g, '')
|
|
126
|
+
.replace(/\s+/g, '');
|
|
127
|
+
const buf = Buffer.from(b64, 'base64');
|
|
128
|
+
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const importPublicKey = async (keyOrPem: string | CryptoKey, alg: 'RS256' | 'ES256'): Promise<CryptoKey> => {
|
|
132
|
+
if (typeof keyOrPem !== 'string') return keyOrPem;
|
|
133
|
+
const cacheKey = `${alg}:${keyOrPem}`;
|
|
134
|
+
const cached = pemKeyCache.get(cacheKey);
|
|
135
|
+
if (cached) return cached;
|
|
136
|
+
const imported = await crypto.subtle.importKey(
|
|
137
|
+
'spki',
|
|
138
|
+
pemToDer(keyOrPem),
|
|
139
|
+
getAsymmetricAlgParams(alg),
|
|
140
|
+
false,
|
|
141
|
+
['verify']
|
|
142
|
+
);
|
|
143
|
+
pemKeyCache.set(cacheKey, imported);
|
|
144
|
+
return imported;
|
|
145
|
+
};
|
|
146
|
+
|
|
91
147
|
/**
|
|
92
148
|
* 1. BARE TOKEN AUTH (Standard JWT Middleware)
|
|
93
|
-
* High-performance, constant-time JWT middleware for BareJS
|
|
149
|
+
* High-performance, constant-time JWT middleware for BareJS.
|
|
150
|
+
* Supports HS256 (sync fast-path), RS256, ES256, and JWKS with kid caching.
|
|
94
151
|
*/
|
|
95
152
|
export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
96
|
-
const
|
|
97
|
-
const
|
|
153
|
+
const opts: BareAuthOptions = typeof secretOrOpts === 'string' ? { secret: secretOrOpts } : secretOrOpts;
|
|
154
|
+
const secret = opts.secret ?? '';
|
|
155
|
+
const customRevoked = opts.isRevoked;
|
|
156
|
+
const revocationStore = opts.revocationStore;
|
|
157
|
+
const publicKey = opts.publicKey;
|
|
158
|
+
const jwksUri = opts.jwksUri;
|
|
159
|
+
const jwksCacheTtlMs = opts.jwksCacheTtlMs ?? 300_000;
|
|
160
|
+
const allowedAlgs: JwtAlgorithm[] = opts.algorithms ?? (publicKey || jwksUri ? ['RS256', 'ES256'] : ['HS256']);
|
|
161
|
+
const expectedIss = opts.issuer === undefined ? null : (Array.isArray(opts.issuer) ? opts.issuer : [opts.issuer]);
|
|
162
|
+
const expectedAud = opts.audience === undefined ? null : (Array.isArray(opts.audience) ? opts.audience : [opts.audience]);
|
|
98
163
|
|
|
99
164
|
const finishAuth = (ctx: any, decoded: any, next: any) => {
|
|
100
165
|
ctx.set('user', decoded);
|
|
@@ -109,9 +174,182 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
|
109
174
|
return;
|
|
110
175
|
};
|
|
111
176
|
|
|
112
|
-
const
|
|
113
|
-
|
|
177
|
+
const checkClaimsAndRevocation = (ctx: any, decoded: any, token: string, next: any) => {
|
|
178
|
+
if (!decoded || typeof decoded !== 'object' || Array.isArray(decoded)) {
|
|
179
|
+
return ctx.status(401).send("Invalid token payload");
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const nowSec = Date.now() * 0.001;
|
|
183
|
+
if (typeof decoded.exp === 'number' && nowSec >= decoded.exp) {
|
|
184
|
+
return ctx.status(401).send("Token expired");
|
|
185
|
+
}
|
|
186
|
+
if (typeof decoded.nbf === 'number' && nowSec < decoded.nbf) {
|
|
187
|
+
return ctx.status(401).send("Token not active");
|
|
188
|
+
}
|
|
189
|
+
if (expectedIss && (typeof decoded.iss !== 'string' || !expectedIss.includes(decoded.iss))) {
|
|
190
|
+
return ctx.status(401).send("Invalid token issuer");
|
|
191
|
+
}
|
|
192
|
+
if (expectedAud) {
|
|
193
|
+
const tokenAud = Array.isArray(decoded.aud) ? decoded.aud : (typeof decoded.aud === 'string' ? [decoded.aud] : []);
|
|
194
|
+
if (!tokenAud.some((a: any) => typeof a === 'string' && expectedAud.includes(a))) {
|
|
195
|
+
return ctx.status(401).send("Invalid token audience");
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
if (isTokenRevoked(token) || (decoded?.jti && isTokenRevoked(String(decoded.jti)))) {
|
|
200
|
+
return ctx.status(401).send("Token revoked");
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if (revocationStore) {
|
|
204
|
+
const checkStore = async () => {
|
|
205
|
+
if (await revocationStore.isRevoked(token)) return ctx.status(401).send("Token revoked");
|
|
206
|
+
if (decoded?.jti && await revocationStore.isRevoked(String(decoded.jti))) {
|
|
207
|
+
return ctx.status(401).send("Token revoked");
|
|
208
|
+
}
|
|
209
|
+
if (customRevoked) {
|
|
210
|
+
const rev = await customRevoked(decoded, token);
|
|
211
|
+
if (rev) return ctx.status(401).send("Token revoked");
|
|
212
|
+
}
|
|
213
|
+
return finishAuth(ctx, decoded, next);
|
|
214
|
+
};
|
|
215
|
+
return checkStore();
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
if (customRevoked) {
|
|
219
|
+
const rev = customRevoked(decoded, token);
|
|
220
|
+
if (rev && typeof (rev as Promise<boolean>).then === 'function') {
|
|
221
|
+
return (rev as Promise<boolean>).then((isRev) =>
|
|
222
|
+
isRev ? ctx.status(401).send("Token revoked") : finishAuth(ctx, decoded, next)
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
if (rev) return ctx.status(401).send("Token revoked");
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return finishAuth(ctx, decoded, next);
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
// Preserve zero-overhead synchronous HS256 fast path when no asymmetric keys/JWKS are configured
|
|
232
|
+
const isSymmetricOnly =
|
|
233
|
+
!publicKey &&
|
|
234
|
+
!jwksUri &&
|
|
235
|
+
allowedAlgs.length === 1 &&
|
|
236
|
+
allowedAlgs[0] === 'HS256';
|
|
237
|
+
|
|
238
|
+
if (isSymmetricOnly) {
|
|
239
|
+
const verifySync = (ctx: any, next: any) => {
|
|
240
|
+
const authHeader = ctx.req.headers.get('Authorization');
|
|
241
|
+
|
|
242
|
+
if (!authHeader?.startsWith('Bearer ')) {
|
|
243
|
+
return ctx.status(401).send("Bearer token required");
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const token = authHeader.slice(7);
|
|
247
|
+
const firstDot = token.indexOf('.');
|
|
248
|
+
const secondDot = firstDot === -1 ? -1 : token.indexOf('.', firstDot + 1);
|
|
249
|
+
if (firstDot === -1 || secondDot === -1 || token.indexOf('.', secondDot + 1) !== -1) {
|
|
250
|
+
return ctx.status(401).send("Malformed JWT token");
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const headerB64 = token.slice(0, firstDot);
|
|
254
|
+
const payloadB64 = token.slice(firstDot + 1, secondDot);
|
|
255
|
+
const sigB64 = token.slice(secondDot + 1);
|
|
256
|
+
const data = token.slice(0, secondDot);
|
|
257
|
+
|
|
258
|
+
try {
|
|
259
|
+
const expectedSig = createHmac('sha256', secret).update(data).digest();
|
|
260
|
+
const actualSig = Buffer.from(sigB64, 'base64url');
|
|
114
261
|
|
|
262
|
+
if (actualSig.length !== expectedSig.length || !timingSafeEqual(actualSig, expectedSig)) {
|
|
263
|
+
return ctx.status(401).send("Invalid signature");
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const headerObj = JSON.parse(fromBase64Url(headerB64));
|
|
267
|
+
if (!headerObj || headerObj.alg !== 'HS256') {
|
|
268
|
+
return ctx.status(401).send("Unsupported token algorithm");
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const decoded = JSON.parse(fromBase64Url(payloadB64));
|
|
272
|
+
return checkClaimsAndRevocation(ctx, decoded, token, next);
|
|
273
|
+
} catch {
|
|
274
|
+
return ctx.status(401).send("Token verification failed");
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
if (customRevoked || revocationStore) {
|
|
279
|
+
return async (ctx: any, next: any) => verifySync(ctx, next);
|
|
280
|
+
}
|
|
281
|
+
return verifySync;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// Asymmetric (RS256 / ES256) and/or JWKS verification path
|
|
285
|
+
let jwksFetchedAt = 0;
|
|
286
|
+
let lastForceRefreshAt = 0;
|
|
287
|
+
let jwksKeys: any[] = [];
|
|
288
|
+
let inFlightJwks: Promise<any[]> | null = null;
|
|
289
|
+
const jwkKeyCache = new Map<string, CryptoKey>();
|
|
290
|
+
const JWKS_FORCE_COOLDOWN_MS = 15_000;
|
|
291
|
+
|
|
292
|
+
const loadJwks = async (forceRefresh = false): Promise<any[]> => {
|
|
293
|
+
const now = Date.now();
|
|
294
|
+
if (!forceRefresh && jwksKeys.length > 0 && now - jwksFetchedAt < jwksCacheTtlMs) {
|
|
295
|
+
return jwksKeys;
|
|
296
|
+
}
|
|
297
|
+
if (forceRefresh && now - lastForceRefreshAt < JWKS_FORCE_COOLDOWN_MS && jwksKeys.length > 0) {
|
|
298
|
+
return jwksKeys;
|
|
299
|
+
}
|
|
300
|
+
if (inFlightJwks) return inFlightJwks;
|
|
301
|
+
|
|
302
|
+
if (forceRefresh) lastForceRefreshAt = now;
|
|
303
|
+
inFlightJwks = (async () => {
|
|
304
|
+
const res = await fetch(jwksUri!, { signal: AbortSignal.timeout(5000) });
|
|
305
|
+
if (!res.ok) throw new Error(`JWKS fetch failed: ${res.status}`);
|
|
306
|
+
const body = (await res.json()) as { keys?: any[] };
|
|
307
|
+
jwksKeys = Array.isArray(body?.keys) ? body.keys : [];
|
|
308
|
+
jwksFetchedAt = Date.now();
|
|
309
|
+
if (forceRefresh) jwkKeyCache.clear();
|
|
310
|
+
return jwksKeys;
|
|
311
|
+
})().finally(() => {
|
|
312
|
+
inFlightJwks = null;
|
|
313
|
+
});
|
|
314
|
+
return inFlightJwks;
|
|
315
|
+
};
|
|
316
|
+
|
|
317
|
+
const matchJwk = (keys: any[], kid: string | undefined, alg: 'RS256' | 'ES256') => {
|
|
318
|
+
const isUsable = (k: any) =>
|
|
319
|
+
k &&
|
|
320
|
+
k.use !== 'enc' &&
|
|
321
|
+
(!k.alg || k.alg === alg);
|
|
322
|
+
return kid
|
|
323
|
+
? keys.find((k) => k.kid === kid && isUsable(k))
|
|
324
|
+
: keys.find((k) => isUsable(k));
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
const resolveJwksKey = async (kid: string | undefined, alg: 'RS256' | 'ES256'): Promise<CryptoKey | null> => {
|
|
328
|
+
const cacheId = `${alg}:${kid ?? '__default__'}`;
|
|
329
|
+
const cached = jwkKeyCache.get(cacheId);
|
|
330
|
+
if (cached && Date.now() - jwksFetchedAt < jwksCacheTtlMs) return cached;
|
|
331
|
+
|
|
332
|
+
let keys = await loadJwks(false);
|
|
333
|
+
let match = matchJwk(keys, kid, alg);
|
|
334
|
+
if (!match && kid) {
|
|
335
|
+
keys = await loadJwks(true);
|
|
336
|
+
match = matchJwk(keys, kid, alg);
|
|
337
|
+
}
|
|
338
|
+
if (!match) return null;
|
|
339
|
+
|
|
340
|
+
const imported = await crypto.subtle.importKey(
|
|
341
|
+
'jwk',
|
|
342
|
+
match,
|
|
343
|
+
getAsymmetricAlgParams(alg),
|
|
344
|
+
false,
|
|
345
|
+
['verify']
|
|
346
|
+
);
|
|
347
|
+
jwkKeyCache.set(cacheId, imported);
|
|
348
|
+
return imported;
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
return async (ctx: any, next: any) => {
|
|
352
|
+
const authHeader = ctx.req.headers.get('Authorization');
|
|
115
353
|
if (!authHeader?.startsWith('Bearer ')) {
|
|
116
354
|
return ctx.status(401).send("Bearer token required");
|
|
117
355
|
}
|
|
@@ -129,51 +367,48 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
|
129
367
|
const data = token.slice(0, secondDot);
|
|
130
368
|
|
|
131
369
|
try {
|
|
132
|
-
const expectedSig = createHmac('sha256', secret).update(data).digest();
|
|
133
|
-
const actualSig = Buffer.from(sigB64, 'base64url');
|
|
134
|
-
|
|
135
|
-
if (actualSig.length !== expectedSig.length || !timingSafeEqual(actualSig, expectedSig)) {
|
|
136
|
-
return ctx.status(401).send("Invalid signature");
|
|
137
|
-
}
|
|
138
|
-
|
|
139
370
|
const headerObj = JSON.parse(fromBase64Url(headerB64));
|
|
140
|
-
|
|
371
|
+
const alg = headerObj?.alg as JwtAlgorithm | undefined;
|
|
372
|
+
if (!alg || !allowedAlgs.includes(alg)) {
|
|
141
373
|
return ctx.status(401).send("Unsupported token algorithm");
|
|
142
374
|
}
|
|
143
375
|
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
376
|
+
if (alg === 'HS256') {
|
|
377
|
+
if (!secret) return ctx.status(401).send("Unsupported token algorithm");
|
|
378
|
+
const expectedSig = createHmac('sha256', secret).update(data).digest();
|
|
379
|
+
const actualSig = Buffer.from(sigB64, 'base64url');
|
|
380
|
+
if (actualSig.length !== expectedSig.length || !timingSafeEqual(actualSig, expectedSig)) {
|
|
381
|
+
return ctx.status(401).send("Invalid signature");
|
|
382
|
+
}
|
|
383
|
+
} else {
|
|
384
|
+
let verifyKey: CryptoKey | null = null;
|
|
385
|
+
if (jwksUri) {
|
|
386
|
+
verifyKey = await resolveJwksKey(headerObj?.kid, alg);
|
|
387
|
+
} else if (publicKey) {
|
|
388
|
+
verifyKey = await importPublicKey(publicKey, alg);
|
|
389
|
+
}
|
|
390
|
+
if (!verifyKey) {
|
|
391
|
+
return ctx.status(401).send("Invalid signature");
|
|
392
|
+
}
|
|
393
|
+
const sigBuf = Buffer.from(sigB64, 'base64url');
|
|
394
|
+
const sigBytes = sigBuf.buffer.slice(sigBuf.byteOffset, sigBuf.byteOffset + sigBuf.byteLength);
|
|
395
|
+
const valid = await crypto.subtle.verify(
|
|
396
|
+
getVerifyParams(alg),
|
|
397
|
+
verifyKey,
|
|
398
|
+
sigBytes,
|
|
399
|
+
encoder.encode(data)
|
|
400
|
+
);
|
|
401
|
+
if (!valid) {
|
|
402
|
+
return ctx.status(401).send("Invalid signature");
|
|
163
403
|
}
|
|
164
|
-
if (rev) return ctx.status(401).send("Token revoked");
|
|
165
404
|
}
|
|
166
405
|
|
|
167
|
-
|
|
406
|
+
const decoded = JSON.parse(fromBase64Url(payloadB64));
|
|
407
|
+
return checkClaimsAndRevocation(ctx, decoded, token, next);
|
|
168
408
|
} catch {
|
|
169
409
|
return ctx.status(401).send("Token verification failed");
|
|
170
410
|
}
|
|
171
411
|
};
|
|
172
|
-
|
|
173
|
-
if (customRevoked) {
|
|
174
|
-
return async (ctx: any, next: any) => verifySync(ctx, next);
|
|
175
|
-
}
|
|
176
|
-
return verifySync;
|
|
177
412
|
};
|
|
178
413
|
|
|
179
414
|
const sha256 = (value: string): Buffer => createHash('sha256').update(value).digest();
|
|
@@ -215,8 +450,6 @@ export const basicAuth = (credentials: { user: string; pass: string }) => {
|
|
|
215
450
|
};
|
|
216
451
|
};
|
|
217
452
|
|
|
218
|
-
|
|
219
|
-
|
|
220
453
|
/**
|
|
221
454
|
* 5. ROLE AUTHORIZATION (Bonus Max Function)
|
|
222
455
|
* Ensures user has specific permissions after bareAuth
|
package/src/security/cors.ts
CHANGED
|
@@ -94,7 +94,31 @@ export const cors = (options: CorsOptions = {}) => {
|
|
|
94
94
|
}
|
|
95
95
|
if (exposeHeaders) ctx.setHeader('Access-Control-Expose-Headers', exposeHeaders);
|
|
96
96
|
|
|
97
|
-
|
|
97
|
+
const res = next?.();
|
|
98
|
+
if (res && typeof (res as any).then === 'function') {
|
|
99
|
+
return (res as Promise<any>).then((r) => {
|
|
100
|
+
if (r instanceof Response) {
|
|
101
|
+
r.headers.set('Vary', 'Origin');
|
|
102
|
+
r.headers.set('Access-Control-Allow-Methods', methods);
|
|
103
|
+
if (matched) {
|
|
104
|
+
r.headers.set('Access-Control-Allow-Origin', matched);
|
|
105
|
+
if (credentials) r.headers.set('Access-Control-Allow-Credentials', 'true');
|
|
106
|
+
}
|
|
107
|
+
if (exposeHeaders) r.headers.set('Access-Control-Expose-Headers', exposeHeaders);
|
|
108
|
+
}
|
|
109
|
+
return r;
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
if (res instanceof Response) {
|
|
113
|
+
res.headers.set('Vary', 'Origin');
|
|
114
|
+
res.headers.set('Access-Control-Allow-Methods', methods);
|
|
115
|
+
if (matched) {
|
|
116
|
+
res.headers.set('Access-Control-Allow-Origin', matched);
|
|
117
|
+
if (credentials) res.headers.set('Access-Control-Allow-Credentials', 'true');
|
|
118
|
+
}
|
|
119
|
+
if (exposeHeaders) res.headers.set('Access-Control-Expose-Headers', exposeHeaders);
|
|
120
|
+
}
|
|
121
|
+
return res;
|
|
98
122
|
};
|
|
99
123
|
return mw;
|
|
100
124
|
};
|
package/src/security/csrf.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Context, Middleware, Next } from '../core/context';
|
|
2
|
+
import { timingSafeEqual } from 'node:crypto';
|
|
2
3
|
|
|
3
4
|
export interface CsrfOptions {
|
|
4
5
|
/** Allowed origins for state-changing requests (defaults to same-origin matching request Host) */
|
|
@@ -71,7 +72,13 @@ export const csrf = (options: CsrfOptions = {}): Middleware => {
|
|
|
71
72
|
if (requireToken) {
|
|
72
73
|
const cookieToken = ctx.cookies[cookieName];
|
|
73
74
|
const headerToken = ctx.req.headers.get(headerName);
|
|
74
|
-
|
|
75
|
+
let tokensMatch = false;
|
|
76
|
+
if (cookieToken && headerToken) {
|
|
77
|
+
const a = Buffer.from(cookieToken);
|
|
78
|
+
const b = Buffer.from(headerToken);
|
|
79
|
+
tokensMatch = a.length === b.length && timingSafeEqual(a, b);
|
|
80
|
+
}
|
|
81
|
+
if (!tokensMatch) {
|
|
75
82
|
return Response.json(
|
|
76
83
|
{ status: 'error', code: 'CSRF_TOKEN_INVALID', message: 'Invalid or missing CSRF token' },
|
|
77
84
|
{ status: 403 }
|