@orchestraai/agent-tools 0.10.16 → 0.10.18

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 (183) hide show
  1. package/.agents/plugins/marketplace.json +1 -1
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.codex-plugin/plugin.json +1 -1
  5. package/.cursor-plugin/plugin.json +1 -1
  6. package/.devin/adapter.json +1 -1
  7. package/.hermes/adapter.json +1 -1
  8. package/.opencode/adapter.json +1 -1
  9. package/dist/commands/claude-setup.d.ts +1 -1
  10. package/dist/runtime/conversation/command-guard.js +1347 -63
  11. package/dist/runtime/conversation/command-guard.js.map +1 -1
  12. package/dist/runtime/conversation/shell-parse.d.ts +44 -0
  13. package/dist/runtime/conversation/shell-parse.js +525 -0
  14. package/dist/runtime/conversation/shell-parse.js.map +1 -0
  15. package/docs/security.md +18 -2
  16. package/node_modules/@hono/node-server/dist/index.cjs +63 -17
  17. package/node_modules/@hono/node-server/dist/index.mjs +63 -17
  18. package/node_modules/@hono/node-server/dist/serve-static.cjs +1 -1
  19. package/node_modules/@hono/node-server/dist/serve-static.mjs +1 -1
  20. package/node_modules/@hono/node-server/package.json +1 -1
  21. package/node_modules/cross-spawn/README.md +19 -3
  22. package/node_modules/cross-spawn/lib/parse.js +38 -10
  23. package/node_modules/cross-spawn/lib/util/escape.js +84 -25
  24. package/node_modules/cross-spawn/lib/util/readShebang.js +8 -2
  25. package/node_modules/cross-spawn/lib/util/resolveCommand.js +8 -1
  26. package/node_modules/cross-spawn/package.json +21 -24
  27. package/node_modules/hono/README.md +2 -3
  28. package/node_modules/hono/dist/adapter/aws-lambda/handler.js +2 -2
  29. package/node_modules/hono/dist/adapter/bun/websocket.js +19 -4
  30. package/node_modules/hono/dist/adapter/lambda-edge/handler.js +5 -1
  31. package/node_modules/hono/dist/cjs/adapter/aws-lambda/handler.js +2 -2
  32. package/node_modules/hono/dist/cjs/adapter/bun/websocket.js +19 -4
  33. package/node_modules/hono/dist/cjs/adapter/lambda-edge/handler.js +5 -1
  34. package/node_modules/hono/dist/cjs/client/fetch-result-please.js +1 -1
  35. package/node_modules/hono/dist/cjs/client/utils.js +9 -5
  36. package/node_modules/hono/dist/cjs/context.js +1 -1
  37. package/node_modules/hono/dist/cjs/helper/accepts/accepts.js +7 -1
  38. package/node_modules/hono/dist/cjs/helper/css/common.js +11 -8
  39. package/node_modules/hono/dist/cjs/helper/css/index.js +1 -1
  40. package/node_modules/hono/dist/cjs/helper/proxy/index.js +2 -0
  41. package/node_modules/hono/dist/cjs/helper/route/index.js +3 -1
  42. package/node_modules/hono/dist/cjs/helper/ssg/ssg.js +5 -3
  43. package/node_modules/hono/dist/cjs/helper/streaming/sse.js +6 -2
  44. package/node_modules/hono/dist/cjs/hono-base.js +9 -10
  45. package/node_modules/hono/dist/cjs/hono.js +0 -1
  46. package/node_modules/hono/dist/cjs/jsx/base.js +51 -32
  47. package/node_modules/hono/dist/cjs/jsx/components.js +2 -2
  48. package/node_modules/hono/dist/cjs/jsx/constants.js +2 -0
  49. package/node_modules/hono/dist/cjs/jsx/context.js +15 -2
  50. package/node_modules/hono/dist/cjs/jsx/dom/components.js +1 -1
  51. package/node_modules/hono/dist/cjs/jsx/dom/hooks/index.js +38 -8
  52. package/node_modules/hono/dist/cjs/jsx/dom/intrinsic-element/components.js +8 -5
  53. package/node_modules/hono/dist/cjs/jsx/dom/render.js +9 -3
  54. package/node_modules/hono/dist/cjs/jsx/jsx-runtime.js +13 -17
  55. package/node_modules/hono/dist/cjs/middleware/basic-auth/index.js +3 -1
  56. package/node_modules/hono/dist/cjs/middleware/bearer-auth/index.js +9 -1
  57. package/node_modules/hono/dist/cjs/middleware/body-limit/index.js +9 -10
  58. package/node_modules/hono/dist/cjs/middleware/combine/index.js +4 -0
  59. package/node_modules/hono/dist/cjs/middleware/compress/index.js +2 -3
  60. package/node_modules/hono/dist/cjs/middleware/csrf/index.js +2 -2
  61. package/node_modules/hono/dist/cjs/middleware/etag/index.js +3 -1
  62. package/node_modules/hono/dist/cjs/middleware/jwk/jwk.js +2 -2
  63. package/node_modules/hono/dist/cjs/middleware/jwt/jwt.js +2 -2
  64. package/node_modules/hono/dist/cjs/middleware/method-not-allowed/index.js +1 -1
  65. package/node_modules/hono/dist/cjs/middleware/method-override/index.js +35 -12
  66. package/node_modules/hono/dist/cjs/middleware/mount/index.js +5 -4
  67. package/node_modules/hono/dist/cjs/middleware/pretty-json/index.js +1 -0
  68. package/node_modules/hono/dist/cjs/middleware/request-id/request-id.js +3 -3
  69. package/node_modules/hono/dist/cjs/middleware/secure-headers/secure-headers.js +6 -3
  70. package/node_modules/hono/dist/cjs/middleware/serve-static/index.js +4 -2
  71. package/node_modules/hono/dist/cjs/middleware/timing/timing.js +4 -3
  72. package/node_modules/hono/dist/cjs/router/reg-exp-router/node.js +13 -11
  73. package/node_modules/hono/dist/cjs/router/reg-exp-router/prepared-router.js +4 -4
  74. package/node_modules/hono/dist/cjs/router/reg-exp-router/router.js +39 -51
  75. package/node_modules/hono/dist/cjs/router/reg-exp-router/trie.js +15 -5
  76. package/node_modules/hono/dist/cjs/router/trie-router/node.js +6 -4
  77. package/node_modules/hono/dist/cjs/utils/body.js +2 -1
  78. package/node_modules/hono/dist/cjs/utils/cookie.js +3 -3
  79. package/node_modules/hono/dist/cjs/utils/html.js +5 -0
  80. package/node_modules/hono/dist/cjs/utils/jwt/jwt.js +8 -5
  81. package/node_modules/hono/dist/cjs/utils/mime.js +3 -2
  82. package/node_modules/hono/dist/cjs/utils/mount.js +59 -0
  83. package/node_modules/hono/dist/cjs/utils/url.js +23 -11
  84. package/node_modules/hono/dist/cjs/validator/validator.js +5 -5
  85. package/node_modules/hono/dist/client/fetch-result-please.js +1 -1
  86. package/node_modules/hono/dist/client/utils.js +9 -5
  87. package/node_modules/hono/dist/context.js +1 -1
  88. package/node_modules/hono/dist/helper/accepts/accepts.js +7 -1
  89. package/node_modules/hono/dist/helper/css/common.js +11 -8
  90. package/node_modules/hono/dist/helper/css/index.js +1 -1
  91. package/node_modules/hono/dist/helper/proxy/index.js +2 -0
  92. package/node_modules/hono/dist/helper/route/index.js +3 -1
  93. package/node_modules/hono/dist/helper/ssg/ssg.js +5 -3
  94. package/node_modules/hono/dist/helper/streaming/sse.js +6 -2
  95. package/node_modules/hono/dist/hono-base.js +9 -10
  96. package/node_modules/hono/dist/hono.js +0 -1
  97. package/node_modules/hono/dist/jsx/base.js +51 -34
  98. package/node_modules/hono/dist/jsx/components.js +2 -2
  99. package/node_modules/hono/dist/jsx/constants.js +2 -1
  100. package/node_modules/hono/dist/jsx/context.js +15 -2
  101. package/node_modules/hono/dist/jsx/dom/components.js +2 -2
  102. package/node_modules/hono/dist/jsx/dom/hooks/index.js +39 -9
  103. package/node_modules/hono/dist/jsx/dom/intrinsic-element/components.js +8 -5
  104. package/node_modules/hono/dist/jsx/dom/render.js +9 -3
  105. package/node_modules/hono/dist/jsx/jsx-runtime.js +15 -19
  106. package/node_modules/hono/dist/middleware/basic-auth/index.js +3 -1
  107. package/node_modules/hono/dist/middleware/bearer-auth/index.js +9 -1
  108. package/node_modules/hono/dist/middleware/body-limit/index.js +9 -10
  109. package/node_modules/hono/dist/middleware/combine/index.js +4 -0
  110. package/node_modules/hono/dist/middleware/compress/index.js +2 -3
  111. package/node_modules/hono/dist/middleware/csrf/index.js +2 -2
  112. package/node_modules/hono/dist/middleware/etag/index.js +3 -1
  113. package/node_modules/hono/dist/middleware/jwk/jwk.js +2 -2
  114. package/node_modules/hono/dist/middleware/jwt/jwt.js +2 -2
  115. package/node_modules/hono/dist/middleware/method-not-allowed/index.js +1 -1
  116. package/node_modules/hono/dist/middleware/method-override/index.js +35 -12
  117. package/node_modules/hono/dist/middleware/mount/index.js +5 -4
  118. package/node_modules/hono/dist/middleware/pretty-json/index.js +1 -0
  119. package/node_modules/hono/dist/middleware/request-id/request-id.js +3 -3
  120. package/node_modules/hono/dist/middleware/secure-headers/secure-headers.js +6 -3
  121. package/node_modules/hono/dist/middleware/serve-static/index.js +4 -2
  122. package/node_modules/hono/dist/middleware/timing/timing.js +4 -3
  123. package/node_modules/hono/dist/router/reg-exp-router/node.js +13 -11
  124. package/node_modules/hono/dist/router/reg-exp-router/prepared-router.js +5 -5
  125. package/node_modules/hono/dist/router/reg-exp-router/router.js +40 -52
  126. package/node_modules/hono/dist/router/reg-exp-router/trie.js +15 -5
  127. package/node_modules/hono/dist/router/trie-router/node.js +6 -4
  128. package/node_modules/hono/dist/types/adapter/aws-lambda/conninfo.d.ts +1 -1
  129. package/node_modules/hono/dist/types/adapter/bun/conninfo.d.ts +1 -1
  130. package/node_modules/hono/dist/types/adapter/bun/ssg.d.ts +1 -1
  131. package/node_modules/hono/dist/types/adapter/cloudflare-pages/conninfo.d.ts +1 -1
  132. package/node_modules/hono/dist/types/adapter/cloudflare-workers/conninfo.d.ts +1 -1
  133. package/node_modules/hono/dist/types/adapter/deno/conninfo.d.ts +1 -1
  134. package/node_modules/hono/dist/types/adapter/deno/ssg.d.ts +1 -1
  135. package/node_modules/hono/dist/types/adapter/lambda-edge/conninfo.d.ts +1 -1
  136. package/node_modules/hono/dist/types/adapter/netlify/conninfo.d.ts +1 -1
  137. package/node_modules/hono/dist/types/adapter/vercel/conninfo.d.ts +1 -1
  138. package/node_modules/hono/dist/types/helper/accepts/accepts.d.ts +5 -0
  139. package/node_modules/hono/dist/types/helper/factory/index.d.ts +1 -1
  140. package/node_modules/hono/dist/types/helper/ssg/ssg.d.ts +6 -1
  141. package/node_modules/hono/dist/types/helper/streaming/sse.d.ts +1 -1
  142. package/node_modules/hono/dist/types/helper/streaming/stream.d.ts +1 -1
  143. package/node_modules/hono/dist/types/helper/streaming/text.d.ts +1 -1
  144. package/node_modules/hono/dist/types/helper/testing/index.d.ts +2 -1
  145. package/node_modules/hono/dist/types/helper/websocket/index.d.ts +13 -3
  146. package/node_modules/hono/dist/types/hono-base.d.ts +23 -9
  147. package/node_modules/hono/dist/types/index.d.ts +1 -1
  148. package/node_modules/hono/dist/types/jsx/base.d.ts +6 -3
  149. package/node_modules/hono/dist/types/jsx/components.d.ts +2 -2
  150. package/node_modules/hono/dist/types/jsx/constants.d.ts +1 -0
  151. package/node_modules/hono/dist/types/jsx/context.d.ts +2 -2
  152. package/node_modules/hono/dist/types/jsx/dom/components.d.ts +2 -2
  153. package/node_modules/hono/dist/types/jsx/dom/css.d.ts +2 -2
  154. package/node_modules/hono/dist/types/jsx/dom/hooks/index.d.ts +5 -3
  155. package/node_modules/hono/dist/types/jsx/dom/index.d.ts +1 -1
  156. package/node_modules/hono/dist/types/jsx/dom/server.d.ts +1 -1
  157. package/node_modules/hono/dist/types/jsx/index.d.ts +1 -1
  158. package/node_modules/hono/dist/types/jsx/jsx-runtime.d.ts +2 -1
  159. package/node_modules/hono/dist/types/jsx/streaming.d.ts +4 -3
  160. package/node_modules/hono/dist/types/middleware/basic-auth/index.d.ts +1 -0
  161. package/node_modules/hono/dist/types/middleware/bearer-auth/index.d.ts +2 -1
  162. package/node_modules/hono/dist/types/middleware/ip-restriction/index.d.ts +3 -3
  163. package/node_modules/hono/dist/types/middleware/jsx-renderer/index.d.ts +3 -3
  164. package/node_modules/hono/dist/types/middleware/mount/index.d.ts +2 -0
  165. package/node_modules/hono/dist/types/middleware/request-id/request-id.d.ts +3 -3
  166. package/node_modules/hono/dist/types/middleware/secure-headers/secure-headers.d.ts +2 -0
  167. package/node_modules/hono/dist/types/router/reg-exp-router/node.d.ts +3 -3
  168. package/node_modules/hono/dist/types/router/reg-exp-router/trie.d.ts +1 -1
  169. package/node_modules/hono/dist/types/utils/cookie.d.ts +1 -1
  170. package/node_modules/hono/dist/types/utils/ipaddr.d.ts +1 -1
  171. package/node_modules/hono/dist/types/utils/jwt/jwt.d.ts +4 -2
  172. package/node_modules/hono/dist/types/utils/mount.d.ts +4 -0
  173. package/node_modules/hono/dist/types/utils/types.d.ts +12 -2
  174. package/node_modules/hono/dist/utils/body.js +2 -1
  175. package/node_modules/hono/dist/utils/cookie.js +3 -3
  176. package/node_modules/hono/dist/utils/html.js +5 -0
  177. package/node_modules/hono/dist/utils/jwt/jwt.js +8 -5
  178. package/node_modules/hono/dist/utils/mime.js +3 -2
  179. package/node_modules/hono/dist/utils/mount.js +58 -0
  180. package/node_modules/hono/dist/utils/url.js +23 -11
  181. package/node_modules/hono/dist/validator/validator.js +5 -5
  182. package/node_modules/hono/package.json +1 -1
  183. package/package.json +1 -1
@@ -2,6 +2,13 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_utils_body = require("../../utils/body.js");
3
3
  //#region src/middleware/method-override/index.ts
4
4
  const DEFAULT_METHOD_FORM_NAME = "_method";
5
+ const isBodylessMethod = (method) => /^(?:GET|HEAD)$/i.test(method);
6
+ const withoutBodyHeaders = (headers) => {
7
+ const newHeaders = new Headers(headers);
8
+ newHeaders.delete("content-type");
9
+ newHeaders.delete("content-length");
10
+ return newHeaders;
11
+ };
5
12
  /**
6
13
  * Method Override Middleware for Hono.
7
14
  *
@@ -38,16 +45,21 @@ const methodOverride = (options) => async function methodOverride(c, next) {
38
45
  if (contentType?.startsWith("multipart/form-data")) {
39
46
  const method = (await clonedRequest.formData()).get(methodFormName);
40
47
  if (method) {
41
- const newForm = await newRequest.formData();
42
- newForm.delete(methodFormName);
43
- const newHeaders = new Headers(clonedRequest.headers);
44
- newHeaders.delete("content-type");
45
- newHeaders.delete("content-length");
46
- const request = new Request(c.req.url, {
47
- body: newForm,
48
+ const newHeaders = withoutBodyHeaders(clonedRequest.headers);
49
+ let request;
50
+ if (isBodylessMethod(method)) request = new Request(c.req.url, {
48
51
  headers: newHeaders,
49
52
  method
50
53
  });
54
+ else {
55
+ const newForm = await newRequest.formData();
56
+ newForm.delete(methodFormName);
57
+ request = new Request(c.req.url, {
58
+ body: newForm,
59
+ headers: newHeaders,
60
+ method
61
+ });
62
+ }
51
63
  return app.fetch(request, c.env, getExecutionCtx(c));
52
64
  }
53
65
  }
@@ -56,9 +68,14 @@ const methodOverride = (options) => async function methodOverride(c, next) {
56
68
  const method = params[methodFormName];
57
69
  if (method) {
58
70
  delete params[methodFormName];
59
- const newParams = new URLSearchParams(params);
60
- const request = new Request(newRequest, {
61
- body: newParams,
71
+ const newHeaders = new Headers(newRequest.headers);
72
+ newHeaders.delete("content-length");
73
+ const request = isBodylessMethod(method) ? new Request(c.req.url, {
74
+ headers: withoutBodyHeaders(newHeaders),
75
+ method
76
+ }) : new Request(newRequest, {
77
+ body: new URLSearchParams(params),
78
+ headers: newHeaders,
62
79
  method
63
80
  });
64
81
  return app.fetch(request, c.env, getExecutionCtx(c));
@@ -70,7 +87,10 @@ const methodOverride = (options) => async function methodOverride(c, next) {
70
87
  if (method) {
71
88
  const newHeaders = new Headers(c.req.raw.headers);
72
89
  newHeaders.delete(headerName);
73
- const request = new Request(c.req.raw, {
90
+ const request = isBodylessMethod(method) ? new Request(c.req.url, {
91
+ headers: withoutBodyHeaders(newHeaders),
92
+ method
93
+ }) : new Request(c.req.raw, {
74
94
  headers: newHeaders,
75
95
  method
76
96
  });
@@ -82,7 +102,10 @@ const methodOverride = (options) => async function methodOverride(c, next) {
82
102
  if (method) {
83
103
  const url = new URL(c.req.url);
84
104
  url.searchParams.delete(queryName);
85
- const requestInit = {
105
+ const requestInit = isBodylessMethod(method) ? {
106
+ headers: withoutBodyHeaders(c.req.raw.headers),
107
+ method
108
+ } : {
86
109
  body: c.req.raw.body,
87
110
  headers: c.req.raw.headers,
88
111
  method,
@@ -1,11 +1,10 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_helper_route_index = require("../../helper/route/index.js");
3
+ const require_utils_mount = require("../../utils/mount.js");
3
4
  //#region src/middleware/mount/index.ts
4
5
  const defaultReplaceRequest = (c) => {
5
- const pathPrefix = require_helper_route_index.routePath(c).replace(/\/\*$/, "");
6
- const url = new URL(c.req.raw.url);
7
- url.pathname = c.req.path.slice(pathPrefix.length) || "/";
8
- return new Request(url, c.req.raw);
6
+ const path = require_helper_route_index.routePath(c);
7
+ return require_utils_mount.createMountedRequest(c, path.replace(/\/?\*$/, ""), path);
9
8
  };
10
9
  const defaultGetOptions = (c) => {
11
10
  let executionContext = void 0;
@@ -22,6 +21,8 @@ const defaultGetOptions = (c) => {
22
21
  * @param {Function} applicationHandler - other Request Handler
23
22
  * @param {MountOptions} [options] - options of `mount()`
24
23
  * @returns {MiddlewareHandler} handler to register with `app.all()`
24
+ * @throws {Error} If the route ends with a wildcard inside a segment (e.g. `/assets*`), or automatic request rewriting encounters duplicate path parameter names or an optional regular expression parameter.
25
+ * @throws {HTTPException} With status 400 if automatic request rewriting cannot safely preserve the routed path.
25
26
  *
26
27
  * @example
27
28
  * ```ts
@@ -32,6 +32,7 @@ const prettyJSON = (options) => {
32
32
  } catch {
33
33
  return;
34
34
  }
35
+ await c.res.body?.cancel();
35
36
  c.res = new Response(JSON.stringify(obj, null, options?.space ?? 2), c.res);
36
37
  c.res.headers.delete("Content-Length");
37
38
  }
@@ -3,10 +3,10 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  /**
4
4
  * Request ID Middleware for Hono.
5
5
  *
6
- * @param {object} options - Options for Request ID middleware.
6
+ * @param {RequestIdOptions} [options] - Options for Request ID middleware.
7
7
  * @param {number} [options.limitLength=255] - The maximum length of request id.
8
- * @param {string} [options.headerName=X-Request-Id] - The header name used in request id.
9
- * @param {generator} [options.generator=() => crypto.randomUUID()] - The request id generation function.
8
+ * @param {string} [options.headerName='X-Request-Id'] - The header name used in request id.
9
+ * @param {(c: Context) => string} [options.generator=() => crypto.randomUUID()] - The request id generation function.
10
10
  *
11
11
  * @returns {MiddlewareHandler} The middleware handler function.
12
12
  *
@@ -29,7 +29,8 @@ const DEFAULT_OPTIONS = {
29
29
  xPermittedCrossDomainPolicies: true,
30
30
  xXssProtection: true,
31
31
  removePoweredBy: true,
32
- permissionsPolicy: {}
32
+ permissionsPolicy: {},
33
+ overwrite: true
33
34
  };
34
35
  const generateNonce = () => {
35
36
  const arrayBuffer = /* @__PURE__ */ new Uint8Array(16);
@@ -67,6 +68,7 @@ const NONCE = (ctx) => {
67
68
  * @param {overridableHeader} [customOptions.xXssProtection=true] - Settings for the X-XSS-Protection header.
68
69
  * @param {boolean} [customOptions.removePoweredBy=true] - Settings for remove X-Powered-By header.
69
70
  * @param {PermissionsPolicyOptions} [customOptions.permissionsPolicy] - Settings for the Permissions-Policy header.
71
+ * @param {boolean} [customOptions.overwrite=true] - Whether to replace a header that the response already has. Set `false` to keep a header that a handler set itself.
70
72
  * @returns {MiddlewareHandler} The middleware handler function.
71
73
  *
72
74
  * @example
@@ -98,7 +100,7 @@ const secureHeaders = (customOptions) => {
98
100
  return async function secureHeaders(ctx, next) {
99
101
  const headersToSetForReq = callbacks.length === 0 ? headersToSet : callbacks.reduce((acc, cb) => cb(ctx, acc), headersToSet);
100
102
  await next();
101
- setHeaders(ctx, headersToSetForReq);
103
+ setHeaders(ctx, headersToSetForReq, options.overwrite !== false);
102
104
  if (options?.removePoweredBy) ctx.res.headers.delete("X-Powered-By");
103
105
  };
104
106
  };
@@ -156,8 +158,9 @@ function getReportingEndpoints(reportingEndpoints = []) {
156
158
  function getReportToOptions(reportTo = []) {
157
159
  return reportTo.map((option) => JSON.stringify(option)).join(", ");
158
160
  }
159
- function setHeaders(ctx, headersToSet) {
161
+ function setHeaders(ctx, headersToSet, overwrite) {
160
162
  headersToSet.forEach(([header, value]) => {
163
+ if (!overwrite && ctx.res.headers.has(header)) return;
161
164
  ctx.res.headers.set(header, value);
162
165
  });
163
166
  }
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_utils_url = require("../../utils/url.js");
3
+ const require_utils_accept = require("../../utils/accept.js");
3
4
  const require_utils_compress = require("../../utils/compress.js");
4
5
  const require_utils_mime = require("../../utils/mime.js");
5
6
  const require_middleware_serve_static_path = require("./path.js");
@@ -20,11 +21,12 @@ const serveStatic = (options) => {
20
21
  const join = options.join ?? require_middleware_serve_static_path.defaultJoin;
21
22
  return async (c, next) => {
22
23
  if (c.finalized) return next();
24
+ if (c.req.method !== "GET" && c.req.method !== "HEAD") return next();
23
25
  let filename;
24
26
  if (options.path) filename = options.path;
25
27
  else try {
26
- if (!options.allowPercentInPath && c.req.path.includes("%")) throw new Error();
27
28
  filename = require_utils_url.tryDecodeURI(c.req.path);
29
+ if (c.req.path.includes("%") && (!options.allowPercentInPath || filename !== c.req.path.replace(/%25/g, "%"))) throw new Error();
28
30
  if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(filename)) throw new Error();
29
31
  } catch {
30
32
  await options.onNotFound?.(c.req.path, c);
@@ -39,7 +41,7 @@ const serveStatic = (options) => {
39
41
  const mimeType = options.mimes && require_utils_mime.getMimeType(path, options.mimes) || require_utils_mime.getMimeType(path);
40
42
  c.header("Content-Type", mimeType || "application/octet-stream");
41
43
  if (options.precompressed && (!mimeType || require_utils_compress.COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
42
- const acceptEncodingSet = new Set(c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim()));
44
+ const acceptEncodingSet = new Set(require_utils_accept.parseAccept(c.req.header("Accept-Encoding") ?? "").filter((encoding) => encoding.q > 0).map((encoding) => encoding.type));
43
45
  for (const encoding of ENCODINGS_ORDERED_KEYS) {
44
46
  if (!acceptEncodingSet.has(encoding)) continue;
45
47
  const compressedContent = await getContent(path + ENCODINGS[encoding], c);
@@ -75,6 +75,7 @@ const timing = (config) => {
75
75
  }
76
76
  };
77
77
  };
78
+ const quote = (s) => `"${s.replace(/[\\"]/g, "\\$&")}"`;
78
79
  /**
79
80
  * Set a metric for the timing middleware.
80
81
  *
@@ -97,11 +98,11 @@ const setMetric = (c, name, valueDescription, description, precision) => {
97
98
  return;
98
99
  }
99
100
  if (typeof valueDescription === "number") {
100
- const dur = valueDescription.toFixed(precision || 1);
101
- const metric = description ? `${name};dur=${dur};desc="${description}"` : `${name};dur=${dur}`;
101
+ const dur = valueDescription.toFixed(precision ?? 1);
102
+ const metric = description ? `${name};dur=${dur};desc=${quote(description)}` : `${name};dur=${dur}`;
102
103
  metrics.headers.push(metric);
103
104
  } else {
104
- const metric = valueDescription ? `${name};desc="${valueDescription}"` : `${name}`;
105
+ const metric = valueDescription ? `${name};desc=${quote(valueDescription)}` : `${name}`;
105
106
  metrics.headers.push(metric);
106
107
  }
107
108
  };
@@ -2,8 +2,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_router_utils = require("../utils.js");
3
3
  //#region src/router/reg-exp-router/node.ts
4
4
  const LABEL_REG_EXP_STR = "[^/]+";
5
- const ONLY_WILDCARD_REG_EXP_STR = ".*";
6
- const TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
5
+ const ONLY_WILDCARD_REG_EXP_STR = "[^]*";
6
+ const TAIL_WILDCARD_REG_EXP_STR = "(?:|/[^]*)";
7
7
  const PATH_ERROR = Symbol();
8
8
  const regExpMetaChars = /* @__PURE__ */ new Set(".\\+*[^]$()");
9
9
  /**
@@ -16,8 +16,8 @@ const regExpMetaChars = /* @__PURE__ */ new Set(".\\+*[^]$()");
16
16
  function compareKey(a, b) {
17
17
  if (a.length === 1) return b.length === 1 ? a < b ? -1 : 1 : -1;
18
18
  if (b.length === 1) return 1;
19
- if (a === ".*" || a === "(?:|/.*)") return b === "(?:|/.*)" ? -1 : 1;
20
- else if (b === ".*" || b === "(?:|/.*)") return -1;
19
+ if (a === "[^]*" || a === "(?:|/[^]*)") return b === "[^]*" ? -1 : 1;
20
+ else if (b === "[^]*" || b === "(?:|/[^]*)") return -1;
21
21
  if (a === "[^/]+") return 1;
22
22
  else if (b === "[^/]+") return -1;
23
23
  return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
@@ -26,14 +26,14 @@ var Node = class Node {
26
26
  #index;
27
27
  #varIndex;
28
28
  #children = require_router_utils.createNullObject();
29
- insert(tokens, index, paramMap, context, isStatic) {
29
+ insert(tokens, index, paramMap, context, keys) {
30
30
  let node = this;
31
31
  for (let i = 0, len = tokens.length; i < len; i++) {
32
32
  const token = tokens[i];
33
33
  const pattern = token.length === 1 ? token === "*" ? i === len - 1 ? [
34
34
  "",
35
35
  "",
36
- ".*"
36
+ ONLY_WILDCARD_REG_EXP_STR
37
37
  ] : [
38
38
  "",
39
39
  "",
@@ -48,15 +48,16 @@ var Node = class Node {
48
48
  const name = pattern[1];
49
49
  let regexpStr = pattern[2] || "[^/]+";
50
50
  if (name && pattern[2]) {
51
- if (regexpStr === ".*") throw PATH_ERROR;
51
+ if (new RegExp(regexpStr).test("")) throw PATH_ERROR;
52
52
  regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
53
53
  if (/\((?!\?:)/.test(regexpStr)) throw PATH_ERROR;
54
54
  if (regexpStr.length === 1 && regExpMetaChars.has(regexpStr)) throw PATH_ERROR;
55
55
  }
56
+ keys.push(regexpStr);
56
57
  nextNode = node.#children[regexpStr];
57
58
  if (!nextNode) {
58
- if (regexpStr !== ".*" && regexpStr !== "(?:|/.*)") {
59
- for (const k in node.#children) if ((regexpStr.length > 1 || k.length > 1) && k !== ".*" && k !== "(?:|/.*)") throw PATH_ERROR;
59
+ if (regexpStr !== "[^]*" && regexpStr !== "(?:|/[^]*)") {
60
+ for (const k in node.#children) if ((regexpStr.length > 1 || k.length > 1) && k !== "[^]*" && k !== "(?:|/[^]*)") throw PATH_ERROR;
60
61
  }
61
62
  nextNode = node.#children[regexpStr] = new Node();
62
63
  }
@@ -65,16 +66,17 @@ var Node = class Node {
65
66
  paramMap.push([name, nextNode.#varIndex]);
66
67
  }
67
68
  } else {
69
+ keys.push(token);
68
70
  nextNode = node.#children[token];
69
71
  if (!nextNode) {
70
- for (const k in node.#children) if (k.length > 1 && k !== ".*" && k !== "(?:|/.*)") throw PATH_ERROR;
72
+ for (const k in node.#children) if (k.length > 1 && k !== "[^]*" && k !== "(?:|/[^]*)") throw PATH_ERROR;
71
73
  nextNode = node.#children[token] = new Node();
72
74
  }
73
75
  }
74
76
  node = nextNode;
75
77
  }
76
78
  if (node.#index !== void 0) throw PATH_ERROR;
77
- node.#index = isStatic ? -1 : index;
79
+ node.#index = index;
78
80
  }
79
81
  buildRegExpStr() {
80
82
  const strList = Object.keys(this.#children).sort(compareKey).map((k) => {
@@ -28,7 +28,7 @@ var PreparedRegExpRouter = class {
28
28
  if (!this.#matchers[method]) {
29
29
  const all = this.#matchers["ALL"];
30
30
  const staticMap = {};
31
- for (const key in all[2]) staticMap[key] = [all[2][key][0].slice(), require_router_reg_exp_router_matcher.emptyParam];
31
+ for (const key in all[2]) staticMap[key] = [all[2][key][0].slice(), all[2][key][1]];
32
32
  this.#matchers[method] = [
33
33
  all[0],
34
34
  all[1].map((list) => Array.isArray(list) ? list.slice() : 0),
@@ -72,7 +72,7 @@ const buildInitParams = ({ paths }) => {
72
72
  ...map
73
73
  };
74
74
  else relocateMap[path] = [[[], map]];
75
- if (relocateMap[path][0][0].findIndex((j) => j === i) === -1) relocateMap[path][0][0].push(i);
75
+ if (!relocateMap[path][0][0].includes(i)) relocateMap[path][0][0].push(i);
76
76
  }
77
77
  });
78
78
  });
@@ -80,7 +80,7 @@ const buildInitParams = ({ paths }) => {
80
80
  if (p === path) {
81
81
  relocateMap[path] ||= [[[]]];
82
82
  const value = path2 === path ? "" : path2;
83
- if (relocateMap[path][0][0].findIndex((v) => v === value) === -1) relocateMap[path][0][0].push(value);
83
+ if (!relocateMap[path][0][0].includes(value)) relocateMap[path][0][0].push(value);
84
84
  }
85
85
  });
86
86
  }
@@ -89,7 +89,7 @@ const buildInitParams = ({ paths }) => {
89
89
  return [matchers, relocateMap];
90
90
  };
91
91
  const serializeInitParams = ([matchers, relocateMap]) => {
92
- return `[${JSON.stringify(matchers, (_, value) => value instanceof RegExp ? `##${value.toString()}##` : value).replace(/"##(.+?)##"/g, (_, str) => str.replace(/\\\\/g, "\\"))},${JSON.stringify(relocateMap)}]`;
92
+ return `[${JSON.stringify(matchers, (_, value) => value instanceof RegExp || value === void 0 ? `##${value}##` : value).replace(/"##(.+?)##"/g, (_, str) => str.replace(/\\\\/g, "\\"))},${JSON.stringify(relocateMap)}]`;
93
93
  };
94
94
  //#endregion
95
95
  exports.PreparedRegExpRouter = PreparedRegExpRouter;
@@ -6,21 +6,21 @@ const require_router_reg_exp_router_matcher = require("./matcher.js");
6
6
  const require_router_reg_exp_router_node = require("./node.js");
7
7
  const require_router_reg_exp_router_trie = require("./trie.js");
8
8
  //#region src/router/reg-exp-router/router.ts
9
- let wildcardRegExpCache = require_router_utils.createNullObject();
10
- function buildWildcardRegExp(path) {
11
- return wildcardRegExpCache[path] ??= new RegExp(`^${path.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g, (match, metaChar) => metaChar ? `\\${metaChar}` : match === "/*" ? require_router_reg_exp_router_node.TAIL_WILDCARD_REG_EXP_STR : match === "*" ? ".*" : `/:${require_router_reg_exp_router_node.LABEL_REG_EXP_STR}`)}$`);
9
+ function endsWithWildcard(keys) {
10
+ const tail = keys[keys.length - 1];
11
+ return tail === "[^]*" || tail === "(?:|/[^]*)";
12
12
  }
13
- function findMiddleware(middleware, path) {
14
- for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) if (buildWildcardRegExp(k).test(path)) return [...middleware[k]];
13
+ function covers(wildcard, target) {
14
+ const last = wildcard.length - 1;
15
+ for (let i = 0; i < last; i++) if (wildcard[i] !== target[i]) return false;
16
+ return wildcard[last] === "[^]*" || target.length === last || target[last] === "/";
15
17
  }
16
18
  var RegExpRouter = class {
17
19
  name = "RegExpRouter";
18
- #middleware;
19
- #routes;
20
+ #handlers;
20
21
  #tries;
21
22
  constructor() {
22
- this.#middleware = { ["ALL"]: require_router_utils.createNullObject() };
23
- this.#routes = { ["ALL"]: require_router_utils.createNullObject() };
23
+ this.#handlers = { ["ALL"]: [] };
24
24
  this.#tries = { ["ALL"]: new require_router_reg_exp_router_trie.Trie() };
25
25
  }
26
26
  #insertPath(method, path) {
@@ -31,65 +31,53 @@ var RegExpRouter = class {
31
31
  }
32
32
  }
33
33
  add(method, path, handler) {
34
- const middleware = this.#middleware;
35
- const routes = this.#routes;
36
- if (!middleware) throw new Error(require_router.MESSAGE_MATCHER_IS_ALREADY_BUILT);
37
- if (!middleware[method]) {
38
- this.#tries[method] = new require_router_reg_exp_router_trie.Trie();
39
- for (const handlerMap of [middleware, routes]) {
40
- handlerMap[method] = require_router_utils.createNullObject();
41
- for (const p in handlerMap["ALL"]) {
42
- handlerMap[method][p] = [...handlerMap["ALL"][p]];
43
- this.#insertPath(method, p);
44
- }
45
- }
34
+ const handlers = this.#handlers;
35
+ if (!handlers) throw new Error(require_router.MESSAGE_MATCHER_IS_ALREADY_BUILT);
36
+ const tries = this.#tries;
37
+ if (!handlers[method]) {
38
+ tries[method] = new require_router_reg_exp_router_trie.Trie();
39
+ handlers[method] = [...handlers["ALL"]];
40
+ for (const p in tries["ALL"].paths) this.#insertPath(method, p);
46
41
  }
47
42
  if (path === "/*") path = "*";
48
- const methods = method === "ALL" ? Object.keys(middleware) : [method];
49
- if (/\*$/.test(path)) {
50
- const re = buildWildcardRegExp(path);
51
- for (const m of methods) if (!middleware[m][path]) {
52
- this.#insertPath(m, path);
53
- middleware[m][path] = findMiddleware(middleware[m], path) || findMiddleware(middleware["ALL"], path) || [];
54
- }
55
- for (const handlerMap of [middleware, routes]) for (const m of methods) for (const p in handlerMap[m]) re.test(p) && handlerMap[m][p].push([handler, path]);
56
- return;
57
- }
43
+ const methods = method === "ALL" ? Object.keys(handlers) : [method];
58
44
  const paths = require_utils_url.checkOptionalParameter(path) || [path];
59
45
  for (const path of paths) for (const m of methods) {
60
- if (!routes[m][path]) {
61
- this.#insertPath(m, path);
62
- routes[m][path] = findMiddleware(middleware[m], path) || findMiddleware(middleware["ALL"], path) || [];
63
- }
64
- routes[m][path].push([handler, path]);
46
+ if (!tries[m].paths[path]) this.#insertPath(m, path);
47
+ handlers[m].push([handler, path]);
65
48
  }
66
49
  }
67
50
  match = require_router_reg_exp_router_matcher.match;
68
51
  buildAllMatchers() {
69
52
  const matchers = require_router_utils.createNullObject();
70
- for (const method of Object.keys(this.#routes)) matchers[method] = this.#buildMatcher(method);
71
- this.#middleware = this.#routes = this.#tries = void 0;
72
- wildcardRegExpCache = require_router_utils.createNullObject();
53
+ for (const method of Object.keys(this.#handlers)) matchers[method] = this.#buildMatcher(method);
54
+ this.#handlers = this.#tries = void 0;
73
55
  return matchers;
74
56
  }
75
57
  #buildMatcher(method) {
76
- const middleware = this.#middleware[method];
77
- const routes = this.#routes[method];
58
+ const handlers = this.#handlers[method];
78
59
  const trie = this.#tries[method];
79
60
  const staticMap = require_router_utils.createNullObject();
80
61
  const handlerData = [];
81
62
  const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
82
- for (const r of [middleware, routes]) for (const path in r) {
83
- const handlers = r[path];
84
- const pathData = trie.paths[path];
85
- if (!pathData) {
86
- staticMap[path] = [handlers.map(([h]) => [h, require_router_utils.createNullObject()]), require_router_reg_exp_router_matcher.emptyParam];
87
- continue;
88
- }
89
- handlerData[pathData[0]] = handlers.map(([h, handlerPath]) => [h, trie.paths[handlerPath][1].reduceRight((map, [key], i) => {
90
- map[key] = paramReplacementMap[pathData[1][i][1]];
63
+ const own = require_router_utils.createNullObject();
64
+ const entries = handlers.map(([h, p], i) => {
65
+ (own[p] ??= []).push(i);
66
+ return [h, trie.paths[p][1].reduceRight((map, [key, varIndex]) => {
67
+ map[key] = paramReplacementMap[varIndex];
91
68
  return map;
92
- }, require_router_utils.createNullObject())]);
69
+ }, require_router_utils.createNullObject())];
70
+ });
71
+ const wildcards = Object.keys(own).filter((p) => endsWithWildcard(trie.paths[p][2]));
72
+ for (const path in trie.paths) {
73
+ const [index, , keys] = trie.paths[path];
74
+ const indexes = [...own[path]];
75
+ for (const p of wildcards) if (p !== path && covers(trie.paths[p][2], keys)) indexes.push(...own[p]);
76
+ const data = indexes.sort((a, b) => a - b).map((i) => entries[i]);
77
+ if (index === -1) {
78
+ const last = Math.max(-1, ...data.flatMap(([, map]) => Object.values(map)));
79
+ staticMap[path] = [data, last === -1 ? require_router_reg_exp_router_matcher.emptyParam : path.match(regexp).slice(0, last + 1)];
80
+ } else handlerData[index] = data;
93
81
  }
94
82
  return [
95
83
  regexp,
@@ -8,8 +8,14 @@ var Trie = class {
8
8
  #index = 0;
9
9
  paths = require_router_utils.createNullObject();
10
10
  insert(path, isStatic) {
11
+ const keys = [];
11
12
  if (isStatic) {
12
- this.#root.insert(path.split(""), 0, [], this.#context, true);
13
+ this.#root.insert(path.split(""), -1, [], this.#context, keys);
14
+ this.paths[path] = [
15
+ -1,
16
+ [],
17
+ keys
18
+ ];
13
19
  return;
14
20
  }
15
21
  const paramAssoc = [];
@@ -17,7 +23,7 @@ var Trie = class {
17
23
  let markedPath = path;
18
24
  for (let i = 0;;) {
19
25
  let replaced = false;
20
- markedPath = markedPath.replace(/\{[^}]+\}/g, (m) => {
26
+ markedPath = markedPath.replace(/\{(?:\{[\d,]+\}|[^}])+\}/g, (m) => {
21
27
  const mark = `@\\${i}`;
22
28
  groups[i] = [mark, m];
23
29
  i++;
@@ -31,7 +37,7 @@ var Trie = class {
31
37
  * - /* wildcard
32
38
  * - character
33
39
  */
34
- const tokens = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
40
+ const tokens = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./gs) || [];
35
41
  for (let i = groups.length - 1; i >= 0; i--) {
36
42
  const [mark] = groups[i];
37
43
  for (let j = tokens.length - 1; j >= 0; j--) if (tokens[j].indexOf(mark) !== -1) {
@@ -39,8 +45,12 @@ var Trie = class {
39
45
  break;
40
46
  }
41
47
  }
42
- this.#root.insert(tokens, this.#index, paramAssoc, this.#context, false);
43
- this.paths[path] = [this.#index++, paramAssoc];
48
+ this.#root.insert(tokens, this.#index, paramAssoc, this.#context, keys);
49
+ this.paths[path] = [
50
+ this.#index++,
51
+ paramAssoc,
52
+ keys
53
+ ];
44
54
  }
45
55
  buildRegExp() {
46
56
  let regexp = this.#root.buildRegExpStr();
@@ -29,11 +29,13 @@ var Node = class Node {
29
29
  curNode = child;
30
30
  if (isParam) possibleKeys.add(pattern[1]);
31
31
  }
32
- curNode.#methods.push({ [method]: {
32
+ const methodMap = require_router_utils.createNullObject();
33
+ methodMap[method] = {
33
34
  handler,
34
35
  possibleKeys: [...possibleKeys],
35
36
  score: ++order
36
- } });
37
+ };
38
+ curNode.#methods.push(methodMap);
37
39
  }
38
40
  #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
39
41
  for (let i = 0, len = node.#methods.length; i < len; i++) {
@@ -98,7 +100,7 @@ var Node = class Node {
98
100
  const restPathString = path.slice(partOffsets[i]);
99
101
  const m = matcher.exec(restPathString);
100
102
  if (m) {
101
- params[name] = m[0];
103
+ if (!Object.hasOwn(params, name)) params[name] = m[0];
102
104
  this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
103
105
  if (m[0].length === restPathString.length && child.#children["*"]) this.#pushHandlerSets(handlerSets, child.#children["*"], method, node.#params, params);
104
106
  for (const _ in child.#children) {
@@ -111,7 +113,7 @@ var Node = class Node {
111
113
  }
112
114
  }
113
115
  if (matcher === true || matcher.test(part)) {
114
- params[name] = part;
116
+ if (!Object.hasOwn(params, name)) params[name] = part;
115
117
  if (isLast) {
116
118
  this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
117
119
  if (child.#children["*"]) this.#pushHandlerSets(handlerSets, child.#children["*"], method, params, node.#params);
@@ -73,9 +73,10 @@ const handleParsingAllValues = (form, key, value) => {
73
73
  * @param {BodyData} form - The form data object.
74
74
  * @param {string} key - The dot notation key.
75
75
  * @param {BodyDataValue} value - The value to assign.
76
+ * @param {{ count: number }} state - The state object tracking nesting depth.
76
77
  */
77
78
  const handleParsingNestedValues = (form, key, value, state) => {
78
- if (/(?:^|\.)__proto__\./.test(key)) return;
79
+ if (/(?:^|\.)(?:__proto__|constructor\.prototype)\./.test(key)) return;
79
80
  let nestedForm = form;
80
81
  const keys = key.split(".", 34);
81
82
  if (keys.length > 33) throwNestingLimitExceeded();
@@ -56,7 +56,7 @@ const parse = (cookie, name) => {
56
56
  const cookieName = trimCookieWhitespace(pairStr.substring(0, valueStartPos));
57
57
  if (name && name !== cookieName || !relaxedCookieNameRegEx.test(cookieName) || cookieName in parsedCookie) continue;
58
58
  let cookieValue = trimCookieWhitespace(pairStr.substring(valueStartPos + 1));
59
- if (cookieValue.startsWith("\"") && cookieValue.endsWith("\"")) cookieValue = cookieValue.slice(1, -1);
59
+ if (cookieValue.length >= 2 && cookieValue.startsWith("\"") && cookieValue.endsWith("\"")) cookieValue = cookieValue.slice(1, -1);
60
60
  if (validCookieValueRegEx.test(cookieValue)) {
61
61
  parsedCookie[cookieName] = require_utils_url.tryDecodeURIComponent(cookieValue);
62
62
  if (name) break;
@@ -80,8 +80,8 @@ const parseSigned = async (cookie, secret, name) => {
80
80
  const _serialize = (name, value, opt = {}) => {
81
81
  if (!validCookieNameRegEx.test(name)) throw new Error("Invalid cookie name");
82
82
  let cookie = `${name}=${value}`;
83
- if (name.startsWith("__Secure-") && !opt.secure) throw new Error("__Secure- Cookie must have Secure attributes");
84
- if (name.startsWith("__Host-")) {
83
+ if (/^__secure-/i.test(name) && !opt.secure) throw new Error("__Secure- Cookie must have Secure attributes");
84
+ if (/^__host-/i.test(name)) {
85
85
  if (!opt.secure) throw new Error("__Host- Cookie must have Secure attributes");
86
86
  if (opt.path !== "/") throw new Error("__Host- Cookie must have Path attributes with \"/\"");
87
87
  if (opt.domain) throw new Error("__Host- Cookie must not have Domain attributes");
@@ -25,6 +25,11 @@ const stringBufferToString = async (buffer, callbacks) => {
25
25
  i--;
26
26
  if (i < 0) break;
27
27
  let r = resolvedBuffer[i];
28
+ if (r == null || typeof r === "boolean") continue;
29
+ if (typeof r === "number") {
30
+ str += r;
31
+ continue;
32
+ }
28
33
  if (typeof r === "object") callbacks.push(...r.callbacks || []);
29
34
  const isEscaped = r.isEscaped;
30
35
  r = await (typeof r === "object" ? r.toString() : r);
@@ -13,10 +13,12 @@ const require_utils_jwt_jws = require("./jws.js");
13
13
  const encodeJwtPart = (part) => require_utils_encode.encodeBase64Url(require_utils_jwt_utf8.utf8Encoder.encode(JSON.stringify(part)).buffer).replace(/=/g, "");
14
14
  const encodeSignaturePart = (buf) => require_utils_encode.encodeBase64Url(buf).replace(/=/g, "");
15
15
  const decodeJwtPart = (part) => JSON.parse(require_utils_jwt_utf8.utf8Decoder.decode(require_utils_encode.decodeBase64Url(part)));
16
- function isTokenHeader(obj) {
16
+ const normalizeTyp = (typ) => typ.toLowerCase().replace(/^application\//, "");
17
+ const isTyp = (value, expected) => typeof value === "string" && [expected].flat().some((typ) => normalizeTyp(typ) === normalizeTyp(value));
18
+ function isTokenHeader(obj, typ) {
17
19
  if (typeof obj === "object" && obj !== null) {
18
20
  const objWithAlg = obj;
19
- return "alg" in objWithAlg && Object.values(require_utils_jwt_jwa.AlgorithmTypes).includes(objWithAlg.alg) && (!("typ" in objWithAlg) || objWithAlg.typ === "JWT");
21
+ return "alg" in objWithAlg && Object.values(require_utils_jwt_jwa.AlgorithmTypes).includes(objWithAlg.alg) && (typ === void 0 ? !("typ" in objWithAlg) || isTyp(objWithAlg.typ, "JWT") : isTyp(objWithAlg.typ, typ)) && !("crit" in objWithAlg);
20
22
  }
21
23
  return false;
22
24
  }
@@ -40,12 +42,12 @@ const sign = async (payload, privateKey, alg = "HS256") => {
40
42
  };
41
43
  const verify = async (token, publicKey, algOrOptions) => {
42
44
  if (!algOrOptions) throw new require_utils_jwt_types.JwtAlgorithmRequired();
43
- const { alg, iss, nbf = true, exp = true, iat = true, aud } = typeof algOrOptions === "string" ? { alg: algOrOptions } : algOrOptions;
45
+ const { alg, iss, nbf = true, exp = true, iat = true, aud, typ } = typeof algOrOptions === "string" ? { alg: algOrOptions } : algOrOptions;
44
46
  if (!alg) throw new require_utils_jwt_types.JwtAlgorithmRequired();
45
47
  const tokenParts = token.split(".");
46
48
  if (tokenParts.length !== 3) throw new require_utils_jwt_types.JwtTokenInvalid(token);
47
49
  const { header, payload } = decode(token);
48
- if (!isTokenHeader(header)) throw new require_utils_jwt_types.JwtHeaderInvalid(header);
50
+ if (!isTokenHeader(header, typ)) throw new require_utils_jwt_types.JwtHeaderInvalid(header);
49
51
  if (header.alg !== alg) throw new require_utils_jwt_types.JwtAlgorithmMismatch(alg, header.alg);
50
52
  const now = Math.floor(Date.now() / 1e3);
51
53
  if (nbf && payload.nbf !== void 0) {
@@ -73,6 +75,7 @@ const verify = async (token, publicKey, algOrOptions) => {
73
75
  } catch {
74
76
  throw new require_utils_jwt_types.JwtTokenInvalid(token);
75
77
  }
78
+ if (encodeSignaturePart(signature.buffer) !== tokenParts[2]) throw new require_utils_jwt_types.JwtTokenInvalid(token);
76
79
  if (!await require_utils_jwt_jws.verifying(publicKey, alg, signature, require_utils_jwt_utf8.utf8Encoder.encode(headerPayload))) throw new require_utils_jwt_types.JwtTokenSignatureMismatched(token);
77
80
  return payload;
78
81
  };
@@ -84,7 +87,7 @@ const symmetricAlgorithms = [
84
87
  const verifyWithJwks = async (token, options, init) => {
85
88
  const verifyOpts = options.verification || {};
86
89
  const header = decodeHeader(token);
87
- if (!isTokenHeader(header)) throw new require_utils_jwt_types.JwtHeaderInvalid(header);
90
+ if (!isTokenHeader(header, verifyOpts.typ)) throw new require_utils_jwt_types.JwtHeaderInvalid(header);
88
91
  if (!header.kid) throw new require_utils_jwt_types.JwtHeaderRequiresKid(header);
89
92
  if (symmetricAlgorithms.includes(header.alg)) throw new require_utils_jwt_types.JwtSymmetricAlgorithmNotAllowed(header.alg);
90
93
  if (!options.allowedAlgorithms.includes(header.alg)) throw new require_utils_jwt_types.JwtAlgorithmNotAllowed(header.alg, options.allowedAlgorithms);