@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,77 @@
|
|
|
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/express.ts
|
|
14
|
+
function createExpressHeaderGetter(headers) {
|
|
15
|
+
return (name) => {
|
|
16
|
+
const value = headers[name.toLowerCase()];
|
|
17
|
+
if (typeof value === "string") return value;
|
|
18
|
+
if (Array.isArray(value)) return value[0] ?? null;
|
|
19
|
+
return null;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function createExpressMiddleware(sigil, options) {
|
|
23
|
+
const excludePaths = normalizePathSet(options?.excludePaths ?? []);
|
|
24
|
+
const tokenEndpointPath = normalizePath(options?.tokenEndpointPath ?? DEFAULT_TOKEN_ENDPOINT_PATH);
|
|
25
|
+
const oneShotEndpointPath = normalizePath(options?.oneShotEndpointPath ?? DEFAULT_ONESHOT_ENDPOINT_PATH);
|
|
26
|
+
return (req, res, next) => {
|
|
27
|
+
if (excludePaths.has(normalizePath(req.path))) {
|
|
28
|
+
next();
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
handleRequest(sigil, req, res, next, tokenEndpointPath, oneShotEndpointPath).catch(next);
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
async function handleRequest(sigil, req, res, next, tokenEndpointPath, oneShotEndpointPath) {
|
|
35
|
+
const reqPath = normalizePath(req.path);
|
|
36
|
+
const getHeaderForToken = createExpressHeaderGetter(req.headers);
|
|
37
|
+
const csrfTokenValue = getHeaderForToken(sigil.config.headerName);
|
|
38
|
+
const tokenResult = await handleTokenEndpoint(
|
|
39
|
+
sigil,
|
|
40
|
+
req.method,
|
|
41
|
+
reqPath,
|
|
42
|
+
req.body,
|
|
43
|
+
tokenEndpointPath,
|
|
44
|
+
oneShotEndpointPath,
|
|
45
|
+
csrfTokenValue
|
|
46
|
+
);
|
|
47
|
+
if (tokenResult !== null) {
|
|
48
|
+
for (const [key, value] of Object.entries(tokenResult.headers)) {
|
|
49
|
+
res.setHeader(key, value);
|
|
50
|
+
}
|
|
51
|
+
res.status(tokenResult.status).json(tokenResult.body);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const getHeader = createExpressHeaderGetter(req.headers);
|
|
55
|
+
const contentType = parseContentType(getHeader("content-type"));
|
|
56
|
+
const tokenSource = resolveTokenSource(
|
|
57
|
+
getHeader,
|
|
58
|
+
req.body,
|
|
59
|
+
contentType,
|
|
60
|
+
sigil.config.headerName
|
|
61
|
+
);
|
|
62
|
+
const metadata = extractRequestMetadata(req.method, getHeader, tokenSource);
|
|
63
|
+
const result = await sigil.protect(metadata);
|
|
64
|
+
if (!result.allowed) {
|
|
65
|
+
const errorResponse = createErrorResponse(result.expired);
|
|
66
|
+
for (const [key, value] of Object.entries(errorResponse.headers)) {
|
|
67
|
+
res.setHeader(key, value);
|
|
68
|
+
}
|
|
69
|
+
res.status(errorResponse.status).json(errorResponse.body);
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
next();
|
|
73
|
+
}
|
|
74
|
+
export {
|
|
75
|
+
createExpressMiddleware
|
|
76
|
+
};
|
|
77
|
+
//# sourceMappingURL=express.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/express.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"],"mappings":";;;;;;;;;;;;;AAkDA,SAAS,0BACP,SACc;AACd,SAAO,CAAC,SAAgC;AACtC,UAAM,QAAQ,QAAQ,KAAK,YAAY,CAAC;AACxC,QAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,CAAC,KAAK;AAC7C,WAAO;AAAA,EACT;AACF;AAkCO,SAAS,wBACd,OACA,SACmB;AACnB,QAAM,eAAe,iBAAiB,SAAS,gBAAgB,CAAC,CAAC;AACjE,QAAM,oBAAoB,cAAc,SAAS,qBAAqB,2BAA2B;AACjG,QAAM,sBAAsB,cAAc,SAAS,uBAAuB,6BAA6B;AAGvG,SAAO,CAAC,KAAK,KAAK,SAAS;AAEzB,QAAI,aAAa,IAAI,cAAc,IAAI,IAAI,CAAC,GAAG;AAC7C,WAAK;AACL;AAAA,IACF;AAGA,kBAAc,OAAO,KAAK,KAAK,MAAM,mBAAmB,mBAAmB,EAAE,MAAM,IAAI;AAAA,EACzF;AACF;AAKA,eAAe,cACb,OACA,KACA,KACA,MACA,mBACA,qBACe;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,308 @@
|
|
|
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/fastify.ts
|
|
21
|
+
var fastify_exports = {};
|
|
22
|
+
__export(fastify_exports, {
|
|
23
|
+
createFastifyPlugin: () => createFastifyPlugin
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(fastify_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/fastify.ts
|
|
222
|
+
function createFastifyHeaderGetter(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 extractPath(url) {
|
|
231
|
+
const qIndex = url.indexOf("?");
|
|
232
|
+
return qIndex >= 0 ? url.slice(0, qIndex) : url;
|
|
233
|
+
}
|
|
234
|
+
function createFastifyPlugin(sigil, options) {
|
|
235
|
+
const excludePaths = normalizePathSet(options?.excludePaths ?? []);
|
|
236
|
+
const tokenEndpointPath = normalizePath(options?.tokenEndpointPath ?? DEFAULT_TOKEN_ENDPOINT_PATH);
|
|
237
|
+
const oneShotEndpointPath = normalizePath(options?.oneShotEndpointPath ?? DEFAULT_ONESHOT_ENDPOINT_PATH);
|
|
238
|
+
return (fastify, _opts, done) => {
|
|
239
|
+
fastify.get(tokenEndpointPath, async (request, reply) => {
|
|
240
|
+
const result = await handleTokenEndpoint(
|
|
241
|
+
sigil,
|
|
242
|
+
request.method,
|
|
243
|
+
tokenEndpointPath,
|
|
244
|
+
void 0,
|
|
245
|
+
tokenEndpointPath,
|
|
246
|
+
oneShotEndpointPath
|
|
247
|
+
);
|
|
248
|
+
if (result !== null) {
|
|
249
|
+
for (const [key, value] of Object.entries(result.headers)) {
|
|
250
|
+
reply.header(key, value);
|
|
251
|
+
}
|
|
252
|
+
reply.code(result.status).send(result.body);
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
if (sigil.config.oneShotEnabled) {
|
|
256
|
+
fastify.post(oneShotEndpointPath, async (request, reply) => {
|
|
257
|
+
const body = typeof request.body === "object" && request.body !== null ? request.body : void 0;
|
|
258
|
+
const getHeader = createFastifyHeaderGetter(request.headers);
|
|
259
|
+
const csrfTokenValue = getHeader(sigil.config.headerName);
|
|
260
|
+
const result = await handleTokenEndpoint(
|
|
261
|
+
sigil,
|
|
262
|
+
request.method,
|
|
263
|
+
oneShotEndpointPath,
|
|
264
|
+
body,
|
|
265
|
+
tokenEndpointPath,
|
|
266
|
+
oneShotEndpointPath,
|
|
267
|
+
csrfTokenValue
|
|
268
|
+
);
|
|
269
|
+
if (result !== null) {
|
|
270
|
+
for (const [key, value] of Object.entries(result.headers)) {
|
|
271
|
+
reply.header(key, value);
|
|
272
|
+
}
|
|
273
|
+
reply.code(result.status).send(result.body);
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
fastify.addHook("preHandler", async (request, reply) => {
|
|
278
|
+
const path = normalizePath(extractPath(request.url));
|
|
279
|
+
if (excludePaths.has(path)) return;
|
|
280
|
+
if (path === tokenEndpointPath) return;
|
|
281
|
+
if (sigil.config.oneShotEnabled && path === oneShotEndpointPath) return;
|
|
282
|
+
const getHeader = createFastifyHeaderGetter(request.headers);
|
|
283
|
+
const contentType = parseContentType(getHeader("content-type"));
|
|
284
|
+
const body = typeof request.body === "object" && request.body !== null ? request.body : void 0;
|
|
285
|
+
const tokenSource = resolveTokenSource(
|
|
286
|
+
getHeader,
|
|
287
|
+
body,
|
|
288
|
+
contentType,
|
|
289
|
+
sigil.config.headerName
|
|
290
|
+
);
|
|
291
|
+
const metadata = extractRequestMetadata(request.method, getHeader, tokenSource);
|
|
292
|
+
const result = await sigil.protect(metadata);
|
|
293
|
+
if (!result.allowed) {
|
|
294
|
+
const errorResponse = createErrorResponse(result.expired);
|
|
295
|
+
for (const [key, value] of Object.entries(errorResponse.headers)) {
|
|
296
|
+
reply.header(key, value);
|
|
297
|
+
}
|
|
298
|
+
reply.code(errorResponse.status).send(errorResponse.body);
|
|
299
|
+
}
|
|
300
|
+
});
|
|
301
|
+
done();
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
305
|
+
0 && (module.exports = {
|
|
306
|
+
createFastifyPlugin
|
|
307
|
+
});
|
|
308
|
+
//# sourceMappingURL=fastify.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/fastify.ts","../../src/types.ts","../../src/extract-metadata.ts","../../src/error-response.ts","../../src/token-endpoint.ts"],"sourcesContent":["// @sigil-security/runtime — Fastify plugin 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 Fastify-Compatible Types\n// ============================================================\n\n/** Minimal Fastify-compatible request */\nexport interface FastifyLikeRequest {\n readonly method: string\n readonly url: string\n readonly headers: Readonly<Record<string, string | string[] | undefined>>\n body?: unknown\n}\n\n/** Minimal Fastify-compatible reply */\nexport interface FastifyLikeReply {\n status(code: number): FastifyLikeReply\n code(code: number): FastifyLikeReply\n send(payload?: unknown): FastifyLikeReply\n header(name: string, value: string): FastifyLikeReply\n readonly sent: boolean\n}\n\n/** Minimal Fastify-compatible instance */\nexport interface FastifyLikeInstance {\n addHook(\n name: 'preHandler',\n handler: (\n request: FastifyLikeRequest,\n reply: FastifyLikeReply,\n ) => Promise<void>,\n ): void\n get(\n path: string,\n handler: (request: FastifyLikeRequest, reply: FastifyLikeReply) => Promise<void>,\n ): void\n post(\n path: string,\n handler: (request: FastifyLikeRequest, reply: FastifyLikeReply) => Promise<void>,\n ): void\n}\n\n/** Fastify plugin done callback */\nexport type FastifyPluginDone = (err?: Error) => void\n\n/** Fastify plugin signature */\nexport type FastifyPlugin = (\n fastify: FastifyLikeInstance,\n options: MiddlewareOptions | undefined,\n done: FastifyPluginDone,\n) => void\n\n// ============================================================\n// Header Getter for Fastify\n// ============================================================\n\nfunction createFastifyHeaderGetter(\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 * Extracts the path portion from a Fastify URL (which may include query strings).\n */\nfunction extractPath(url: string): string {\n const qIndex = url.indexOf('?')\n return qIndex >= 0 ? url.slice(0, qIndex) : url\n}\n\n// ============================================================\n// Fastify Plugin Factory\n// ============================================================\n\n/**\n * Creates a Fastify plugin for Sigil CSRF protection.\n *\n * Registers:\n * - Token generation routes (GET /api/csrf/token, POST /api/csrf/one-shot)\n * - `preHandler` hook for CSRF validation on protected methods (runs after body parsing)\n *\n * @param sigil - Initialized SigilInstance\n * @param options - Middleware configuration options\n * @returns Fastify plugin function\n *\n * @example\n * ```typescript\n * import Fastify from 'fastify'\n * import { createSigil } from '@sigil-security/runtime'\n * import { createFastifyPlugin } from '@sigil-security/runtime/fastify'\n *\n * const sigil = await createSigil({ ... })\n * const fastify = Fastify()\n * fastify.register(createFastifyPlugin(sigil))\n * ```\n */\nexport function createFastifyPlugin(\n sigil: SigilInstance,\n options?: MiddlewareOptions,\n): FastifyPlugin {\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 (fastify, _opts, done) => {\n // Register token generation routes\n fastify.get(tokenEndpointPath, async (request, reply) => {\n const result = await handleTokenEndpoint(\n sigil,\n request.method,\n tokenEndpointPath,\n undefined,\n tokenEndpointPath,\n oneShotEndpointPath,\n )\n\n if (result !== null) {\n for (const [key, value] of Object.entries(result.headers)) {\n reply.header(key, value)\n }\n reply.code(result.status).send(result.body)\n }\n })\n\n if (sigil.config.oneShotEnabled) {\n fastify.post(oneShotEndpointPath, async (request, reply) => {\n const body = typeof request.body === 'object' && request.body !== null\n ? (request.body as Record<string, unknown>)\n : undefined\n\n const getHeader = createFastifyHeaderGetter(request.headers)\n const csrfTokenValue = getHeader(sigil.config.headerName)\n\n const result = await handleTokenEndpoint(\n sigil,\n request.method,\n oneShotEndpointPath,\n body,\n tokenEndpointPath,\n oneShotEndpointPath,\n csrfTokenValue,\n )\n\n if (result !== null) {\n for (const [key, value] of Object.entries(result.headers)) {\n reply.header(key, value)\n }\n reply.code(result.status).send(result.body)\n }\n })\n }\n\n // Register preHandler hook for CSRF validation\n // NOTE: preHandler runs AFTER body parsing, so request.body is available.\n // onRequest would run BEFORE body parsing — body-based tokens would never work.\n fastify.addHook('preHandler', async (request, reply) => {\n const path = normalizePath(extractPath(request.url))\n\n // Skip excluded paths (normalized comparison)\n if (excludePaths.has(path)) return\n\n // Skip token endpoints (handled by routes above)\n if (path === tokenEndpointPath) return\n if (sigil.config.oneShotEnabled && path === oneShotEndpointPath) return\n\n // Extract metadata\n const getHeader = createFastifyHeaderGetter(request.headers)\n const contentType = parseContentType(getHeader('content-type'))\n\n const body = typeof request.body === 'object' && request.body !== null\n ? (request.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(request.method, getHeader, tokenSource)\n\n // 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 reply.header(key, value)\n }\n reply.code(errorResponse.status).send(errorResponse.body)\n }\n })\n\n done()\n }\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,W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UAAI,aAAa,IAAI,IAAI,EAAG;AAG5B,UAAI,SAAS,kBAAmB;AAChC,UAAI,MAAM,OAAO,kBAAkB,SAAS,oBAAqB;AAGjE,YAAM,YAAY,0BAA0B,QAAQ,OAAO;AAC3D,YAAM,cAAc,iBAAiB,UAAU,cAAc,CAAC;AAE9D,YAAM,OAAO,OAAO,QAAQ,SAAS,YAAY,QAAQ,SAAS,OAC7D,QAAQ,OACT;AAEJ,YAAM,cAAc;AAAA,QAClB;AAAA,QACA;AAAA,QACA;AAAA,QACA,MAAM,OAAO;AAAA,MACf;AAEA,YAAM,WAAW,uBAAuB,QAAQ,QAAQ,WAAW,WAAW;AAG9E,YAAM,SAAwB,MAAM,MAAM,QAAQ,QAAQ;AAE1D,UAAI,CAAC,OAAO,SAAS;AACnB,cAAM,gBAAgB,oBAAoB,OAAO,OAAO;AACxD,mBAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,cAAc,OAAO,GAAG;AAChE,gBAAM,OAAO,KAAK,KAAK;AAAA,QACzB;AACA,cAAM,KAAK,cAAc,MAAM,EAAE,KAAK,cAAc,IAAI;AAAA,MAC1D;AAAA,IACF,CAAC;AAED,SAAK;AAAA,EACP;AACF;","names":[]}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { c as MiddlewareOptions, a as SigilInstance } from '../types-DySgT8rA.cjs';
|
|
2
|
+
import '@sigil-security/core';
|
|
3
|
+
import '@sigil-security/policy';
|
|
4
|
+
|
|
5
|
+
/** Minimal Fastify-compatible request */
|
|
6
|
+
interface FastifyLikeRequest {
|
|
7
|
+
readonly method: string;
|
|
8
|
+
readonly url: string;
|
|
9
|
+
readonly headers: Readonly<Record<string, string | string[] | undefined>>;
|
|
10
|
+
body?: unknown;
|
|
11
|
+
}
|
|
12
|
+
/** Minimal Fastify-compatible reply */
|
|
13
|
+
interface FastifyLikeReply {
|
|
14
|
+
status(code: number): FastifyLikeReply;
|
|
15
|
+
code(code: number): FastifyLikeReply;
|
|
16
|
+
send(payload?: unknown): FastifyLikeReply;
|
|
17
|
+
header(name: string, value: string): FastifyLikeReply;
|
|
18
|
+
readonly sent: boolean;
|
|
19
|
+
}
|
|
20
|
+
/** Minimal Fastify-compatible instance */
|
|
21
|
+
interface FastifyLikeInstance {
|
|
22
|
+
addHook(name: 'preHandler', handler: (request: FastifyLikeRequest, reply: FastifyLikeReply) => Promise<void>): void;
|
|
23
|
+
get(path: string, handler: (request: FastifyLikeRequest, reply: FastifyLikeReply) => Promise<void>): void;
|
|
24
|
+
post(path: string, handler: (request: FastifyLikeRequest, reply: FastifyLikeReply) => Promise<void>): void;
|
|
25
|
+
}
|
|
26
|
+
/** Fastify plugin done callback */
|
|
27
|
+
type FastifyPluginDone = (err?: Error) => void;
|
|
28
|
+
/** Fastify plugin signature */
|
|
29
|
+
type FastifyPlugin = (fastify: FastifyLikeInstance, options: MiddlewareOptions | undefined, done: FastifyPluginDone) => void;
|
|
30
|
+
/**
|
|
31
|
+
* Creates a Fastify plugin for Sigil CSRF protection.
|
|
32
|
+
*
|
|
33
|
+
* Registers:
|
|
34
|
+
* - Token generation routes (GET /api/csrf/token, POST /api/csrf/one-shot)
|
|
35
|
+
* - `preHandler` hook for CSRF validation on protected methods (runs after body parsing)
|
|
36
|
+
*
|
|
37
|
+
* @param sigil - Initialized SigilInstance
|
|
38
|
+
* @param options - Middleware configuration options
|
|
39
|
+
* @returns Fastify plugin function
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```typescript
|
|
43
|
+
* import Fastify from 'fastify'
|
|
44
|
+
* import { createSigil } from '@sigil-security/runtime'
|
|
45
|
+
* import { createFastifyPlugin } from '@sigil-security/runtime/fastify'
|
|
46
|
+
*
|
|
47
|
+
* const sigil = await createSigil({ ... })
|
|
48
|
+
* const fastify = Fastify()
|
|
49
|
+
* fastify.register(createFastifyPlugin(sigil))
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
declare function createFastifyPlugin(sigil: SigilInstance, options?: MiddlewareOptions): FastifyPlugin;
|
|
53
|
+
|
|
54
|
+
export { type FastifyLikeInstance, type FastifyLikeReply, type FastifyLikeRequest, type FastifyPlugin, type FastifyPluginDone, createFastifyPlugin };
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { c as MiddlewareOptions, a as SigilInstance } from '../types-DySgT8rA.js';
|
|
2
|
+
import '@sigil-security/core';
|
|
3
|
+
import '@sigil-security/policy';
|
|
4
|
+
|
|
5
|
+
/** Minimal Fastify-compatible request */
|
|
6
|
+
interface FastifyLikeRequest {
|
|
7
|
+
readonly method: string;
|
|
8
|
+
readonly url: string;
|
|
9
|
+
readonly headers: Readonly<Record<string, string | string[] | undefined>>;
|
|
10
|
+
body?: unknown;
|
|
11
|
+
}
|
|
12
|
+
/** Minimal Fastify-compatible reply */
|
|
13
|
+
interface FastifyLikeReply {
|
|
14
|
+
status(code: number): FastifyLikeReply;
|
|
15
|
+
code(code: number): FastifyLikeReply;
|
|
16
|
+
send(payload?: unknown): FastifyLikeReply;
|
|
17
|
+
header(name: string, value: string): FastifyLikeReply;
|
|
18
|
+
readonly sent: boolean;
|
|
19
|
+
}
|
|
20
|
+
/** Minimal Fastify-compatible instance */
|
|
21
|
+
interface FastifyLikeInstance {
|
|
22
|
+
addHook(name: 'preHandler', handler: (request: FastifyLikeRequest, reply: FastifyLikeReply) => Promise<void>): void;
|
|
23
|
+
get(path: string, handler: (request: FastifyLikeRequest, reply: FastifyLikeReply) => Promise<void>): void;
|
|
24
|
+
post(path: string, handler: (request: FastifyLikeRequest, reply: FastifyLikeReply) => Promise<void>): void;
|
|
25
|
+
}
|
|
26
|
+
/** Fastify plugin done callback */
|
|
27
|
+
type FastifyPluginDone = (err?: Error) => void;
|
|
28
|
+
/** Fastify plugin signature */
|
|
29
|
+
type FastifyPlugin = (fastify: FastifyLikeInstance, options: MiddlewareOptions | undefined, done: FastifyPluginDone) => void;
|
|
30
|
+
/**
|
|
31
|
+
* Creates a Fastify plugin for Sigil CSRF protection.
|
|
32
|
+
*
|
|
33
|
+
* Registers:
|
|
34
|
+
* - Token generation routes (GET /api/csrf/token, POST /api/csrf/one-shot)
|
|
35
|
+
* - `preHandler` hook for CSRF validation on protected methods (runs after body parsing)
|
|
36
|
+
*
|
|
37
|
+
* @param sigil - Initialized SigilInstance
|
|
38
|
+
* @param options - Middleware configuration options
|
|
39
|
+
* @returns Fastify plugin function
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```typescript
|
|
43
|
+
* import Fastify from 'fastify'
|
|
44
|
+
* import { createSigil } from '@sigil-security/runtime'
|
|
45
|
+
* import { createFastifyPlugin } from '@sigil-security/runtime/fastify'
|
|
46
|
+
*
|
|
47
|
+
* const sigil = await createSigil({ ... })
|
|
48
|
+
* const fastify = Fastify()
|
|
49
|
+
* fastify.register(createFastifyPlugin(sigil))
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
declare function createFastifyPlugin(sigil: SigilInstance, options?: MiddlewareOptions): FastifyPlugin;
|
|
53
|
+
|
|
54
|
+
export { type FastifyLikeInstance, type FastifyLikeReply, type FastifyLikeRequest, type FastifyPlugin, type FastifyPluginDone, createFastifyPlugin };
|