@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.
Files changed (48) hide show
  1. package/LICENSE +201 -0
  2. package/dist/adapters/elysia.cjs +307 -0
  3. package/dist/adapters/elysia.cjs.map +1 -0
  4. package/dist/adapters/elysia.d.cts +41 -0
  5. package/dist/adapters/elysia.d.ts +41 -0
  6. package/dist/adapters/elysia.js +98 -0
  7. package/dist/adapters/elysia.js.map +1 -0
  8. package/dist/adapters/express.cjs +286 -0
  9. package/dist/adapters/express.cjs.map +1 -0
  10. package/dist/adapters/express.d.cts +59 -0
  11. package/dist/adapters/express.d.ts +59 -0
  12. package/dist/adapters/express.js +77 -0
  13. package/dist/adapters/express.js.map +1 -0
  14. package/dist/adapters/fastify.cjs +308 -0
  15. package/dist/adapters/fastify.cjs.map +1 -0
  16. package/dist/adapters/fastify.d.cts +54 -0
  17. package/dist/adapters/fastify.d.ts +54 -0
  18. package/dist/adapters/fastify.js +99 -0
  19. package/dist/adapters/fastify.js.map +1 -0
  20. package/dist/adapters/fetch.cjs +359 -0
  21. package/dist/adapters/fetch.cjs.map +1 -0
  22. package/dist/adapters/fetch.d.cts +46 -0
  23. package/dist/adapters/fetch.d.ts +46 -0
  24. package/dist/adapters/fetch.js +149 -0
  25. package/dist/adapters/fetch.js.map +1 -0
  26. package/dist/adapters/hono.cjs +300 -0
  27. package/dist/adapters/hono.cjs.map +1 -0
  28. package/dist/adapters/hono.d.cts +41 -0
  29. package/dist/adapters/hono.d.ts +41 -0
  30. package/dist/adapters/hono.js +91 -0
  31. package/dist/adapters/hono.js.map +1 -0
  32. package/dist/adapters/oak.cjs +318 -0
  33. package/dist/adapters/oak.cjs.map +1 -0
  34. package/dist/adapters/oak.d.cts +48 -0
  35. package/dist/adapters/oak.d.ts +48 -0
  36. package/dist/adapters/oak.js +109 -0
  37. package/dist/adapters/oak.js.map +1 -0
  38. package/dist/chunk-JPT5I5W5.js +225 -0
  39. package/dist/chunk-JPT5I5W5.js.map +1 -0
  40. package/dist/index.cjs +486 -0
  41. package/dist/index.cjs.map +1 -0
  42. package/dist/index.d.cts +201 -0
  43. package/dist/index.d.ts +201 -0
  44. package/dist/index.js +284 -0
  45. package/dist/index.js.map +1 -0
  46. package/dist/types-DySgT8rA.d.cts +184 -0
  47. package/dist/types-DySgT8rA.d.ts +184 -0
  48. package/package.json +141 -0
@@ -0,0 +1,109 @@
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/oak.ts
14
+ function createOakHeaderGetter(headers) {
15
+ return (name) => {
16
+ return headers.get(name.toLowerCase());
17
+ };
18
+ }
19
+ function createOakMiddleware(sigil, options) {
20
+ const excludePaths = normalizePathSet(options?.excludePaths ?? []);
21
+ const tokenEndpointPath = normalizePath(options?.tokenEndpointPath ?? DEFAULT_TOKEN_ENDPOINT_PATH);
22
+ const oneShotEndpointPath = normalizePath(options?.oneShotEndpointPath ?? DEFAULT_ONESHOT_ENDPOINT_PATH);
23
+ return async (ctx, next) => {
24
+ const path = normalizePath(ctx.request.url.pathname);
25
+ if (excludePaths.has(path)) {
26
+ await next();
27
+ return;
28
+ }
29
+ let body;
30
+ const method = ctx.request.method.toUpperCase();
31
+ if (method === "POST" && path === oneShotEndpointPath) {
32
+ try {
33
+ const bodyReader = ctx.request.body();
34
+ if (bodyReader.type === "json") {
35
+ const value = await bodyReader.value;
36
+ if (typeof value === "object" && value !== null) {
37
+ body = value;
38
+ }
39
+ }
40
+ } catch {
41
+ }
42
+ }
43
+ const getHeaderForToken = createOakHeaderGetter(ctx.request.headers);
44
+ const csrfTokenValue = getHeaderForToken(sigil.config.headerName);
45
+ const tokenResult = await handleTokenEndpoint(
46
+ sigil,
47
+ method,
48
+ path,
49
+ body,
50
+ tokenEndpointPath,
51
+ oneShotEndpointPath,
52
+ csrfTokenValue
53
+ );
54
+ if (tokenResult !== null) {
55
+ ctx.response.status = tokenResult.status;
56
+ ctx.response.body = tokenResult.body;
57
+ for (const [key, value] of Object.entries(tokenResult.headers)) {
58
+ ctx.response.headers.set(key, value);
59
+ }
60
+ return;
61
+ }
62
+ const getHeader = createOakHeaderGetter(ctx.request.headers);
63
+ const contentType = parseContentType(getHeader("content-type"));
64
+ let protectionBody;
65
+ if (method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && body === void 0) {
66
+ try {
67
+ const bodyReader = ctx.request.body();
68
+ if (bodyReader.type === "json") {
69
+ const value = await bodyReader.value;
70
+ if (typeof value === "object" && value !== null) {
71
+ protectionBody = value;
72
+ }
73
+ } else if (bodyReader.type === "form") {
74
+ const formData = await bodyReader.value;
75
+ const formObj = {};
76
+ formData.forEach((val, key) => {
77
+ formObj[key] = val;
78
+ });
79
+ protectionBody = formObj;
80
+ }
81
+ } catch {
82
+ }
83
+ } else {
84
+ protectionBody = body;
85
+ }
86
+ const tokenSource = resolveTokenSource(
87
+ getHeader,
88
+ protectionBody,
89
+ contentType,
90
+ sigil.config.headerName
91
+ );
92
+ const metadata = extractRequestMetadata(method, getHeader, tokenSource);
93
+ const result = await sigil.protect(metadata);
94
+ if (!result.allowed) {
95
+ const errorResponse = createErrorResponse(result.expired);
96
+ ctx.response.status = errorResponse.status;
97
+ ctx.response.body = errorResponse.body;
98
+ for (const [key, value] of Object.entries(errorResponse.headers)) {
99
+ ctx.response.headers.set(key, value);
100
+ }
101
+ return;
102
+ }
103
+ await next();
104
+ };
105
+ }
106
+ export {
107
+ createOakMiddleware
108
+ };
109
+ //# sourceMappingURL=oak.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/adapters/oak.ts"],"sourcesContent":["// @sigil-security/runtime — Oak middleware adapter (Deno)\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 Oak-Compatible Types\n// ============================================================\n\n/** Minimal Oak-compatible context */\nexport interface OakLikeContext {\n readonly request: {\n readonly method: string\n readonly url: URL\n readonly headers: Headers\n body: () => OakBody\n }\n response: {\n status: number\n body: unknown\n headers: Headers\n }\n}\n\n/** Oak body reader */\nexport interface OakBody {\n readonly type: string | undefined\n value: Promise<unknown>\n}\n\n/** Oak next function */\nexport type OakNext = () => Promise<unknown>\n\n/** Oak middleware signature */\nexport type OakMiddleware = (ctx: OakLikeContext, next: OakNext) => Promise<void>\n\n// ============================================================\n// Header Getter for Oak\n// ============================================================\n\nfunction createOakHeaderGetter(headers: Headers): HeaderGetter {\n return (name: string): string | null => {\n return headers.get(name.toLowerCase())\n }\n}\n\n// ============================================================\n// Oak Middleware Factory\n// ============================================================\n\n/**\n * Creates Oak middleware for Sigil CSRF protection (Deno).\n *\n * @param sigil - Initialized SigilInstance\n * @param options - Middleware configuration options\n * @returns Oak middleware function\n *\n * @example\n * ```typescript\n * import { Application } from '@oak/oak'\n * import { createSigil } from '@sigil-security/runtime'\n * import { createOakMiddleware } from '@sigil-security/runtime/oak'\n *\n * const sigil = await createSigil({ ... })\n * const app = new Application()\n * app.use(createOakMiddleware(sigil))\n * ```\n */\nexport function createOakMiddleware(\n sigil: SigilInstance,\n options?: MiddlewareOptions,\n): OakMiddleware {\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 (ctx, next) => {\n const path = normalizePath(ctx.request.url.pathname)\n\n // Skip excluded paths (normalized comparison)\n if (excludePaths.has(path)) {\n await next()\n return\n }\n\n // Step 1: Handle token endpoint requests\n let body: Record<string, unknown> | undefined\n const method = ctx.request.method.toUpperCase()\n\n if (method === 'POST' && path === oneShotEndpointPath) {\n try {\n const bodyReader = ctx.request.body()\n if (bodyReader.type === 'json') {\n const value = await bodyReader.value\n if (typeof value === 'object' && value !== null) {\n body = value as Record<string, unknown>\n }\n }\n } catch {\n // Body parsing failed\n }\n }\n\n const getHeaderForToken = createOakHeaderGetter(ctx.request.headers)\n const csrfTokenValue = getHeaderForToken(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 ctx.response.status = tokenResult.status\n ctx.response.body = tokenResult.body\n for (const [key, value] of Object.entries(tokenResult.headers)) {\n ctx.response.headers.set(key, value)\n }\n return\n }\n\n // Step 2: Extract metadata for protection\n const getHeader = createOakHeaderGetter(ctx.request.headers)\n const contentType = parseContentType(getHeader('content-type'))\n\n // Try to extract body for token resolution.\n // Supports both JSON and form-encoded bodies via Oak's body reader.\n let protectionBody: Record<string, unknown> | undefined\n if (method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && body === undefined) {\n try {\n const bodyReader = ctx.request.body()\n if (bodyReader.type === 'json') {\n const value = await bodyReader.value\n if (typeof value === 'object' && value !== null) {\n protectionBody = value as Record<string, unknown>\n }\n } else if (bodyReader.type === 'form') {\n const formData = await bodyReader.value as URLSearchParams\n const formObj: Record<string, unknown> = {}\n formData.forEach((val, key) => {\n formObj[key] = val\n })\n protectionBody = formObj\n }\n } catch {\n // Body not available or parsing failed — token might be in header\n }\n } else {\n protectionBody = body\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 ctx.response.status = errorResponse.status\n ctx.response.body = errorResponse.body\n for (const [key, value] of Object.entries(errorResponse.headers)) {\n ctx.response.headers.set(key, value)\n }\n return\n }\n\n // Step 4: Request allowed — continue\n await next()\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA6CA,SAAS,sBAAsB,SAAgC;AAC7D,SAAO,CAAC,SAAgC;AACtC,WAAO,QAAQ,IAAI,KAAK,YAAY,CAAC;AAAA,EACvC;AACF;AAwBO,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,OAAO,KAAK,SAAS;AAC1B,UAAM,OAAO,cAAc,IAAI,QAAQ,IAAI,QAAQ;AAGnD,QAAI,aAAa,IAAI,IAAI,GAAG;AAC1B,YAAM,KAAK;AACX;AAAA,IACF;AAGA,QAAI;AACJ,UAAM,SAAS,IAAI,QAAQ,OAAO,YAAY;AAE9C,QAAI,WAAW,UAAU,SAAS,qBAAqB;AACrD,UAAI;AACF,cAAM,aAAa,IAAI,QAAQ,KAAK;AACpC,YAAI,WAAW,SAAS,QAAQ;AAC9B,gBAAM,QAAQ,MAAM,WAAW;AAC/B,cAAI,OAAO,UAAU,YAAY,UAAU,MAAM;AAC/C,mBAAO;AAAA,UACT;AAAA,QACF;AAAA,MACF,QAAQ;AAAA,MAER;AAAA,IACF;AAEA,UAAM,oBAAoB,sBAAsB,IAAI,QAAQ,OAAO;AACnE,UAAM,iBAAiB,kBAAkB,M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;AACxD,UAAI,SAAS,SAAS,cAAc;AACpC,UAAI,SAAS,OAAO,cAAc;AAClC,iBAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,cAAc,OAAO,GAAG;AAChE,YAAI,SAAS,QAAQ,IAAI,KAAK,KAAK;AAAA,MACrC;AACA;AAAA,IACF;AAGA,UAAM,KAAK;AAAA,EACb;AACF;","names":[]}
@@ -0,0 +1,225 @@
1
+ // src/types.ts
2
+ var DEFAULT_TOKEN_ENDPOINT_PATH = "/api/csrf/token";
3
+ var DEFAULT_ONESHOT_ENDPOINT_PATH = "/api/csrf/one-shot";
4
+
5
+ // src/error-response.ts
6
+ var CSRF_FAILURE_MESSAGE = "CSRF validation failed";
7
+ var EXPIRED_HEADER_NAME = "X-CSRF-Token-Expired";
8
+ function createErrorResponse(expired) {
9
+ const headers = {};
10
+ if (expired) {
11
+ headers[EXPIRED_HEADER_NAME] = "true";
12
+ }
13
+ return {
14
+ status: 403,
15
+ body: { error: CSRF_FAILURE_MESSAGE },
16
+ headers
17
+ };
18
+ }
19
+ function createTokenResponse(token, expiresAt) {
20
+ return {
21
+ status: 200,
22
+ body: { token, expiresAt }
23
+ };
24
+ }
25
+ function createOneShotTokenResponse(token, expiresAt, action) {
26
+ return {
27
+ status: 200,
28
+ body: { token, expiresAt, action }
29
+ };
30
+ }
31
+
32
+ // src/extract-metadata.ts
33
+ import {
34
+ DEFAULT_FORM_FIELD_NAME,
35
+ DEFAULT_HEADER_NAME,
36
+ DEFAULT_JSON_FIELD_NAME
37
+ } from "@sigil-security/policy";
38
+ function normalizePath(path) {
39
+ if (path.length === 0 || path === "/") return "/";
40
+ let end = path.length;
41
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
42
+ if (end === path.length) return path;
43
+ if (end === 0) return "/";
44
+ return path.slice(0, end);
45
+ }
46
+ function normalizePathSet(paths) {
47
+ return new Set(paths.map(normalizePath));
48
+ }
49
+ function extractRequestMetadata(method, getHeader, tokenSource) {
50
+ return {
51
+ method: method.toUpperCase(),
52
+ origin: getHeader("origin"),
53
+ referer: getHeader("referer"),
54
+ secFetchSite: getHeader("sec-fetch-site"),
55
+ secFetchMode: getHeader("sec-fetch-mode"),
56
+ secFetchDest: getHeader("sec-fetch-dest"),
57
+ contentType: parseContentType(getHeader("content-type")),
58
+ tokenSource,
59
+ clientType: getHeader("x-client-type") ?? void 0
60
+ };
61
+ }
62
+ function parseContentType(contentType) {
63
+ if (contentType === null) return null;
64
+ const semicolonIdx = contentType.indexOf(";");
65
+ const mimeType = semicolonIdx >= 0 ? contentType.substring(0, semicolonIdx) : contentType;
66
+ return mimeType.trim().toLowerCase();
67
+ }
68
+ function extractTokenFromHeader(getHeader, headerName = DEFAULT_HEADER_NAME) {
69
+ const value = getHeader(headerName);
70
+ if (value !== null && value !== "") {
71
+ return { from: "header", value };
72
+ }
73
+ return { from: "none" };
74
+ }
75
+ function extractTokenFromJsonBody(body, fieldName = DEFAULT_JSON_FIELD_NAME) {
76
+ if (body !== null && body !== void 0 && typeof body === "object") {
77
+ const value = body[fieldName];
78
+ if (typeof value === "string" && value !== "") {
79
+ return { from: "body-json", value };
80
+ }
81
+ }
82
+ return null;
83
+ }
84
+ function extractTokenFromFormBody(body, fieldName = DEFAULT_FORM_FIELD_NAME) {
85
+ if (body !== null && body !== void 0 && typeof body === "object") {
86
+ const value = body[fieldName];
87
+ if (typeof value === "string" && value !== "") {
88
+ return { from: "body-form", value };
89
+ }
90
+ }
91
+ return null;
92
+ }
93
+ function resolveTokenSource(getHeader, body, contentType, headerName, jsonFieldName, formFieldName) {
94
+ const headerToken = extractTokenFromHeader(getHeader, headerName);
95
+ if (headerToken.from !== "none") return headerToken;
96
+ if (contentType !== null && contentType.includes("application/json")) {
97
+ const jsonToken = extractTokenFromJsonBody(body, jsonFieldName);
98
+ if (jsonToken !== null) return jsonToken;
99
+ }
100
+ if (contentType !== null && (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data"))) {
101
+ const formToken = extractTokenFromFormBody(body, formFieldName);
102
+ if (formToken !== null) return formToken;
103
+ }
104
+ return { from: "none" };
105
+ }
106
+
107
+ // src/token-endpoint.ts
108
+ async function handleTokenEndpoint(sigil, method, path, body, tokenEndpointPath, oneShotEndpointPath, csrfTokenValue) {
109
+ const upperMethod = method.toUpperCase();
110
+ if (path === tokenEndpointPath && upperMethod === "GET") {
111
+ return handleRegularTokenGeneration(sigil);
112
+ }
113
+ if (sigil.config.oneShotEnabled && path === oneShotEndpointPath && upperMethod === "POST") {
114
+ if (csrfTokenValue === void 0 || csrfTokenValue === null || csrfTokenValue === "") {
115
+ const errorResponse = createErrorResponse(false);
116
+ return {
117
+ handled: true,
118
+ status: errorResponse.status,
119
+ body: errorResponse.body,
120
+ headers: errorResponse.headers
121
+ };
122
+ }
123
+ const csrfResult = await sigil.validateToken(csrfTokenValue);
124
+ if (!csrfResult.valid) {
125
+ const errorResponse = createErrorResponse(false);
126
+ return {
127
+ handled: true,
128
+ status: errorResponse.status,
129
+ body: errorResponse.body,
130
+ headers: errorResponse.headers
131
+ };
132
+ }
133
+ return handleOneShotTokenGeneration(sigil, body);
134
+ }
135
+ return null;
136
+ }
137
+ async function handleRegularTokenGeneration(sigil) {
138
+ const result = await sigil.generateToken();
139
+ if (!result.success) {
140
+ return {
141
+ handled: true,
142
+ status: 500,
143
+ body: { error: "Token generation failed" },
144
+ headers: {}
145
+ };
146
+ }
147
+ const response = createTokenResponse(result.token, result.expiresAt);
148
+ return {
149
+ handled: true,
150
+ status: response.status,
151
+ body: response.body,
152
+ headers: {}
153
+ };
154
+ }
155
+ async function handleOneShotTokenGeneration(sigil, body) {
156
+ if (body === null || body === void 0 || typeof body !== "object") {
157
+ return {
158
+ handled: true,
159
+ status: 400,
160
+ body: { error: "Request body required" },
161
+ headers: {}
162
+ };
163
+ }
164
+ const action = body["action"];
165
+ if (typeof action !== "string" || action === "") {
166
+ return {
167
+ handled: true,
168
+ status: 400,
169
+ body: { error: "Missing or invalid action parameter" },
170
+ headers: {}
171
+ };
172
+ }
173
+ let context;
174
+ const rawContext = body["context"];
175
+ if (Array.isArray(rawContext)) {
176
+ const isAllStrings = rawContext.every((item) => typeof item === "string");
177
+ if (isAllStrings) {
178
+ context = rawContext;
179
+ }
180
+ }
181
+ const result = await sigil.generateOneShotToken(action, context);
182
+ if (!result.success) {
183
+ return {
184
+ handled: true,
185
+ status: 500,
186
+ body: { error: "One-shot token generation failed" },
187
+ headers: {}
188
+ };
189
+ }
190
+ const response = createOneShotTokenResponse(result.token, result.expiresAt, action);
191
+ return {
192
+ handled: true,
193
+ status: response.status,
194
+ body: response.body,
195
+ headers: {}
196
+ };
197
+ }
198
+ function createTokenEndpointError(expired) {
199
+ const errorResponse = createErrorResponse(expired);
200
+ return {
201
+ handled: true,
202
+ status: errorResponse.status,
203
+ body: errorResponse.body,
204
+ headers: errorResponse.headers
205
+ };
206
+ }
207
+
208
+ export {
209
+ DEFAULT_TOKEN_ENDPOINT_PATH,
210
+ DEFAULT_ONESHOT_ENDPOINT_PATH,
211
+ createErrorResponse,
212
+ createTokenResponse,
213
+ createOneShotTokenResponse,
214
+ normalizePath,
215
+ normalizePathSet,
216
+ extractRequestMetadata,
217
+ parseContentType,
218
+ extractTokenFromHeader,
219
+ extractTokenFromJsonBody,
220
+ extractTokenFromFormBody,
221
+ resolveTokenSource,
222
+ handleTokenEndpoint,
223
+ createTokenEndpointError
224
+ };
225
+ //# sourceMappingURL=chunk-JPT5I5W5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts","../src/error-response.ts","../src/extract-metadata.ts","../src/token-endpoint.ts"],"sourcesContent":["// @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 — 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 — 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 — 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":";AAyRO,IAAM,8BAA8B;AAGpC,IAAM,gCAAgC;;;ACnR7C,IAAM,uBAAuB;AAG7B,IAAM,sBAAsB;AAuBrB,SAAS,oBAAoB,SAAiC;AACnE,QAAM,UAAkC,CAAC;AACzC,MAAI,SAAS;AACX,YAAQ,mBAAmB,IAAI;AAAA,EACjC;AACA,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,MAAM,EAAE,OAAO,qBAAqB;AAAA,IACpC;AAAA,EACF;AACF;AAQO,SAAS,oBACd,OACA,WACoG;AACpG,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,MAAM,EAAE,OAAO,UAAU;AAAA,EAC3B;AACF;AASO,SAAS,2BACd,OACA,WACA,QAIA;AACA,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,MAAM,EAAE,OAAO,WAAW,OAAO;AAAA,EACnC;AACF;;;AC9EA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;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,I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