@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
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Erdem Arslan
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,307 @@
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/elysia.ts
21
+ var elysia_exports = {};
22
+ __export(elysia_exports, {
23
+ createElysiaPlugin: () => createElysiaPlugin
24
+ });
25
+ module.exports = __toCommonJS(elysia_exports);
26
+
27
+ // src/types.ts
28
+ var DEFAULT_TOKEN_ENDPOINT_PATH = "/api/csrf/token";
29
+ var DEFAULT_ONESHOT_ENDPOINT_PATH = "/api/csrf/one-shot";
30
+
31
+ // src/extract-metadata.ts
32
+ var import_policy = require("@sigil-security/policy");
33
+ function normalizePath(path) {
34
+ if (path.length === 0 || path === "/") return "/";
35
+ let end = path.length;
36
+ while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
37
+ if (end === path.length) return path;
38
+ if (end === 0) return "/";
39
+ return path.slice(0, end);
40
+ }
41
+ function normalizePathSet(paths) {
42
+ return new Set(paths.map(normalizePath));
43
+ }
44
+ function extractRequestMetadata(method, getHeader, tokenSource) {
45
+ return {
46
+ method: method.toUpperCase(),
47
+ origin: getHeader("origin"),
48
+ referer: getHeader("referer"),
49
+ secFetchSite: getHeader("sec-fetch-site"),
50
+ secFetchMode: getHeader("sec-fetch-mode"),
51
+ secFetchDest: getHeader("sec-fetch-dest"),
52
+ contentType: parseContentType(getHeader("content-type")),
53
+ tokenSource,
54
+ clientType: getHeader("x-client-type") ?? void 0
55
+ };
56
+ }
57
+ function parseContentType(contentType) {
58
+ if (contentType === null) return null;
59
+ const semicolonIdx = contentType.indexOf(";");
60
+ const mimeType = semicolonIdx >= 0 ? contentType.substring(0, semicolonIdx) : contentType;
61
+ return mimeType.trim().toLowerCase();
62
+ }
63
+ function extractTokenFromHeader(getHeader, headerName = import_policy.DEFAULT_HEADER_NAME) {
64
+ const value = getHeader(headerName);
65
+ if (value !== null && value !== "") {
66
+ return { from: "header", value };
67
+ }
68
+ return { from: "none" };
69
+ }
70
+ function extractTokenFromJsonBody(body, fieldName = import_policy.DEFAULT_JSON_FIELD_NAME) {
71
+ if (body !== null && body !== void 0 && typeof body === "object") {
72
+ const value = body[fieldName];
73
+ if (typeof value === "string" && value !== "") {
74
+ return { from: "body-json", value };
75
+ }
76
+ }
77
+ return null;
78
+ }
79
+ function extractTokenFromFormBody(body, fieldName = import_policy.DEFAULT_FORM_FIELD_NAME) {
80
+ if (body !== null && body !== void 0 && typeof body === "object") {
81
+ const value = body[fieldName];
82
+ if (typeof value === "string" && value !== "") {
83
+ return { from: "body-form", value };
84
+ }
85
+ }
86
+ return null;
87
+ }
88
+ function resolveTokenSource(getHeader, body, contentType, headerName, jsonFieldName, formFieldName) {
89
+ const headerToken = extractTokenFromHeader(getHeader, headerName);
90
+ if (headerToken.from !== "none") return headerToken;
91
+ if (contentType !== null && contentType.includes("application/json")) {
92
+ const jsonToken = extractTokenFromJsonBody(body, jsonFieldName);
93
+ if (jsonToken !== null) return jsonToken;
94
+ }
95
+ if (contentType !== null && (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data"))) {
96
+ const formToken = extractTokenFromFormBody(body, formFieldName);
97
+ if (formToken !== null) return formToken;
98
+ }
99
+ return { from: "none" };
100
+ }
101
+
102
+ // src/error-response.ts
103
+ var CSRF_FAILURE_MESSAGE = "CSRF validation failed";
104
+ var EXPIRED_HEADER_NAME = "X-CSRF-Token-Expired";
105
+ function createErrorResponse(expired) {
106
+ const headers = {};
107
+ if (expired) {
108
+ headers[EXPIRED_HEADER_NAME] = "true";
109
+ }
110
+ return {
111
+ status: 403,
112
+ body: { error: CSRF_FAILURE_MESSAGE },
113
+ headers
114
+ };
115
+ }
116
+ function createTokenResponse(token, expiresAt) {
117
+ return {
118
+ status: 200,
119
+ body: { token, expiresAt }
120
+ };
121
+ }
122
+ function createOneShotTokenResponse(token, expiresAt, action) {
123
+ return {
124
+ status: 200,
125
+ body: { token, expiresAt, action }
126
+ };
127
+ }
128
+
129
+ // src/token-endpoint.ts
130
+ async function handleTokenEndpoint(sigil, method, path, body, tokenEndpointPath, oneShotEndpointPath, csrfTokenValue) {
131
+ const upperMethod = method.toUpperCase();
132
+ if (path === tokenEndpointPath && upperMethod === "GET") {
133
+ return handleRegularTokenGeneration(sigil);
134
+ }
135
+ if (sigil.config.oneShotEnabled && path === oneShotEndpointPath && upperMethod === "POST") {
136
+ if (csrfTokenValue === void 0 || csrfTokenValue === null || csrfTokenValue === "") {
137
+ const errorResponse = createErrorResponse(false);
138
+ return {
139
+ handled: true,
140
+ status: errorResponse.status,
141
+ body: errorResponse.body,
142
+ headers: errorResponse.headers
143
+ };
144
+ }
145
+ const csrfResult = await sigil.validateToken(csrfTokenValue);
146
+ if (!csrfResult.valid) {
147
+ const errorResponse = createErrorResponse(false);
148
+ return {
149
+ handled: true,
150
+ status: errorResponse.status,
151
+ body: errorResponse.body,
152
+ headers: errorResponse.headers
153
+ };
154
+ }
155
+ return handleOneShotTokenGeneration(sigil, body);
156
+ }
157
+ return null;
158
+ }
159
+ async function handleRegularTokenGeneration(sigil) {
160
+ const result = await sigil.generateToken();
161
+ if (!result.success) {
162
+ return {
163
+ handled: true,
164
+ status: 500,
165
+ body: { error: "Token generation failed" },
166
+ headers: {}
167
+ };
168
+ }
169
+ const response = createTokenResponse(result.token, result.expiresAt);
170
+ return {
171
+ handled: true,
172
+ status: response.status,
173
+ body: response.body,
174
+ headers: {}
175
+ };
176
+ }
177
+ async function handleOneShotTokenGeneration(sigil, body) {
178
+ if (body === null || body === void 0 || typeof body !== "object") {
179
+ return {
180
+ handled: true,
181
+ status: 400,
182
+ body: { error: "Request body required" },
183
+ headers: {}
184
+ };
185
+ }
186
+ const action = body["action"];
187
+ if (typeof action !== "string" || action === "") {
188
+ return {
189
+ handled: true,
190
+ status: 400,
191
+ body: { error: "Missing or invalid action parameter" },
192
+ headers: {}
193
+ };
194
+ }
195
+ let context;
196
+ const rawContext = body["context"];
197
+ if (Array.isArray(rawContext)) {
198
+ const isAllStrings = rawContext.every((item) => typeof item === "string");
199
+ if (isAllStrings) {
200
+ context = rawContext;
201
+ }
202
+ }
203
+ const result = await sigil.generateOneShotToken(action, context);
204
+ if (!result.success) {
205
+ return {
206
+ handled: true,
207
+ status: 500,
208
+ body: { error: "One-shot token generation failed" },
209
+ headers: {}
210
+ };
211
+ }
212
+ const response = createOneShotTokenResponse(result.token, result.expiresAt, action);
213
+ return {
214
+ handled: true,
215
+ status: response.status,
216
+ body: response.body,
217
+ headers: {}
218
+ };
219
+ }
220
+
221
+ // src/adapters/elysia.ts
222
+ function createElysiaHeaderGetter(request) {
223
+ return (name) => {
224
+ return request.headers.get(name.toLowerCase());
225
+ };
226
+ }
227
+ function createElysiaPlugin(sigil, options) {
228
+ const excludePaths = normalizePathSet(options?.excludePaths ?? []);
229
+ const tokenEndpointPath = normalizePath(options?.tokenEndpointPath ?? DEFAULT_TOKEN_ENDPOINT_PATH);
230
+ const oneShotEndpointPath = normalizePath(options?.oneShotEndpointPath ?? DEFAULT_ONESHOT_ENDPOINT_PATH);
231
+ return (app) => {
232
+ app.get(tokenEndpointPath, async (context) => {
233
+ const result = await handleTokenEndpoint(
234
+ sigil,
235
+ "GET",
236
+ tokenEndpointPath,
237
+ void 0,
238
+ tokenEndpointPath,
239
+ oneShotEndpointPath
240
+ );
241
+ if (result !== null) {
242
+ context.set.status = result.status;
243
+ Object.assign(context.set.headers, result.headers);
244
+ return result.body;
245
+ }
246
+ context.set.status = 404;
247
+ return { error: "Not found" };
248
+ });
249
+ if (sigil.config.oneShotEnabled) {
250
+ app.post(oneShotEndpointPath, async (context) => {
251
+ const body = typeof context.body === "object" && context.body !== null ? context.body : void 0;
252
+ const getHeader = createElysiaHeaderGetter(context.request);
253
+ const csrfTokenValue = getHeader(sigil.config.headerName);
254
+ const result = await handleTokenEndpoint(
255
+ sigil,
256
+ "POST",
257
+ oneShotEndpointPath,
258
+ body,
259
+ tokenEndpointPath,
260
+ oneShotEndpointPath,
261
+ csrfTokenValue
262
+ );
263
+ if (result !== null) {
264
+ context.set.status = result.status;
265
+ Object.assign(context.set.headers, result.headers);
266
+ return result.body;
267
+ }
268
+ context.set.status = 404;
269
+ return { error: "Not found" };
270
+ });
271
+ }
272
+ app.onBeforeHandle(async (context) => {
273
+ const path = normalizePath(context.path);
274
+ if (excludePaths.has(path)) return void 0;
275
+ if (path === tokenEndpointPath) return void 0;
276
+ if (sigil.config.oneShotEnabled && path === oneShotEndpointPath) return void 0;
277
+ const getHeader = createElysiaHeaderGetter(context.request);
278
+ const contentType = parseContentType(getHeader("content-type"));
279
+ const body = typeof context.body === "object" && context.body !== null ? context.body : void 0;
280
+ const tokenSource = resolveTokenSource(
281
+ getHeader,
282
+ body,
283
+ contentType,
284
+ sigil.config.headerName
285
+ );
286
+ const metadata = extractRequestMetadata(
287
+ context.request.method,
288
+ getHeader,
289
+ tokenSource
290
+ );
291
+ const result = await sigil.protect(metadata);
292
+ if (!result.allowed) {
293
+ const errorResponse = createErrorResponse(result.expired);
294
+ context.set.status = errorResponse.status;
295
+ Object.assign(context.set.headers, errorResponse.headers);
296
+ return errorResponse.body;
297
+ }
298
+ return void 0;
299
+ });
300
+ return app;
301
+ };
302
+ }
303
+ // Annotate the CommonJS export names for ESM import in node:
304
+ 0 && (module.exports = {
305
+ createElysiaPlugin
306
+ });
307
+ //# sourceMappingURL=elysia.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/adapters/elysia.ts","../../src/types.ts","../../src/extract-metadata.ts","../../src/error-response.ts","../../src/token-endpoint.ts"],"sourcesContent":["// @sigil-security/runtime — Elysia plugin adapter (Bun)\n// Reference: SPECIFICATION.md §3\n\nimport type { SigilInstance, MiddlewareOptions, ProtectResult } from '../types.js'\nimport { DEFAULT_TOKEN_ENDPOINT_PATH, DEFAULT_ONESHOT_ENDPOINT_PATH } from '../types.js'\nimport { extractRequestMetadata, resolveTokenSource, parseContentType, normalizePath, normalizePathSet } from '../extract-metadata.js'\nimport type { HeaderGetter } from '../extract-metadata.js'\nimport { createErrorResponse } from '../error-response.js'\nimport { handleTokenEndpoint } from '../token-endpoint.js'\n\n// ============================================================\n// Minimal Elysia-Compatible Types\n// ============================================================\n\n/** Minimal Elysia-compatible context */\nexport interface ElysiaLikeContext {\n readonly request: Request\n readonly path: string\n body?: unknown\n set: {\n status?: number | undefined\n headers: Record<string, string>\n }\n}\n\n/** Elysia plugin builder (minimal, chainable) */\nexport interface ElysiaLikeApp {\n onBeforeHandle(\n handler: (context: ElysiaLikeContext) => Promise<unknown>,\n ): ElysiaLikeApp\n get(\n path: string,\n handler: (context: ElysiaLikeContext) => Promise<unknown>,\n ): ElysiaLikeApp\n post(\n path: string,\n handler: (context: ElysiaLikeContext) => Promise<unknown>,\n ): ElysiaLikeApp\n}\n\n// ============================================================\n// Header Getter for Elysia\n// ============================================================\n\nfunction createElysiaHeaderGetter(request: Request): HeaderGetter {\n return (name: string): string | null => {\n return request.headers.get(name.toLowerCase())\n }\n}\n\n// ============================================================\n// Elysia Plugin Factory\n// ============================================================\n\n/**\n * Creates an Elysia plugin for Sigil CSRF protection (Bun).\n *\n * @param sigil - Initialized SigilInstance\n * @param options - Middleware configuration options\n * @returns Function that accepts an Elysia instance and configures it\n *\n * @example\n * ```typescript\n * import { Elysia } from 'elysia'\n * import { createSigil } from '@sigil-security/runtime'\n * import { createElysiaPlugin } from '@sigil-security/runtime/elysia'\n *\n * const sigil = await createSigil({ ... })\n * const app = new Elysia()\n * .use(createElysiaPlugin(sigil))\n * ```\n */\nexport function createElysiaPlugin(\n sigil: SigilInstance,\n options?: MiddlewareOptions,\n): (app: ElysiaLikeApp) => ElysiaLikeApp {\n const excludePaths = normalizePathSet(options?.excludePaths ?? [])\n const tokenEndpointPath = normalizePath(options?.tokenEndpointPath ?? DEFAULT_TOKEN_ENDPOINT_PATH)\n const oneShotEndpointPath = normalizePath(options?.oneShotEndpointPath ?? DEFAULT_ONESHOT_ENDPOINT_PATH)\n\n return (app) => {\n // Register token generation routes\n app.get(tokenEndpointPath, async (context) => {\n const result = await handleTokenEndpoint(\n sigil,\n 'GET',\n tokenEndpointPath,\n undefined,\n tokenEndpointPath,\n oneShotEndpointPath,\n )\n\n if (result !== null) {\n context.set.status = result.status\n Object.assign(context.set.headers, result.headers)\n return result.body\n }\n\n // Should never reach here — route matches token endpoint path\n context.set.status = 404\n return { error: 'Not found' }\n })\n\n if (sigil.config.oneShotEnabled) {\n app.post(oneShotEndpointPath, async (context) => {\n const body = typeof context.body === 'object' && context.body !== null\n ? (context.body as Record<string, unknown>)\n : undefined\n\n const getHeader = createElysiaHeaderGetter(context.request)\n const csrfTokenValue = getHeader(sigil.config.headerName)\n\n const result = await handleTokenEndpoint(\n sigil,\n 'POST',\n oneShotEndpointPath,\n body,\n tokenEndpointPath,\n oneShotEndpointPath,\n csrfTokenValue,\n )\n\n if (result !== null) {\n context.set.status = result.status\n Object.assign(context.set.headers, result.headers)\n return result.body\n }\n\n // Should never reach here — route matches one-shot endpoint path\n context.set.status = 404\n return { error: 'Not found' }\n })\n }\n\n // Register beforeHandle hook for CSRF validation\n app.onBeforeHandle(async (context) => {\n const path = normalizePath(context.path)\n\n // Skip excluded paths (normalized comparison)\n if (excludePaths.has(path)) return undefined\n\n // Skip token endpoints (handled by routes above)\n if (path === tokenEndpointPath) return undefined\n if (sigil.config.oneShotEnabled && path === oneShotEndpointPath) return undefined\n\n // Extract metadata\n const getHeader = createElysiaHeaderGetter(context.request)\n const contentType = parseContentType(getHeader('content-type'))\n\n const body = typeof context.body === 'object' && context.body !== null\n ? (context.body as Record<string, unknown>)\n : undefined\n\n const tokenSource = resolveTokenSource(\n getHeader,\n body,\n contentType,\n sigil.config.headerName,\n )\n\n const metadata = extractRequestMetadata(\n context.request.method,\n getHeader,\n tokenSource,\n )\n\n // Run protection\n const result: ProtectResult = await sigil.protect(metadata)\n\n if (!result.allowed) {\n const errorResponse = createErrorResponse(result.expired)\n context.set.status = errorResponse.status\n Object.assign(context.set.headers, errorResponse.headers)\n return errorResponse.body\n }\n\n // Allowed — continue to handler\n return undefined\n })\n\n return app\n }\n}\n","// @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":";;;;;;;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BAAmB,QAAO;AACvC,UAAI,MAAM,OAAO,kBAAkB,SAAS,oBAAqB,QAAO;AAGxE,YAAM,YAAY,yBAAyB,QAAQ,OAAO;AAC1D,YAAM,cAAc,iBAAiB,UAAU,cAAc,CAAC;AAE9D,YAAM,OAAO,OAAO,QAAQ,SAAS,YAAY,QAAQ,SAAS,OAC7D,QAAQ,OACT;AAEJ,YAAM,cAAc;AAAA,QAClB;AAAA,QACA;AAAA,QACA;AAAA,QACA,MAAM,OAAO;AAAA,MACf;AAEA,YAAM,WAAW;AAAA,QACf,QAAQ,QAAQ;AAAA,QAChB;AAAA,QACA;AAAA,MACF;AAGA,YAAM,SAAwB,MAAM,MAAM,QAAQ,QAAQ;AAE1D,UAAI,CAAC,OAAO,SAAS;AACnB,cAAM,gBAAgB,oBAAoB,OAAO,OAAO;AACxD,gBAAQ,IAAI,SAAS,cAAc;AACnC,eAAO,OAAO,QAAQ,IAAI,SAAS,cAAc,OAAO;AACxD,eAAO,cAAc;AAAA,MACvB;AAGA,aAAO;AAAA,IACT,CAAC;AAED,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -0,0 +1,41 @@
1
+ import { a as SigilInstance, c as MiddlewareOptions } from '../types-DySgT8rA.cjs';
2
+ import '@sigil-security/core';
3
+ import '@sigil-security/policy';
4
+
5
+ /** Minimal Elysia-compatible context */
6
+ interface ElysiaLikeContext {
7
+ readonly request: Request;
8
+ readonly path: string;
9
+ body?: unknown;
10
+ set: {
11
+ status?: number | undefined;
12
+ headers: Record<string, string>;
13
+ };
14
+ }
15
+ /** Elysia plugin builder (minimal, chainable) */
16
+ interface ElysiaLikeApp {
17
+ onBeforeHandle(handler: (context: ElysiaLikeContext) => Promise<unknown>): ElysiaLikeApp;
18
+ get(path: string, handler: (context: ElysiaLikeContext) => Promise<unknown>): ElysiaLikeApp;
19
+ post(path: string, handler: (context: ElysiaLikeContext) => Promise<unknown>): ElysiaLikeApp;
20
+ }
21
+ /**
22
+ * Creates an Elysia plugin for Sigil CSRF protection (Bun).
23
+ *
24
+ * @param sigil - Initialized SigilInstance
25
+ * @param options - Middleware configuration options
26
+ * @returns Function that accepts an Elysia instance and configures it
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * import { Elysia } from 'elysia'
31
+ * import { createSigil } from '@sigil-security/runtime'
32
+ * import { createElysiaPlugin } from '@sigil-security/runtime/elysia'
33
+ *
34
+ * const sigil = await createSigil({ ... })
35
+ * const app = new Elysia()
36
+ * .use(createElysiaPlugin(sigil))
37
+ * ```
38
+ */
39
+ declare function createElysiaPlugin(sigil: SigilInstance, options?: MiddlewareOptions): (app: ElysiaLikeApp) => ElysiaLikeApp;
40
+
41
+ export { type ElysiaLikeApp, type ElysiaLikeContext, createElysiaPlugin };