@sigil-security/runtime 0.0.0
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/dist/adapters/elysia.cjs +307 -0
- package/dist/adapters/elysia.cjs.map +1 -0
- package/dist/adapters/elysia.d.cts +41 -0
- package/dist/adapters/elysia.d.ts +41 -0
- package/dist/adapters/elysia.js +98 -0
- package/dist/adapters/elysia.js.map +1 -0
- package/dist/adapters/express.cjs +286 -0
- package/dist/adapters/express.cjs.map +1 -0
- package/dist/adapters/express.d.cts +59 -0
- package/dist/adapters/express.d.ts +59 -0
- package/dist/adapters/express.js +77 -0
- package/dist/adapters/express.js.map +1 -0
- package/dist/adapters/fastify.cjs +308 -0
- package/dist/adapters/fastify.cjs.map +1 -0
- package/dist/adapters/fastify.d.cts +54 -0
- package/dist/adapters/fastify.d.ts +54 -0
- package/dist/adapters/fastify.js +99 -0
- package/dist/adapters/fastify.js.map +1 -0
- package/dist/adapters/fetch.cjs +359 -0
- package/dist/adapters/fetch.cjs.map +1 -0
- package/dist/adapters/fetch.d.cts +46 -0
- package/dist/adapters/fetch.d.ts +46 -0
- package/dist/adapters/fetch.js +149 -0
- package/dist/adapters/fetch.js.map +1 -0
- package/dist/adapters/hono.cjs +300 -0
- package/dist/adapters/hono.cjs.map +1 -0
- package/dist/adapters/hono.d.cts +41 -0
- package/dist/adapters/hono.d.ts +41 -0
- package/dist/adapters/hono.js +91 -0
- package/dist/adapters/hono.js.map +1 -0
- package/dist/adapters/oak.cjs +318 -0
- package/dist/adapters/oak.cjs.map +1 -0
- package/dist/adapters/oak.d.cts +48 -0
- package/dist/adapters/oak.d.ts +48 -0
- package/dist/adapters/oak.js +109 -0
- package/dist/adapters/oak.js.map +1 -0
- package/dist/chunk-JPT5I5W5.js +225 -0
- package/dist/chunk-JPT5I5W5.js.map +1 -0
- package/dist/index.cjs +486 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +201 -0
- package/dist/index.d.ts +201 -0
- package/dist/index.js +284 -0
- package/dist/index.js.map +1 -0
- package/dist/types-DySgT8rA.d.cts +184 -0
- package/dist/types-DySgT8rA.d.ts +184 -0
- package/package.json +141 -0
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { a as SigilInstance, c as MiddlewareOptions } from '../types-DySgT8rA.js';
|
|
2
|
+
import '@sigil-security/core';
|
|
3
|
+
import '@sigil-security/policy';
|
|
4
|
+
|
|
5
|
+
/** Minimal Elysia-compatible context */
|
|
6
|
+
interface ElysiaLikeContext {
|
|
7
|
+
readonly request: Request;
|
|
8
|
+
readonly path: string;
|
|
9
|
+
body?: unknown;
|
|
10
|
+
set: {
|
|
11
|
+
status?: number | undefined;
|
|
12
|
+
headers: Record<string, string>;
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/** Elysia plugin builder (minimal, chainable) */
|
|
16
|
+
interface ElysiaLikeApp {
|
|
17
|
+
onBeforeHandle(handler: (context: ElysiaLikeContext) => Promise<unknown>): ElysiaLikeApp;
|
|
18
|
+
get(path: string, handler: (context: ElysiaLikeContext) => Promise<unknown>): ElysiaLikeApp;
|
|
19
|
+
post(path: string, handler: (context: ElysiaLikeContext) => Promise<unknown>): ElysiaLikeApp;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Creates an Elysia plugin for Sigil CSRF protection (Bun).
|
|
23
|
+
*
|
|
24
|
+
* @param sigil - Initialized SigilInstance
|
|
25
|
+
* @param options - Middleware configuration options
|
|
26
|
+
* @returns Function that accepts an Elysia instance and configures it
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```typescript
|
|
30
|
+
* import { Elysia } from 'elysia'
|
|
31
|
+
* import { createSigil } from '@sigil-security/runtime'
|
|
32
|
+
* import { createElysiaPlugin } from '@sigil-security/runtime/elysia'
|
|
33
|
+
*
|
|
34
|
+
* const sigil = await createSigil({ ... })
|
|
35
|
+
* const app = new Elysia()
|
|
36
|
+
* .use(createElysiaPlugin(sigil))
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
declare function createElysiaPlugin(sigil: SigilInstance, options?: MiddlewareOptions): (app: ElysiaLikeApp) => ElysiaLikeApp;
|
|
40
|
+
|
|
41
|
+
export { type ElysiaLikeApp, type ElysiaLikeContext, createElysiaPlugin };
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_ONESHOT_ENDPOINT_PATH,
|
|
3
|
+
DEFAULT_TOKEN_ENDPOINT_PATH,
|
|
4
|
+
createErrorResponse,
|
|
5
|
+
extractRequestMetadata,
|
|
6
|
+
handleTokenEndpoint,
|
|
7
|
+
normalizePath,
|
|
8
|
+
normalizePathSet,
|
|
9
|
+
parseContentType,
|
|
10
|
+
resolveTokenSource
|
|
11
|
+
} from "../chunk-JPT5I5W5.js";
|
|
12
|
+
|
|
13
|
+
// src/adapters/elysia.ts
|
|
14
|
+
function createElysiaHeaderGetter(request) {
|
|
15
|
+
return (name) => {
|
|
16
|
+
return request.headers.get(name.toLowerCase());
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
function createElysiaPlugin(sigil, options) {
|
|
20
|
+
const excludePaths = normalizePathSet(options?.excludePaths ?? []);
|
|
21
|
+
const tokenEndpointPath = normalizePath(options?.tokenEndpointPath ?? DEFAULT_TOKEN_ENDPOINT_PATH);
|
|
22
|
+
const oneShotEndpointPath = normalizePath(options?.oneShotEndpointPath ?? DEFAULT_ONESHOT_ENDPOINT_PATH);
|
|
23
|
+
return (app) => {
|
|
24
|
+
app.get(tokenEndpointPath, async (context) => {
|
|
25
|
+
const result = await handleTokenEndpoint(
|
|
26
|
+
sigil,
|
|
27
|
+
"GET",
|
|
28
|
+
tokenEndpointPath,
|
|
29
|
+
void 0,
|
|
30
|
+
tokenEndpointPath,
|
|
31
|
+
oneShotEndpointPath
|
|
32
|
+
);
|
|
33
|
+
if (result !== null) {
|
|
34
|
+
context.set.status = result.status;
|
|
35
|
+
Object.assign(context.set.headers, result.headers);
|
|
36
|
+
return result.body;
|
|
37
|
+
}
|
|
38
|
+
context.set.status = 404;
|
|
39
|
+
return { error: "Not found" };
|
|
40
|
+
});
|
|
41
|
+
if (sigil.config.oneShotEnabled) {
|
|
42
|
+
app.post(oneShotEndpointPath, async (context) => {
|
|
43
|
+
const body = typeof context.body === "object" && context.body !== null ? context.body : void 0;
|
|
44
|
+
const getHeader = createElysiaHeaderGetter(context.request);
|
|
45
|
+
const csrfTokenValue = getHeader(sigil.config.headerName);
|
|
46
|
+
const result = await handleTokenEndpoint(
|
|
47
|
+
sigil,
|
|
48
|
+
"POST",
|
|
49
|
+
oneShotEndpointPath,
|
|
50
|
+
body,
|
|
51
|
+
tokenEndpointPath,
|
|
52
|
+
oneShotEndpointPath,
|
|
53
|
+
csrfTokenValue
|
|
54
|
+
);
|
|
55
|
+
if (result !== null) {
|
|
56
|
+
context.set.status = result.status;
|
|
57
|
+
Object.assign(context.set.headers, result.headers);
|
|
58
|
+
return result.body;
|
|
59
|
+
}
|
|
60
|
+
context.set.status = 404;
|
|
61
|
+
return { error: "Not found" };
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
app.onBeforeHandle(async (context) => {
|
|
65
|
+
const path = normalizePath(context.path);
|
|
66
|
+
if (excludePaths.has(path)) return void 0;
|
|
67
|
+
if (path === tokenEndpointPath) return void 0;
|
|
68
|
+
if (sigil.config.oneShotEnabled && path === oneShotEndpointPath) return void 0;
|
|
69
|
+
const getHeader = createElysiaHeaderGetter(context.request);
|
|
70
|
+
const contentType = parseContentType(getHeader("content-type"));
|
|
71
|
+
const body = typeof context.body === "object" && context.body !== null ? context.body : void 0;
|
|
72
|
+
const tokenSource = resolveTokenSource(
|
|
73
|
+
getHeader,
|
|
74
|
+
body,
|
|
75
|
+
contentType,
|
|
76
|
+
sigil.config.headerName
|
|
77
|
+
);
|
|
78
|
+
const metadata = extractRequestMetadata(
|
|
79
|
+
context.request.method,
|
|
80
|
+
getHeader,
|
|
81
|
+
tokenSource
|
|
82
|
+
);
|
|
83
|
+
const result = await sigil.protect(metadata);
|
|
84
|
+
if (!result.allowed) {
|
|
85
|
+
const errorResponse = createErrorResponse(result.expired);
|
|
86
|
+
context.set.status = errorResponse.status;
|
|
87
|
+
Object.assign(context.set.headers, errorResponse.headers);
|
|
88
|
+
return errorResponse.body;
|
|
89
|
+
}
|
|
90
|
+
return void 0;
|
|
91
|
+
});
|
|
92
|
+
return app;
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
export {
|
|
96
|
+
createElysiaPlugin
|
|
97
|
+
};
|
|
98
|
+
//# sourceMappingURL=elysia.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/elysia.ts"],"sourcesContent":["// @sigil-security/runtime — Elysia plugin adapter (Bun)\n// Reference: SPECIFICATION.md §3\n\nimport type { SigilInstance, MiddlewareOptions, ProtectResult } from '../types.js'\nimport { DEFAULT_TOKEN_ENDPOINT_PATH, DEFAULT_ONESHOT_ENDPOINT_PATH } from '../types.js'\nimport { extractRequestMetadata, resolveTokenSource, parseContentType, normalizePath, normalizePathSet } from '../extract-metadata.js'\nimport type { HeaderGetter } from '../extract-metadata.js'\nimport { createErrorResponse } from '../error-response.js'\nimport { handleTokenEndpoint } from '../token-endpoint.js'\n\n// ============================================================\n// Minimal Elysia-Compatible Types\n// ============================================================\n\n/** Minimal Elysia-compatible context */\nexport interface ElysiaLikeContext {\n readonly request: Request\n readonly path: string\n body?: unknown\n set: {\n status?: number | undefined\n headers: Record<string, string>\n }\n}\n\n/** Elysia plugin builder (minimal, chainable) */\nexport interface ElysiaLikeApp {\n onBeforeHandle(\n handler: (context: ElysiaLikeContext) => Promise<unknown>,\n ): ElysiaLikeApp\n get(\n path: string,\n handler: (context: ElysiaLikeContext) => Promise<unknown>,\n ): ElysiaLikeApp\n post(\n path: string,\n handler: (context: ElysiaLikeContext) => Promise<unknown>,\n ): ElysiaLikeApp\n}\n\n// ============================================================\n// Header Getter for Elysia\n// ============================================================\n\nfunction createElysiaHeaderGetter(request: Request): HeaderGetter {\n return (name: string): string | null => {\n return request.headers.get(name.toLowerCase())\n }\n}\n\n// ============================================================\n// Elysia Plugin Factory\n// ============================================================\n\n/**\n * Creates an Elysia plugin for Sigil CSRF protection (Bun).\n *\n * @param sigil - Initialized SigilInstance\n * @param options - Middleware configuration options\n * @returns Function that accepts an Elysia instance and configures it\n *\n * @example\n * ```typescript\n * import { Elysia } from 'elysia'\n * import { createSigil } from '@sigil-security/runtime'\n * import { createElysiaPlugin } from '@sigil-security/runtime/elysia'\n *\n * const sigil = await createSigil({ ... })\n * const app = new Elysia()\n * .use(createElysiaPlugin(sigil))\n * ```\n */\nexport function createElysiaPlugin(\n sigil: SigilInstance,\n options?: MiddlewareOptions,\n): (app: ElysiaLikeApp) => ElysiaLikeApp {\n const excludePaths = normalizePathSet(options?.excludePaths ?? [])\n const tokenEndpointPath = normalizePath(options?.tokenEndpointPath ?? DEFAULT_TOKEN_ENDPOINT_PATH)\n const oneShotEndpointPath = normalizePath(options?.oneShotEndpointPath ?? DEFAULT_ONESHOT_ENDPOINT_PATH)\n\n return (app) => {\n // Register token generation routes\n app.get(tokenEndpointPath, async (context) => {\n const result = await handleTokenEndpoint(\n sigil,\n 'GET',\n tokenEndpointPath,\n undefined,\n tokenEndpointPath,\n oneShotEndpointPath,\n )\n\n if (result !== null) {\n context.set.status = result.status\n Object.assign(context.set.headers, result.headers)\n return result.body\n }\n\n // Should never reach here — route matches token endpoint path\n context.set.status = 404\n return { error: 'Not found' }\n })\n\n if (sigil.config.oneShotEnabled) {\n app.post(oneShotEndpointPath, async (context) => {\n const body = typeof context.body === 'object' && context.body !== null\n ? (context.body as Record<string, unknown>)\n : undefined\n\n const getHeader = createElysiaHeaderGetter(context.request)\n const csrfTokenValue = getHeader(sigil.config.headerName)\n\n const result = await handleTokenEndpoint(\n sigil,\n 'POST',\n oneShotEndpointPath,\n body,\n tokenEndpointPath,\n oneShotEndpointPath,\n csrfTokenValue,\n )\n\n if (result !== null) {\n context.set.status = result.status\n Object.assign(context.set.headers, result.headers)\n return result.body\n }\n\n // Should never reach here — route matches one-shot endpoint path\n context.set.status = 404\n return { error: 'Not found' }\n })\n }\n\n // Register beforeHandle hook for CSRF validation\n app.onBeforeHandle(async (context) => {\n const path = normalizePath(context.path)\n\n // Skip excluded paths (normalized comparison)\n if (excludePaths.has(path)) return undefined\n\n // Skip token endpoints (handled by routes above)\n if (path === tokenEndpointPath) return undefined\n if (sigil.config.oneShotEnabled && path === oneShotEndpointPath) return undefined\n\n // Extract metadata\n const getHeader = createElysiaHeaderGetter(context.request)\n const contentType = parseContentType(getHeader('content-type'))\n\n const body = typeof context.body === 'object' && context.body !== null\n ? (context.body as Record<string, unknown>)\n : undefined\n\n const tokenSource = resolveTokenSource(\n getHeader,\n body,\n contentType,\n sigil.config.headerName,\n )\n\n const metadata = extractRequestMetadata(\n context.request.method,\n getHeader,\n tokenSource,\n )\n\n // Run protection\n const result: ProtectResult = await sigil.protect(metadata)\n\n if (!result.allowed) {\n const errorResponse = createErrorResponse(result.expired)\n context.set.status = errorResponse.status\n Object.assign(context.set.headers, errorResponse.headers)\n return errorResponse.body\n }\n\n // Allowed — continue to handler\n return undefined\n })\n\n return app\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA4CA,SAAS,yBAAyB,SAAgC;AAChE,SAAO,CAAC,SAAgC;AACtC,WAAO,QAAQ,QAAQ,IAAI,KAAK,YAAY,CAAC;AAAA,EAC/C;AACF;AAwBO,SAAS,mBACd,OACA,SACuC;AACvC,QAAM,eAAe,iBAAiB,SAAS,gBAAgB,CAAC,CAAC;AACjE,QAAM,oBAAoB,cAAc,SAAS,qBAAqB,2BAA2B;AACjG,QAAM,sBAAsB,cAAc,SAAS,uBAAuB,6BAA6B;AAEvG,SAAO,CAAC,QAAQ;AAEd,QAAI,IAAI,mBAAmB,OAAO,YAAY;AAC5C,YAAM,SAAS,MAAM;AAAA,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Ac;AAAA,QAClB;AAAA,QACA;AAAA,QACA;AAAA,QACA,MAAM,OAAO;AAAA,MACf;AAEA,YAAM,WAAW;AAAA,QACf,QAAQ,QAAQ;AAAA,QAChB;AAAA,QACA;AAAA,MACF;AAGA,YAAM,SAAwB,MAAM,MAAM,QAAQ,QAAQ;AAE1D,UAAI,CAAC,OAAO,SAAS;AACnB,cAAM,gBAAgB,oBAAoB,OAAO,OAAO;AACxD,gBAAQ,IAAI,SAAS,cAAc;AACnC,eAAO,OAAO,QAAQ,IAAI,SAAS,cAAc,OAAO;AACxD,eAAO,cAAc;AAAA,MACvB;AAGA,aAAO;AAAA,IACT,CAAC;AAED,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/adapters/express.ts
|
|
21
|
+
var express_exports = {};
|
|
22
|
+
__export(express_exports, {
|
|
23
|
+
createExpressMiddleware: () => createExpressMiddleware
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(express_exports);
|
|
26
|
+
|
|
27
|
+
// src/types.ts
|
|
28
|
+
var DEFAULT_TOKEN_ENDPOINT_PATH = "/api/csrf/token";
|
|
29
|
+
var DEFAULT_ONESHOT_ENDPOINT_PATH = "/api/csrf/one-shot";
|
|
30
|
+
|
|
31
|
+
// src/extract-metadata.ts
|
|
32
|
+
var import_policy = require("@sigil-security/policy");
|
|
33
|
+
function normalizePath(path) {
|
|
34
|
+
if (path.length === 0 || path === "/") return "/";
|
|
35
|
+
let end = path.length;
|
|
36
|
+
while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
|
|
37
|
+
if (end === path.length) return path;
|
|
38
|
+
if (end === 0) return "/";
|
|
39
|
+
return path.slice(0, end);
|
|
40
|
+
}
|
|
41
|
+
function normalizePathSet(paths) {
|
|
42
|
+
return new Set(paths.map(normalizePath));
|
|
43
|
+
}
|
|
44
|
+
function extractRequestMetadata(method, getHeader, tokenSource) {
|
|
45
|
+
return {
|
|
46
|
+
method: method.toUpperCase(),
|
|
47
|
+
origin: getHeader("origin"),
|
|
48
|
+
referer: getHeader("referer"),
|
|
49
|
+
secFetchSite: getHeader("sec-fetch-site"),
|
|
50
|
+
secFetchMode: getHeader("sec-fetch-mode"),
|
|
51
|
+
secFetchDest: getHeader("sec-fetch-dest"),
|
|
52
|
+
contentType: parseContentType(getHeader("content-type")),
|
|
53
|
+
tokenSource,
|
|
54
|
+
clientType: getHeader("x-client-type") ?? void 0
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function parseContentType(contentType) {
|
|
58
|
+
if (contentType === null) return null;
|
|
59
|
+
const semicolonIdx = contentType.indexOf(";");
|
|
60
|
+
const mimeType = semicolonIdx >= 0 ? contentType.substring(0, semicolonIdx) : contentType;
|
|
61
|
+
return mimeType.trim().toLowerCase();
|
|
62
|
+
}
|
|
63
|
+
function extractTokenFromHeader(getHeader, headerName = import_policy.DEFAULT_HEADER_NAME) {
|
|
64
|
+
const value = getHeader(headerName);
|
|
65
|
+
if (value !== null && value !== "") {
|
|
66
|
+
return { from: "header", value };
|
|
67
|
+
}
|
|
68
|
+
return { from: "none" };
|
|
69
|
+
}
|
|
70
|
+
function extractTokenFromJsonBody(body, fieldName = import_policy.DEFAULT_JSON_FIELD_NAME) {
|
|
71
|
+
if (body !== null && body !== void 0 && typeof body === "object") {
|
|
72
|
+
const value = body[fieldName];
|
|
73
|
+
if (typeof value === "string" && value !== "") {
|
|
74
|
+
return { from: "body-json", value };
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
function extractTokenFromFormBody(body, fieldName = import_policy.DEFAULT_FORM_FIELD_NAME) {
|
|
80
|
+
if (body !== null && body !== void 0 && typeof body === "object") {
|
|
81
|
+
const value = body[fieldName];
|
|
82
|
+
if (typeof value === "string" && value !== "") {
|
|
83
|
+
return { from: "body-form", value };
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
function resolveTokenSource(getHeader, body, contentType, headerName, jsonFieldName, formFieldName) {
|
|
89
|
+
const headerToken = extractTokenFromHeader(getHeader, headerName);
|
|
90
|
+
if (headerToken.from !== "none") return headerToken;
|
|
91
|
+
if (contentType !== null && contentType.includes("application/json")) {
|
|
92
|
+
const jsonToken = extractTokenFromJsonBody(body, jsonFieldName);
|
|
93
|
+
if (jsonToken !== null) return jsonToken;
|
|
94
|
+
}
|
|
95
|
+
if (contentType !== null && (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data"))) {
|
|
96
|
+
const formToken = extractTokenFromFormBody(body, formFieldName);
|
|
97
|
+
if (formToken !== null) return formToken;
|
|
98
|
+
}
|
|
99
|
+
return { from: "none" };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// src/error-response.ts
|
|
103
|
+
var CSRF_FAILURE_MESSAGE = "CSRF validation failed";
|
|
104
|
+
var EXPIRED_HEADER_NAME = "X-CSRF-Token-Expired";
|
|
105
|
+
function createErrorResponse(expired) {
|
|
106
|
+
const headers = {};
|
|
107
|
+
if (expired) {
|
|
108
|
+
headers[EXPIRED_HEADER_NAME] = "true";
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
status: 403,
|
|
112
|
+
body: { error: CSRF_FAILURE_MESSAGE },
|
|
113
|
+
headers
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
function createTokenResponse(token, expiresAt) {
|
|
117
|
+
return {
|
|
118
|
+
status: 200,
|
|
119
|
+
body: { token, expiresAt }
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function createOneShotTokenResponse(token, expiresAt, action) {
|
|
123
|
+
return {
|
|
124
|
+
status: 200,
|
|
125
|
+
body: { token, expiresAt, action }
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// src/token-endpoint.ts
|
|
130
|
+
async function handleTokenEndpoint(sigil, method, path, body, tokenEndpointPath, oneShotEndpointPath, csrfTokenValue) {
|
|
131
|
+
const upperMethod = method.toUpperCase();
|
|
132
|
+
if (path === tokenEndpointPath && upperMethod === "GET") {
|
|
133
|
+
return handleRegularTokenGeneration(sigil);
|
|
134
|
+
}
|
|
135
|
+
if (sigil.config.oneShotEnabled && path === oneShotEndpointPath && upperMethod === "POST") {
|
|
136
|
+
if (csrfTokenValue === void 0 || csrfTokenValue === null || csrfTokenValue === "") {
|
|
137
|
+
const errorResponse = createErrorResponse(false);
|
|
138
|
+
return {
|
|
139
|
+
handled: true,
|
|
140
|
+
status: errorResponse.status,
|
|
141
|
+
body: errorResponse.body,
|
|
142
|
+
headers: errorResponse.headers
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
const csrfResult = await sigil.validateToken(csrfTokenValue);
|
|
146
|
+
if (!csrfResult.valid) {
|
|
147
|
+
const errorResponse = createErrorResponse(false);
|
|
148
|
+
return {
|
|
149
|
+
handled: true,
|
|
150
|
+
status: errorResponse.status,
|
|
151
|
+
body: errorResponse.body,
|
|
152
|
+
headers: errorResponse.headers
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
return handleOneShotTokenGeneration(sigil, body);
|
|
156
|
+
}
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
async function handleRegularTokenGeneration(sigil) {
|
|
160
|
+
const result = await sigil.generateToken();
|
|
161
|
+
if (!result.success) {
|
|
162
|
+
return {
|
|
163
|
+
handled: true,
|
|
164
|
+
status: 500,
|
|
165
|
+
body: { error: "Token generation failed" },
|
|
166
|
+
headers: {}
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
const response = createTokenResponse(result.token, result.expiresAt);
|
|
170
|
+
return {
|
|
171
|
+
handled: true,
|
|
172
|
+
status: response.status,
|
|
173
|
+
body: response.body,
|
|
174
|
+
headers: {}
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
async function handleOneShotTokenGeneration(sigil, body) {
|
|
178
|
+
if (body === null || body === void 0 || typeof body !== "object") {
|
|
179
|
+
return {
|
|
180
|
+
handled: true,
|
|
181
|
+
status: 400,
|
|
182
|
+
body: { error: "Request body required" },
|
|
183
|
+
headers: {}
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
const action = body["action"];
|
|
187
|
+
if (typeof action !== "string" || action === "") {
|
|
188
|
+
return {
|
|
189
|
+
handled: true,
|
|
190
|
+
status: 400,
|
|
191
|
+
body: { error: "Missing or invalid action parameter" },
|
|
192
|
+
headers: {}
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
let context;
|
|
196
|
+
const rawContext = body["context"];
|
|
197
|
+
if (Array.isArray(rawContext)) {
|
|
198
|
+
const isAllStrings = rawContext.every((item) => typeof item === "string");
|
|
199
|
+
if (isAllStrings) {
|
|
200
|
+
context = rawContext;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
const result = await sigil.generateOneShotToken(action, context);
|
|
204
|
+
if (!result.success) {
|
|
205
|
+
return {
|
|
206
|
+
handled: true,
|
|
207
|
+
status: 500,
|
|
208
|
+
body: { error: "One-shot token generation failed" },
|
|
209
|
+
headers: {}
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
const response = createOneShotTokenResponse(result.token, result.expiresAt, action);
|
|
213
|
+
return {
|
|
214
|
+
handled: true,
|
|
215
|
+
status: response.status,
|
|
216
|
+
body: response.body,
|
|
217
|
+
headers: {}
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// src/adapters/express.ts
|
|
222
|
+
function createExpressHeaderGetter(headers) {
|
|
223
|
+
return (name) => {
|
|
224
|
+
const value = headers[name.toLowerCase()];
|
|
225
|
+
if (typeof value === "string") return value;
|
|
226
|
+
if (Array.isArray(value)) return value[0] ?? null;
|
|
227
|
+
return null;
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
function createExpressMiddleware(sigil, options) {
|
|
231
|
+
const excludePaths = normalizePathSet(options?.excludePaths ?? []);
|
|
232
|
+
const tokenEndpointPath = normalizePath(options?.tokenEndpointPath ?? DEFAULT_TOKEN_ENDPOINT_PATH);
|
|
233
|
+
const oneShotEndpointPath = normalizePath(options?.oneShotEndpointPath ?? DEFAULT_ONESHOT_ENDPOINT_PATH);
|
|
234
|
+
return (req, res, next) => {
|
|
235
|
+
if (excludePaths.has(normalizePath(req.path))) {
|
|
236
|
+
next();
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
handleRequest(sigil, req, res, next, tokenEndpointPath, oneShotEndpointPath).catch(next);
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
async function handleRequest(sigil, req, res, next, tokenEndpointPath, oneShotEndpointPath) {
|
|
243
|
+
const reqPath = normalizePath(req.path);
|
|
244
|
+
const getHeaderForToken = createExpressHeaderGetter(req.headers);
|
|
245
|
+
const csrfTokenValue = getHeaderForToken(sigil.config.headerName);
|
|
246
|
+
const tokenResult = await handleTokenEndpoint(
|
|
247
|
+
sigil,
|
|
248
|
+
req.method,
|
|
249
|
+
reqPath,
|
|
250
|
+
req.body,
|
|
251
|
+
tokenEndpointPath,
|
|
252
|
+
oneShotEndpointPath,
|
|
253
|
+
csrfTokenValue
|
|
254
|
+
);
|
|
255
|
+
if (tokenResult !== null) {
|
|
256
|
+
for (const [key, value] of Object.entries(tokenResult.headers)) {
|
|
257
|
+
res.setHeader(key, value);
|
|
258
|
+
}
|
|
259
|
+
res.status(tokenResult.status).json(tokenResult.body);
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
const getHeader = createExpressHeaderGetter(req.headers);
|
|
263
|
+
const contentType = parseContentType(getHeader("content-type"));
|
|
264
|
+
const tokenSource = resolveTokenSource(
|
|
265
|
+
getHeader,
|
|
266
|
+
req.body,
|
|
267
|
+
contentType,
|
|
268
|
+
sigil.config.headerName
|
|
269
|
+
);
|
|
270
|
+
const metadata = extractRequestMetadata(req.method, getHeader, tokenSource);
|
|
271
|
+
const result = await sigil.protect(metadata);
|
|
272
|
+
if (!result.allowed) {
|
|
273
|
+
const errorResponse = createErrorResponse(result.expired);
|
|
274
|
+
for (const [key, value] of Object.entries(errorResponse.headers)) {
|
|
275
|
+
res.setHeader(key, value);
|
|
276
|
+
}
|
|
277
|
+
res.status(errorResponse.status).json(errorResponse.body);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
next();
|
|
281
|
+
}
|
|
282
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
283
|
+
0 && (module.exports = {
|
|
284
|
+
createExpressMiddleware
|
|
285
|
+
});
|
|
286
|
+
//# sourceMappingURL=express.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/express.ts","../../src/types.ts","../../src/extract-metadata.ts","../../src/error-response.ts","../../src/token-endpoint.ts"],"sourcesContent":["// @sigil-security/runtime — Express middleware adapter\n// Reference: SPECIFICATION.md §3\n\nimport type { SigilInstance, MiddlewareOptions, ProtectResult } from '../types.js'\nimport { DEFAULT_TOKEN_ENDPOINT_PATH, DEFAULT_ONESHOT_ENDPOINT_PATH } from '../types.js'\nimport { extractRequestMetadata, resolveTokenSource, parseContentType, normalizePath, normalizePathSet } from '../extract-metadata.js'\nimport type { HeaderGetter } from '../extract-metadata.js'\nimport { createErrorResponse } from '../error-response.js'\nimport { handleTokenEndpoint } from '../token-endpoint.js'\n\n// ============================================================\n// Minimal Express-Compatible Types\n// ============================================================\n\n/**\n * Minimal Express-compatible request interface.\n * Structurally compatible with `express.Request`.\n */\nexport interface ExpressLikeRequest {\n readonly method: string\n readonly path: string\n readonly headers: Readonly<Record<string, string | string[] | undefined>>\n body?: Record<string, unknown> | undefined\n}\n\n/**\n * Minimal Express-compatible response interface.\n * Structurally compatible with `express.Response`.\n */\nexport interface ExpressLikeResponse {\n status(code: number): ExpressLikeResponse\n json(body: unknown): ExpressLikeResponse\n setHeader(name: string, value: string): ExpressLikeResponse\n readonly headersSent: boolean\n}\n\n/** Express-compatible next function */\nexport type ExpressNextFunction = (err?: unknown) => void\n\n/** Express middleware signature */\nexport type ExpressMiddleware = (\n req: ExpressLikeRequest,\n res: ExpressLikeResponse,\n next: ExpressNextFunction,\n) => void\n\n// ============================================================\n// Header Getter for Express\n// ============================================================\n\nfunction createExpressHeaderGetter(\n headers: Readonly<Record<string, string | string[] | undefined>>,\n): HeaderGetter {\n return (name: string): string | null => {\n const value = headers[name.toLowerCase()]\n if (typeof value === 'string') return value\n if (Array.isArray(value)) return value[0] ?? null\n return null\n }\n}\n\n// ============================================================\n// Express Middleware Factory\n// ============================================================\n\n/**\n * Creates Express middleware for Sigil CSRF protection.\n *\n * This middleware:\n * 1. Handles token generation endpoints (GET /api/csrf/token, POST /api/csrf/one-shot)\n * 2. Validates CSRF tokens on protected methods (POST, PUT, PATCH, DELETE)\n * 3. Passes through safe methods (GET, HEAD, OPTIONS) without validation\n * 4. Returns uniform 403 responses on validation failure\n *\n * @param sigil - Initialized SigilInstance\n * @param options - Middleware configuration options\n * @returns Express middleware function\n *\n * @example\n * ```typescript\n * import express from 'express'\n * import { createSigil } from '@sigil-security/runtime'\n * import { createExpressMiddleware } from '@sigil-security/runtime/express'\n *\n * const sigil = await createSigil({\n * masterSecret: process.env.CSRF_SECRET!,\n * allowedOrigins: ['https://example.com'],\n * })\n *\n * const app = express()\n * app.use(createExpressMiddleware(sigil))\n * ```\n */\nexport function createExpressMiddleware(\n sigil: SigilInstance,\n options?: MiddlewareOptions,\n): ExpressMiddleware {\n const excludePaths = normalizePathSet(options?.excludePaths ?? [])\n const tokenEndpointPath = normalizePath(options?.tokenEndpointPath ?? DEFAULT_TOKEN_ENDPOINT_PATH)\n const oneShotEndpointPath = normalizePath(options?.oneShotEndpointPath ?? DEFAULT_ONESHOT_ENDPOINT_PATH)\n\n // Express middleware must NOT be async — errors are caught and forwarded to next()\n return (req, res, next) => {\n // Skip excluded paths (normalized comparison)\n if (excludePaths.has(normalizePath(req.path))) {\n next()\n return\n }\n\n // Handle async operations with proper error forwarding\n handleRequest(sigil, req, res, next, tokenEndpointPath, oneShotEndpointPath).catch(next)\n }\n}\n\n/**\n * Internal async handler for Express requests.\n */\nasync function handleRequest(\n sigil: SigilInstance,\n req: ExpressLikeRequest,\n res: ExpressLikeResponse,\n next: ExpressNextFunction,\n tokenEndpointPath: string,\n oneShotEndpointPath: string,\n): Promise<void> {\n // Step 1: Check if this is a token endpoint request\n const reqPath = normalizePath(req.path)\n const getHeaderForToken = createExpressHeaderGetter(req.headers)\n const csrfTokenValue = getHeaderForToken(sigil.config.headerName)\n\n const tokenResult = await handleTokenEndpoint(\n sigil,\n req.method,\n reqPath,\n req.body,\n tokenEndpointPath,\n oneShotEndpointPath,\n csrfTokenValue,\n )\n\n if (tokenResult !== null) {\n for (const [key, value] of Object.entries(tokenResult.headers)) {\n res.setHeader(key, value)\n }\n res.status(tokenResult.status).json(tokenResult.body)\n return\n }\n\n // Step 2: Extract metadata for protection\n const getHeader = createExpressHeaderGetter(req.headers)\n const contentType = parseContentType(getHeader('content-type'))\n\n const tokenSource = resolveTokenSource(\n getHeader,\n req.body,\n contentType,\n sigil.config.headerName,\n )\n\n const metadata = extractRequestMetadata(req.method, getHeader, tokenSource)\n\n // Step 3: Run protection\n const result: ProtectResult = await sigil.protect(metadata)\n\n if (!result.allowed) {\n const errorResponse = createErrorResponse(result.expired)\n for (const [key, value] of Object.entries(errorResponse.headers)) {\n res.setHeader(key, value)\n }\n res.status(errorResponse.status).json(errorResponse.body)\n return\n }\n\n // Step 4: Request allowed — continue\n next()\n}\n","// @sigil-security/runtime — Types and configuration interfaces\n// Reference: SPECIFICATION.md Sections 3, 8\n\nimport type { CryptoProvider } from '@sigil-security/core'\nimport type {\n ContextBindingConfig,\n LegacyBrowserMode,\n PolicyChainResult,\n RequestMetadata,\n} from '@sigil-security/policy'\n\n// ============================================================\n// Sigil Configuration\n// ============================================================\n\n/**\n * Main configuration for Sigil runtime.\n *\n * This is the single entry point for configuring CSRF protection.\n * The runtime layer orchestrates all interactions between core and policy.\n *\n * @example\n * ```typescript\n * const sigil = await createSigil({\n * masterSecret: process.env.CSRF_SECRET,\n * allowedOrigins: ['https://example.com'],\n * })\n * ```\n */\nexport interface SigilConfig {\n // ---- Core ----\n\n /** Master secret for HKDF key derivation (minimum 32 bytes recommended) */\n readonly masterSecret: ArrayBuffer | string\n\n /** Token TTL in milliseconds (default: 20 minutes = 1_200_000ms) */\n readonly tokenTTL?: number | undefined\n\n /** Grace window after TTL expiry for in-flight requests (default: 60s = 60_000ms) */\n readonly graceWindow?: number | undefined\n\n // ---- Policy ----\n\n /** List of allowed origins (e.g., ['https://example.com']) */\n readonly allowedOrigins: readonly string[]\n\n /** How to handle legacy browsers without Fetch Metadata (default: 'degraded') */\n readonly legacyBrowserMode?: LegacyBrowserMode | undefined\n\n /** Allow API mode (non-browser clients with token-only validation) (default: true) */\n readonly allowApiMode?: boolean | undefined\n\n /** HTTP methods that require CSRF protection (default: ['POST','PUT','PATCH','DELETE']) */\n readonly protectedMethods?: readonly string[] | undefined\n\n // ---- Context Binding ----\n\n /** Context binding configuration (risk tier model) */\n readonly contextBinding?: ContextBindingConfig | undefined\n\n // ---- One-Shot ----\n\n /** Enable one-shot token support (default: false) */\n readonly oneShotEnabled?: boolean | undefined\n\n /** One-shot token TTL in milliseconds (default: 5 minutes = 300_000ms) */\n readonly oneShotTTL?: number | undefined\n\n // ---- Token Transport ----\n\n /** Custom header name for CSRF tokens (default: 'x-csrf-token') */\n readonly headerName?: string | undefined\n\n /** Custom header name for one-shot tokens (default: 'x-csrf-one-shot-token') */\n readonly oneShotHeaderName?: string | undefined\n\n // ---- Security Hardening ----\n\n /**\n * Disable X-Client-Type header override for mode detection.\n * When true, clients cannot self-declare as API mode to bypass\n * Fetch Metadata and Origin validation policies.\n *\n * Enable this if CORS configuration cannot be tightly controlled.\n * Default: false\n */\n readonly disableClientModeOverride?: boolean | undefined\n\n // ---- Provider Override ----\n\n /** Custom CryptoProvider implementation (default: WebCryptoCryptoProvider) */\n readonly cryptoProvider?: CryptoProvider | undefined\n}\n\n// ============================================================\n// Resolved Configuration (defaults applied)\n// ============================================================\n\n/**\n * Fully resolved configuration with all defaults applied.\n * Exposed as `sigil.config` on a SigilInstance.\n */\nexport interface ResolvedSigilConfig {\n readonly tokenTTL: number\n readonly graceWindow: number\n readonly allowedOrigins: readonly string[]\n readonly legacyBrowserMode: LegacyBrowserMode\n readonly allowApiMode: boolean\n readonly protectedMethods: readonly string[]\n readonly contextBinding: ContextBindingConfig | undefined\n readonly oneShotEnabled: boolean\n readonly oneShotTTL: number\n readonly headerName: string\n readonly oneShotHeaderName: string\n readonly disableClientModeOverride: boolean\n}\n\n// ============================================================\n// Sigil Instance (Orchestration Core)\n// ============================================================\n\n/**\n * The Sigil runtime instance.\n *\n * Created by `createSigil(config)`. Holds the keyring, nonce cache,\n * and provides token generation / validation / protection methods.\n */\nexport interface SigilInstance {\n /** Generate a new CSRF token */\n generateToken(context?: readonly string[]): Promise<TokenGenerationResponse>\n\n /** Validate a CSRF token */\n validateToken(\n tokenString: string,\n expectedContext?: readonly string[],\n ): Promise<TokenValidationResponse>\n\n /** Generate a one-shot token (requires `oneShotEnabled: true`) */\n generateOneShotToken(\n action: string,\n context?: readonly string[],\n ): Promise<TokenGenerationResponse>\n\n /** Validate a one-shot token (tries all keys in the oneshot keyring) */\n validateOneShotToken(\n tokenString: string,\n expectedAction: string,\n expectedContext?: readonly string[],\n ): Promise<TokenValidationResponse>\n\n /** Rotate keyrings — new key becomes active, oldest dropped */\n rotateKeys(): Promise<void>\n\n /**\n * Full request protection: policy chain + token validation.\n *\n * 1. Checks if the method needs protection\n * 2. Detects client mode (browser vs API)\n * 3. Runs appropriate policy chain\n * 4. Validates CSRF token\n *\n * @param metadata - Normalized request metadata (extracted by adapter)\n * @param contextBindings - Optional context bindings for token validation\n */\n protect(\n metadata: RequestMetadata,\n contextBindings?: readonly string[],\n ): Promise<ProtectResult>\n\n /** Resolved configuration (readonly) */\n readonly config: ResolvedSigilConfig\n}\n\n// ============================================================\n// Token Response Types\n// ============================================================\n\n/** Token generation response */\nexport type TokenGenerationResponse =\n | { readonly success: true; readonly token: string; readonly expiresAt: number }\n | { readonly success: false; readonly reason: string }\n\n/** Token validation response */\nexport type TokenValidationResponse =\n | { readonly valid: true }\n | { readonly valid: false; readonly reason: string }\n\n// ============================================================\n// Protection Result\n// ============================================================\n\n/**\n * Result of full request protection (policy chain + token validation).\n *\n * - `allowed: true` → request passed all checks\n * - `allowed: false` → request blocked, `reason` is for internal logging only\n */\nexport type ProtectResult =\n | {\n readonly allowed: true\n readonly tokenValid: boolean\n readonly policyResult: PolicyChainResult\n }\n | {\n readonly allowed: false\n readonly reason: string\n readonly expired: boolean\n readonly policyResult: PolicyChainResult | null\n }\n\n// ============================================================\n// Metadata Extractor Contract\n// ============================================================\n\n/**\n * Extracts normalized `RequestMetadata` from a framework-specific request object.\n *\n * Each framework adapter implements this for its own request type.\n * This bridges framework HTTP objects to the policy layer.\n */\nexport type MetadataExtractor<TRequest> = (req: TRequest) => RequestMetadata\n\n// ============================================================\n// Token Endpoint Types\n// ============================================================\n\n/** Minimal request shape for the token endpoint handler */\nexport interface TokenEndpointRequest {\n readonly method: string\n readonly path: string\n readonly body?: Record<string, unknown> | undefined\n}\n\n/** Token endpoint response (returned by `handleTokenEndpoint`) */\nexport interface TokenEndpointResult {\n readonly handled: boolean\n readonly status: number\n readonly body: Record<string, unknown>\n readonly headers: Record<string, string>\n}\n\n/** One-shot token request body */\nexport interface OneShotTokenRequestBody {\n readonly action: string\n readonly context?: readonly string[] | undefined\n}\n\n// ============================================================\n// Error Response Types\n// ============================================================\n\n/** Uniform error response body — NEVER differentiates error types to client */\nexport interface ErrorResponseBody {\n readonly error: string\n}\n\n// ============================================================\n// Middleware Options\n// ============================================================\n\n/**\n * Options for framework middleware adapters.\n *\n * Controls path exclusion, token endpoint paths, and context binding extraction.\n */\nexport interface MiddlewareOptions {\n /** Paths to exclude from protection (exact match) */\n readonly excludePaths?: readonly string[] | undefined\n\n /** Token generation endpoint path (default: '/api/csrf/token') */\n readonly tokenEndpointPath?: string | undefined\n\n /** One-shot token endpoint path (default: '/api/csrf/one-shot') */\n readonly oneShotEndpointPath?: string | undefined\n}\n\n// ============================================================\n// Default Constants\n// ============================================================\n\n/** Default token generation endpoint path */\nexport const DEFAULT_TOKEN_ENDPOINT_PATH = '/api/csrf/token'\n\n/** Default one-shot token endpoint path */\nexport const DEFAULT_ONESHOT_ENDPOINT_PATH = '/api/csrf/one-shot'\n","// @sigil-security/runtime — Request metadata extraction helpers\n// Reference: SPECIFICATION.md §8.3\n\nimport type { RequestMetadata, TokenSource } from '@sigil-security/policy'\nimport {\n DEFAULT_FORM_FIELD_NAME,\n DEFAULT_HEADER_NAME,\n DEFAULT_JSON_FIELD_NAME,\n} from '@sigil-security/policy'\n\n// ============================================================\n// Path Normalization\n// ============================================================\n\n/**\n * Normalizes a URL path for consistent comparison.\n *\n * **Security (L3 fix):** Strips trailing slashes to prevent\n * protection bypass via `/health/` vs `/health` mismatch.\n * Does NOT lowercase (paths are case-sensitive per RFC 3986).\n *\n * @param path - URL path to normalize\n * @returns Normalized path (no trailing slash, except for root \"/\")\n */\nexport function normalizePath(path: string): string {\n if (path.length === 0 || path === '/') return '/'\n\n let end = path.length\n while (end > 0 && path.charCodeAt(end - 1) === 47) end--\n\n if (end === path.length) return path // no trailing slash → zero allocation\n if (end === 0) return '/'\n return path.slice(0, end)\n}\n\n/**\n * Creates a normalized Set from an array of paths for consistent matching.\n *\n * @param paths - Array of paths to normalize\n * @returns Set of normalized paths\n */\nexport function normalizePathSet(paths: readonly string[]): Set<string> {\n return new Set(paths.map(normalizePath))\n}\n\n// ============================================================\n// Header Getter Abstraction\n// ============================================================\n\n/**\n * Generic header getter function.\n * Adapters implement this to bridge framework-specific header access.\n */\nexport type HeaderGetter = (name: string) => string | null\n\n// ============================================================\n// Request Metadata Assembly\n// ============================================================\n\n/**\n * Assembles normalized `RequestMetadata` from generic request components.\n *\n * This is the single point where framework-specific HTTP objects\n * are transformed into the policy layer's input format.\n *\n * @param method - HTTP method (will be uppercased)\n * @param getHeader - Framework-specific header getter\n * @param tokenSource - Pre-resolved token source\n * @returns Normalized RequestMetadata for the policy layer\n */\nexport function extractRequestMetadata(\n method: string,\n getHeader: HeaderGetter,\n tokenSource: TokenSource,\n): RequestMetadata {\n return {\n method: method.toUpperCase(),\n origin: getHeader('origin'),\n referer: getHeader('referer'),\n secFetchSite: getHeader('sec-fetch-site'),\n secFetchMode: getHeader('sec-fetch-mode'),\n secFetchDest: getHeader('sec-fetch-dest'),\n contentType: parseContentType(getHeader('content-type')),\n tokenSource,\n clientType: getHeader('x-client-type') ?? undefined,\n }\n}\n\n// ============================================================\n// Content-Type Parsing\n// ============================================================\n\n/**\n * Parses Content-Type header, stripping parameters (charset, boundary, etc.).\n *\n * @example\n * parseContentType(\"application/json; charset=utf-8\") → \"application/json\"\n * parseContentType(null) → null\n */\nexport function parseContentType(contentType: string | null): string | null {\n if (contentType === null) return null\n const semicolonIdx = contentType.indexOf(';')\n const mimeType = semicolonIdx >= 0 ? contentType.substring(0, semicolonIdx) : contentType\n return mimeType.trim().toLowerCase()\n}\n\n// ============================================================\n// Token Source Resolution\n// ============================================================\n\n/**\n * Extracts CSRF token from a custom header.\n *\n * @param getHeader - Header getter function\n * @param headerName - Header name to check (default: 'x-csrf-token')\n * @returns TokenSource from header, or { from: 'none' }\n */\nexport function extractTokenFromHeader(\n getHeader: HeaderGetter,\n headerName: string = DEFAULT_HEADER_NAME,\n): TokenSource {\n const value = getHeader(headerName)\n if (value !== null && value !== '') {\n return { from: 'header', value }\n }\n return { from: 'none' }\n}\n\n/**\n * Extracts CSRF token from a parsed JSON body.\n *\n * @param body - Parsed request body (or null/undefined)\n * @param fieldName - JSON field name (default: 'csrf_token')\n * @returns TokenSource if found, or null\n */\nexport function extractTokenFromJsonBody(\n body: Record<string, unknown> | null | undefined,\n fieldName: string = DEFAULT_JSON_FIELD_NAME,\n): TokenSource | null {\n if (body !== null && body !== undefined && typeof body === 'object') {\n const value = body[fieldName]\n if (typeof value === 'string' && value !== '') {\n return { from: 'body-json', value }\n }\n }\n return null\n}\n\n/**\n * Extracts CSRF token from a parsed form body.\n *\n * @param body - Parsed form body (or null/undefined)\n * @param fieldName - Form field name (default: 'csrf_token')\n * @returns TokenSource if found, or null\n */\nexport function extractTokenFromFormBody(\n body: Record<string, unknown> | null | undefined,\n fieldName: string = DEFAULT_FORM_FIELD_NAME,\n): TokenSource | null {\n if (body !== null && body !== undefined && typeof body === 'object') {\n const value = body[fieldName]\n if (typeof value === 'string' && value !== '') {\n return { from: 'body-form', value }\n }\n }\n return null\n}\n\n/**\n * Resolves token source following the transport precedence from SPECIFICATION.md §8.3:\n *\n * 1. Custom header (highest priority): `X-CSRF-Token`\n * 2. Request body (JSON): `{ \"csrf_token\": \"...\" }`\n * 3. Request body (form): `csrf_token=...`\n * 4. Query parameter: NEVER (not supported)\n *\n * First valid token wins. Multiple tokens → first match wins.\n *\n * @param getHeader - Header getter function\n * @param body - Parsed request body (JSON or form-encoded)\n * @param contentType - Parsed Content-Type MIME (lowercase, no params)\n * @param headerName - Custom header name override\n * @param jsonFieldName - Custom JSON field name override\n * @param formFieldName - Custom form field name override\n * @returns Resolved TokenSource\n */\nexport function resolveTokenSource(\n getHeader: HeaderGetter,\n body: Record<string, unknown> | null | undefined,\n contentType: string | null,\n headerName?: string,\n jsonFieldName?: string,\n formFieldName?: string,\n): TokenSource {\n // 1. Custom header (highest precedence)\n const headerToken = extractTokenFromHeader(getHeader, headerName)\n if (headerToken.from !== 'none') return headerToken\n\n // 2. JSON body\n if (contentType !== null && contentType.includes('application/json')) {\n const jsonToken = extractTokenFromJsonBody(body, jsonFieldName)\n if (jsonToken !== null) return jsonToken\n }\n\n // 3. Form body\n if (\n contentType !== null &&\n (contentType.includes('application/x-www-form-urlencoded') ||\n contentType.includes('multipart/form-data'))\n ) {\n const formToken = extractTokenFromFormBody(body, formFieldName)\n if (formToken !== null) return formToken\n }\n\n // No token found\n return { from: 'none' }\n}\n","// @sigil-security/runtime — Uniform error responses\n// Reference: SPECIFICATION.md §5.8 — NEVER differentiate error types to client\n\n/**\n * Uniform CSRF validation failure message.\n *\n * **CRITICAL:** This is the ONLY error message sent to the client.\n * Detailed failure reasons go to internal logs ONLY — never in HTTP response body.\n */\nconst CSRF_FAILURE_MESSAGE = 'CSRF validation failed'\n\n/** HTTP header name indicating token expiry */\nconst EXPIRED_HEADER_NAME = 'X-CSRF-Token-Expired'\n\n/**\n * Framework-agnostic error response structure.\n *\n * Used by all adapters to produce consistent 403 responses.\n */\nexport interface ErrorResponse {\n readonly status: number\n readonly body: { readonly error: string }\n readonly headers: Readonly<Record<string, string>>\n}\n\n/**\n * Creates a uniform 403 error response.\n *\n * - Always returns `403 { error: \"CSRF validation failed\" }`\n * - If the token is expired, adds `X-CSRF-Token-Expired: true` header\n * (allows client-side silent refresh without exposing failure reason)\n *\n * @param expired - Whether the failure is due to token expiry\n * @returns Framework-agnostic error response\n */\nexport function createErrorResponse(expired: boolean): ErrorResponse {\n const headers: Record<string, string> = {}\n if (expired) {\n headers[EXPIRED_HEADER_NAME] = 'true'\n }\n return {\n status: 403,\n body: { error: CSRF_FAILURE_MESSAGE },\n headers,\n }\n}\n\n/**\n * Creates a framework-agnostic success response for token generation.\n *\n * @param token - Generated token string\n * @param expiresAt - Token expiration timestamp (milliseconds)\n */\nexport function createTokenResponse(\n token: string,\n expiresAt: number,\n): { readonly status: number; readonly body: { readonly token: string; readonly expiresAt: number } } {\n return {\n status: 200,\n body: { token, expiresAt },\n }\n}\n\n/**\n * Creates a framework-agnostic success response for one-shot token generation.\n *\n * @param token - Generated one-shot token string\n * @param expiresAt - Token expiration timestamp (milliseconds)\n * @param action - The action the token is bound to\n */\nexport function createOneShotTokenResponse(\n token: string,\n expiresAt: number,\n action: string,\n): {\n readonly status: number\n readonly body: { readonly token: string; readonly expiresAt: number; readonly action: string }\n} {\n return {\n status: 200,\n body: { token, expiresAt, action },\n }\n}\n","// @sigil-security/runtime — Token endpoint handler\n// Reference: SPECIFICATION.md §3 — Token generation endpoints\n\nimport type { SigilInstance, TokenEndpointResult } from './types.js'\nimport {\n createErrorResponse,\n createTokenResponse,\n createOneShotTokenResponse,\n} from './error-response.js'\n\n/**\n * Handles token generation requests.\n *\n * This is a framework-agnostic handler that processes token endpoint requests.\n * Each adapter calls this and maps the result to framework-specific responses.\n *\n * Supported endpoints:\n * - `GET {tokenEndpointPath}` → Generate a regular CSRF token\n * - `POST {oneShotEndpointPath}` → Generate a one-shot token (requires action binding)\n *\n * **Security (M2 fix):** The one-shot endpoint (POST) requires a valid regular\n * CSRF token in the request header. This prevents cross-origin one-shot token\n * generation and nonce cache exhaustion attacks.\n *\n * @param sigil - The Sigil instance\n * @param method - HTTP method (uppercase)\n * @param path - Request path\n * @param body - Parsed request body (for POST endpoints)\n * @param tokenEndpointPath - Token generation endpoint path\n * @param oneShotEndpointPath - One-shot token endpoint path\n * @param csrfTokenValue - CSRF token from request header (required for POST one-shot endpoint)\n * @returns TokenEndpointResult if the request was handled, or null if not a token endpoint\n */\nexport async function handleTokenEndpoint(\n sigil: SigilInstance,\n method: string,\n path: string,\n body: Record<string, unknown> | null | undefined,\n tokenEndpointPath: string,\n oneShotEndpointPath: string,\n csrfTokenValue?: string | null,\n): Promise<TokenEndpointResult | null> {\n const upperMethod = method.toUpperCase()\n\n // GET /api/csrf/token → Generate regular CSRF token\n if (path === tokenEndpointPath && upperMethod === 'GET') {\n return handleRegularTokenGeneration(sigil)\n }\n\n // POST /api/csrf/one-shot → Generate one-shot token\n // Requires a valid regular CSRF token for defense-in-depth\n if (\n sigil.config.oneShotEnabled &&\n path === oneShotEndpointPath &&\n upperMethod === 'POST'\n ) {\n // Validate CSRF token before generating one-shot token\n if (csrfTokenValue === undefined || csrfTokenValue === null || csrfTokenValue === '') {\n const errorResponse = createErrorResponse(false)\n return {\n handled: true,\n status: errorResponse.status,\n body: errorResponse.body,\n headers: errorResponse.headers as Record<string, string>,\n }\n }\n\n const csrfResult = await sigil.validateToken(csrfTokenValue)\n if (!csrfResult.valid) {\n const errorResponse = createErrorResponse(false)\n return {\n handled: true,\n status: errorResponse.status,\n body: errorResponse.body,\n headers: errorResponse.headers as Record<string, string>,\n }\n }\n\n return handleOneShotTokenGeneration(sigil, body)\n }\n\n // Not a token endpoint request\n return null\n}\n\n/**\n * Generates a regular CSRF token.\n */\nasync function handleRegularTokenGeneration(\n sigil: SigilInstance,\n): Promise<TokenEndpointResult> {\n const result = await sigil.generateToken()\n\n if (!result.success) {\n return {\n handled: true,\n status: 500,\n body: { error: 'Token generation failed' },\n headers: {},\n }\n }\n\n const response = createTokenResponse(result.token, result.expiresAt)\n return {\n handled: true,\n status: response.status,\n body: response.body,\n headers: {},\n }\n}\n\n/**\n * Generates a one-shot token with action binding.\n */\nasync function handleOneShotTokenGeneration(\n sigil: SigilInstance,\n body: Record<string, unknown> | null | undefined,\n): Promise<TokenEndpointResult> {\n // Validate request body\n if (body === null || body === undefined || typeof body !== 'object') {\n return {\n handled: true,\n status: 400,\n body: { error: 'Request body required' },\n headers: {},\n }\n }\n\n const action = body['action']\n if (typeof action !== 'string' || action === '') {\n return {\n handled: true,\n status: 400,\n body: { error: 'Missing or invalid action parameter' },\n headers: {},\n }\n }\n\n // Optional context bindings\n let context: readonly string[] | undefined\n const rawContext = body['context']\n if (Array.isArray(rawContext)) {\n const isAllStrings = rawContext.every((item): item is string => typeof item === 'string')\n if (isAllStrings) {\n context = rawContext\n }\n }\n\n const result = await sigil.generateOneShotToken(action, context)\n\n if (!result.success) {\n return {\n handled: true,\n status: 500,\n body: { error: 'One-shot token generation failed' },\n headers: {},\n }\n }\n\n const response = createOneShotTokenResponse(result.token, result.expiresAt, action)\n return {\n handled: true,\n status: response.status,\n body: response.body,\n headers: {},\n }\n}\n\n/**\n * Creates a standardized error result for the token endpoint.\n * Used by adapters when they need to produce error responses.\n */\nexport function createTokenEndpointError(\n expired: boolean,\n): TokenEndpointResult {\n const errorResponse = createErrorResponse(expired)\n return {\n handled: true,\n status: errorResponse.status,\n body: errorResponse.body,\n headers: errorResponse.headers as Record<string, string>,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACyRO,IAAM,8BAA8B;AAGpC,IAAM,gCAAgC;;;ACxR7C,oBAIO;AAgBA,SAAS,cAAc,MAAsB;AAClD,MAAI,KAAK,WAAW,KAAK,SAAS,IAAK,QAAO;AAE9C,MAAI,MAAM,KAAK;AACf,SAAO,MAAM,KAAK,KAAK,WAAW,MAAM,CAAC,MAAM,GAAI;AAEnD,MAAI,QAAQ,KAAK,OAAQ,QAAO;AAChC,MAAI,QAAQ,EAAG,QAAO;AACtB,SAAO,KAAK,MAAM,GAAG,GAAG;AAC1B;AAQO,SAAS,iBAAiB,OAAuC;AACtE,SAAO,IAAI,IAAI,MAAM,IAAI,aAAa,CAAC;AACzC;AA2BO,SAAS,uBACd,QACA,WACA,aACiB;AAC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;AAEf,QAAM,UAAU,cAAc,IAAI,IAAI;AACtC,QAAM,oBAAoB,0BAA0B,IAAI,OAAO;AAC/D,QAAM,iBAAiB,kBAAkB,MAAM,OAAO,UAAU;AAEhE,QAAM,cAAc,MAAM;AAAA,IACxB;AAAA,IACA,IAAI;AAAA,IACJ;AAAA,IACA,IAAI;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,MAAI,gBAAgB,MAAM;AACxB,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,YAAY,OAAO,GAAG;AAC9D,UAAI,UAAU,KAAK,KAAK;AAAA,IAC1B;AACA,QAAI,OAAO,YAAY,MAAM,EAAE,KAAK,YAAY,IAAI;AACpD;AAAA,EACF;AAGA,QAAM,YAAY,0BAA0B,IAAI,OAAO;AACvD,QAAM,cAAc,iBAAiB,UAAU,cAAc,CAAC;AAE9D,QAAM,cAAc;AAAA,IAClB;AAAA,IACA,IAAI;AAAA,IACJ;AAAA,IACA,MAAM,OAAO;AAAA,EACf;AAEA,QAAM,WAAW,uBAAuB,IAAI,QAAQ,WAAW,WAAW;AAG1E,QAAM,SAAwB,MAAM,MAAM,QAAQ,QAAQ;AAE1D,MAAI,CAAC,OAAO,SAAS;AACnB,UAAM,gBAAgB,oBAAoB,OAAO,OAAO;AACxD,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,cAAc,OAAO,GAAG;AAChE,UAAI,UAAU,KAAK,KAAK;AAAA,IAC1B;AACA,QAAI,OAAO,cAAc,MAAM,EAAE,KAAK,cAAc,IAAI;AACxD;AAAA,EACF;AAGA,OAAK;AACP;","names":[]}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { a as SigilInstance, c as MiddlewareOptions } from '../types-DySgT8rA.cjs';
|
|
2
|
+
import '@sigil-security/core';
|
|
3
|
+
import '@sigil-security/policy';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Minimal Express-compatible request interface.
|
|
7
|
+
* Structurally compatible with `express.Request`.
|
|
8
|
+
*/
|
|
9
|
+
interface ExpressLikeRequest {
|
|
10
|
+
readonly method: string;
|
|
11
|
+
readonly path: string;
|
|
12
|
+
readonly headers: Readonly<Record<string, string | string[] | undefined>>;
|
|
13
|
+
body?: Record<string, unknown> | undefined;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Minimal Express-compatible response interface.
|
|
17
|
+
* Structurally compatible with `express.Response`.
|
|
18
|
+
*/
|
|
19
|
+
interface ExpressLikeResponse {
|
|
20
|
+
status(code: number): ExpressLikeResponse;
|
|
21
|
+
json(body: unknown): ExpressLikeResponse;
|
|
22
|
+
setHeader(name: string, value: string): ExpressLikeResponse;
|
|
23
|
+
readonly headersSent: boolean;
|
|
24
|
+
}
|
|
25
|
+
/** Express-compatible next function */
|
|
26
|
+
type ExpressNextFunction = (err?: unknown) => void;
|
|
27
|
+
/** Express middleware signature */
|
|
28
|
+
type ExpressMiddleware = (req: ExpressLikeRequest, res: ExpressLikeResponse, next: ExpressNextFunction) => void;
|
|
29
|
+
/**
|
|
30
|
+
* Creates Express middleware for Sigil CSRF protection.
|
|
31
|
+
*
|
|
32
|
+
* This middleware:
|
|
33
|
+
* 1. Handles token generation endpoints (GET /api/csrf/token, POST /api/csrf/one-shot)
|
|
34
|
+
* 2. Validates CSRF tokens on protected methods (POST, PUT, PATCH, DELETE)
|
|
35
|
+
* 3. Passes through safe methods (GET, HEAD, OPTIONS) without validation
|
|
36
|
+
* 4. Returns uniform 403 responses on validation failure
|
|
37
|
+
*
|
|
38
|
+
* @param sigil - Initialized SigilInstance
|
|
39
|
+
* @param options - Middleware configuration options
|
|
40
|
+
* @returns Express middleware function
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```typescript
|
|
44
|
+
* import express from 'express'
|
|
45
|
+
* import { createSigil } from '@sigil-security/runtime'
|
|
46
|
+
* import { createExpressMiddleware } from '@sigil-security/runtime/express'
|
|
47
|
+
*
|
|
48
|
+
* const sigil = await createSigil({
|
|
49
|
+
* masterSecret: process.env.CSRF_SECRET!,
|
|
50
|
+
* allowedOrigins: ['https://example.com'],
|
|
51
|
+
* })
|
|
52
|
+
*
|
|
53
|
+
* const app = express()
|
|
54
|
+
* app.use(createExpressMiddleware(sigil))
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
declare function createExpressMiddleware(sigil: SigilInstance, options?: MiddlewareOptions): ExpressMiddleware;
|
|
58
|
+
|
|
59
|
+
export { type ExpressLikeRequest, type ExpressLikeResponse, type ExpressMiddleware, type ExpressNextFunction, createExpressMiddleware };
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { a as SigilInstance, c as MiddlewareOptions } from '../types-DySgT8rA.js';
|
|
2
|
+
import '@sigil-security/core';
|
|
3
|
+
import '@sigil-security/policy';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Minimal Express-compatible request interface.
|
|
7
|
+
* Structurally compatible with `express.Request`.
|
|
8
|
+
*/
|
|
9
|
+
interface ExpressLikeRequest {
|
|
10
|
+
readonly method: string;
|
|
11
|
+
readonly path: string;
|
|
12
|
+
readonly headers: Readonly<Record<string, string | string[] | undefined>>;
|
|
13
|
+
body?: Record<string, unknown> | undefined;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Minimal Express-compatible response interface.
|
|
17
|
+
* Structurally compatible with `express.Response`.
|
|
18
|
+
*/
|
|
19
|
+
interface ExpressLikeResponse {
|
|
20
|
+
status(code: number): ExpressLikeResponse;
|
|
21
|
+
json(body: unknown): ExpressLikeResponse;
|
|
22
|
+
setHeader(name: string, value: string): ExpressLikeResponse;
|
|
23
|
+
readonly headersSent: boolean;
|
|
24
|
+
}
|
|
25
|
+
/** Express-compatible next function */
|
|
26
|
+
type ExpressNextFunction = (err?: unknown) => void;
|
|
27
|
+
/** Express middleware signature */
|
|
28
|
+
type ExpressMiddleware = (req: ExpressLikeRequest, res: ExpressLikeResponse, next: ExpressNextFunction) => void;
|
|
29
|
+
/**
|
|
30
|
+
* Creates Express middleware for Sigil CSRF protection.
|
|
31
|
+
*
|
|
32
|
+
* This middleware:
|
|
33
|
+
* 1. Handles token generation endpoints (GET /api/csrf/token, POST /api/csrf/one-shot)
|
|
34
|
+
* 2. Validates CSRF tokens on protected methods (POST, PUT, PATCH, DELETE)
|
|
35
|
+
* 3. Passes through safe methods (GET, HEAD, OPTIONS) without validation
|
|
36
|
+
* 4. Returns uniform 403 responses on validation failure
|
|
37
|
+
*
|
|
38
|
+
* @param sigil - Initialized SigilInstance
|
|
39
|
+
* @param options - Middleware configuration options
|
|
40
|
+
* @returns Express middleware function
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```typescript
|
|
44
|
+
* import express from 'express'
|
|
45
|
+
* import { createSigil } from '@sigil-security/runtime'
|
|
46
|
+
* import { createExpressMiddleware } from '@sigil-security/runtime/express'
|
|
47
|
+
*
|
|
48
|
+
* const sigil = await createSigil({
|
|
49
|
+
* masterSecret: process.env.CSRF_SECRET!,
|
|
50
|
+
* allowedOrigins: ['https://example.com'],
|
|
51
|
+
* })
|
|
52
|
+
*
|
|
53
|
+
* const app = express()
|
|
54
|
+
* app.use(createExpressMiddleware(sigil))
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
declare function createExpressMiddleware(sigil: SigilInstance, options?: MiddlewareOptions): ExpressMiddleware;
|
|
58
|
+
|
|
59
|
+
export { type ExpressLikeRequest, type ExpressLikeResponse, type ExpressMiddleware, type ExpressNextFunction, createExpressMiddleware };
|