barejs 0.1.47 → 0.1.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +20 -20
- package/README.md +184 -184
- package/dist/index.js +89 -187
- package/dist/types/security/auth.d.ts +2 -2
- package/package.json +68 -68
- package/src/core/bare.ts +315 -318
- package/src/core/config.ts +31 -31
- package/src/core/context.ts +111 -111
- package/src/core/loader.ts +12 -12
- package/src/core/radix.ts +184 -171
- package/src/core/router.ts +60 -62
- package/src/index.ts +60 -60
- package/src/security/auth.ts +174 -153
- package/src/security/cors.ts +45 -26
- package/src/security/hash.ts +22 -19
- package/src/security/validators.ts +133 -133
- package/src/utils/static.ts +42 -25
package/src/core/router.ts
CHANGED
|
@@ -1,62 +1,60 @@
|
|
|
1
|
-
import {
|
|
2
|
-
type Middleware,
|
|
3
|
-
type Handler,
|
|
4
|
-
type GroupCallback
|
|
5
|
-
} from '../core/context';
|
|
6
|
-
|
|
7
|
-
type HandlersChain = (Middleware | Handler)[];
|
|
8
|
-
|
|
9
|
-
export class BareRouter {
|
|
10
|
-
public routes: any[] = [];
|
|
11
|
-
|
|
12
|
-
constructor(
|
|
13
|
-
public prefix: string = "",
|
|
14
|
-
public groupMiddleware: any[] = []
|
|
15
|
-
) { }
|
|
16
|
-
|
|
17
|
-
private _add(method: string, path: string, handlers: HandlersChain) {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
public
|
|
35
|
-
public
|
|
36
|
-
public
|
|
37
|
-
public
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
this
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
this.
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
}
|
|
62
|
-
}
|
|
1
|
+
import {
|
|
2
|
+
type Middleware,
|
|
3
|
+
type Handler,
|
|
4
|
+
type GroupCallback
|
|
5
|
+
} from '../core/context';
|
|
6
|
+
|
|
7
|
+
type HandlersChain = (Middleware | Handler)[];
|
|
8
|
+
|
|
9
|
+
export class BareRouter {
|
|
10
|
+
public routes: any[] = [];
|
|
11
|
+
|
|
12
|
+
constructor(
|
|
13
|
+
public prefix: string = "",
|
|
14
|
+
public groupMiddleware: any[] = []
|
|
15
|
+
) { }
|
|
16
|
+
|
|
17
|
+
private _add(method: string, path: string, handlers: HandlersChain) {
|
|
18
|
+
let fullPath = (this.prefix + "/" + path)
|
|
19
|
+
.replace(/\/+/g, "/")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
if (fullPath.endsWith("/")) fullPath = fullPath.slice(0, -1);
|
|
24
|
+
|
|
25
|
+
this.routes.push({
|
|
26
|
+
method: method.toUpperCase(),
|
|
27
|
+
path: fullPath || "",
|
|
28
|
+
handlers: [...this.groupMiddleware, ...handlers]
|
|
29
|
+
});
|
|
30
|
+
return this;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
public get = (path: string, ...h: HandlersChain) => this._add("GET", path, h);
|
|
34
|
+
public post = (path: string, ...h: HandlersChain) => this._add("POST", path, h);
|
|
35
|
+
public put = (path: string, ...h: HandlersChain) => this._add("PUT", path, h);
|
|
36
|
+
public patch = (path: string, ...h: HandlersChain) => this._add("PATCH", path, h);
|
|
37
|
+
public delete = (path: string, ...h: HandlersChain) => this._add("DELETE", path, h);
|
|
38
|
+
|
|
39
|
+
public group = (path: string, ...args: any[]) => {
|
|
40
|
+
const callback = args.pop();
|
|
41
|
+
const middleware = args;
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
const newPrefix = (this.prefix + "/" + path).replace(/\/+/g, "/");
|
|
45
|
+
const subRouter = new BareRouter(newPrefix, [...this.groupMiddleware, ...middleware]);
|
|
46
|
+
|
|
47
|
+
callback(subRouter);
|
|
48
|
+
this.routes.push(...subRouter.routes);
|
|
49
|
+
return this;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
public use(mw: any) {
|
|
53
|
+
if (mw instanceof BareRouter || (mw && mw.routes)) {
|
|
54
|
+
this.routes.push(...mw.routes);
|
|
55
|
+
} else {
|
|
56
|
+
this.groupMiddleware.push(mw);
|
|
57
|
+
}
|
|
58
|
+
return this;
|
|
59
|
+
}
|
|
60
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,61 +1,61 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* BareJS: The Metal of Web Frameworks
|
|
3
|
-
* All comments must be in English [2026-01-06]
|
|
4
|
-
* Built for Bun with Mechanical Sympathy
|
|
5
|
-
* Optimized to outperform competitors by 55% [2026-01-05]
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
// --- 1. Core Engine ---
|
|
9
|
-
export { BareJS } from './core/bare';
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Plugin Interface for BareJS
|
|
13
|
-
*/
|
|
14
|
-
export interface BarePlugin {
|
|
15
|
-
install: (app: any) => void;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
// --- 2. Context & Types ---
|
|
19
|
-
export type {
|
|
20
|
-
Middleware,
|
|
21
|
-
Handler,
|
|
22
|
-
Next,
|
|
23
|
-
Context,
|
|
24
|
-
Params,
|
|
25
|
-
AuthUser
|
|
26
|
-
} from './core/context';
|
|
27
|
-
|
|
28
|
-
// --- 3. The Validation Suite (Builders - สำหรับสร้าง Schema) ---
|
|
29
|
-
import { Type } from "@sinclair/typebox";
|
|
30
|
-
export { Type, Type as T, Type as TypeBox };
|
|
31
|
-
|
|
32
|
-
// --- 4. The Validation Suite (Engines - สำหรับเป็น Middleware) ---
|
|
33
|
-
import { typebox, zod, native, validate, Z } from './security/validators';
|
|
34
|
-
export {
|
|
35
|
-
// TypeBox Engine
|
|
36
|
-
typebox,
|
|
37
|
-
typebox as t,
|
|
38
|
-
// Zod Engine & Builder
|
|
39
|
-
zod,
|
|
40
|
-
zod as z,
|
|
41
|
-
Z,
|
|
42
|
-
Z as Zod,
|
|
43
|
-
// Native Engine
|
|
44
|
-
native,
|
|
45
|
-
native as n,
|
|
46
|
-
// Auto-Detect Engine
|
|
47
|
-
validate,
|
|
48
|
-
validate as v
|
|
49
|
-
};
|
|
50
|
-
|
|
51
|
-
// --- 5. Middlewares & Utilities ---
|
|
52
|
-
// export { logger } from './utils/logger';
|
|
53
|
-
export { cors } from './security/cors';
|
|
54
|
-
export { staticFile } from './utils/static';
|
|
55
|
-
export { BareRouter } from './core/router';
|
|
56
|
-
|
|
57
|
-
// --- 6. Authentication (Bun Native) ---
|
|
58
|
-
// Always deploy using process.env [2026-01-06]
|
|
59
|
-
export { bareAuth, createToken } from './security/auth';
|
|
60
|
-
// --- 7. Hashing ---
|
|
1
|
+
/**
|
|
2
|
+
* BareJS: The Metal of Web Frameworks
|
|
3
|
+
* All comments must be in English [2026-01-06]
|
|
4
|
+
* Built for Bun with Mechanical Sympathy
|
|
5
|
+
* Optimized to outperform competitors by 55% [2026-01-05]
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
// --- 1. Core Engine ---
|
|
9
|
+
export { BareJS } from './core/bare';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Plugin Interface for BareJS
|
|
13
|
+
*/
|
|
14
|
+
export interface BarePlugin {
|
|
15
|
+
install: (app: any) => void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// --- 2. Context & Types ---
|
|
19
|
+
export type {
|
|
20
|
+
Middleware,
|
|
21
|
+
Handler,
|
|
22
|
+
Next,
|
|
23
|
+
Context,
|
|
24
|
+
Params,
|
|
25
|
+
AuthUser
|
|
26
|
+
} from './core/context';
|
|
27
|
+
|
|
28
|
+
// --- 3. The Validation Suite (Builders - สำหรับสร้าง Schema) ---
|
|
29
|
+
import { Type } from "@sinclair/typebox";
|
|
30
|
+
export { Type, Type as T, Type as TypeBox };
|
|
31
|
+
|
|
32
|
+
// --- 4. The Validation Suite (Engines - สำหรับเป็น Middleware) ---
|
|
33
|
+
import { typebox, zod, native, validate, Z } from './security/validators';
|
|
34
|
+
export {
|
|
35
|
+
// TypeBox Engine
|
|
36
|
+
typebox,
|
|
37
|
+
typebox as t,
|
|
38
|
+
// Zod Engine & Builder
|
|
39
|
+
zod,
|
|
40
|
+
zod as z,
|
|
41
|
+
Z,
|
|
42
|
+
Z as Zod,
|
|
43
|
+
// Native Engine
|
|
44
|
+
native,
|
|
45
|
+
native as n,
|
|
46
|
+
// Auto-Detect Engine
|
|
47
|
+
validate,
|
|
48
|
+
validate as v
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
// --- 5. Middlewares & Utilities ---
|
|
52
|
+
// export { logger } from './utils/logger';
|
|
53
|
+
export { cors } from './security/cors';
|
|
54
|
+
export { staticFile } from './utils/static';
|
|
55
|
+
export { BareRouter } from './core/router';
|
|
56
|
+
|
|
57
|
+
// --- 6. Authentication (Bun Native) ---
|
|
58
|
+
// Always deploy using process.env [2026-01-06]
|
|
59
|
+
export { bareAuth, createToken } from './security/auth';
|
|
60
|
+
// --- 7. Hashing ---
|
|
61
61
|
export{Hash as Password, Hash} from './security/hash';
|
package/src/security/auth.ts
CHANGED
|
@@ -1,154 +1,175 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* UTILS: Internal Crypto Helpers using Native Web Crypto
|
|
6
|
-
* Optimized for Bun performance and
|
|
7
|
-
*/
|
|
8
|
-
const encoder = new TextEncoder();
|
|
9
|
-
|
|
10
|
-
//
|
|
11
|
-
const base64Url = (input: Uint8Array | string): string => {
|
|
12
|
-
|
|
13
|
-
? Buffer.from(input).toString('
|
|
14
|
-
: Buffer.from(input).toString('
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
const
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
const
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
const
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
if (
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
const
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
1
|
+
import type { Next } from '../core/context';
|
|
2
|
+
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* UTILS: Internal Crypto Helpers using Native Web Crypto & Node Crypto
|
|
6
|
+
* Optimized for Bun performance and constant-time security.
|
|
7
|
+
*/
|
|
8
|
+
const encoder = new TextEncoder();
|
|
9
|
+
|
|
10
|
+
// Base64Url Helpers (RFC 4648) using native C++ Buffer encoding
|
|
11
|
+
const base64Url = (input: Uint8Array | string): string => {
|
|
12
|
+
return typeof input === 'string'
|
|
13
|
+
? Buffer.from(input).toString('base64url')
|
|
14
|
+
: Buffer.from(input).toString('base64url');
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const fromBase64Url = (str: string): string => {
|
|
18
|
+
return Buffer.from(str, 'base64url').toString('utf-8');
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
// PERF: Cache CryptoKeys to avoid repeated async importKey calls for createToken
|
|
22
|
+
const keyCache = new Map<string, CryptoKey>();
|
|
23
|
+
|
|
24
|
+
const importKey = async (secret: string): Promise<CryptoKey> => {
|
|
25
|
+
if (keyCache.has(secret)) return keyCache.get(secret)!;
|
|
26
|
+
|
|
27
|
+
const key = await crypto.subtle.importKey(
|
|
28
|
+
"raw",
|
|
29
|
+
encoder.encode(secret),
|
|
30
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
31
|
+
false,
|
|
32
|
+
["sign", "verify"]
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
keyCache.set(secret, key);
|
|
36
|
+
return key;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 4. TOKEN GENERATOR (Standard JWT)
|
|
41
|
+
*/
|
|
42
|
+
export const createToken = async (payload: object, secret: string): Promise<string> => {
|
|
43
|
+
const header = JSON.stringify({ alg: "HS256", typ: "JWT" });
|
|
44
|
+
const body = JSON.stringify(payload);
|
|
45
|
+
|
|
46
|
+
const encodedHeader = base64Url(header);
|
|
47
|
+
const encodedBody = base64Url(body);
|
|
48
|
+
const data = `${encodedHeader}.${encodedBody}`;
|
|
49
|
+
|
|
50
|
+
const key = await importKey(secret);
|
|
51
|
+
const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(data));
|
|
52
|
+
const encodedSig = base64Url(new Uint8Array(signature));
|
|
53
|
+
|
|
54
|
+
return `${data}.${encodedSig}`;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 1. BARE TOKEN AUTH (Standard JWT Middleware)
|
|
59
|
+
* High-performance, constant-time JWT middleware for BareJS
|
|
60
|
+
*/
|
|
61
|
+
export const bareAuth = (secret: string) => {
|
|
62
|
+
return (ctx: any, next: any) => {
|
|
63
|
+
const authHeader = ctx.req.headers.get('Authorization');
|
|
64
|
+
|
|
65
|
+
if (!authHeader?.startsWith('Bearer ')) {
|
|
66
|
+
return ctx.status(401).send("Bearer token required");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const token = authHeader.slice(7);
|
|
70
|
+
const firstDot = token.indexOf('.');
|
|
71
|
+
const secondDot = firstDot === -1 ? -1 : token.indexOf('.', firstDot + 1);
|
|
72
|
+
if (firstDot === -1 || secondDot === -1 || token.indexOf('.', secondDot + 1) !== -1) {
|
|
73
|
+
return ctx.status(401).send("Malformed JWT token");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const headerB64 = token.slice(0, firstDot);
|
|
77
|
+
const payloadB64 = token.slice(firstDot + 1, secondDot);
|
|
78
|
+
const sigB64 = token.slice(secondDot + 1);
|
|
79
|
+
const data = token.slice(0, secondDot);
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
const expectedSig = createHmac('sha256', secret).update(data).digest();
|
|
83
|
+
const actualSig = Buffer.from(sigB64, 'base64url');
|
|
84
|
+
|
|
85
|
+
if (actualSig.length !== expectedSig.length || !timingSafeEqual(actualSig, expectedSig)) {
|
|
86
|
+
return ctx.status(401).send("Invalid signature");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const headerObj = JSON.parse(fromBase64Url(headerB64));
|
|
90
|
+
if (!headerObj || headerObj.alg !== 'HS256') {
|
|
91
|
+
return ctx.status(401).send("Unsupported token algorithm");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const decoded = JSON.parse(fromBase64Url(payloadB64));
|
|
95
|
+
const nowSec = Date.now() * 0.001;
|
|
96
|
+
if (typeof decoded.exp === 'number' && nowSec >= decoded.exp) {
|
|
97
|
+
return ctx.status(401).send("Token expired");
|
|
98
|
+
}
|
|
99
|
+
if (typeof decoded.nbf === 'number' && nowSec < decoded.nbf) {
|
|
100
|
+
return ctx.status(401).send("Token not active");
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
ctx.set('user', decoded);
|
|
104
|
+
|
|
105
|
+
if (Array.isArray(next)) {
|
|
106
|
+
if (next.length === 0) return;
|
|
107
|
+
const [current, ...rest] = next;
|
|
108
|
+
return current(ctx, rest);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (typeof next === 'function') {
|
|
112
|
+
return next();
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return;
|
|
116
|
+
} catch {
|
|
117
|
+
return ctx.status(401).send("Token verification failed");
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const sha256 = (value: string): Buffer => createHash('sha256').update(value).digest();
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* 2. BASIC AUTH
|
|
126
|
+
* Useful for internal tools and simple admin panels
|
|
127
|
+
*/
|
|
128
|
+
export const basicAuth = (credentials: { user: string; pass: string }) => {
|
|
129
|
+
const expectedUserHash = sha256(credentials.user);
|
|
130
|
+
const expectedPassHash = sha256(credentials.pass);
|
|
131
|
+
|
|
132
|
+
return async (ctx: any, next: Next) => {
|
|
133
|
+
const authHeader = ctx.req.headers.get('Authorization');
|
|
134
|
+
if (!authHeader?.startsWith('Basic ')) {
|
|
135
|
+
return ctx.status(401).json({ status: 'error', message: 'Basic Auth required' });
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const token = authHeader.slice(6).trim();
|
|
139
|
+
if (!token) return ctx.status(401).json({ status: 'error', message: 'Missing credentials' });
|
|
140
|
+
|
|
141
|
+
const decoded = Buffer.from(token, 'base64').toString('utf-8');
|
|
142
|
+
const colonIdx = decoded.indexOf(':');
|
|
143
|
+
if (colonIdx === -1) {
|
|
144
|
+
return ctx.status(401).json({ status: 'error', message: 'Invalid credentials' });
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const user = decoded.slice(0, colonIdx);
|
|
148
|
+
const pass = decoded.slice(colonIdx + 1);
|
|
149
|
+
|
|
150
|
+
const userMatch = timingSafeEqual(sha256(user), expectedUserHash);
|
|
151
|
+
const passMatch = timingSafeEqual(sha256(pass), expectedPassHash);
|
|
152
|
+
|
|
153
|
+
if (userMatch && passMatch) {
|
|
154
|
+
return next();
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
return ctx.status(401).json({ status: 'error', message: 'Invalid credentials' });
|
|
158
|
+
};
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 5. ROLE AUTHORIZATION (Bonus Max Function)
|
|
165
|
+
* Ensures user has specific permissions after bareAuth
|
|
166
|
+
*/
|
|
167
|
+
export const hasRole = (role: string) => {
|
|
168
|
+
return async (ctx: any, next: Next) => {
|
|
169
|
+
const user = ctx.get('user');
|
|
170
|
+
if (!user || user.role !== role) {
|
|
171
|
+
return ctx.status(403).json({ status: 'error', message: `Required role: ${role}` });
|
|
172
|
+
}
|
|
173
|
+
return next();
|
|
174
|
+
};
|
|
154
175
|
};
|
package/src/security/cors.ts
CHANGED
|
@@ -1,27 +1,46 @@
|
|
|
1
|
-
import type { Middleware } from '../core/context';
|
|
2
|
-
|
|
3
|
-
export const cors = (options: { origin?: string; methods?: string } = {}) => {
|
|
4
|
-
const origin = options.origin || '*';
|
|
5
|
-
const methods = options.methods || 'GET,POST,PUT,PATCH,DELETE,OPTIONS';
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
1
|
+
import type { Middleware } from '../core/context';
|
|
2
|
+
|
|
3
|
+
export const cors = (options: { origin?: string; methods?: string } = {}) => {
|
|
4
|
+
const origin = options.origin || '*';
|
|
5
|
+
const methods = options.methods || 'GET,POST,PUT,PATCH,DELETE,OPTIONS';
|
|
6
|
+
const preflightHeaders: Record<string, string> = {
|
|
7
|
+
'Access-Control-Allow-Origin': origin,
|
|
8
|
+
'Access-Control-Allow-Methods': methods,
|
|
9
|
+
'Access-Control-Allow-Headers': 'Content-Type, Authorization'
|
|
10
|
+
};
|
|
11
|
+
if (origin !== '*') {
|
|
12
|
+
preflightHeaders['Vary'] = 'Origin';
|
|
13
|
+
}
|
|
14
|
+
const preflightInit = { status: 204, headers: preflightHeaders };
|
|
15
|
+
|
|
16
|
+
const mw: Middleware = (ctx, next) => {
|
|
17
|
+
if (ctx.req.method === 'OPTIONS') {
|
|
18
|
+
return new Response(null, preflightInit);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
ctx.setHeader('Access-Control-Allow-Origin', origin);
|
|
22
|
+
ctx.setHeader('Access-Control-Allow-Methods', methods);
|
|
23
|
+
if (origin !== '*') {
|
|
24
|
+
ctx.setHeader('Vary', 'Origin');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const res = next?.();
|
|
28
|
+
if (res && typeof (res as any).then === 'function') {
|
|
29
|
+
return (res as Promise<any>).then((r) => {
|
|
30
|
+
if (r instanceof Response) {
|
|
31
|
+
r.headers.set('Access-Control-Allow-Origin', origin);
|
|
32
|
+
r.headers.set('Access-Control-Allow-Methods', methods);
|
|
33
|
+
if (origin !== '*') r.headers.set('Vary', 'Origin');
|
|
34
|
+
}
|
|
35
|
+
return r;
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
if (res instanceof Response) {
|
|
39
|
+
res.headers.set('Access-Control-Allow-Origin', origin);
|
|
40
|
+
res.headers.set('Access-Control-Allow-Methods', methods);
|
|
41
|
+
if (origin !== '*') res.headers.set('Vary', 'Origin');
|
|
42
|
+
}
|
|
43
|
+
return res;
|
|
44
|
+
};
|
|
45
|
+
return mw;
|
|
27
46
|
};
|