@benchcutlogic/edge-kit 0.0.0-stage → 0.2.1
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 +201 -0
- package/README.md +172 -2
- package/dist/analytics.d.ts +41 -0
- package/dist/analytics.js +212 -0
- package/dist/body.d.ts +55 -0
- package/dist/body.js +177 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/scrub.d.ts +128 -0
- package/dist/scrub.js +636 -0
- package/dist/ssrf.d.ts +165 -0
- package/dist/ssrf.js +643 -0
- package/dist/sveltekit.d.ts +60 -0
- package/dist/sveltekit.js +149 -0
- package/dist/tenant.d.ts +44 -0
- package/dist/tenant.js +43 -0
- package/package.json +87 -3
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export interface RequestEventLike {
|
|
2
|
+
readonly request: Request;
|
|
3
|
+
readonly url: URL;
|
|
4
|
+
readonly route?: {
|
|
5
|
+
readonly id: string | null;
|
|
6
|
+
};
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The `resolve` function SvelteKit passes to a `handle`. It is generic over the
|
|
10
|
+
* event so that SvelteKit's own `resolve(event: RequestEvent, opts?)` is
|
|
11
|
+
* assignable without widening its parameter.
|
|
12
|
+
*/
|
|
13
|
+
export type ResolveLike<E extends RequestEventLike = RequestEventLike> = (event: E) => Promise<Response> | Response;
|
|
14
|
+
/**
|
|
15
|
+
* A SvelteKit `handle`. The event type is inferred from the caller, so the value
|
|
16
|
+
* is assignable to `Handle` from `@sveltejs/kit` (kit 2) or `@sveltejs/kit/hooks`
|
|
17
|
+
* (kit 3) under `strict` without a cast.
|
|
18
|
+
*/
|
|
19
|
+
export type SvelteKitHandle = <E extends RequestEventLike>(input: {
|
|
20
|
+
readonly event: E;
|
|
21
|
+
readonly resolve: ResolveLike<E>;
|
|
22
|
+
}) => Promise<Response>;
|
|
23
|
+
export interface SecurityHeadersConfig {
|
|
24
|
+
readonly strictTransportSecurity?: string | false;
|
|
25
|
+
readonly contentSecurityPolicy?: string | false;
|
|
26
|
+
readonly referrerPolicy?: string | false;
|
|
27
|
+
readonly xContentTypeOptions?: string | false;
|
|
28
|
+
readonly xFrameOptions?: string | false;
|
|
29
|
+
readonly permissionsPolicy?: string | false;
|
|
30
|
+
}
|
|
31
|
+
export interface MethodRule {
|
|
32
|
+
readonly pattern: string | RegExp;
|
|
33
|
+
readonly methods: ReadonlyArray<string>;
|
|
34
|
+
}
|
|
35
|
+
export interface CsrfConfig {
|
|
36
|
+
readonly enabled?: boolean;
|
|
37
|
+
readonly allowedOrigins?: ReadonlyArray<string>;
|
|
38
|
+
readonly exemptPaths?: ReadonlyArray<string | RegExp>;
|
|
39
|
+
}
|
|
40
|
+
export interface EdgeSecurityOptions {
|
|
41
|
+
readonly headers?: SecurityHeadersConfig;
|
|
42
|
+
readonly methodRules?: ReadonlyArray<MethodRule>;
|
|
43
|
+
readonly csrf?: CsrfConfig;
|
|
44
|
+
readonly csrfExemptPaths?: ReadonlyArray<string | RegExp>;
|
|
45
|
+
readonly allowedOrigins?: ReadonlyArray<string>;
|
|
46
|
+
readonly onError?: (error: unknown, event: RequestEventLike) => void;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Applies configured edge security headers to any `Response`, safely cloning
|
|
50
|
+
* responses whose headers are immutable (such as `Response.redirect`).
|
|
51
|
+
*/
|
|
52
|
+
export declare function applySecurityHeaders(response: Response, config?: SecurityHeadersConfig): Response;
|
|
53
|
+
/**
|
|
54
|
+
* Creates a SvelteKit-compatible `Handle` that:
|
|
55
|
+
* - enforces per-route HTTP method rules (405 + accurate `Allow` header)
|
|
56
|
+
* - enforces Origin/CSRF validation on state-changing requests (`POST`/`PUT`/`PATCH`/`DELETE`)
|
|
57
|
+
* with an explicit `csrfExemptPaths` allowlist
|
|
58
|
+
* - emits security headers on ALL responses including 404, 405, 403, redirects, and caught 500s.
|
|
59
|
+
*/
|
|
60
|
+
export declare function createEdgeSecurityHandle(options?: EdgeSecurityOptions): SvelteKitHandle;
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
const DEFAULT_HSTS = 'max-age=63072000; includeSubDomains; preload';
|
|
2
|
+
const DEFAULT_CSP = "default-src 'self'; base-uri 'self'; frame-ancestors 'none'; object-src 'none'";
|
|
3
|
+
const DEFAULT_REFERRER_POLICY = 'strict-origin-when-cross-origin';
|
|
4
|
+
const DEFAULT_X_CONTENT_TYPE_OPTIONS = 'nosniff';
|
|
5
|
+
const DEFAULT_X_FRAME_OPTIONS = 'DENY';
|
|
6
|
+
const STATE_CHANGING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
|
|
7
|
+
function matchesPathPattern(pathname, pattern) {
|
|
8
|
+
if (pattern instanceof RegExp) {
|
|
9
|
+
pattern.lastIndex = 0;
|
|
10
|
+
return pattern.test(pathname);
|
|
11
|
+
}
|
|
12
|
+
if (pattern.endsWith('/*')) {
|
|
13
|
+
const prefix = pattern.slice(0, -2);
|
|
14
|
+
return pathname === prefix || pathname.startsWith(`${prefix}/`);
|
|
15
|
+
}
|
|
16
|
+
return pathname === pattern;
|
|
17
|
+
}
|
|
18
|
+
function normalizeOrigin(origin) {
|
|
19
|
+
try {
|
|
20
|
+
return new URL(origin).origin.toLowerCase();
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Applies configured edge security headers to any `Response`, safely cloning
|
|
28
|
+
* responses whose headers are immutable (such as `Response.redirect`).
|
|
29
|
+
*/
|
|
30
|
+
export function applySecurityHeaders(response, config) {
|
|
31
|
+
const headerEntries = [];
|
|
32
|
+
const hsts = config?.strictTransportSecurity;
|
|
33
|
+
if (hsts !== false) {
|
|
34
|
+
headerEntries.push(['Strict-Transport-Security', hsts ?? DEFAULT_HSTS]);
|
|
35
|
+
}
|
|
36
|
+
const referrerPolicy = config?.referrerPolicy;
|
|
37
|
+
if (referrerPolicy !== false) {
|
|
38
|
+
headerEntries.push(['Referrer-Policy', referrerPolicy ?? DEFAULT_REFERRER_POLICY]);
|
|
39
|
+
}
|
|
40
|
+
const xContentTypeOptions = config?.xContentTypeOptions;
|
|
41
|
+
if (xContentTypeOptions !== false) {
|
|
42
|
+
headerEntries.push([
|
|
43
|
+
'X-Content-Type-Options',
|
|
44
|
+
xContentTypeOptions ?? DEFAULT_X_CONTENT_TYPE_OPTIONS
|
|
45
|
+
]);
|
|
46
|
+
}
|
|
47
|
+
const xFrameOptions = config?.xFrameOptions;
|
|
48
|
+
if (xFrameOptions !== false) {
|
|
49
|
+
headerEntries.push(['X-Frame-Options', xFrameOptions ?? DEFAULT_X_FRAME_OPTIONS]);
|
|
50
|
+
}
|
|
51
|
+
if (typeof config?.permissionsPolicy === 'string') {
|
|
52
|
+
headerEntries.push(['Permissions-Policy', config.permissionsPolicy]);
|
|
53
|
+
}
|
|
54
|
+
const nextHeaders = new Headers(response.headers);
|
|
55
|
+
for (const [name, value] of headerEntries) {
|
|
56
|
+
nextHeaders.set(name, value);
|
|
57
|
+
}
|
|
58
|
+
const csp = config?.contentSecurityPolicy;
|
|
59
|
+
if (typeof csp === 'string') {
|
|
60
|
+
nextHeaders.set('Content-Security-Policy', csp);
|
|
61
|
+
}
|
|
62
|
+
else if (csp !== false && !nextHeaders.has('Content-Security-Policy')) {
|
|
63
|
+
nextHeaders.set('Content-Security-Policy', DEFAULT_CSP);
|
|
64
|
+
}
|
|
65
|
+
return new Response(response.body, {
|
|
66
|
+
status: response.status,
|
|
67
|
+
statusText: response.statusText,
|
|
68
|
+
headers: nextHeaders
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Creates a SvelteKit-compatible `Handle` that:
|
|
73
|
+
* - enforces per-route HTTP method rules (405 + accurate `Allow` header)
|
|
74
|
+
* - enforces Origin/CSRF validation on state-changing requests (`POST`/`PUT`/`PATCH`/`DELETE`)
|
|
75
|
+
* with an explicit `csrfExemptPaths` allowlist
|
|
76
|
+
* - emits security headers on ALL responses including 404, 405, 403, redirects, and caught 500s.
|
|
77
|
+
*/
|
|
78
|
+
export function createEdgeSecurityHandle(options) {
|
|
79
|
+
const headerConfig = options?.headers;
|
|
80
|
+
const methodRules = options?.methodRules ?? [];
|
|
81
|
+
const csrfEnabled = options?.csrf?.enabled ?? true;
|
|
82
|
+
const csrfExemptPaths = [
|
|
83
|
+
...(options?.csrfExemptPaths ?? []),
|
|
84
|
+
...(options?.csrf?.exemptPaths ?? [])
|
|
85
|
+
];
|
|
86
|
+
const configuredAllowedOrigins = [
|
|
87
|
+
...(options?.allowedOrigins ?? []),
|
|
88
|
+
...(options?.csrf?.allowedOrigins ?? [])
|
|
89
|
+
]
|
|
90
|
+
.map(normalizeOrigin)
|
|
91
|
+
.filter((origin) => origin !== undefined);
|
|
92
|
+
return async ({ event, resolve }) => {
|
|
93
|
+
const method = event.request.method.toUpperCase();
|
|
94
|
+
const pathname = event.url.pathname;
|
|
95
|
+
// 1. Per-route HTTP method enforcement
|
|
96
|
+
for (const rule of methodRules) {
|
|
97
|
+
if (matchesPathPattern(pathname, rule.pattern)) {
|
|
98
|
+
const allowed = [...new Set(rule.methods.map((m) => m.toUpperCase()))];
|
|
99
|
+
if (!allowed.includes(method)) {
|
|
100
|
+
const response = new Response('Method Not Allowed', {
|
|
101
|
+
status: 405,
|
|
102
|
+
headers: {
|
|
103
|
+
Allow: allowed.join(', '),
|
|
104
|
+
'Content-Type': 'text/plain; charset=utf-8'
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
return applySecurityHeaders(response, headerConfig);
|
|
108
|
+
}
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
// 2. Origin / CSRF check on state-changing requests
|
|
113
|
+
if (csrfEnabled && STATE_CHANGING_METHODS.has(method)) {
|
|
114
|
+
const isExempt = csrfExemptPaths.some((pattern) => matchesPathPattern(pathname, pattern));
|
|
115
|
+
if (!isExempt) {
|
|
116
|
+
const originHeader = event.request.headers.get('origin');
|
|
117
|
+
const requestOrigin = event.url.origin.toLowerCase();
|
|
118
|
+
const normalizedOrigin = originHeader !== null ? normalizeOrigin(originHeader) : undefined;
|
|
119
|
+
const isAllowedOrigin = normalizedOrigin !== undefined &&
|
|
120
|
+
(normalizedOrigin === requestOrigin ||
|
|
121
|
+
configuredAllowedOrigins.includes(normalizedOrigin));
|
|
122
|
+
if (!isAllowedOrigin) {
|
|
123
|
+
const response = new Response('Cross-site request forbidden', {
|
|
124
|
+
status: 403,
|
|
125
|
+
headers: {
|
|
126
|
+
'Content-Type': 'text/plain; charset=utf-8'
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
return applySecurityHeaders(response, headerConfig);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
// 3. Downstream resolution with guaranteed security headers even on thrown 500s
|
|
134
|
+
try {
|
|
135
|
+
const response = await resolve(event);
|
|
136
|
+
return applySecurityHeaders(response, headerConfig);
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
options?.onError?.(error, event);
|
|
140
|
+
const response = new Response('Internal Server Error', {
|
|
141
|
+
status: 500,
|
|
142
|
+
headers: {
|
|
143
|
+
'Content-Type': 'text/plain; charset=utf-8'
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
return applySecurityHeaders(response, headerConfig);
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
}
|
package/dist/tenant.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import * as Context from 'effect/Context';
|
|
2
|
+
import * as Effect from 'effect/Effect';
|
|
3
|
+
import * as Schema from 'effect/Schema';
|
|
4
|
+
/**
|
|
5
|
+
* Branded non-empty tenant identifier schema.
|
|
6
|
+
*/
|
|
7
|
+
export declare const TenantId: Schema.brand<Schema.NonEmptyString, "TenantId">;
|
|
8
|
+
export type TenantId = typeof TenantId.Type;
|
|
9
|
+
/**
|
|
10
|
+
* Authenticated actor + tenant principal decoded at ingress boundaries.
|
|
11
|
+
*/
|
|
12
|
+
export declare const ActorAuth: Schema.Struct<{
|
|
13
|
+
readonly actorId: Schema.NonEmptyString;
|
|
14
|
+
readonly tenantId: Schema.brand<Schema.NonEmptyString, "TenantId">;
|
|
15
|
+
readonly roles: Schema.optional<Schema.$Array<Schema.NonEmptyString>>;
|
|
16
|
+
}>;
|
|
17
|
+
export type ActorAuth = typeof ActorAuth.Type;
|
|
18
|
+
declare const CurrentTenant_base: Context.ServiceClass<CurrentTenant, "@benchcutlogic/edge-kit/CurrentTenant", {
|
|
19
|
+
readonly actorId: string;
|
|
20
|
+
readonly tenantId: string & import("effect/Brand").Brand<"TenantId">;
|
|
21
|
+
readonly roles?: readonly string[] | undefined;
|
|
22
|
+
}>;
|
|
23
|
+
/**
|
|
24
|
+
* Effect service holding the authenticated actor and tenant for the current request scope.
|
|
25
|
+
*/
|
|
26
|
+
export declare class CurrentTenant extends CurrentTenant_base {
|
|
27
|
+
}
|
|
28
|
+
export interface ScopedQueryContext<Db> {
|
|
29
|
+
readonly db: Db;
|
|
30
|
+
readonly tenantId: TenantId;
|
|
31
|
+
readonly actor: ActorAuth;
|
|
32
|
+
}
|
|
33
|
+
export interface ScopedQueryRunner<Db> {
|
|
34
|
+
readonly run: <A, E, R = never>(fn: (ctx: ScopedQueryContext<Db>) => Effect.Effect<A, E, R>) => Effect.Effect<A, E, CurrentTenant | R>;
|
|
35
|
+
readonly tenantId: Effect.Effect<TenantId, never, CurrentTenant>;
|
|
36
|
+
readonly actor: Effect.Effect<ActorAuth, never, CurrentTenant>;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Wraps a database handle so every query executed through the runner requires
|
|
40
|
+
* `CurrentTenant` in the Effect context and receives the verified `tenantId`
|
|
41
|
+
* and `actor` alongside `db`.
|
|
42
|
+
*/
|
|
43
|
+
export declare function createScopedQueryRunner<Db>(db: Db): ScopedQueryRunner<Db>;
|
|
44
|
+
export {};
|
package/dist/tenant.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import * as Context from 'effect/Context';
|
|
2
|
+
import * as Effect from 'effect/Effect';
|
|
3
|
+
import * as Schema from 'effect/Schema';
|
|
4
|
+
/**
|
|
5
|
+
* Branded non-empty tenant identifier schema.
|
|
6
|
+
*/
|
|
7
|
+
export const TenantId = Schema.NonEmptyString.pipe(Schema.brand('TenantId'));
|
|
8
|
+
/**
|
|
9
|
+
* Authenticated actor + tenant principal decoded at ingress boundaries.
|
|
10
|
+
*/
|
|
11
|
+
export const ActorAuth = Schema.Struct({
|
|
12
|
+
actorId: Schema.NonEmptyString,
|
|
13
|
+
tenantId: TenantId,
|
|
14
|
+
roles: Schema.optional(Schema.Array(Schema.NonEmptyString))
|
|
15
|
+
});
|
|
16
|
+
/**
|
|
17
|
+
* Effect service holding the authenticated actor and tenant for the current request scope.
|
|
18
|
+
*/
|
|
19
|
+
export class CurrentTenant extends Context.Service()('@benchcutlogic/edge-kit/CurrentTenant') {
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Wraps a database handle so every query executed through the runner requires
|
|
23
|
+
* `CurrentTenant` in the Effect context and receives the verified `tenantId`
|
|
24
|
+
* and `actor` alongside `db`.
|
|
25
|
+
*/
|
|
26
|
+
export function createScopedQueryRunner(db) {
|
|
27
|
+
const actor = Effect.gen(function* () {
|
|
28
|
+
return yield* CurrentTenant;
|
|
29
|
+
});
|
|
30
|
+
const tenantId = Effect.map(actor, (current) => current.tenantId);
|
|
31
|
+
return {
|
|
32
|
+
actor,
|
|
33
|
+
tenantId,
|
|
34
|
+
run: (fn) => Effect.gen(function* () {
|
|
35
|
+
const current = yield* CurrentTenant;
|
|
36
|
+
return yield* fn({
|
|
37
|
+
db,
|
|
38
|
+
tenantId: current.tenantId,
|
|
39
|
+
actor: current
|
|
40
|
+
});
|
|
41
|
+
})
|
|
42
|
+
};
|
|
43
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,90 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@benchcutlogic/edge-kit",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "Edge security, SSRF protection, capped body readers, error scrubbing, safe analytics, SvelteKit security handle, and tenant scoping utilities.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"import": "./dist/index.js",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./ssrf": {
|
|
14
|
+
"types": "./dist/ssrf.d.ts",
|
|
15
|
+
"import": "./dist/ssrf.js",
|
|
16
|
+
"default": "./dist/ssrf.js"
|
|
17
|
+
},
|
|
18
|
+
"./body": {
|
|
19
|
+
"types": "./dist/body.d.ts",
|
|
20
|
+
"import": "./dist/body.js",
|
|
21
|
+
"default": "./dist/body.js"
|
|
22
|
+
},
|
|
23
|
+
"./scrub": {
|
|
24
|
+
"types": "./dist/scrub.d.ts",
|
|
25
|
+
"import": "./dist/scrub.js",
|
|
26
|
+
"default": "./dist/scrub.js"
|
|
27
|
+
},
|
|
28
|
+
"./analytics": {
|
|
29
|
+
"types": "./dist/analytics.d.ts",
|
|
30
|
+
"import": "./dist/analytics.js",
|
|
31
|
+
"default": "./dist/analytics.js"
|
|
32
|
+
},
|
|
33
|
+
"./sveltekit": {
|
|
34
|
+
"types": "./dist/sveltekit.d.ts",
|
|
35
|
+
"import": "./dist/sveltekit.js",
|
|
36
|
+
"default": "./dist/sveltekit.js"
|
|
37
|
+
},
|
|
38
|
+
"./tenant": {
|
|
39
|
+
"types": "./dist/tenant.d.ts",
|
|
40
|
+
"import": "./dist/tenant.js",
|
|
41
|
+
"default": "./dist/tenant.js"
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
"sideEffects": false,
|
|
45
|
+
"files": [
|
|
46
|
+
"dist",
|
|
47
|
+
"LICENSE",
|
|
48
|
+
"README.md"
|
|
49
|
+
],
|
|
50
|
+
"engines": {
|
|
51
|
+
"node": ">=20"
|
|
52
|
+
},
|
|
53
|
+
"repository": {
|
|
54
|
+
"type": "git",
|
|
55
|
+
"url": "git+https://github.com/benchcutlogic/bench.git",
|
|
56
|
+
"directory": "packages/edge-kit"
|
|
57
|
+
},
|
|
58
|
+
"homepage": "https://github.com/benchcutlogic/bench/tree/main/packages/edge-kit",
|
|
59
|
+
"bugs": {
|
|
60
|
+
"url": "https://github.com/benchcutlogic/bench/issues"
|
|
61
|
+
},
|
|
62
|
+
"publishConfig": {
|
|
63
|
+
"registry": "https://registry.npmjs.org",
|
|
64
|
+
"access": "public",
|
|
65
|
+
"provenance": false
|
|
66
|
+
},
|
|
67
|
+
"dependencies": {
|
|
68
|
+
"ipaddr.js": "^2.2.0"
|
|
69
|
+
},
|
|
70
|
+
"peerDependencies": {
|
|
71
|
+
"effect": "^4.0.7"
|
|
72
|
+
},
|
|
73
|
+
"devDependencies": {
|
|
74
|
+
"@sveltejs/kit": "^2.70.3",
|
|
75
|
+
"@sveltejs/vite-plugin-svelte": "^6.2.4",
|
|
76
|
+
"@types/node": "^22.15.0",
|
|
77
|
+
"effect": "^4.0.7",
|
|
78
|
+
"svelte": "^5.57.3",
|
|
79
|
+
"typescript": "^5.9.3",
|
|
80
|
+
"vite": "^7.3.6",
|
|
81
|
+
"vitest": "^4.1.11"
|
|
82
|
+
},
|
|
83
|
+
"scripts": {
|
|
84
|
+
"package": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json",
|
|
85
|
+
"build": "pnpm run package",
|
|
86
|
+
"check": "tsc --noEmit",
|
|
87
|
+
"typecheck": "pnpm run check",
|
|
88
|
+
"test": "vitest run"
|
|
89
|
+
}
|
|
6
90
|
}
|