@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,99 @@
|
|
|
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/fastify.ts
|
|
14
|
+
function createFastifyHeaderGetter(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 extractPath(url) {
|
|
23
|
+
const qIndex = url.indexOf("?");
|
|
24
|
+
return qIndex >= 0 ? url.slice(0, qIndex) : url;
|
|
25
|
+
}
|
|
26
|
+
function createFastifyPlugin(sigil, options) {
|
|
27
|
+
const excludePaths = normalizePathSet(options?.excludePaths ?? []);
|
|
28
|
+
const tokenEndpointPath = normalizePath(options?.tokenEndpointPath ?? DEFAULT_TOKEN_ENDPOINT_PATH);
|
|
29
|
+
const oneShotEndpointPath = normalizePath(options?.oneShotEndpointPath ?? DEFAULT_ONESHOT_ENDPOINT_PATH);
|
|
30
|
+
return (fastify, _opts, done) => {
|
|
31
|
+
fastify.get(tokenEndpointPath, async (request, reply) => {
|
|
32
|
+
const result = await handleTokenEndpoint(
|
|
33
|
+
sigil,
|
|
34
|
+
request.method,
|
|
35
|
+
tokenEndpointPath,
|
|
36
|
+
void 0,
|
|
37
|
+
tokenEndpointPath,
|
|
38
|
+
oneShotEndpointPath
|
|
39
|
+
);
|
|
40
|
+
if (result !== null) {
|
|
41
|
+
for (const [key, value] of Object.entries(result.headers)) {
|
|
42
|
+
reply.header(key, value);
|
|
43
|
+
}
|
|
44
|
+
reply.code(result.status).send(result.body);
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
if (sigil.config.oneShotEnabled) {
|
|
48
|
+
fastify.post(oneShotEndpointPath, async (request, reply) => {
|
|
49
|
+
const body = typeof request.body === "object" && request.body !== null ? request.body : void 0;
|
|
50
|
+
const getHeader = createFastifyHeaderGetter(request.headers);
|
|
51
|
+
const csrfTokenValue = getHeader(sigil.config.headerName);
|
|
52
|
+
const result = await handleTokenEndpoint(
|
|
53
|
+
sigil,
|
|
54
|
+
request.method,
|
|
55
|
+
oneShotEndpointPath,
|
|
56
|
+
body,
|
|
57
|
+
tokenEndpointPath,
|
|
58
|
+
oneShotEndpointPath,
|
|
59
|
+
csrfTokenValue
|
|
60
|
+
);
|
|
61
|
+
if (result !== null) {
|
|
62
|
+
for (const [key, value] of Object.entries(result.headers)) {
|
|
63
|
+
reply.header(key, value);
|
|
64
|
+
}
|
|
65
|
+
reply.code(result.status).send(result.body);
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
fastify.addHook("preHandler", async (request, reply) => {
|
|
70
|
+
const path = normalizePath(extractPath(request.url));
|
|
71
|
+
if (excludePaths.has(path)) return;
|
|
72
|
+
if (path === tokenEndpointPath) return;
|
|
73
|
+
if (sigil.config.oneShotEnabled && path === oneShotEndpointPath) return;
|
|
74
|
+
const getHeader = createFastifyHeaderGetter(request.headers);
|
|
75
|
+
const contentType = parseContentType(getHeader("content-type"));
|
|
76
|
+
const body = typeof request.body === "object" && request.body !== null ? request.body : void 0;
|
|
77
|
+
const tokenSource = resolveTokenSource(
|
|
78
|
+
getHeader,
|
|
79
|
+
body,
|
|
80
|
+
contentType,
|
|
81
|
+
sigil.config.headerName
|
|
82
|
+
);
|
|
83
|
+
const metadata = extractRequestMetadata(request.method, getHeader, tokenSource);
|
|
84
|
+
const result = await sigil.protect(metadata);
|
|
85
|
+
if (!result.allowed) {
|
|
86
|
+
const errorResponse = createErrorResponse(result.expired);
|
|
87
|
+
for (const [key, value] of Object.entries(errorResponse.headers)) {
|
|
88
|
+
reply.header(key, value);
|
|
89
|
+
}
|
|
90
|
+
reply.code(errorResponse.status).send(errorResponse.body);
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
done();
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
export {
|
|
97
|
+
createFastifyPlugin
|
|
98
|
+
};
|
|
99
|
+
//# sourceMappingURL=fastify.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/fastify.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"],"mappings":";;;;;;;;;;;;;AAgEA,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;AAKA,SAAS,YAAY,KAAqB;AACxC,QAAM,SAAS,IAAI,QAAQ,GAAG;AAC9B,SAAO,UAAU,IAAI,IAAI,MAAM,GAAG,MAAM,IAAI;AAC9C;AA4BO,SAAS,oBACd,OACA,SACe;AACf,QAAM,eAAe,iBAAiB,SAAS,gBAAgB,CAAC,CAAC;AACjE,QAAM,oBAAoB,cAAc,SAAS,qBAAqB,2BAA2B;AACjG,QAAM,sBAAsB,cAAc,SAAS,uBAAuB,6BAA6B;AAEvG,SAAO,CAAC,SAAS,OAAO,SAAS;AAE/B,YAAQ,IAAI,mBAAmB,OAAO,SAAS,UAAU;AACvD,YAAM,SAAS,MAAM;AAAA,QACnB;AAAA,QACA,QAAQ;AAAA,QACR;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAEA,UAAI,WAAW,MAAM;AACnB,mBAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,OAAO,OAAO,GAAG;AACzD,gBAAM,OAAO,KAAK,KAAK;AAAA,QACzB;AACA,cAAM,KAAK,OAAO,MAAM,EAAE,KAAK,OAAO,IAAI;AAAA,MAC5C;AAAA,IACF,CAAC;AAED,QAAI,MAAM,OAAO,gBAAgB;AAC/B,cAAQ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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,359 @@
|
|
|
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/fetch.ts
|
|
21
|
+
var fetch_exports = {};
|
|
22
|
+
__export(fetch_exports, {
|
|
23
|
+
createFetchMiddleware: () => createFetchMiddleware,
|
|
24
|
+
createFetchTokenEndpoint: () => createFetchTokenEndpoint
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(fetch_exports);
|
|
27
|
+
|
|
28
|
+
// src/types.ts
|
|
29
|
+
var DEFAULT_TOKEN_ENDPOINT_PATH = "/api/csrf/token";
|
|
30
|
+
var DEFAULT_ONESHOT_ENDPOINT_PATH = "/api/csrf/one-shot";
|
|
31
|
+
|
|
32
|
+
// src/extract-metadata.ts
|
|
33
|
+
var import_policy = require("@sigil-security/policy");
|
|
34
|
+
function normalizePath(path) {
|
|
35
|
+
if (path.length === 0 || path === "/") return "/";
|
|
36
|
+
let end = path.length;
|
|
37
|
+
while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
|
|
38
|
+
if (end === path.length) return path;
|
|
39
|
+
if (end === 0) return "/";
|
|
40
|
+
return path.slice(0, end);
|
|
41
|
+
}
|
|
42
|
+
function normalizePathSet(paths) {
|
|
43
|
+
return new Set(paths.map(normalizePath));
|
|
44
|
+
}
|
|
45
|
+
function extractRequestMetadata(method, getHeader, tokenSource) {
|
|
46
|
+
return {
|
|
47
|
+
method: method.toUpperCase(),
|
|
48
|
+
origin: getHeader("origin"),
|
|
49
|
+
referer: getHeader("referer"),
|
|
50
|
+
secFetchSite: getHeader("sec-fetch-site"),
|
|
51
|
+
secFetchMode: getHeader("sec-fetch-mode"),
|
|
52
|
+
secFetchDest: getHeader("sec-fetch-dest"),
|
|
53
|
+
contentType: parseContentType(getHeader("content-type")),
|
|
54
|
+
tokenSource,
|
|
55
|
+
clientType: getHeader("x-client-type") ?? void 0
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function parseContentType(contentType) {
|
|
59
|
+
if (contentType === null) return null;
|
|
60
|
+
const semicolonIdx = contentType.indexOf(";");
|
|
61
|
+
const mimeType = semicolonIdx >= 0 ? contentType.substring(0, semicolonIdx) : contentType;
|
|
62
|
+
return mimeType.trim().toLowerCase();
|
|
63
|
+
}
|
|
64
|
+
function extractTokenFromHeader(getHeader, headerName = import_policy.DEFAULT_HEADER_NAME) {
|
|
65
|
+
const value = getHeader(headerName);
|
|
66
|
+
if (value !== null && value !== "") {
|
|
67
|
+
return { from: "header", value };
|
|
68
|
+
}
|
|
69
|
+
return { from: "none" };
|
|
70
|
+
}
|
|
71
|
+
function extractTokenFromJsonBody(body, fieldName = import_policy.DEFAULT_JSON_FIELD_NAME) {
|
|
72
|
+
if (body !== null && body !== void 0 && typeof body === "object") {
|
|
73
|
+
const value = body[fieldName];
|
|
74
|
+
if (typeof value === "string" && value !== "") {
|
|
75
|
+
return { from: "body-json", value };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
function extractTokenFromFormBody(body, fieldName = import_policy.DEFAULT_FORM_FIELD_NAME) {
|
|
81
|
+
if (body !== null && body !== void 0 && typeof body === "object") {
|
|
82
|
+
const value = body[fieldName];
|
|
83
|
+
if (typeof value === "string" && value !== "") {
|
|
84
|
+
return { from: "body-form", value };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
function resolveTokenSource(getHeader, body, contentType, headerName, jsonFieldName, formFieldName) {
|
|
90
|
+
const headerToken = extractTokenFromHeader(getHeader, headerName);
|
|
91
|
+
if (headerToken.from !== "none") return headerToken;
|
|
92
|
+
if (contentType !== null && contentType.includes("application/json")) {
|
|
93
|
+
const jsonToken = extractTokenFromJsonBody(body, jsonFieldName);
|
|
94
|
+
if (jsonToken !== null) return jsonToken;
|
|
95
|
+
}
|
|
96
|
+
if (contentType !== null && (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data"))) {
|
|
97
|
+
const formToken = extractTokenFromFormBody(body, formFieldName);
|
|
98
|
+
if (formToken !== null) return formToken;
|
|
99
|
+
}
|
|
100
|
+
return { from: "none" };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// src/error-response.ts
|
|
104
|
+
var CSRF_FAILURE_MESSAGE = "CSRF validation failed";
|
|
105
|
+
var EXPIRED_HEADER_NAME = "X-CSRF-Token-Expired";
|
|
106
|
+
function createErrorResponse(expired) {
|
|
107
|
+
const headers = {};
|
|
108
|
+
if (expired) {
|
|
109
|
+
headers[EXPIRED_HEADER_NAME] = "true";
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
status: 403,
|
|
113
|
+
body: { error: CSRF_FAILURE_MESSAGE },
|
|
114
|
+
headers
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
function createTokenResponse(token, expiresAt) {
|
|
118
|
+
return {
|
|
119
|
+
status: 200,
|
|
120
|
+
body: { token, expiresAt }
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
function createOneShotTokenResponse(token, expiresAt, action) {
|
|
124
|
+
return {
|
|
125
|
+
status: 200,
|
|
126
|
+
body: { token, expiresAt, action }
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// src/token-endpoint.ts
|
|
131
|
+
async function handleTokenEndpoint(sigil, method, path, body, tokenEndpointPath, oneShotEndpointPath, csrfTokenValue) {
|
|
132
|
+
const upperMethod = method.toUpperCase();
|
|
133
|
+
if (path === tokenEndpointPath && upperMethod === "GET") {
|
|
134
|
+
return handleRegularTokenGeneration(sigil);
|
|
135
|
+
}
|
|
136
|
+
if (sigil.config.oneShotEnabled && path === oneShotEndpointPath && upperMethod === "POST") {
|
|
137
|
+
if (csrfTokenValue === void 0 || csrfTokenValue === null || csrfTokenValue === "") {
|
|
138
|
+
const errorResponse = createErrorResponse(false);
|
|
139
|
+
return {
|
|
140
|
+
handled: true,
|
|
141
|
+
status: errorResponse.status,
|
|
142
|
+
body: errorResponse.body,
|
|
143
|
+
headers: errorResponse.headers
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
const csrfResult = await sigil.validateToken(csrfTokenValue);
|
|
147
|
+
if (!csrfResult.valid) {
|
|
148
|
+
const errorResponse = createErrorResponse(false);
|
|
149
|
+
return {
|
|
150
|
+
handled: true,
|
|
151
|
+
status: errorResponse.status,
|
|
152
|
+
body: errorResponse.body,
|
|
153
|
+
headers: errorResponse.headers
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
return handleOneShotTokenGeneration(sigil, body);
|
|
157
|
+
}
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
async function handleRegularTokenGeneration(sigil) {
|
|
161
|
+
const result = await sigil.generateToken();
|
|
162
|
+
if (!result.success) {
|
|
163
|
+
return {
|
|
164
|
+
handled: true,
|
|
165
|
+
status: 500,
|
|
166
|
+
body: { error: "Token generation failed" },
|
|
167
|
+
headers: {}
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
const response = createTokenResponse(result.token, result.expiresAt);
|
|
171
|
+
return {
|
|
172
|
+
handled: true,
|
|
173
|
+
status: response.status,
|
|
174
|
+
body: response.body,
|
|
175
|
+
headers: {}
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
async function handleOneShotTokenGeneration(sigil, body) {
|
|
179
|
+
if (body === null || body === void 0 || typeof body !== "object") {
|
|
180
|
+
return {
|
|
181
|
+
handled: true,
|
|
182
|
+
status: 400,
|
|
183
|
+
body: { error: "Request body required" },
|
|
184
|
+
headers: {}
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
const action = body["action"];
|
|
188
|
+
if (typeof action !== "string" || action === "") {
|
|
189
|
+
return {
|
|
190
|
+
handled: true,
|
|
191
|
+
status: 400,
|
|
192
|
+
body: { error: "Missing or invalid action parameter" },
|
|
193
|
+
headers: {}
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
let context;
|
|
197
|
+
const rawContext = body["context"];
|
|
198
|
+
if (Array.isArray(rawContext)) {
|
|
199
|
+
const isAllStrings = rawContext.every((item) => typeof item === "string");
|
|
200
|
+
if (isAllStrings) {
|
|
201
|
+
context = rawContext;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
const result = await sigil.generateOneShotToken(action, context);
|
|
205
|
+
if (!result.success) {
|
|
206
|
+
return {
|
|
207
|
+
handled: true,
|
|
208
|
+
status: 500,
|
|
209
|
+
body: { error: "One-shot token generation failed" },
|
|
210
|
+
headers: {}
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
const response = createOneShotTokenResponse(result.token, result.expiresAt, action);
|
|
214
|
+
return {
|
|
215
|
+
handled: true,
|
|
216
|
+
status: response.status,
|
|
217
|
+
body: response.body,
|
|
218
|
+
headers: {}
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// src/adapters/fetch.ts
|
|
223
|
+
function createFetchHeaderGetter(headers) {
|
|
224
|
+
return (name) => {
|
|
225
|
+
return headers.get(name.toLowerCase());
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
function extractPathname(request) {
|
|
229
|
+
try {
|
|
230
|
+
return new URL(request.url).pathname;
|
|
231
|
+
} catch {
|
|
232
|
+
const qIndex = request.url.indexOf("?");
|
|
233
|
+
return qIndex >= 0 ? request.url.slice(0, qIndex) : request.url;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
function createFetchMiddleware(sigil, handler, options) {
|
|
237
|
+
const excludePaths = normalizePathSet(options?.excludePaths ?? []);
|
|
238
|
+
const tokenEndpointPath = normalizePath(options?.tokenEndpointPath ?? DEFAULT_TOKEN_ENDPOINT_PATH);
|
|
239
|
+
const oneShotEndpointPath = normalizePath(options?.oneShotEndpointPath ?? DEFAULT_ONESHOT_ENDPOINT_PATH);
|
|
240
|
+
return async (request) => {
|
|
241
|
+
const path = normalizePath(extractPathname(request));
|
|
242
|
+
const method = request.method.toUpperCase();
|
|
243
|
+
if (excludePaths.has(path)) {
|
|
244
|
+
return handler(request);
|
|
245
|
+
}
|
|
246
|
+
let body;
|
|
247
|
+
if (method === "POST" && path === oneShotEndpointPath) {
|
|
248
|
+
try {
|
|
249
|
+
body = await request.clone().json();
|
|
250
|
+
} catch {
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
const csrfTokenValue = request.headers.get(sigil.config.headerName);
|
|
254
|
+
const tokenResult = await handleTokenEndpoint(
|
|
255
|
+
sigil,
|
|
256
|
+
method,
|
|
257
|
+
path,
|
|
258
|
+
body,
|
|
259
|
+
tokenEndpointPath,
|
|
260
|
+
oneShotEndpointPath,
|
|
261
|
+
csrfTokenValue
|
|
262
|
+
);
|
|
263
|
+
if (tokenResult !== null) {
|
|
264
|
+
return new Response(JSON.stringify(tokenResult.body), {
|
|
265
|
+
status: tokenResult.status,
|
|
266
|
+
headers: {
|
|
267
|
+
"content-type": "application/json",
|
|
268
|
+
...tokenResult.headers
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
const getHeader = createFetchHeaderGetter(request.headers);
|
|
273
|
+
const contentType = parseContentType(getHeader("content-type"));
|
|
274
|
+
let protectionBody;
|
|
275
|
+
if (method !== "GET" && method !== "HEAD" && method !== "OPTIONS") {
|
|
276
|
+
if (contentType !== null && contentType.includes("application/json")) {
|
|
277
|
+
try {
|
|
278
|
+
protectionBody = await request.clone().json();
|
|
279
|
+
} catch {
|
|
280
|
+
}
|
|
281
|
+
} else if (contentType !== null && contentType.includes("application/x-www-form-urlencoded")) {
|
|
282
|
+
try {
|
|
283
|
+
const cloned = request.clone();
|
|
284
|
+
const text = await cloned.text();
|
|
285
|
+
const params = new URLSearchParams(text);
|
|
286
|
+
const formObj = {};
|
|
287
|
+
params.forEach((val, key) => {
|
|
288
|
+
formObj[key] = val;
|
|
289
|
+
});
|
|
290
|
+
protectionBody = formObj;
|
|
291
|
+
} catch {
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
const tokenSource = resolveTokenSource(
|
|
296
|
+
getHeader,
|
|
297
|
+
protectionBody,
|
|
298
|
+
contentType,
|
|
299
|
+
sigil.config.headerName
|
|
300
|
+
);
|
|
301
|
+
const metadata = extractRequestMetadata(method, getHeader, tokenSource);
|
|
302
|
+
const result = await sigil.protect(metadata);
|
|
303
|
+
if (!result.allowed) {
|
|
304
|
+
const errorResponse = createErrorResponse(result.expired);
|
|
305
|
+
return new Response(JSON.stringify(errorResponse.body), {
|
|
306
|
+
status: errorResponse.status,
|
|
307
|
+
headers: {
|
|
308
|
+
"content-type": "application/json",
|
|
309
|
+
...errorResponse.headers
|
|
310
|
+
}
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
return handler(request);
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
function createFetchTokenEndpoint(sigil, options) {
|
|
317
|
+
const tokenEndpointPath = normalizePath(options?.tokenEndpointPath ?? DEFAULT_TOKEN_ENDPOINT_PATH);
|
|
318
|
+
const oneShotEndpointPath = normalizePath(options?.oneShotEndpointPath ?? DEFAULT_ONESHOT_ENDPOINT_PATH);
|
|
319
|
+
return async (request) => {
|
|
320
|
+
const path = normalizePath(extractPathname(request));
|
|
321
|
+
const method = request.method.toUpperCase();
|
|
322
|
+
let body;
|
|
323
|
+
if (method === "POST") {
|
|
324
|
+
try {
|
|
325
|
+
body = await request.json();
|
|
326
|
+
} catch {
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
const csrfTokenValue = request.headers.get(sigil.config.headerName);
|
|
330
|
+
const result = await handleTokenEndpoint(
|
|
331
|
+
sigil,
|
|
332
|
+
method,
|
|
333
|
+
path,
|
|
334
|
+
body,
|
|
335
|
+
tokenEndpointPath,
|
|
336
|
+
oneShotEndpointPath,
|
|
337
|
+
csrfTokenValue
|
|
338
|
+
);
|
|
339
|
+
if (result !== null) {
|
|
340
|
+
return new Response(JSON.stringify(result.body), {
|
|
341
|
+
status: result.status,
|
|
342
|
+
headers: {
|
|
343
|
+
"content-type": "application/json",
|
|
344
|
+
...result.headers
|
|
345
|
+
}
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
return new Response(JSON.stringify({ error: "Not found" }), {
|
|
349
|
+
status: 404,
|
|
350
|
+
headers: { "content-type": "application/json" }
|
|
351
|
+
});
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
355
|
+
0 && (module.exports = {
|
|
356
|
+
createFetchMiddleware,
|
|
357
|
+
createFetchTokenEndpoint
|
|
358
|
+
});
|
|
359
|
+
//# sourceMappingURL=fetch.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/adapters/fetch.ts","../../src/types.ts","../../src/extract-metadata.ts","../../src/error-response.ts","../../src/token-endpoint.ts"],"sourcesContent":["// @sigil-security/runtime — Native Fetch adapter (Edge runtime, Cloudflare Workers, etc.)\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// Types\n// ============================================================\n\n/** A handler that processes a Request and returns a Response */\nexport type FetchHandler = (request: Request) => Promise<Response> | Response\n\n// ============================================================\n// Header Getter for Fetch API\n// ============================================================\n\nfunction createFetchHeaderGetter(headers: Headers): HeaderGetter {\n return (name: string): string | null => {\n return headers.get(name.toLowerCase())\n }\n}\n\n/**\n * Extracts the pathname from a Request URL.\n */\nfunction extractPathname(request: Request): string {\n try {\n return new URL(request.url).pathname\n } catch {\n // Fallback for relative URLs\n const qIndex = request.url.indexOf('?')\n return qIndex >= 0 ? request.url.slice(0, qIndex) : request.url\n }\n}\n\n// ============================================================\n// Fetch Middleware Factory\n// ============================================================\n\n/**\n * Creates a Fetch API middleware wrapper for Sigil CSRF protection.\n *\n * Wraps a request handler and intercepts requests for CSRF validation\n * and token endpoint handling. Compatible with any platform using the\n * standard Fetch API: Cloudflare Workers, Deno Deploy, Bun, etc.\n *\n * @param sigil - Initialized SigilInstance\n * @param handler - The underlying request handler to protect\n * @param options - Middleware configuration options\n * @returns A new FetchHandler with Sigil protection\n *\n * @example\n * ```typescript\n * import { createSigil } from '@sigil-security/runtime'\n * import { createFetchMiddleware } from '@sigil-security/runtime/fetch'\n *\n * const sigil = await createSigil({ ... })\n *\n * const handler = (request: Request) => new Response('OK')\n * const protectedHandler = createFetchMiddleware(sigil, handler)\n *\n * // Cloudflare Workers\n * export default { fetch: protectedHandler }\n * ```\n */\nexport function createFetchMiddleware(\n sigil: SigilInstance,\n handler: FetchHandler,\n options?: MiddlewareOptions,\n): FetchHandler {\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 async (request: Request): Promise<Response> => {\n const path = normalizePath(extractPathname(request))\n const method = request.method.toUpperCase()\n\n // Skip excluded paths (normalized comparison)\n if (excludePaths.has(path)) {\n return handler(request)\n }\n\n // Step 1: Handle token endpoint requests\n let body: Record<string, unknown> | undefined\n if (method === 'POST' && path === oneShotEndpointPath) {\n try {\n body = (await request.clone().json()) as Record<string, unknown>\n } catch {\n // Body parsing failed\n }\n }\n\n const csrfTokenValue = request.headers.get(sigil.config.headerName)\n\n const tokenResult = await handleTokenEndpoint(\n sigil,\n method,\n path,\n body,\n tokenEndpointPath,\n oneShotEndpointPath,\n csrfTokenValue,\n )\n\n if (tokenResult !== null) {\n return new Response(JSON.stringify(tokenResult.body), {\n status: tokenResult.status,\n headers: {\n 'content-type': 'application/json',\n ...tokenResult.headers,\n },\n })\n }\n\n // Step 2: Extract metadata for protection\n const getHeader = createFetchHeaderGetter(request.headers)\n const contentType = parseContentType(getHeader('content-type'))\n\n // Try to get body for token extraction (clone to preserve original).\n // Supports both JSON and form-encoded bodies via the Fetch API.\n let protectionBody: Record<string, unknown> | undefined\n if (method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS') {\n if (contentType !== null && contentType.includes('application/json')) {\n try {\n protectionBody = (await request.clone().json()) as Record<string, unknown>\n } catch {\n // Body not valid JSON — token might be in header\n }\n } else if (\n contentType !== null &&\n contentType.includes('application/x-www-form-urlencoded')\n ) {\n try {\n const cloned = request.clone()\n const text = await cloned.text()\n const params = new URLSearchParams(text)\n const formObj: Record<string, unknown> = {}\n params.forEach((val, key) => {\n formObj[key] = val\n })\n protectionBody = formObj\n } catch {\n // Form body parsing failed — token might be in header\n }\n }\n }\n\n const tokenSource = resolveTokenSource(\n getHeader,\n protectionBody,\n contentType,\n sigil.config.headerName,\n )\n\n const metadata = extractRequestMetadata(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 return new Response(JSON.stringify(errorResponse.body), {\n status: errorResponse.status,\n headers: {\n 'content-type': 'application/json',\n ...errorResponse.headers,\n },\n })\n }\n\n // Step 4: Request allowed — forward to handler\n return handler(request)\n }\n}\n\n/**\n * Creates a standalone token endpoint handler using the Fetch API.\n *\n * Unlike `createFetchMiddleware`, this does NOT wrap another handler.\n * It only handles token generation requests and returns 404 for everything else.\n *\n * @param sigil - Initialized SigilInstance\n * @param options - Middleware configuration options\n * @returns FetchHandler for token endpoints only\n */\nexport function createFetchTokenEndpoint(\n sigil: SigilInstance,\n options?: MiddlewareOptions,\n): FetchHandler {\n const tokenEndpointPath = normalizePath(options?.tokenEndpointPath ?? DEFAULT_TOKEN_ENDPOINT_PATH)\n const oneShotEndpointPath = normalizePath(options?.oneShotEndpointPath ?? DEFAULT_ONESHOT_ENDPOINT_PATH)\n\n return async (request: Request): Promise<Response> => {\n const path = normalizePath(extractPathname(request))\n const method = request.method.toUpperCase()\n\n let body: Record<string, unknown> | undefined\n if (method === 'POST') {\n try {\n body = (await request.json()) as Record<string, unknown>\n } catch {\n // Body parsing failed\n }\n }\n\n const csrfTokenValue = request.headers.get(sigil.config.headerName)\n\n const result = await handleTokenEndpoint(\n sigil,\n method,\n path,\n body,\n tokenEndpointPath,\n oneShotEndpointPath,\n csrfTokenValue,\n )\n\n if (result !== null) {\n return new Response(JSON.stringify(result.body), {\n status: result.status,\n headers: {\n 'content-type': 'application/json',\n ...result.headers,\n },\n })\n }\n\n return new Response(JSON.stringify({ error: 'Not found' }), {\n status: 404,\n headers: { 'content-type': 'application/json' },\n })\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;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;AACjB,SAAO;AAAA,IACL,QAAQ,OAAO,YAAY;AAAA,IAC3B,QAAQ,UAAU,QAAQ;AAAA,IAC1B,SAAS,UAAU,SAAS;AAAA,IAC5B,cAAc,UAAU,gBAAgB;AAAA,IACxC,cAAc,UAAU,gBAAgB;AAAA,IACxC,cAAc,UAAU,gBAAgB;AAAA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-DySgT8rA.cjs';
|
|
2
|
+
import '@sigil-security/core';
|
|
3
|
+
import '@sigil-security/policy';
|
|
4
|
+
|
|
5
|
+
/** A handler that processes a Request and returns a Response */
|
|
6
|
+
type FetchHandler = (request: Request) => Promise<Response> | Response;
|
|
7
|
+
/**
|
|
8
|
+
* Creates a Fetch API middleware wrapper for Sigil CSRF protection.
|
|
9
|
+
*
|
|
10
|
+
* Wraps a request handler and intercepts requests for CSRF validation
|
|
11
|
+
* and token endpoint handling. Compatible with any platform using the
|
|
12
|
+
* standard Fetch API: Cloudflare Workers, Deno Deploy, Bun, etc.
|
|
13
|
+
*
|
|
14
|
+
* @param sigil - Initialized SigilInstance
|
|
15
|
+
* @param handler - The underlying request handler to protect
|
|
16
|
+
* @param options - Middleware configuration options
|
|
17
|
+
* @returns A new FetchHandler with Sigil protection
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```typescript
|
|
21
|
+
* import { createSigil } from '@sigil-security/runtime'
|
|
22
|
+
* import { createFetchMiddleware } from '@sigil-security/runtime/fetch'
|
|
23
|
+
*
|
|
24
|
+
* const sigil = await createSigil({ ... })
|
|
25
|
+
*
|
|
26
|
+
* const handler = (request: Request) => new Response('OK')
|
|
27
|
+
* const protectedHandler = createFetchMiddleware(sigil, handler)
|
|
28
|
+
*
|
|
29
|
+
* // Cloudflare Workers
|
|
30
|
+
* export default { fetch: protectedHandler }
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
declare function createFetchMiddleware(sigil: SigilInstance, handler: FetchHandler, options?: MiddlewareOptions): FetchHandler;
|
|
34
|
+
/**
|
|
35
|
+
* Creates a standalone token endpoint handler using the Fetch API.
|
|
36
|
+
*
|
|
37
|
+
* Unlike `createFetchMiddleware`, this does NOT wrap another handler.
|
|
38
|
+
* It only handles token generation requests and returns 404 for everything else.
|
|
39
|
+
*
|
|
40
|
+
* @param sigil - Initialized SigilInstance
|
|
41
|
+
* @param options - Middleware configuration options
|
|
42
|
+
* @returns FetchHandler for token endpoints only
|
|
43
|
+
*/
|
|
44
|
+
declare function createFetchTokenEndpoint(sigil: SigilInstance, options?: MiddlewareOptions): FetchHandler;
|
|
45
|
+
|
|
46
|
+
export { type FetchHandler, createFetchMiddleware, createFetchTokenEndpoint };
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { a as SigilInstance, c as MiddlewareOptions } from '../types-DySgT8rA.js';
|
|
2
|
+
import '@sigil-security/core';
|
|
3
|
+
import '@sigil-security/policy';
|
|
4
|
+
|
|
5
|
+
/** A handler that processes a Request and returns a Response */
|
|
6
|
+
type FetchHandler = (request: Request) => Promise<Response> | Response;
|
|
7
|
+
/**
|
|
8
|
+
* Creates a Fetch API middleware wrapper for Sigil CSRF protection.
|
|
9
|
+
*
|
|
10
|
+
* Wraps a request handler and intercepts requests for CSRF validation
|
|
11
|
+
* and token endpoint handling. Compatible with any platform using the
|
|
12
|
+
* standard Fetch API: Cloudflare Workers, Deno Deploy, Bun, etc.
|
|
13
|
+
*
|
|
14
|
+
* @param sigil - Initialized SigilInstance
|
|
15
|
+
* @param handler - The underlying request handler to protect
|
|
16
|
+
* @param options - Middleware configuration options
|
|
17
|
+
* @returns A new FetchHandler with Sigil protection
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* ```typescript
|
|
21
|
+
* import { createSigil } from '@sigil-security/runtime'
|
|
22
|
+
* import { createFetchMiddleware } from '@sigil-security/runtime/fetch'
|
|
23
|
+
*
|
|
24
|
+
* const sigil = await createSigil({ ... })
|
|
25
|
+
*
|
|
26
|
+
* const handler = (request: Request) => new Response('OK')
|
|
27
|
+
* const protectedHandler = createFetchMiddleware(sigil, handler)
|
|
28
|
+
*
|
|
29
|
+
* // Cloudflare Workers
|
|
30
|
+
* export default { fetch: protectedHandler }
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
declare function createFetchMiddleware(sigil: SigilInstance, handler: FetchHandler, options?: MiddlewareOptions): FetchHandler;
|
|
34
|
+
/**
|
|
35
|
+
* Creates a standalone token endpoint handler using the Fetch API.
|
|
36
|
+
*
|
|
37
|
+
* Unlike `createFetchMiddleware`, this does NOT wrap another handler.
|
|
38
|
+
* It only handles token generation requests and returns 404 for everything else.
|
|
39
|
+
*
|
|
40
|
+
* @param sigil - Initialized SigilInstance
|
|
41
|
+
* @param options - Middleware configuration options
|
|
42
|
+
* @returns FetchHandler for token endpoints only
|
|
43
|
+
*/
|
|
44
|
+
declare function createFetchTokenEndpoint(sigil: SigilInstance, options?: MiddlewareOptions): FetchHandler;
|
|
45
|
+
|
|
46
|
+
export { type FetchHandler, createFetchMiddleware, createFetchTokenEndpoint };
|