@sigil-dev/grimoire 0.9.21 → 0.9.22
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 +83 -83
- package/index.ts +50 -48
- package/package.json +16 -5
- package/public/__grimoire__/grimoire-client.js +12 -0
- package/public/__grimoire__/runtime.js +1241 -0
- package/server.ts +22 -20
- package/src/adapters/bun.ts +17 -0
- package/src/adapters/static.ts +41 -0
- package/src/adapters/types.ts +36 -0
- package/src/base.ts +91 -0
- package/src/client/csrf.ts +47 -47
- package/src/client/deferred.ts +179 -179
- package/src/client/enhance.ts +160 -160
- package/src/client/router.ts +870 -833
- package/src/dev/compile-module.ts +211 -211
- package/src/dev/loader.ts +141 -141
- package/src/dev/resolve.ts +70 -70
- package/src/dev/runtime-bundle.ts +51 -51
- package/src/env/modules.ts +62 -62
- package/src/env/required.ts +42 -0
- package/src/env/typegen.ts +61 -61
- package/src/headers.ts +105 -105
- package/src/logger/transports.ts +117 -117
- package/src/rendering/head.ts +49 -49
- package/src/rendering/hydrate.ts +161 -161
- package/src/rendering/images.ts +43 -43
- package/src/rendering/index.ts +755 -749
- package/src/rendering/preload.ts +101 -101
- package/src/rendering/ssrPlugin.ts +108 -108
- package/src/rendering/timing.ts +40 -40
- package/src/routing/router.ts +186 -186
- package/src/routing/scanner.ts +225 -196
- package/src/routing/transform-routes.ts +102 -102
- package/src/server/after-response.ts +206 -206
- package/src/server/asset-cache.ts +57 -57
- package/src/server/build.ts +262 -262
- package/src/server/cached.ts +114 -114
- package/src/server/client-address.ts +82 -82
- package/src/server/client-dir.ts +57 -57
- package/src/server/client-entry.ts +44 -44
- package/src/server/cookie-utils.ts +80 -80
- package/src/server/coordinator.ts +476 -471
- package/src/server/hooks.ts +122 -122
- package/src/server/index.ts +1138 -1018
- package/src/server/plugins.ts +172 -172
- package/src/server/prerender.ts +444 -0
- package/src/server/reserved.ts +17 -0
- package/src/server/resolver.ts +98 -98
- package/src/server/rewrite.ts +28 -0
- package/src/server/warm.ts +91 -91
- package/src/server/with-headers.ts +27 -27
- package/src/server/worker.ts +74 -72
- package/src/testing/dom.ts +73 -0
- package/src/testing/index.ts +169 -0
- package/src/testing/server.ts +162 -0
- package/src/typegen/index.ts +450 -450
- package/src/types.ts +501 -432
- package/test/after-response.test.ts +132 -132
- package/test/asset-cache-policy.test.ts +96 -96
- package/test/base.test.ts +134 -0
- package/test/cached.test.ts +126 -126
- package/test/client-address.test.ts +78 -78
- package/test/client-csrf.test.ts +61 -61
- package/test/client-dir.test.ts +101 -101
- package/test/client-router.test.ts +789 -734
- package/test/coordinator.test.ts +96 -94
- package/test/deferred.test.ts +256 -256
- package/test/dev-loader.test.ts +30 -30
- package/test/env.test.ts +168 -168
- package/test/force-production.test.ts +44 -0
- package/test/images.test.ts +49 -49
- package/test/locals-header.test.ts +61 -0
- package/test/middleware.test.ts +243 -243
- package/test/parser-plugins.test.ts +92 -92
- package/test/plugin-handle.test.ts +62 -62
- package/test/plugin-services-context.test.ts +97 -97
- package/test/preload.test.ts +48 -48
- package/test/prerender.test.ts +353 -0
- package/test/rendering.test.ts +798 -798
- package/test/required-env.test.ts +32 -0
- package/test/rewrite-html.test.ts +90 -0
- package/test/scanning.test.ts +349 -314
- package/test/server.test.ts +640 -619
- package/test/services.test.ts +90 -90
- package/test/streaming.test.ts +378 -378
- package/test/testing-helpers.test.ts +166 -0
- package/test/typegen.test.ts +805 -799
- package/test/warm.test.ts +96 -96
- package/test/worker-context.test.ts +59 -59
- package/test/workspace-files.test.ts +149 -146
- package/test/workspace-versions.test.ts +131 -131
- package/.grimoire/_routes.ts +0 -4
- package/public/__grimoire__/client.js +0 -55
- package/public/__grimoire__/hydrate.js +0 -63
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { GrimoireConfig } from "../types";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Names that must be set before a server starts, from `env.required` in the
|
|
5
|
+
* config and from each plugin's `requiredEnv`.
|
|
6
|
+
*
|
|
7
|
+
* `$env/*` reads a missing variable as "", which turns an unset secret into a
|
|
8
|
+
* confusing failure somewhere far from the cause. Checking at boot moves the
|
|
9
|
+
* failure to the one place that can name the variable.
|
|
10
|
+
*
|
|
11
|
+
* Empty counts as missing: `FOO=` in a compose file is how a variable ends up
|
|
12
|
+
* "set" and useless.
|
|
13
|
+
*/
|
|
14
|
+
export function missingEnv(
|
|
15
|
+
config: Pick<GrimoireConfig, "env" | "plugins">,
|
|
16
|
+
env: Record<string, string | undefined> = process.env,
|
|
17
|
+
): { name: string; by: string }[] {
|
|
18
|
+
const wanted = new Map<string, string>();
|
|
19
|
+
for (const name of config.env?.required ?? [])
|
|
20
|
+
wanted.set(name, "sigil.config.ts");
|
|
21
|
+
for (const plugin of config.plugins ?? []) {
|
|
22
|
+
for (const name of plugin.requiredEnv ?? []) {
|
|
23
|
+
if (!wanted.has(name)) wanted.set(name, `plugin "${plugin.name}"`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return [...wanted]
|
|
27
|
+
.filter(([name]) => !env[name])
|
|
28
|
+
.map(([name, by]) => ({ name, by }));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Throws one error listing every missing variable, so a deploy is fixed in one pass. */
|
|
32
|
+
export function assertRequiredEnv(
|
|
33
|
+
config: Pick<GrimoireConfig, "env" | "plugins">,
|
|
34
|
+
env: Record<string, string | undefined> = process.env,
|
|
35
|
+
): void {
|
|
36
|
+
const missing = missingEnv(config, env);
|
|
37
|
+
if (!missing.length) return;
|
|
38
|
+
throw new Error(
|
|
39
|
+
`Missing required environment variable${missing.length > 1 ? "s" : ""}:\n` +
|
|
40
|
+
missing.map((m) => ` ${m.name} (required by ${m.by})`).join("\n"),
|
|
41
|
+
);
|
|
42
|
+
}
|
package/src/env/typegen.ts
CHANGED
|
@@ -1,61 +1,61 @@
|
|
|
1
|
-
import { readFile, writeFile } from "node:fs/promises";
|
|
2
|
-
import { join } from "node:path";
|
|
3
|
-
|
|
4
|
-
export async function generateEnvTypes(
|
|
5
|
-
projectRoot: string,
|
|
6
|
-
outDir: string,
|
|
7
|
-
): Promise<void> {
|
|
8
|
-
const envPath = join(projectRoot, ".env");
|
|
9
|
-
let envContent = "";
|
|
10
|
-
try {
|
|
11
|
-
envContent = await readFile(envPath, "utf-8");
|
|
12
|
-
} catch {
|
|
13
|
-
// no .env file — generate empty types
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
const publicVars: string[] = [];
|
|
17
|
-
const privateVars: string[] = [];
|
|
18
|
-
|
|
19
|
-
for (const line of envContent.split("\n")) {
|
|
20
|
-
const trimmed = line.trim();
|
|
21
|
-
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
22
|
-
const eqIndex = trimmed.indexOf("=");
|
|
23
|
-
if (eqIndex === -1) continue;
|
|
24
|
-
const key = trimmed.slice(0, eqIndex).trim();
|
|
25
|
-
if (!key) continue;
|
|
26
|
-
if (key.startsWith("PUBLIC_")) {
|
|
27
|
-
publicVars.push(key);
|
|
28
|
-
} else {
|
|
29
|
-
privateVars.push(key);
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
const publicTypeContent = `// Auto-generated by Grimoire. Do not edit.
|
|
34
|
-
declare module "$env/static/public" {
|
|
35
|
-
\texport const env: Record<string, string>;
|
|
36
|
-
${publicVars.map((v) => `\texport const ${v}: string;`).join("\n")}
|
|
37
|
-
}
|
|
38
|
-
`;
|
|
39
|
-
|
|
40
|
-
const privateTypeContent = `// Auto-generated by Grimoire. Do not edit.
|
|
41
|
-
declare module "$env/static/private" {
|
|
42
|
-
\texport const env: Record<string, string>;
|
|
43
|
-
${privateVars.map((v) => `\texport const ${v}: string;`).join("\n")}
|
|
44
|
-
}
|
|
45
|
-
`;
|
|
46
|
-
|
|
47
|
-
const dynamicTypeContent = `// Auto-generated by Grimoire. Do not edit.
|
|
48
|
-
declare module "$env/dynamic/public" {
|
|
49
|
-
\texport const env: Record<string, string>;
|
|
50
|
-
}
|
|
51
|
-
declare module "$env/dynamic/private" {
|
|
52
|
-
\texport const env: Record<string, string>;
|
|
53
|
-
}
|
|
54
|
-
`;
|
|
55
|
-
|
|
56
|
-
await Promise.all([
|
|
57
|
-
writeFile(join(outDir, "env-public.d.ts"), publicTypeContent, "utf-8"),
|
|
58
|
-
writeFile(join(outDir, "env-private.d.ts"), privateTypeContent, "utf-8"),
|
|
59
|
-
writeFile(join(outDir, "env-dynamic.d.ts"), dynamicTypeContent, "utf-8"),
|
|
60
|
-
]);
|
|
61
|
-
}
|
|
1
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
export async function generateEnvTypes(
|
|
5
|
+
projectRoot: string,
|
|
6
|
+
outDir: string,
|
|
7
|
+
): Promise<void> {
|
|
8
|
+
const envPath = join(projectRoot, ".env");
|
|
9
|
+
let envContent = "";
|
|
10
|
+
try {
|
|
11
|
+
envContent = await readFile(envPath, "utf-8");
|
|
12
|
+
} catch {
|
|
13
|
+
// no .env file — generate empty types
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const publicVars: string[] = [];
|
|
17
|
+
const privateVars: string[] = [];
|
|
18
|
+
|
|
19
|
+
for (const line of envContent.split("\n")) {
|
|
20
|
+
const trimmed = line.trim();
|
|
21
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
22
|
+
const eqIndex = trimmed.indexOf("=");
|
|
23
|
+
if (eqIndex === -1) continue;
|
|
24
|
+
const key = trimmed.slice(0, eqIndex).trim();
|
|
25
|
+
if (!key) continue;
|
|
26
|
+
if (key.startsWith("PUBLIC_")) {
|
|
27
|
+
publicVars.push(key);
|
|
28
|
+
} else {
|
|
29
|
+
privateVars.push(key);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const publicTypeContent = `// Auto-generated by Grimoire. Do not edit.
|
|
34
|
+
declare module "$env/static/public" {
|
|
35
|
+
\texport const env: Record<string, string>;
|
|
36
|
+
${publicVars.map((v) => `\texport const ${v}: string;`).join("\n")}
|
|
37
|
+
}
|
|
38
|
+
`;
|
|
39
|
+
|
|
40
|
+
const privateTypeContent = `// Auto-generated by Grimoire. Do not edit.
|
|
41
|
+
declare module "$env/static/private" {
|
|
42
|
+
\texport const env: Record<string, string>;
|
|
43
|
+
${privateVars.map((v) => `\texport const ${v}: string;`).join("\n")}
|
|
44
|
+
}
|
|
45
|
+
`;
|
|
46
|
+
|
|
47
|
+
const dynamicTypeContent = `// Auto-generated by Grimoire. Do not edit.
|
|
48
|
+
declare module "$env/dynamic/public" {
|
|
49
|
+
\texport const env: Record<string, string>;
|
|
50
|
+
}
|
|
51
|
+
declare module "$env/dynamic/private" {
|
|
52
|
+
\texport const env: Record<string, string>;
|
|
53
|
+
}
|
|
54
|
+
`;
|
|
55
|
+
|
|
56
|
+
await Promise.all([
|
|
57
|
+
writeFile(join(outDir, "env-public.d.ts"), publicTypeContent, "utf-8"),
|
|
58
|
+
writeFile(join(outDir, "env-private.d.ts"), privateTypeContent, "utf-8"),
|
|
59
|
+
writeFile(join(outDir, "env-dynamic.d.ts"), dynamicTypeContent, "utf-8"),
|
|
60
|
+
]);
|
|
61
|
+
}
|
package/src/headers.ts
CHANGED
|
@@ -1,105 +1,105 @@
|
|
|
1
|
-
import { withHeaders } from "./server/with-headers";
|
|
2
|
-
import type { GrimoirePlugin } from "./types";
|
|
3
|
-
|
|
4
|
-
export interface SecurityHeadersConfig {
|
|
5
|
-
/** Content-Security-Policy. Set false to omit. */
|
|
6
|
-
contentSecurityPolicy?: string | false;
|
|
7
|
-
/** X-Content-Type-Options. Default: "nosniff" */
|
|
8
|
-
contentTypeOptions?: string | false;
|
|
9
|
-
/** X-Frame-Options. Default: "DENY" */
|
|
10
|
-
frameOptions?: string | false;
|
|
11
|
-
/** X-XSS-Protection. Default: "0" (modern browsers; "1; mode=block" for legacy) */
|
|
12
|
-
xssProtection?: string | false;
|
|
13
|
-
/** Referrer-Policy. Default: "strict-origin-when-cross-origin" */
|
|
14
|
-
referrerPolicy?: string | false;
|
|
15
|
-
/** Strict-Transport-Security. Set false to omit. */
|
|
16
|
-
strictTransportSecurity?: string | false;
|
|
17
|
-
/** Permissions-Policy. Default: "camera=(), microphone=(), geolocation=()" */
|
|
18
|
-
permissionsPolicy?: string | false;
|
|
19
|
-
/** Per-route overrides: path pattern → partial config */
|
|
20
|
-
routes?: Record<string, Partial<SecurityHeadersConfig>>;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
const DEFAULTS: Required<Omit<SecurityHeadersConfig, "routes">> = {
|
|
24
|
-
contentSecurityPolicy:
|
|
25
|
-
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;",
|
|
26
|
-
contentTypeOptions: "nosniff",
|
|
27
|
-
frameOptions: "DENY",
|
|
28
|
-
xssProtection: "0",
|
|
29
|
-
referrerPolicy: "strict-origin-when-cross-origin",
|
|
30
|
-
strictTransportSecurity: "max-age=31536000; includeSubDomains",
|
|
31
|
-
permissionsPolicy: "camera=(), microphone=(), geolocation=()",
|
|
32
|
-
};
|
|
33
|
-
|
|
34
|
-
function resolveHeaders(
|
|
35
|
-
config: SecurityHeadersConfig,
|
|
36
|
-
pathname: string,
|
|
37
|
-
): Record<string, string> {
|
|
38
|
-
// Start with defaults, overlay user config
|
|
39
|
-
const merged = { ...DEFAULTS, ...config };
|
|
40
|
-
delete (merged as any).routes;
|
|
41
|
-
|
|
42
|
-
// Apply route overrides
|
|
43
|
-
if (config.routes) {
|
|
44
|
-
for (const pattern in config.routes) {
|
|
45
|
-
if (pathname.startsWith(pattern)) {
|
|
46
|
-
Object.assign(merged, config.routes[pattern]);
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
const headers: Record<string, string> = {};
|
|
52
|
-
|
|
53
|
-
if (merged.contentSecurityPolicy !== false)
|
|
54
|
-
headers["Content-Security-Policy"] = merged.contentSecurityPolicy;
|
|
55
|
-
if (merged.contentTypeOptions !== false)
|
|
56
|
-
headers["X-Content-Type-Options"] = merged.contentTypeOptions;
|
|
57
|
-
if (merged.frameOptions !== false)
|
|
58
|
-
headers["X-Frame-Options"] = merged.frameOptions;
|
|
59
|
-
if (merged.xssProtection !== false)
|
|
60
|
-
headers["X-XSS-Protection"] = merged.xssProtection;
|
|
61
|
-
if (merged.referrerPolicy !== false)
|
|
62
|
-
headers["Referrer-Policy"] = merged.referrerPolicy;
|
|
63
|
-
if (merged.strictTransportSecurity !== false)
|
|
64
|
-
headers["Strict-Transport-Security"] = merged.strictTransportSecurity;
|
|
65
|
-
if (merged.permissionsPolicy !== false)
|
|
66
|
-
headers["Permissions-Policy"] = merged.permissionsPolicy;
|
|
67
|
-
|
|
68
|
-
return headers;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* Security headers plugin.
|
|
73
|
-
* Adds standard security headers to all responses.
|
|
74
|
-
*
|
|
75
|
-
* Usage:
|
|
76
|
-
*
|
|
77
|
-
* import { securityHeaders } from "@sigil-dev/grimoire/headers";
|
|
78
|
-
*
|
|
79
|
-
* createServer({
|
|
80
|
-
* plugins: [
|
|
81
|
-
* securityHeaders({
|
|
82
|
-
* // override defaults
|
|
83
|
-
* frameOptions: "SAMEORIGIN",
|
|
84
|
-
* // per-route
|
|
85
|
-
* routes: {
|
|
86
|
-
* "/admin": { contentSecurityPolicy: "default-src 'self'" },
|
|
87
|
-
* },
|
|
88
|
-
* }),
|
|
89
|
-
* ],
|
|
90
|
-
* });
|
|
91
|
-
*/
|
|
92
|
-
export function securityHeaders(
|
|
93
|
-
config: SecurityHeadersConfig = {},
|
|
94
|
-
): GrimoirePlugin {
|
|
95
|
-
return {
|
|
96
|
-
name: "grimoire-security-headers",
|
|
97
|
-
async onRequest(req, next) {
|
|
98
|
-
const res = await next();
|
|
99
|
-
const url = new URL(req.url);
|
|
100
|
-
const headers = resolveHeaders(config, url.pathname);
|
|
101
|
-
|
|
102
|
-
return withHeaders(res, Object.entries(headers));
|
|
103
|
-
},
|
|
104
|
-
};
|
|
105
|
-
}
|
|
1
|
+
import { withHeaders } from "./server/with-headers";
|
|
2
|
+
import type { GrimoirePlugin } from "./types";
|
|
3
|
+
|
|
4
|
+
export interface SecurityHeadersConfig {
|
|
5
|
+
/** Content-Security-Policy. Set false to omit. */
|
|
6
|
+
contentSecurityPolicy?: string | false;
|
|
7
|
+
/** X-Content-Type-Options. Default: "nosniff" */
|
|
8
|
+
contentTypeOptions?: string | false;
|
|
9
|
+
/** X-Frame-Options. Default: "DENY" */
|
|
10
|
+
frameOptions?: string | false;
|
|
11
|
+
/** X-XSS-Protection. Default: "0" (modern browsers; "1; mode=block" for legacy) */
|
|
12
|
+
xssProtection?: string | false;
|
|
13
|
+
/** Referrer-Policy. Default: "strict-origin-when-cross-origin" */
|
|
14
|
+
referrerPolicy?: string | false;
|
|
15
|
+
/** Strict-Transport-Security. Set false to omit. */
|
|
16
|
+
strictTransportSecurity?: string | false;
|
|
17
|
+
/** Permissions-Policy. Default: "camera=(), microphone=(), geolocation=()" */
|
|
18
|
+
permissionsPolicy?: string | false;
|
|
19
|
+
/** Per-route overrides: path pattern → partial config */
|
|
20
|
+
routes?: Record<string, Partial<SecurityHeadersConfig>>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const DEFAULTS: Required<Omit<SecurityHeadersConfig, "routes">> = {
|
|
24
|
+
contentSecurityPolicy:
|
|
25
|
+
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;",
|
|
26
|
+
contentTypeOptions: "nosniff",
|
|
27
|
+
frameOptions: "DENY",
|
|
28
|
+
xssProtection: "0",
|
|
29
|
+
referrerPolicy: "strict-origin-when-cross-origin",
|
|
30
|
+
strictTransportSecurity: "max-age=31536000; includeSubDomains",
|
|
31
|
+
permissionsPolicy: "camera=(), microphone=(), geolocation=()",
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
function resolveHeaders(
|
|
35
|
+
config: SecurityHeadersConfig,
|
|
36
|
+
pathname: string,
|
|
37
|
+
): Record<string, string> {
|
|
38
|
+
// Start with defaults, overlay user config
|
|
39
|
+
const merged = { ...DEFAULTS, ...config };
|
|
40
|
+
delete (merged as any).routes;
|
|
41
|
+
|
|
42
|
+
// Apply route overrides
|
|
43
|
+
if (config.routes) {
|
|
44
|
+
for (const pattern in config.routes) {
|
|
45
|
+
if (pathname.startsWith(pattern)) {
|
|
46
|
+
Object.assign(merged, config.routes[pattern]);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const headers: Record<string, string> = {};
|
|
52
|
+
|
|
53
|
+
if (merged.contentSecurityPolicy !== false)
|
|
54
|
+
headers["Content-Security-Policy"] = merged.contentSecurityPolicy;
|
|
55
|
+
if (merged.contentTypeOptions !== false)
|
|
56
|
+
headers["X-Content-Type-Options"] = merged.contentTypeOptions;
|
|
57
|
+
if (merged.frameOptions !== false)
|
|
58
|
+
headers["X-Frame-Options"] = merged.frameOptions;
|
|
59
|
+
if (merged.xssProtection !== false)
|
|
60
|
+
headers["X-XSS-Protection"] = merged.xssProtection;
|
|
61
|
+
if (merged.referrerPolicy !== false)
|
|
62
|
+
headers["Referrer-Policy"] = merged.referrerPolicy;
|
|
63
|
+
if (merged.strictTransportSecurity !== false)
|
|
64
|
+
headers["Strict-Transport-Security"] = merged.strictTransportSecurity;
|
|
65
|
+
if (merged.permissionsPolicy !== false)
|
|
66
|
+
headers["Permissions-Policy"] = merged.permissionsPolicy;
|
|
67
|
+
|
|
68
|
+
return headers;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Security headers plugin.
|
|
73
|
+
* Adds standard security headers to all responses.
|
|
74
|
+
*
|
|
75
|
+
* Usage:
|
|
76
|
+
*
|
|
77
|
+
* import { securityHeaders } from "@sigil-dev/grimoire/headers";
|
|
78
|
+
*
|
|
79
|
+
* createServer({
|
|
80
|
+
* plugins: [
|
|
81
|
+
* securityHeaders({
|
|
82
|
+
* // override defaults
|
|
83
|
+
* frameOptions: "SAMEORIGIN",
|
|
84
|
+
* // per-route
|
|
85
|
+
* routes: {
|
|
86
|
+
* "/admin": { contentSecurityPolicy: "default-src 'self'" },
|
|
87
|
+
* },
|
|
88
|
+
* }),
|
|
89
|
+
* ],
|
|
90
|
+
* });
|
|
91
|
+
*/
|
|
92
|
+
export function securityHeaders(
|
|
93
|
+
config: SecurityHeadersConfig = {},
|
|
94
|
+
): GrimoirePlugin {
|
|
95
|
+
return {
|
|
96
|
+
name: "grimoire-security-headers",
|
|
97
|
+
async onRequest(req, next) {
|
|
98
|
+
const res = await next();
|
|
99
|
+
const url = new URL(req.url);
|
|
100
|
+
const headers = resolveHeaders(config, url.pathname);
|
|
101
|
+
|
|
102
|
+
return withHeaders(res, Object.entries(headers));
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
}
|
package/src/logger/transports.ts
CHANGED
|
@@ -1,117 +1,117 @@
|
|
|
1
|
-
// packages/grimoire/src/logger/transports.ts
|
|
2
|
-
|
|
3
|
-
import { appendFileSync } from "node:fs";
|
|
4
|
-
import type { LogEntry, LogTransport } from "./types.ts";
|
|
5
|
-
|
|
6
|
-
// ── colours (only applied when stdout is a TTY) ──────────────────────────────
|
|
7
|
-
|
|
8
|
-
const isTTY = process.stdout.isTTY;
|
|
9
|
-
const c = isTTY
|
|
10
|
-
? {
|
|
11
|
-
reset: "\x1b[0m",
|
|
12
|
-
dim: "\x1b[2m",
|
|
13
|
-
bold: "\x1b[1m",
|
|
14
|
-
debug: "\x1b[90m", // grey
|
|
15
|
-
info: "\x1b[36m", // cyan
|
|
16
|
-
warn: "\x1b[33m", // yellow
|
|
17
|
-
error: "\x1b[31m", // red
|
|
18
|
-
fatal: "\x1b[35m", // magenta
|
|
19
|
-
scope: "\x1b[34m", // blue
|
|
20
|
-
req: "\x1b[32m", // green
|
|
21
|
-
}
|
|
22
|
-
: (Object.fromEntries(
|
|
23
|
-
[
|
|
24
|
-
"reset",
|
|
25
|
-
"dim",
|
|
26
|
-
"bold",
|
|
27
|
-
"debug",
|
|
28
|
-
"info",
|
|
29
|
-
"warn",
|
|
30
|
-
"error",
|
|
31
|
-
"fatal",
|
|
32
|
-
"scope",
|
|
33
|
-
"req",
|
|
34
|
-
].map((k) => [k, ""]),
|
|
35
|
-
) as Record<string, string>);
|
|
36
|
-
|
|
37
|
-
const LEVEL_LABEL: Record<string, string> = {
|
|
38
|
-
debug: "DBG",
|
|
39
|
-
info: "INF",
|
|
40
|
-
warn: "WRN",
|
|
41
|
-
error: "ERR",
|
|
42
|
-
fatal: "FTL",
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
function ts(timestamp: number): string {
|
|
46
|
-
return new Date(timestamp).toISOString().slice(11, 23); // HH:mm:ss.ms
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
function formatData(data: unknown): string {
|
|
50
|
-
if (data === undefined) return "";
|
|
51
|
-
if (data instanceof Error) return `\n ${data.stack ?? data.message}`;
|
|
52
|
-
if (typeof data !== "object" || data === null) return ` ${String(data)}`;
|
|
53
|
-
|
|
54
|
-
// flat key=value for simple objects, JSON block only for nested/complex
|
|
55
|
-
const entries = Object.entries(data as Record<string, unknown>);
|
|
56
|
-
const isFlat = entries.every(([, v]) => typeof v !== "object" || v === null);
|
|
57
|
-
if (isFlat) {
|
|
58
|
-
return ` ${entries.map(([k, v]) => `${c.dim}${k}=${c.reset}${v}`).join(" ")}`;
|
|
59
|
-
}
|
|
60
|
-
// nested — indent but don't pretty-print the whole thing
|
|
61
|
-
return `\n ${JSON.stringify(data).replace(/,/g, ", ")}`;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
// ── ConsoleTransport ─────────────────────────────────────────────────────────
|
|
65
|
-
|
|
66
|
-
export class ConsoleTransport implements LogTransport {
|
|
67
|
-
write(entry: LogEntry) {
|
|
68
|
-
const levelColor = c[entry.level] ?? c.info;
|
|
69
|
-
const label = LEVEL_LABEL[entry.level] ?? entry.level.toUpperCase();
|
|
70
|
-
|
|
71
|
-
const worker = entry.worker ? `${c.dim}[${entry.worker}]${c.reset} ` : "";
|
|
72
|
-
const requestId = entry.requestId
|
|
73
|
-
? `${c.req}#${entry.requestId.slice(0, 8)}${c.reset} `
|
|
74
|
-
: "";
|
|
75
|
-
const scope = `${c.scope}${entry.scope}${c.reset}`;
|
|
76
|
-
const time = `${c.dim}${ts(entry.timestamp)}${c.reset}`;
|
|
77
|
-
const lvl = `${levelColor}${c.bold}${label}${c.reset}`;
|
|
78
|
-
const msg = entry.message;
|
|
79
|
-
const data = formatData(entry.data);
|
|
80
|
-
|
|
81
|
-
const line = `${time} ${lvl} ${worker}${requestId}${scope} ${msg}${data}`;
|
|
82
|
-
|
|
83
|
-
if (entry.level === "error" || entry.level === "fatal") {
|
|
84
|
-
process.stderr.write(`${line}\n`);
|
|
85
|
-
} else {
|
|
86
|
-
process.stdout.write(`${line}\n`);
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
// ── FileTransport ────────────────────────────────────────────────────────────
|
|
92
|
-
// Writes newline-delimited JSON for ingestion by log collectors.
|
|
93
|
-
|
|
94
|
-
export class FileTransport implements LogTransport {
|
|
95
|
-
constructor(private path: string) {}
|
|
96
|
-
|
|
97
|
-
write(entry: LogEntry) {
|
|
98
|
-
try {
|
|
99
|
-
appendFileSync(this.path, `${JSON.stringify(entry)}\n`);
|
|
100
|
-
} catch {
|
|
101
|
-
// if the file write fails we can't really do anything useful
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
// ── NullTransport ────────────────────────────────────────────────────────────
|
|
107
|
-
// For tests — captures entries instead of printing them.
|
|
108
|
-
|
|
109
|
-
export class NullTransport implements LogTransport {
|
|
110
|
-
readonly entries: LogEntry[] = [];
|
|
111
|
-
write(entry: LogEntry) {
|
|
112
|
-
this.entries.push(entry);
|
|
113
|
-
}
|
|
114
|
-
clear() {
|
|
115
|
-
this.entries.length = 0;
|
|
116
|
-
}
|
|
117
|
-
}
|
|
1
|
+
// packages/grimoire/src/logger/transports.ts
|
|
2
|
+
|
|
3
|
+
import { appendFileSync } from "node:fs";
|
|
4
|
+
import type { LogEntry, LogTransport } from "./types.ts";
|
|
5
|
+
|
|
6
|
+
// ── colours (only applied when stdout is a TTY) ──────────────────────────────
|
|
7
|
+
|
|
8
|
+
const isTTY = process.stdout.isTTY;
|
|
9
|
+
const c = isTTY
|
|
10
|
+
? {
|
|
11
|
+
reset: "\x1b[0m",
|
|
12
|
+
dim: "\x1b[2m",
|
|
13
|
+
bold: "\x1b[1m",
|
|
14
|
+
debug: "\x1b[90m", // grey
|
|
15
|
+
info: "\x1b[36m", // cyan
|
|
16
|
+
warn: "\x1b[33m", // yellow
|
|
17
|
+
error: "\x1b[31m", // red
|
|
18
|
+
fatal: "\x1b[35m", // magenta
|
|
19
|
+
scope: "\x1b[34m", // blue
|
|
20
|
+
req: "\x1b[32m", // green
|
|
21
|
+
}
|
|
22
|
+
: (Object.fromEntries(
|
|
23
|
+
[
|
|
24
|
+
"reset",
|
|
25
|
+
"dim",
|
|
26
|
+
"bold",
|
|
27
|
+
"debug",
|
|
28
|
+
"info",
|
|
29
|
+
"warn",
|
|
30
|
+
"error",
|
|
31
|
+
"fatal",
|
|
32
|
+
"scope",
|
|
33
|
+
"req",
|
|
34
|
+
].map((k) => [k, ""]),
|
|
35
|
+
) as Record<string, string>);
|
|
36
|
+
|
|
37
|
+
const LEVEL_LABEL: Record<string, string> = {
|
|
38
|
+
debug: "DBG",
|
|
39
|
+
info: "INF",
|
|
40
|
+
warn: "WRN",
|
|
41
|
+
error: "ERR",
|
|
42
|
+
fatal: "FTL",
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
function ts(timestamp: number): string {
|
|
46
|
+
return new Date(timestamp).toISOString().slice(11, 23); // HH:mm:ss.ms
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function formatData(data: unknown): string {
|
|
50
|
+
if (data === undefined) return "";
|
|
51
|
+
if (data instanceof Error) return `\n ${data.stack ?? data.message}`;
|
|
52
|
+
if (typeof data !== "object" || data === null) return ` ${String(data)}`;
|
|
53
|
+
|
|
54
|
+
// flat key=value for simple objects, JSON block only for nested/complex
|
|
55
|
+
const entries = Object.entries(data as Record<string, unknown>);
|
|
56
|
+
const isFlat = entries.every(([, v]) => typeof v !== "object" || v === null);
|
|
57
|
+
if (isFlat) {
|
|
58
|
+
return ` ${entries.map(([k, v]) => `${c.dim}${k}=${c.reset}${v}`).join(" ")}`;
|
|
59
|
+
}
|
|
60
|
+
// nested — indent but don't pretty-print the whole thing
|
|
61
|
+
return `\n ${JSON.stringify(data).replace(/,/g, ", ")}`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// ── ConsoleTransport ─────────────────────────────────────────────────────────
|
|
65
|
+
|
|
66
|
+
export class ConsoleTransport implements LogTransport {
|
|
67
|
+
write(entry: LogEntry) {
|
|
68
|
+
const levelColor = c[entry.level] ?? c.info;
|
|
69
|
+
const label = LEVEL_LABEL[entry.level] ?? entry.level.toUpperCase();
|
|
70
|
+
|
|
71
|
+
const worker = entry.worker ? `${c.dim}[${entry.worker}]${c.reset} ` : "";
|
|
72
|
+
const requestId = entry.requestId
|
|
73
|
+
? `${c.req}#${entry.requestId.slice(0, 8)}${c.reset} `
|
|
74
|
+
: "";
|
|
75
|
+
const scope = `${c.scope}${entry.scope}${c.reset}`;
|
|
76
|
+
const time = `${c.dim}${ts(entry.timestamp)}${c.reset}`;
|
|
77
|
+
const lvl = `${levelColor}${c.bold}${label}${c.reset}`;
|
|
78
|
+
const msg = entry.message;
|
|
79
|
+
const data = formatData(entry.data);
|
|
80
|
+
|
|
81
|
+
const line = `${time} ${lvl} ${worker}${requestId}${scope} ${msg}${data}`;
|
|
82
|
+
|
|
83
|
+
if (entry.level === "error" || entry.level === "fatal") {
|
|
84
|
+
process.stderr.write(`${line}\n`);
|
|
85
|
+
} else {
|
|
86
|
+
process.stdout.write(`${line}\n`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ── FileTransport ────────────────────────────────────────────────────────────
|
|
92
|
+
// Writes newline-delimited JSON for ingestion by log collectors.
|
|
93
|
+
|
|
94
|
+
export class FileTransport implements LogTransport {
|
|
95
|
+
constructor(private path: string) {}
|
|
96
|
+
|
|
97
|
+
write(entry: LogEntry) {
|
|
98
|
+
try {
|
|
99
|
+
appendFileSync(this.path, `${JSON.stringify(entry)}\n`);
|
|
100
|
+
} catch {
|
|
101
|
+
// if the file write fails we can't really do anything useful
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ── NullTransport ────────────────────────────────────────────────────────────
|
|
107
|
+
// For tests — captures entries instead of printing them.
|
|
108
|
+
|
|
109
|
+
export class NullTransport implements LogTransport {
|
|
110
|
+
readonly entries: LogEntry[] = [];
|
|
111
|
+
write(entry: LogEntry) {
|
|
112
|
+
this.entries.push(entry);
|
|
113
|
+
}
|
|
114
|
+
clear() {
|
|
115
|
+
this.entries.length = 0;
|
|
116
|
+
}
|
|
117
|
+
}
|