@shware/http 1.2.0 → 1.2.1

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 (207) hide show
  1. package/dist/__tests__/index.test.cjs +27 -0
  2. package/dist/__tests__/index.test.cjs.map +1 -0
  3. package/dist/__tests__/index.test.d.cts +2 -0
  4. package/dist/__tests__/index.test.d.ts +2 -0
  5. package/dist/__tests__/index.test.mjs +25 -0
  6. package/dist/__tests__/index.test.mjs.map +1 -0
  7. package/dist/cache/index.cjs +32 -0
  8. package/dist/cache/index.cjs.map +1 -0
  9. package/dist/cache/index.d.cts +9 -0
  10. package/dist/cache/index.d.ts +9 -0
  11. package/dist/cache/index.mjs +7 -0
  12. package/dist/cache/index.mjs.map +1 -0
  13. package/dist/error/detail.cjs +93 -0
  14. package/dist/error/detail.cjs.map +1 -0
  15. package/dist/error/detail.d.cts +99 -0
  16. package/dist/error/detail.d.ts +99 -0
  17. package/dist/error/detail.mjs +67 -0
  18. package/dist/error/detail.mjs.map +1 -0
  19. package/dist/error/i18n/en-us.cjs +31 -0
  20. package/dist/error/i18n/en-us.cjs.map +1 -0
  21. package/dist/error/i18n/en-us.d.cts +3 -0
  22. package/dist/error/i18n/en-us.d.ts +3 -0
  23. package/dist/error/i18n/en-us.mjs +6 -0
  24. package/dist/error/i18n/en-us.mjs.map +1 -0
  25. package/dist/error/index.cjs +63 -0
  26. package/dist/error/index.cjs.map +1 -0
  27. package/dist/error/index.d.cts +19 -0
  28. package/dist/error/index.d.ts +19 -0
  29. package/dist/error/index.mjs +35 -0
  30. package/dist/error/index.mjs.map +1 -0
  31. package/dist/error/parse.cjs +52 -0
  32. package/dist/error/parse.cjs.map +1 -0
  33. package/dist/error/parse.d.cts +16 -0
  34. package/dist/error/parse.d.ts +16 -0
  35. package/dist/error/parse.mjs +27 -0
  36. package/dist/error/parse.mjs.map +1 -0
  37. package/dist/error/reason.cjs +19 -0
  38. package/dist/error/reason.cjs.map +1 -0
  39. package/dist/error/reason.d.cts +66 -0
  40. package/dist/error/reason.d.ts +66 -0
  41. package/dist/error/reason.mjs +1 -0
  42. package/dist/error/reason.mjs.map +1 -0
  43. package/dist/error/status.cjs +266 -0
  44. package/dist/error/status.cjs.map +1 -0
  45. package/dist/error/status.d.cts +69 -0
  46. package/dist/error/status.d.ts +69 -0
  47. package/dist/error/status.mjs +237 -0
  48. package/dist/error/status.mjs.map +1 -0
  49. package/dist/google-one-tap/index.cjs +51 -0
  50. package/dist/google-one-tap/index.cjs.map +1 -0
  51. package/dist/google-one-tap/index.d.cts +17 -0
  52. package/dist/google-one-tap/index.d.ts +17 -0
  53. package/dist/google-one-tap/index.mjs +26 -0
  54. package/dist/google-one-tap/index.mjs.map +1 -0
  55. package/dist/google-one-tap/types.cjs +19 -0
  56. package/dist/google-one-tap/types.cjs.map +1 -0
  57. package/dist/google-one-tap/types.d.cts +155 -0
  58. package/dist/google-one-tap/types.d.ts +155 -0
  59. package/dist/google-one-tap/types.mjs +1 -0
  60. package/dist/google-one-tap/types.mjs.map +1 -0
  61. package/dist/hono/__tests__/authorizer.test.cjs +483 -0
  62. package/dist/hono/__tests__/authorizer.test.cjs.map +1 -0
  63. package/dist/hono/__tests__/authorizer.test.d.cts +2 -0
  64. package/dist/hono/__tests__/authorizer.test.d.ts +2 -0
  65. package/dist/hono/__tests__/authorizer.test.mjs +481 -0
  66. package/dist/hono/__tests__/authorizer.test.mjs.map +1 -0
  67. package/dist/hono/__tests__/csrf.test.cjs +162 -0
  68. package/dist/hono/__tests__/csrf.test.cjs.map +1 -0
  69. package/dist/hono/__tests__/csrf.test.d.cts +2 -0
  70. package/dist/hono/__tests__/csrf.test.d.ts +2 -0
  71. package/dist/hono/__tests__/csrf.test.mjs +160 -0
  72. package/dist/hono/__tests__/csrf.test.mjs.map +1 -0
  73. package/dist/hono/authorizer.cjs +67 -0
  74. package/dist/hono/authorizer.cjs.map +1 -0
  75. package/dist/hono/authorizer.d.cts +18 -0
  76. package/dist/hono/authorizer.d.ts +18 -0
  77. package/dist/hono/authorizer.mjs +42 -0
  78. package/dist/hono/authorizer.mjs.map +1 -0
  79. package/dist/hono/csrf.cjs +95 -0
  80. package/dist/hono/csrf.cjs.map +1 -0
  81. package/dist/hono/csrf.d.cts +65 -0
  82. package/dist/hono/csrf.d.ts +65 -0
  83. package/dist/hono/csrf.mjs +70 -0
  84. package/dist/hono/csrf.mjs.map +1 -0
  85. package/dist/hono/geolocation.cjs +75 -0
  86. package/dist/hono/geolocation.cjs.map +1 -0
  87. package/dist/hono/geolocation.d.cts +17 -0
  88. package/dist/hono/geolocation.d.ts +17 -0
  89. package/dist/hono/geolocation.mjs +50 -0
  90. package/dist/hono/geolocation.mjs.map +1 -0
  91. package/dist/hono/handler.cjs +68 -0
  92. package/dist/hono/handler.cjs.map +1 -0
  93. package/dist/hono/handler.d.cts +13 -0
  94. package/dist/hono/handler.d.ts +13 -0
  95. package/dist/hono/handler.mjs +42 -0
  96. package/dist/hono/handler.mjs.map +1 -0
  97. package/dist/hono/index.cjs +45 -0
  98. package/dist/hono/index.cjs.map +1 -0
  99. package/dist/hono/index.d.cts +12 -0
  100. package/dist/hono/index.d.ts +12 -0
  101. package/dist/hono/index.mjs +15 -0
  102. package/dist/hono/index.mjs.map +1 -0
  103. package/dist/hono/validator.cjs +64 -0
  104. package/dist/hono/validator.cjs.map +1 -0
  105. package/dist/hono/validator.d.cts +28 -0
  106. package/dist/hono/validator.d.ts +28 -0
  107. package/dist/hono/validator.mjs +38 -0
  108. package/dist/hono/validator.mjs.map +1 -0
  109. package/dist/index-BnPgRQDl.d.cts +129 -0
  110. package/dist/index-BnPgRQDl.d.ts +129 -0
  111. package/dist/index.cjs +91 -0
  112. package/dist/index.cjs.map +1 -0
  113. package/dist/index.d.cts +18 -0
  114. package/dist/index.d.ts +18 -0
  115. package/dist/index.mjs +46 -0
  116. package/dist/index.mjs.map +1 -0
  117. package/dist/iso/iso_3601_1.cjs +292 -0
  118. package/dist/iso/iso_3601_1.cjs.map +1 -0
  119. package/dist/iso/iso_3601_1.d.cts +9 -0
  120. package/dist/iso/iso_3601_1.d.ts +9 -0
  121. package/dist/iso/iso_3601_1.mjs +267 -0
  122. package/dist/iso/iso_3601_1.mjs.map +1 -0
  123. package/dist/max-length/index.cjs +94 -0
  124. package/dist/max-length/index.cjs.map +1 -0
  125. package/dist/max-length/index.d.cts +1 -0
  126. package/dist/max-length/index.d.ts +1 -0
  127. package/dist/max-length/index.mjs +48 -0
  128. package/dist/max-length/index.mjs.map +1 -0
  129. package/dist/message.cjs +32 -0
  130. package/dist/message.cjs.map +1 -0
  131. package/dist/message.d.cts +3 -0
  132. package/dist/message.d.ts +3 -0
  133. package/dist/message.mjs +7 -0
  134. package/dist/message.mjs.map +1 -0
  135. package/dist/polyfills/index.cjs +7 -0
  136. package/dist/polyfills/index.cjs.map +1 -0
  137. package/dist/polyfills/index.d.cts +2 -0
  138. package/dist/polyfills/index.d.ts +2 -0
  139. package/dist/polyfills/index.mjs +5 -0
  140. package/dist/polyfills/index.mjs.map +1 -0
  141. package/dist/response.cjs +73 -0
  142. package/dist/response.cjs.map +1 -0
  143. package/dist/response.d.cts +65 -0
  144. package/dist/response.d.ts +65 -0
  145. package/dist/response.mjs +44 -0
  146. package/dist/response.mjs.map +1 -0
  147. package/dist/snowflake.cjs +75 -0
  148. package/dist/snowflake.cjs.map +1 -0
  149. package/dist/snowflake.d.cts +29 -0
  150. package/dist/snowflake.d.ts +29 -0
  151. package/dist/snowflake.mjs +49 -0
  152. package/dist/snowflake.mjs.map +1 -0
  153. package/dist/utils/__tests__/ip.test.cjs +38 -0
  154. package/dist/utils/__tests__/ip.test.cjs.map +1 -0
  155. package/dist/utils/__tests__/ip.test.d.cts +2 -0
  156. package/dist/utils/__tests__/ip.test.d.ts +2 -0
  157. package/dist/utils/__tests__/ip.test.mjs +36 -0
  158. package/dist/utils/__tests__/ip.test.mjs.map +1 -0
  159. package/dist/utils/invariant.cjs +37 -0
  160. package/dist/utils/invariant.cjs.map +1 -0
  161. package/dist/utils/invariant.d.cts +3 -0
  162. package/dist/utils/invariant.d.ts +3 -0
  163. package/dist/utils/invariant.mjs +12 -0
  164. package/dist/utils/invariant.mjs.map +1 -0
  165. package/dist/utils/ip.cjs +53 -0
  166. package/dist/utils/ip.cjs.map +1 -0
  167. package/dist/utils/ip.d.cts +3 -0
  168. package/dist/utils/ip.d.ts +3 -0
  169. package/dist/utils/ip.mjs +28 -0
  170. package/dist/utils/ip.mjs.map +1 -0
  171. package/dist/utils/promise.cjs +47 -0
  172. package/dist/utils/promise.cjs.map +1 -0
  173. package/dist/utils/promise.d.cts +3 -0
  174. package/dist/utils/promise.d.ts +3 -0
  175. package/dist/utils/promise.mjs +22 -0
  176. package/dist/utils/promise.mjs.map +1 -0
  177. package/dist/utils/string.cjs +33 -0
  178. package/dist/utils/string.cjs.map +1 -0
  179. package/dist/utils/string.d.cts +6 -0
  180. package/dist/utils/string.d.ts +6 -0
  181. package/dist/utils/string.mjs +8 -0
  182. package/dist/utils/string.mjs.map +1 -0
  183. package/dist/utils/timing.cjs +74 -0
  184. package/dist/utils/timing.cjs.map +1 -0
  185. package/dist/utils/timing.d.cts +13 -0
  186. package/dist/utils/timing.d.ts +13 -0
  187. package/dist/utils/timing.mjs +49 -0
  188. package/dist/utils/timing.mjs.map +1 -0
  189. package/dist/utils/token-bucket.cjs +73 -0
  190. package/dist/utils/token-bucket.cjs.map +1 -0
  191. package/dist/utils/token-bucket.d.cts +20 -0
  192. package/dist/utils/token-bucket.d.ts +20 -0
  193. package/dist/utils/token-bucket.mjs +48 -0
  194. package/dist/utils/token-bucket.mjs.map +1 -0
  195. package/dist/vaild.cjs +51 -0
  196. package/dist/vaild.cjs.map +1 -0
  197. package/dist/vaild.d.cts +13 -0
  198. package/dist/vaild.d.ts +13 -0
  199. package/dist/vaild.mjs +26 -0
  200. package/dist/vaild.mjs.map +1 -0
  201. package/dist/webhook/index.cjs +77 -0
  202. package/dist/webhook/index.cjs.map +1 -0
  203. package/dist/webhook/index.d.cts +10 -0
  204. package/dist/webhook/index.d.ts +10 -0
  205. package/dist/webhook/index.mjs +52 -0
  206. package/dist/webhook/index.mjs.map +1 -0
  207. package/package.json +3 -3
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+
3
+ // src/hono/__tests__/csrf.test.ts
4
+ var import_hono = require("hono");
5
+ var import_csrf = require("../csrf.cjs");
6
+ var import_handler = require("../handler.cjs");
7
+ describe("CSRF Protection", () => {
8
+ let app;
9
+ beforeEach(() => {
10
+ app = new import_hono.Hono();
11
+ app.onError(import_handler.errorHandler);
12
+ });
13
+ it("should allow GET requests without CSRF token", async () => {
14
+ app.use((0, import_csrf.csrf)());
15
+ app.get("/test", (c) => c.text("OK"));
16
+ const res = await app.request("/test");
17
+ expect(res.status).toBe(200);
18
+ expect(await res.text()).toBe("OK");
19
+ });
20
+ it("should allow HEAD requests without CSRF token", async () => {
21
+ app.use((0, import_csrf.csrf)());
22
+ app.all("/test", (c) => c.text("OK"));
23
+ const res = await app.request("/test", { method: "HEAD" });
24
+ expect(res.status).toBe(200);
25
+ });
26
+ it("should allow OPTIONS requests without CSRF token", async () => {
27
+ app.use((0, import_csrf.csrf)());
28
+ app.options("/test", (c) => c.text("OK"));
29
+ const res = await app.request("/test", { method: "OPTIONS" });
30
+ expect(res.status).toBe(200);
31
+ });
32
+ it("should reject POST requests without CSRF token", async () => {
33
+ app.use((0, import_csrf.csrf)());
34
+ app.post("/test", (c) => c.text("OK"));
35
+ const res = await app.request("/test", { method: "POST" });
36
+ expect(res.status).toBe(403);
37
+ });
38
+ it("should reject POST requests with mismatched tokens", async () => {
39
+ app.use((0, import_csrf.csrf)());
40
+ app.post("/test", (c) => c.text("OK"));
41
+ const res = await app.request("/test", {
42
+ method: "POST",
43
+ headers: { "X-XSRF-TOKEN": "header-token", Cookie: "XSRF-TOKEN=cookie-token" }
44
+ });
45
+ expect(res.status).toBe(403);
46
+ });
47
+ it("should allow POST requests with matching tokens", async () => {
48
+ app.use((0, import_csrf.csrf)());
49
+ app.post("/test", (c) => c.text("OK"));
50
+ const res = await app.request("/test", {
51
+ method: "POST",
52
+ headers: {
53
+ "X-XSRF-TOKEN": "matching-token",
54
+ Cookie: "XSRF-TOKEN=matching-token"
55
+ }
56
+ });
57
+ expect(res.status).toBe(200);
58
+ expect(await res.text()).toBe("OK");
59
+ });
60
+ it("should use custom cookie and header names", async () => {
61
+ app.use((0, import_csrf.csrf)({ cookieName: "csrf-token", headerName: "X-CSRF-Token" }));
62
+ app.post("/test", (c) => c.text("OK"));
63
+ const res = await app.request("/test", {
64
+ method: "POST",
65
+ headers: {
66
+ "X-CSRF-Token": "test-token",
67
+ Cookie: "csrf-token=test-token"
68
+ }
69
+ });
70
+ expect(res.status).toBe(200);
71
+ });
72
+ it("should ignore specified paths", async () => {
73
+ app.use((0, import_csrf.csrf)({ ignores: [{ path: "/webhook/*", methods: ["POST"] }] }));
74
+ app.post("/webhook/stripe", (c) => c.text("OK"));
75
+ app.post("/api/data", (c) => c.text("OK"));
76
+ const webhookRes = await app.request("/webhook/stripe", { method: "POST" });
77
+ expect(webhookRes.status).toBe(200);
78
+ const apiRes = await app.request("/api/data", { method: "POST" });
79
+ expect(apiRes.status).toBe(403);
80
+ });
81
+ it("should ignore all methods for a path when methods not specified", async () => {
82
+ app.use((0, import_csrf.csrf)({ ignores: [{ path: "/auth/apple/callback" }] }));
83
+ app.post("/auth/apple/callback", (c) => c.text("OK"));
84
+ app.put("/auth/apple/callback", (c) => c.text("OK"));
85
+ const postRes = await app.request("/auth/apple/callback", { method: "POST" });
86
+ expect(postRes.status).toBe(200);
87
+ const putRes = await app.request("/auth/apple/callback", { method: "PUT" });
88
+ expect(putRes.status).toBe(200);
89
+ });
90
+ it("should handle empty tokens safely", async () => {
91
+ app.use((0, import_csrf.csrf)());
92
+ app.post("/test", (c) => c.text("OK"));
93
+ const res = await app.request("/test", {
94
+ method: "POST",
95
+ headers: { "X-XSRF-TOKEN": "", Cookie: "XSRF-TOKEN=" }
96
+ });
97
+ expect(res.status).toBe(403);
98
+ });
99
+ it("should handle missing cookie", async () => {
100
+ app.use((0, import_csrf.csrf)());
101
+ app.post("/test", (c) => c.text("OK"));
102
+ const res = await app.request("/test", {
103
+ method: "POST",
104
+ headers: { "X-XSRF-TOKEN": "token" }
105
+ });
106
+ expect(res.status).toBe(403);
107
+ });
108
+ it("should handle missing header", async () => {
109
+ app.use((0, import_csrf.csrf)());
110
+ app.post("/test", (c) => c.text("OK"));
111
+ const res = await app.request("/test", {
112
+ method: "POST",
113
+ headers: { Cookie: "XSRF-TOKEN=token" }
114
+ });
115
+ expect(res.status).toBe(403);
116
+ });
117
+ it("should use custom error message", async () => {
118
+ app.use((0, import_csrf.csrf)({ errorMessage: "Custom CSRF error" }));
119
+ app.post("/test", (c) => c.text("OK"));
120
+ const res = await app.request("/test", { method: "POST" });
121
+ expect(res.status).toBe(403);
122
+ const body = await res.json();
123
+ expect(body.error.message).toBe("Custom CSRF error");
124
+ });
125
+ it("should work with custom safe methods", async () => {
126
+ app.use((0, import_csrf.csrf)({ safeMethods: ["GET"] }));
127
+ app.all("/test", (c) => c.text("OK"));
128
+ const res = await app.request("/test", { method: "HEAD" });
129
+ expect(res.status).toBe(403);
130
+ });
131
+ it("should handle complex ignore patterns", async () => {
132
+ app.use(
133
+ (0, import_csrf.csrf)({
134
+ ignores: [
135
+ { path: "/api/v1/*", methods: ["GET", "POST"] },
136
+ { path: "/api/v2/*", methods: ["POST"] },
137
+ { path: "/public/*" }
138
+ // All methods
139
+ ]
140
+ })
141
+ );
142
+ app.get("/api/v1/users", (c) => c.text("OK"));
143
+ app.post("/api/v1/users", (c) => c.text("OK"));
144
+ app.put("/api/v1/users", (c) => c.text("OK"));
145
+ app.post("/api/v2/users", (c) => c.text("OK"));
146
+ app.get("/api/v2/users", (c) => c.text("OK"));
147
+ app.post("/public/data", (c) => c.text("OK"));
148
+ let res = await app.request("/api/v1/users", { method: "GET" });
149
+ expect(res.status).toBe(200);
150
+ res = await app.request("/api/v1/users", { method: "POST" });
151
+ expect(res.status).toBe(200);
152
+ res = await app.request("/api/v1/users", { method: "PUT" });
153
+ expect(res.status).toBe(403);
154
+ res = await app.request("/api/v2/users", { method: "POST" });
155
+ expect(res.status).toBe(200);
156
+ res = await app.request("/api/v2/users", { method: "GET" });
157
+ expect(res.status).toBe(200);
158
+ res = await app.request("/public/data", { method: "POST" });
159
+ expect(res.status).toBe(200);
160
+ });
161
+ });
162
+ //# sourceMappingURL=csrf.test.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/hono/__tests__/csrf.test.ts"],"sourcesContent":["import { Hono } from 'hono';\nimport { csrf } from '../csrf';\nimport { errorHandler, type Env } from '../handler';\n\ndescribe('CSRF Protection', () => {\n let app: Hono<Env>;\n\n beforeEach(() => {\n app = new Hono();\n app.onError(errorHandler);\n });\n\n it('should allow GET requests without CSRF token', async () => {\n app.use(csrf());\n app.get('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test');\n expect(res.status).toBe(200);\n expect(await res.text()).toBe('OK');\n });\n\n it('should allow HEAD requests without CSRF token', async () => {\n app.use(csrf());\n app.all('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', { method: 'HEAD' });\n expect(res.status).toBe(200);\n });\n\n it('should allow OPTIONS requests without CSRF token', async () => {\n app.use(csrf());\n app.options('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', { method: 'OPTIONS' });\n expect(res.status).toBe(200);\n });\n\n it('should reject POST requests without CSRF token', async () => {\n app.use(csrf());\n app.post('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', { method: 'POST' });\n expect(res.status).toBe(403);\n });\n\n it('should reject POST requests with mismatched tokens', async () => {\n app.use(csrf());\n app.post('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', {\n method: 'POST',\n headers: { 'X-XSRF-TOKEN': 'header-token', Cookie: 'XSRF-TOKEN=cookie-token' },\n });\n expect(res.status).toBe(403);\n });\n\n it('should allow POST requests with matching tokens', async () => {\n app.use(csrf());\n app.post('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', {\n method: 'POST',\n headers: {\n 'X-XSRF-TOKEN': 'matching-token',\n Cookie: 'XSRF-TOKEN=matching-token',\n },\n });\n expect(res.status).toBe(200);\n expect(await res.text()).toBe('OK');\n });\n\n it('should use custom cookie and header names', async () => {\n app.use(csrf({ cookieName: 'csrf-token', headerName: 'X-CSRF-Token' }));\n app.post('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', {\n method: 'POST',\n headers: {\n 'X-CSRF-Token': 'test-token',\n Cookie: 'csrf-token=test-token',\n },\n });\n expect(res.status).toBe(200);\n });\n\n it('should ignore specified paths', async () => {\n app.use(csrf({ ignores: [{ path: '/webhook/*', methods: ['POST'] }] }));\n app.post('/webhook/stripe', (c) => c.text('OK'));\n app.post('/api/data', (c) => c.text('OK'));\n\n // Ignored path should work without CSRF token\n const webhookRes = await app.request('/webhook/stripe', { method: 'POST' });\n expect(webhookRes.status).toBe(200);\n\n // Non-ignored path should require CSRF token\n const apiRes = await app.request('/api/data', { method: 'POST' });\n expect(apiRes.status).toBe(403);\n });\n\n it('should ignore all methods for a path when methods not specified', async () => {\n app.use(csrf({ ignores: [{ path: '/auth/apple/callback' }] }));\n app.post('/auth/apple/callback', (c) => c.text('OK'));\n app.put('/auth/apple/callback', (c) => c.text('OK'));\n\n const postRes = await app.request('/auth/apple/callback', { method: 'POST' });\n expect(postRes.status).toBe(200);\n\n const putRes = await app.request('/auth/apple/callback', { method: 'PUT' });\n expect(putRes.status).toBe(200);\n });\n\n it('should handle empty tokens safely', async () => {\n app.use(csrf());\n app.post('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', {\n method: 'POST',\n headers: { 'X-XSRF-TOKEN': '', Cookie: 'XSRF-TOKEN=' },\n });\n expect(res.status).toBe(403);\n });\n\n it('should handle missing cookie', async () => {\n app.use(csrf());\n app.post('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', {\n method: 'POST',\n headers: { 'X-XSRF-TOKEN': 'token' },\n });\n expect(res.status).toBe(403);\n });\n\n it('should handle missing header', async () => {\n app.use(csrf());\n app.post('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', {\n method: 'POST',\n headers: { Cookie: 'XSRF-TOKEN=token' },\n });\n expect(res.status).toBe(403);\n });\n\n it('should use custom error message', async () => {\n app.use(csrf({ errorMessage: 'Custom CSRF error' }));\n app.post('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', { method: 'POST' });\n expect(res.status).toBe(403);\n const body = await res.json();\n expect(body.error.message).toBe('Custom CSRF error');\n });\n\n it('should work with custom safe methods', async () => {\n app.use(csrf({ safeMethods: ['GET'] }));\n app.all('/test', (c) => c.text('OK'));\n\n // HEAD is no longer safe, should require CSRF token\n const res = await app.request('/test', { method: 'HEAD' });\n expect(res.status).toBe(403);\n });\n\n it('should handle complex ignore patterns', async () => {\n app.use(\n csrf({\n ignores: [\n { path: '/api/v1/*', methods: ['GET', 'POST'] },\n { path: '/api/v2/*', methods: ['POST'] },\n { path: '/public/*' }, // All methods\n ],\n })\n );\n\n app.get('/api/v1/users', (c) => c.text('OK'));\n app.post('/api/v1/users', (c) => c.text('OK'));\n app.put('/api/v1/users', (c) => c.text('OK'));\n app.post('/api/v2/users', (c) => c.text('OK'));\n app.get('/api/v2/users', (c) => c.text('OK'));\n app.post('/public/data', (c) => c.text('OK'));\n\n // Ignored GET and POST for /api/v1/*\n let res = await app.request('/api/v1/users', { method: 'GET' });\n expect(res.status).toBe(200);\n\n res = await app.request('/api/v1/users', { method: 'POST' });\n expect(res.status).toBe(200);\n\n // PUT not ignored for /api/v1/*\n res = await app.request('/api/v1/users', { method: 'PUT' });\n expect(res.status).toBe(403);\n\n // Only POST ignored for /api/v2/*\n res = await app.request('/api/v2/users', { method: 'POST' });\n expect(res.status).toBe(200);\n\n // GET not ignored for /api/v2/* (but GET is safe by default)\n res = await app.request('/api/v2/users', { method: 'GET' });\n expect(res.status).toBe(200);\n\n //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AG;AAAA,EAC7B,CAAC;AACH,CAAC;","names":[]}
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,160 @@
1
+ // src/hono/__tests__/csrf.test.ts
2
+ import { Hono } from "hono";
3
+ import { csrf } from "../csrf.mjs";
4
+ import { errorHandler } from "../handler.mjs";
5
+ describe("CSRF Protection", () => {
6
+ let app;
7
+ beforeEach(() => {
8
+ app = new Hono();
9
+ app.onError(errorHandler);
10
+ });
11
+ it("should allow GET requests without CSRF token", async () => {
12
+ app.use(csrf());
13
+ app.get("/test", (c) => c.text("OK"));
14
+ const res = await app.request("/test");
15
+ expect(res.status).toBe(200);
16
+ expect(await res.text()).toBe("OK");
17
+ });
18
+ it("should allow HEAD requests without CSRF token", async () => {
19
+ app.use(csrf());
20
+ app.all("/test", (c) => c.text("OK"));
21
+ const res = await app.request("/test", { method: "HEAD" });
22
+ expect(res.status).toBe(200);
23
+ });
24
+ it("should allow OPTIONS requests without CSRF token", async () => {
25
+ app.use(csrf());
26
+ app.options("/test", (c) => c.text("OK"));
27
+ const res = await app.request("/test", { method: "OPTIONS" });
28
+ expect(res.status).toBe(200);
29
+ });
30
+ it("should reject POST requests without CSRF token", async () => {
31
+ app.use(csrf());
32
+ app.post("/test", (c) => c.text("OK"));
33
+ const res = await app.request("/test", { method: "POST" });
34
+ expect(res.status).toBe(403);
35
+ });
36
+ it("should reject POST requests with mismatched tokens", async () => {
37
+ app.use(csrf());
38
+ app.post("/test", (c) => c.text("OK"));
39
+ const res = await app.request("/test", {
40
+ method: "POST",
41
+ headers: { "X-XSRF-TOKEN": "header-token", Cookie: "XSRF-TOKEN=cookie-token" }
42
+ });
43
+ expect(res.status).toBe(403);
44
+ });
45
+ it("should allow POST requests with matching tokens", async () => {
46
+ app.use(csrf());
47
+ app.post("/test", (c) => c.text("OK"));
48
+ const res = await app.request("/test", {
49
+ method: "POST",
50
+ headers: {
51
+ "X-XSRF-TOKEN": "matching-token",
52
+ Cookie: "XSRF-TOKEN=matching-token"
53
+ }
54
+ });
55
+ expect(res.status).toBe(200);
56
+ expect(await res.text()).toBe("OK");
57
+ });
58
+ it("should use custom cookie and header names", async () => {
59
+ app.use(csrf({ cookieName: "csrf-token", headerName: "X-CSRF-Token" }));
60
+ app.post("/test", (c) => c.text("OK"));
61
+ const res = await app.request("/test", {
62
+ method: "POST",
63
+ headers: {
64
+ "X-CSRF-Token": "test-token",
65
+ Cookie: "csrf-token=test-token"
66
+ }
67
+ });
68
+ expect(res.status).toBe(200);
69
+ });
70
+ it("should ignore specified paths", async () => {
71
+ app.use(csrf({ ignores: [{ path: "/webhook/*", methods: ["POST"] }] }));
72
+ app.post("/webhook/stripe", (c) => c.text("OK"));
73
+ app.post("/api/data", (c) => c.text("OK"));
74
+ const webhookRes = await app.request("/webhook/stripe", { method: "POST" });
75
+ expect(webhookRes.status).toBe(200);
76
+ const apiRes = await app.request("/api/data", { method: "POST" });
77
+ expect(apiRes.status).toBe(403);
78
+ });
79
+ it("should ignore all methods for a path when methods not specified", async () => {
80
+ app.use(csrf({ ignores: [{ path: "/auth/apple/callback" }] }));
81
+ app.post("/auth/apple/callback", (c) => c.text("OK"));
82
+ app.put("/auth/apple/callback", (c) => c.text("OK"));
83
+ const postRes = await app.request("/auth/apple/callback", { method: "POST" });
84
+ expect(postRes.status).toBe(200);
85
+ const putRes = await app.request("/auth/apple/callback", { method: "PUT" });
86
+ expect(putRes.status).toBe(200);
87
+ });
88
+ it("should handle empty tokens safely", async () => {
89
+ app.use(csrf());
90
+ app.post("/test", (c) => c.text("OK"));
91
+ const res = await app.request("/test", {
92
+ method: "POST",
93
+ headers: { "X-XSRF-TOKEN": "", Cookie: "XSRF-TOKEN=" }
94
+ });
95
+ expect(res.status).toBe(403);
96
+ });
97
+ it("should handle missing cookie", async () => {
98
+ app.use(csrf());
99
+ app.post("/test", (c) => c.text("OK"));
100
+ const res = await app.request("/test", {
101
+ method: "POST",
102
+ headers: { "X-XSRF-TOKEN": "token" }
103
+ });
104
+ expect(res.status).toBe(403);
105
+ });
106
+ it("should handle missing header", async () => {
107
+ app.use(csrf());
108
+ app.post("/test", (c) => c.text("OK"));
109
+ const res = await app.request("/test", {
110
+ method: "POST",
111
+ headers: { Cookie: "XSRF-TOKEN=token" }
112
+ });
113
+ expect(res.status).toBe(403);
114
+ });
115
+ it("should use custom error message", async () => {
116
+ app.use(csrf({ errorMessage: "Custom CSRF error" }));
117
+ app.post("/test", (c) => c.text("OK"));
118
+ const res = await app.request("/test", { method: "POST" });
119
+ expect(res.status).toBe(403);
120
+ const body = await res.json();
121
+ expect(body.error.message).toBe("Custom CSRF error");
122
+ });
123
+ it("should work with custom safe methods", async () => {
124
+ app.use(csrf({ safeMethods: ["GET"] }));
125
+ app.all("/test", (c) => c.text("OK"));
126
+ const res = await app.request("/test", { method: "HEAD" });
127
+ expect(res.status).toBe(403);
128
+ });
129
+ it("should handle complex ignore patterns", async () => {
130
+ app.use(
131
+ csrf({
132
+ ignores: [
133
+ { path: "/api/v1/*", methods: ["GET", "POST"] },
134
+ { path: "/api/v2/*", methods: ["POST"] },
135
+ { path: "/public/*" }
136
+ // All methods
137
+ ]
138
+ })
139
+ );
140
+ app.get("/api/v1/users", (c) => c.text("OK"));
141
+ app.post("/api/v1/users", (c) => c.text("OK"));
142
+ app.put("/api/v1/users", (c) => c.text("OK"));
143
+ app.post("/api/v2/users", (c) => c.text("OK"));
144
+ app.get("/api/v2/users", (c) => c.text("OK"));
145
+ app.post("/public/data", (c) => c.text("OK"));
146
+ let res = await app.request("/api/v1/users", { method: "GET" });
147
+ expect(res.status).toBe(200);
148
+ res = await app.request("/api/v1/users", { method: "POST" });
149
+ expect(res.status).toBe(200);
150
+ res = await app.request("/api/v1/users", { method: "PUT" });
151
+ expect(res.status).toBe(403);
152
+ res = await app.request("/api/v2/users", { method: "POST" });
153
+ expect(res.status).toBe(200);
154
+ res = await app.request("/api/v2/users", { method: "GET" });
155
+ expect(res.status).toBe(200);
156
+ res = await app.request("/public/data", { method: "POST" });
157
+ expect(res.status).toBe(200);
158
+ });
159
+ });
160
+ //# sourceMappingURL=csrf.test.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/hono/__tests__/csrf.test.ts"],"sourcesContent":["import { Hono } from 'hono';\nimport { csrf } from '../csrf';\nimport { errorHandler, type Env } from '../handler';\n\ndescribe('CSRF Protection', () => {\n let app: Hono<Env>;\n\n beforeEach(() => {\n app = new Hono();\n app.onError(errorHandler);\n });\n\n it('should allow GET requests without CSRF token', async () => {\n app.use(csrf());\n app.get('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test');\n expect(res.status).toBe(200);\n expect(await res.text()).toBe('OK');\n });\n\n it('should allow HEAD requests without CSRF token', async () => {\n app.use(csrf());\n app.all('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', { method: 'HEAD' });\n expect(res.status).toBe(200);\n });\n\n it('should allow OPTIONS requests without CSRF token', async () => {\n app.use(csrf());\n app.options('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', { method: 'OPTIONS' });\n expect(res.status).toBe(200);\n });\n\n it('should reject POST requests without CSRF token', async () => {\n app.use(csrf());\n app.post('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', { method: 'POST' });\n expect(res.status).toBe(403);\n });\n\n it('should reject POST requests with mismatched tokens', async () => {\n app.use(csrf());\n app.post('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', {\n method: 'POST',\n headers: { 'X-XSRF-TOKEN': 'header-token', Cookie: 'XSRF-TOKEN=cookie-token' },\n });\n expect(res.status).toBe(403);\n });\n\n it('should allow POST requests with matching tokens', async () => {\n app.use(csrf());\n app.post('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', {\n method: 'POST',\n headers: {\n 'X-XSRF-TOKEN': 'matching-token',\n Cookie: 'XSRF-TOKEN=matching-token',\n },\n });\n expect(res.status).toBe(200);\n expect(await res.text()).toBe('OK');\n });\n\n it('should use custom cookie and header names', async () => {\n app.use(csrf({ cookieName: 'csrf-token', headerName: 'X-CSRF-Token' }));\n app.post('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', {\n method: 'POST',\n headers: {\n 'X-CSRF-Token': 'test-token',\n Cookie: 'csrf-token=test-token',\n },\n });\n expect(res.status).toBe(200);\n });\n\n it('should ignore specified paths', async () => {\n app.use(csrf({ ignores: [{ path: '/webhook/*', methods: ['POST'] }] }));\n app.post('/webhook/stripe', (c) => c.text('OK'));\n app.post('/api/data', (c) => c.text('OK'));\n\n // Ignored path should work without CSRF token\n const webhookRes = await app.request('/webhook/stripe', { method: 'POST' });\n expect(webhookRes.status).toBe(200);\n\n // Non-ignored path should require CSRF token\n const apiRes = await app.request('/api/data', { method: 'POST' });\n expect(apiRes.status).toBe(403);\n });\n\n it('should ignore all methods for a path when methods not specified', async () => {\n app.use(csrf({ ignores: [{ path: '/auth/apple/callback' }] }));\n app.post('/auth/apple/callback', (c) => c.text('OK'));\n app.put('/auth/apple/callback', (c) => c.text('OK'));\n\n const postRes = await app.request('/auth/apple/callback', { method: 'POST' });\n expect(postRes.status).toBe(200);\n\n const putRes = await app.request('/auth/apple/callback', { method: 'PUT' });\n expect(putRes.status).toBe(200);\n });\n\n it('should handle empty tokens safely', async () => {\n app.use(csrf());\n app.post('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', {\n method: 'POST',\n headers: { 'X-XSRF-TOKEN': '', Cookie: 'XSRF-TOKEN=' },\n });\n expect(res.status).toBe(403);\n });\n\n it('should handle missing cookie', async () => {\n app.use(csrf());\n app.post('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', {\n method: 'POST',\n headers: { 'X-XSRF-TOKEN': 'token' },\n });\n expect(res.status).toBe(403);\n });\n\n it('should handle missing header', async () => {\n app.use(csrf());\n app.post('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', {\n method: 'POST',\n headers: { Cookie: 'XSRF-TOKEN=token' },\n });\n expect(res.status).toBe(403);\n });\n\n it('should use custom error message', async () => {\n app.use(csrf({ errorMessage: 'Custom CSRF error' }));\n app.post('/test', (c) => c.text('OK'));\n\n const res = await app.request('/test', { method: 'POST' });\n expect(res.status).toBe(403);\n const body = await res.json();\n expect(body.error.message).toBe('Custom CSRF error');\n });\n\n it('should work with custom safe methods', async () => {\n app.use(csrf({ safeMethods: ['GET'] }));\n app.all('/test', (c) => c.text('OK'));\n\n // HEAD is no longer safe, should require CSRF token\n const res = await app.request('/test', { method: 'HEAD' });\n expect(res.status).toBe(403);\n });\n\n it('should handle complex ignore patterns', async () => {\n app.use(\n csrf({\n ignores: [\n { path: '/api/v1/*', methods: ['GET', 'POST'] },\n { path: '/api/v2/*', methods: ['POST'] },\n { path: '/public/*' }, // All methods\n ],\n })\n );\n\n app.get('/api/v1/users', (c) => c.text('OK'));\n app.post('/api/v1/users', (c) => c.text('OK'));\n app.put('/api/v1/users', (c) => c.text('OK'));\n app.post('/api/v2/users', (c) => c.text('OK'));\n app.get('/api/v2/users', (c) => c.text('OK'));\n app.post('/public/data', (c) => c.text('OK'));\n\n // Ignored GET and POST for /api/v1/*\n let res = await app.request('/api/v1/users', { method: 'GET' });\n expect(res.status).toBe(200);\n\n res = await app.request('/api/v1/users', { method: 'POST' });\n expect(res.status).toBe(200);\n\n // PUT not ignored for /api/v1/*\n res = await app.request('/api/v1/users', { method: 'PUT' });\n expect(res.status).toBe(403);\n\n // Only POST ignored for /api/v2/*\n res = await app.request('/api/v2/users', { method: 'POST' });\n expect(res.status).toBe(200);\n\n // GET not ignored for /api/v2/* (but GET is safe by default)\n res = await app.request('/api/v2/users', { method: 'GET' });\n expect(res.status).toBe(200);\n\n // All methods ignored for /public/*\n res = await app.request('/public/data', { method: 'POST' });\n expect(res.status).toBe(200);\n });\n});\n"],"mappings":";AAAA,SAAS,YAAY;AACrB,SAAS,YAAY;AACrB,SAAS,oBAA8B;AAEvC,SAAS,mBAAmB,MAAM;AAChC,MAAI;AAEJ,aAAW,MAAM;AACf,UAAM,IAAI,KAA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MAAM,EAAE,KAAK,IAAI,CAAC;AAC5C,QAAI,KAAK,iBAAiB,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC;AAC7C,QAAI,IAAI,iBAAiB,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC;AAC5C,QAAI,KAAK,iBAAiB,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC;AAC7C,QAAI,IAAI,iBAAiB,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC;AAC5C,QAAI,KAAK,gBAAgB,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC;AAG5C,QAAI,MAAM,MAAM,IAAI,QAAQ,iBAAiB,EAAE,QAAQ,MAAM,CAAC;AAC9D,WAAO,IAAI,MAAM,EAAE,KAAK,GAAG;AAE3B,UAAM,MAAM,IAAI,QAAQ,iBAAiB,EAAE,QAAQ,OAAO,CAAC;AAC3D,WAAO,IAAI,MAAM,EAAE,KAAK,GAAG;AAG3B,UAAM,MAAM,IAAI,QAAQ,iBAAiB,EAAE,QAAQ,MAAM,CAAC;AAC1D,WAAO,IAAI,MAAM,EAAE,KAAK,GAAG;AAG3B,UAAM,MAAM,IAAI,QAAQ,iBAAiB,EAAE,QAAQ,OAAO,CAAC;AAC3D,WAAO,IAAI,MAAM,EAAE,KAAK,GAAG;AAG3B,UAAM,MAAM,IAAI,QAAQ,iBAAiB,EAAE,QAAQ,MAAM,CAAC;AAC1D,WAAO,IAAI,MAAM,EAAE,KAAK,GAAG;AAG3B,UAAM,MAAM,IAAI,QAAQ,gBAAgB,EAAE,QAAQ,OAAO,CAAC;AAC1D,WAAO,IAAI,MAAM,EAAE,KAAK,GAAG;AAAA,EAC7B,CAAC;AACH,CAAC;","names":[]}
@@ -0,0 +1,67 @@
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/hono/authorizer.ts
21
+ var authorizer_exports = {};
22
+ __export(authorizer_exports, {
23
+ authorizer: () => authorizer
24
+ });
25
+ module.exports = __toCommonJS(authorizer_exports);
26
+ var import_router = require("hono/router");
27
+ var import_reg_exp_router = require("hono/router/reg-exp-router");
28
+ var import_smart_router = require("hono/router/smart-router");
29
+ var import_trie_router = require("hono/router/trie-router");
30
+ var import_status = require("../error/status.cjs");
31
+ function authorizer({
32
+ auth,
33
+ errorMessage = "Unauthorized, please login to continue.",
34
+ rules = []
35
+ }) {
36
+ const router = new import_smart_router.SmartRouter({ routers: [new import_reg_exp_router.RegExpRouter(), new import_trie_router.TrieRouter()] });
37
+ for (const rule of rules) {
38
+ if (typeof rule === "string") {
39
+ router.add(import_router.METHOD_NAME_ALL, rule, null);
40
+ } else if (rule.methods && rule.methods.length > 0) {
41
+ for (const method of rule.methods) {
42
+ router.add(method, rule.path, null);
43
+ }
44
+ } else {
45
+ router.add(import_router.METHOD_NAME_ALL, rule.path, null);
46
+ }
47
+ }
48
+ return async (c, next) => {
49
+ if (c.req.method === "OPTIONS") {
50
+ await next();
51
+ return;
52
+ }
53
+ const [matched] = router.match(c.req.method, c.req.path);
54
+ if (matched.length === 0) {
55
+ await next();
56
+ return;
57
+ }
58
+ const authenticated = await auth.isAuthenticated(c.req.raw);
59
+ if (!authenticated) throw import_status.Status.unauthorized(errorMessage).error();
60
+ await next();
61
+ };
62
+ }
63
+ // Annotate the CommonJS export names for ESM import in node:
64
+ 0 && (module.exports = {
65
+ authorizer
66
+ });
67
+ //# sourceMappingURL=authorizer.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/hono/authorizer.ts"],"sourcesContent":["import { METHOD_NAME_ALL } from 'hono/router';\nimport { RegExpRouter } from 'hono/router/reg-exp-router';\nimport { SmartRouter } from 'hono/router/smart-router';\nimport { TrieRouter } from 'hono/router/trie-router';\nimport { Status } from '../error/status';\nimport type { MiddlewareHandler } from 'hono';\n\ntype Methods = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n\ntype Auth = { isAuthenticated: (request: Request) => Promise<boolean> };\n\nexport type AuthRule = string | { path: string; methods?: [Methods, ...Methods[]] };\n\nexport interface AuthorizerConfig {\n auth: Auth;\n errorMessage?: string;\n rules?: AuthRule[];\n}\n\nexport function authorizer({\n auth,\n errorMessage = 'Unauthorized, please login to continue.',\n rules = [],\n}: AuthorizerConfig): MiddlewareHandler {\n const router = new SmartRouter<null>({ routers: [new RegExpRouter(), new TrieRouter()] });\n\n for (const rule of rules) {\n if (typeof rule === 'string') {\n router.add(METHOD_NAME_ALL, rule, null);\n } else if (rule.methods && rule.methods.length > 0) {\n for (const method of rule.methods) {\n router.add(method, rule.path, null);\n }\n } else {\n router.add(METHOD_NAME_ALL, rule.path, null);\n }\n }\n\n return async (c, next) => {\n if (c.req.method === 'OPTIONS') {\n await next();\n return;\n }\n\n const [matched] = router.match(c.req.method, c.req.path);\n if (matched.length === 0) {\n await next();\n return;\n }\n\n const authenticated = await auth.isAuthenticated(c.req.raw);\n if (!authenticated) throw Status.unauthorized(errorMessage).error();\n await next();\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAgC;AAChC,4BAA6B;AAC7B,0BAA4B;AAC5B,yBAA2B;AAC3B,oBAAuB;AAehB,SAAS,WAAW;AAAA,EACzB;AAAA,EACA,eAAe;AAAA,EACf,QAAQ,CAAC;AACX,GAAwC;AACtC,QAAM,SAAS,IAAI,gCAAkB,EAAE,SAAS,CAAC,IAAI,mCAAa,GAAG,IAAI,8BAAW,CAAC,EAAE,CAAC;AAExF,aAAW,QAAQ,OAAO;AACxB,QAAI,OAAO,SAAS,UAAU;AAC5B,aAAO,IAAI,+BAAiB,MAAM,IAAI;AAAA,IACxC,WAAW,KAAK,WAAW,KAAK,QAAQ,SAAS,GAAG;AAClD,iBAAW,UAAU,KAAK,SAAS;AACjC,eAAO,IAAI,QAAQ,KAAK,MAAM,IAAI;AAAA,MACpC;AAAA,IACF,OAAO;AACL,aAAO,IAAI,+BAAiB,KAAK,MAAM,IAAI;AAAA,IAC7C;AAAA,EACF;AAEA,SAAO,OAAO,GAAG,SAAS;AACxB,QAAI,EAAE,IAAI,WAAW,WAAW;AAC9B,YAAM,KAAK;AACX;AAAA,IACF;AAEA,UAAM,CAAC,OAAO,IAAI,OAAO,MAAM,EAAE,IAAI,QAAQ,EAAE,IAAI,IAAI;AACvD,QAAI,QAAQ,WAAW,GAAG;AACxB,YAAM,KAAK;AACX;AAAA,IACF;AAEA,UAAM,gBAAgB,MAAM,KAAK,gBAAgB,EAAE,IAAI,GAAG;AAC1D,QAAI,CAAC,cAAe,OAAM,qBAAO,aAAa,YAAY,EAAE,MAAM;AAClE,UAAM,KAAK;AAAA,EACb;AACF;","names":[]}
@@ -0,0 +1,18 @@
1
+ import { MiddlewareHandler } from 'hono';
2
+
3
+ type Methods = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
4
+ type Auth = {
5
+ isAuthenticated: (request: Request) => Promise<boolean>;
6
+ };
7
+ type AuthRule = string | {
8
+ path: string;
9
+ methods?: [Methods, ...Methods[]];
10
+ };
11
+ interface AuthorizerConfig {
12
+ auth: Auth;
13
+ errorMessage?: string;
14
+ rules?: AuthRule[];
15
+ }
16
+ declare function authorizer({ auth, errorMessage, rules, }: AuthorizerConfig): MiddlewareHandler;
17
+
18
+ export { type AuthRule, type AuthorizerConfig, authorizer };
@@ -0,0 +1,18 @@
1
+ import { MiddlewareHandler } from 'hono';
2
+
3
+ type Methods = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
4
+ type Auth = {
5
+ isAuthenticated: (request: Request) => Promise<boolean>;
6
+ };
7
+ type AuthRule = string | {
8
+ path: string;
9
+ methods?: [Methods, ...Methods[]];
10
+ };
11
+ interface AuthorizerConfig {
12
+ auth: Auth;
13
+ errorMessage?: string;
14
+ rules?: AuthRule[];
15
+ }
16
+ declare function authorizer({ auth, errorMessage, rules, }: AuthorizerConfig): MiddlewareHandler;
17
+
18
+ export { type AuthRule, type AuthorizerConfig, authorizer };
@@ -0,0 +1,42 @@
1
+ // src/hono/authorizer.ts
2
+ import { METHOD_NAME_ALL } from "hono/router";
3
+ import { RegExpRouter } from "hono/router/reg-exp-router";
4
+ import { SmartRouter } from "hono/router/smart-router";
5
+ import { TrieRouter } from "hono/router/trie-router";
6
+ import { Status } from "../error/status.mjs";
7
+ function authorizer({
8
+ auth,
9
+ errorMessage = "Unauthorized, please login to continue.",
10
+ rules = []
11
+ }) {
12
+ const router = new SmartRouter({ routers: [new RegExpRouter(), new TrieRouter()] });
13
+ for (const rule of rules) {
14
+ if (typeof rule === "string") {
15
+ router.add(METHOD_NAME_ALL, rule, null);
16
+ } else if (rule.methods && rule.methods.length > 0) {
17
+ for (const method of rule.methods) {
18
+ router.add(method, rule.path, null);
19
+ }
20
+ } else {
21
+ router.add(METHOD_NAME_ALL, rule.path, null);
22
+ }
23
+ }
24
+ return async (c, next) => {
25
+ if (c.req.method === "OPTIONS") {
26
+ await next();
27
+ return;
28
+ }
29
+ const [matched] = router.match(c.req.method, c.req.path);
30
+ if (matched.length === 0) {
31
+ await next();
32
+ return;
33
+ }
34
+ const authenticated = await auth.isAuthenticated(c.req.raw);
35
+ if (!authenticated) throw Status.unauthorized(errorMessage).error();
36
+ await next();
37
+ };
38
+ }
39
+ export {
40
+ authorizer
41
+ };
42
+ //# sourceMappingURL=authorizer.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/hono/authorizer.ts"],"sourcesContent":["import { METHOD_NAME_ALL } from 'hono/router';\nimport { RegExpRouter } from 'hono/router/reg-exp-router';\nimport { SmartRouter } from 'hono/router/smart-router';\nimport { TrieRouter } from 'hono/router/trie-router';\nimport { Status } from '../error/status';\nimport type { MiddlewareHandler } from 'hono';\n\ntype Methods = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n\ntype Auth = { isAuthenticated: (request: Request) => Promise<boolean> };\n\nexport type AuthRule = string | { path: string; methods?: [Methods, ...Methods[]] };\n\nexport interface AuthorizerConfig {\n auth: Auth;\n errorMessage?: string;\n rules?: AuthRule[];\n}\n\nexport function authorizer({\n auth,\n errorMessage = 'Unauthorized, please login to continue.',\n rules = [],\n}: AuthorizerConfig): MiddlewareHandler {\n const router = new SmartRouter<null>({ routers: [new RegExpRouter(), new TrieRouter()] });\n\n for (const rule of rules) {\n if (typeof rule === 'string') {\n router.add(METHOD_NAME_ALL, rule, null);\n } else if (rule.methods && rule.methods.length > 0) {\n for (const method of rule.methods) {\n router.add(method, rule.path, null);\n }\n } else {\n router.add(METHOD_NAME_ALL, rule.path, null);\n }\n }\n\n return async (c, next) => {\n if (c.req.method === 'OPTIONS') {\n await next();\n return;\n }\n\n const [matched] = router.match(c.req.method, c.req.path);\n if (matched.length === 0) {\n await next();\n return;\n }\n\n const authenticated = await auth.isAuthenticated(c.req.raw);\n if (!authenticated) throw Status.unauthorized(errorMessage).error();\n await next();\n };\n}\n"],"mappings":";AAAA,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;AAC7B,SAAS,mBAAmB;AAC5B,SAAS,kBAAkB;AAC3B,SAAS,cAAc;AAehB,SAAS,WAAW;AAAA,EACzB;AAAA,EACA,eAAe;AAAA,EACf,QAAQ,CAAC;AACX,GAAwC;AACtC,QAAM,SAAS,IAAI,YAAkB,EAAE,SAAS,CAAC,IAAI,aAAa,GAAG,IAAI,WAAW,CAAC,EAAE,CAAC;AAExF,aAAW,QAAQ,OAAO;AACxB,QAAI,OAAO,SAAS,UAAU;AAC5B,aAAO,IAAI,iBAAiB,MAAM,IAAI;AAAA,IACxC,WAAW,KAAK,WAAW,KAAK,QAAQ,SAAS,GAAG;AAClD,iBAAW,UAAU,KAAK,SAAS;AACjC,eAAO,IAAI,QAAQ,KAAK,MAAM,IAAI;AAAA,MACpC;AAAA,IACF,OAAO;AACL,aAAO,IAAI,iBAAiB,KAAK,MAAM,IAAI;AAAA,IAC7C;AAAA,EACF;AAEA,SAAO,OAAO,GAAG,SAAS;AACxB,QAAI,EAAE,IAAI,WAAW,WAAW;AAC9B,YAAM,KAAK;AACX;AAAA,IACF;AAEA,UAAM,CAAC,OAAO,IAAI,OAAO,MAAM,EAAE,IAAI,QAAQ,EAAE,IAAI,IAAI;AACvD,QAAI,QAAQ,WAAW,GAAG;AACxB,YAAM,KAAK;AACX;AAAA,IACF;AAEA,UAAM,gBAAgB,MAAM,KAAK,gBAAgB,EAAE,IAAI,GAAG;AAC1D,QAAI,CAAC,cAAe,OAAM,OAAO,aAAa,YAAY,EAAE,MAAM;AAClE,UAAM,KAAK;AAAA,EACb;AACF;","names":[]}
@@ -0,0 +1,95 @@
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/hono/csrf.ts
21
+ var csrf_exports = {};
22
+ __export(csrf_exports, {
23
+ csrf: () => csrf
24
+ });
25
+ module.exports = __toCommonJS(csrf_exports);
26
+ var import_crypto = require("crypto");
27
+ var import_cookie = require("hono/cookie");
28
+ var import_router = require("hono/router");
29
+ var import_reg_exp_router = require("hono/router/reg-exp-router");
30
+ var import_smart_router = require("hono/router/smart-router");
31
+ var import_trie_router = require("hono/router/trie-router");
32
+ var import_status = require("../error/status.cjs");
33
+ function safeCompare(a, b) {
34
+ if (typeof a !== "string" || typeof b !== "string") return false;
35
+ if (a.length === 0 || b.length === 0) return false;
36
+ const bufferA = Buffer.from(a, "utf-8");
37
+ const bufferB = Buffer.from(b, "utf-8");
38
+ if (bufferA.length !== bufferB.length) return false;
39
+ return (0, import_crypto.timingSafeEqual)(bufferA, bufferB);
40
+ }
41
+ function csrf(config = {}) {
42
+ const cookieName = config.cookieName ?? "XSRF-TOKEN";
43
+ const headerName = config.headerName ?? "X-XSRF-TOKEN";
44
+ const safeMethods = new Set(config.safeMethods ?? ["GET", "HEAD", "OPTIONS"]);
45
+ const errorMessage = config.errorMessage ?? "CSRF token validation failed";
46
+ const router = new import_smart_router.SmartRouter({
47
+ routers: [new import_reg_exp_router.RegExpRouter(), new import_trie_router.TrieRouter()]
48
+ });
49
+ if (config.ignores) {
50
+ for (const rule of config.ignores) {
51
+ if (typeof rule === "string") {
52
+ router.add(import_router.METHOD_NAME_ALL, rule, true);
53
+ } else if (rule.methods && rule.methods.length > 0) {
54
+ for (const method of rule.methods) {
55
+ router.add(method, rule.path, true);
56
+ }
57
+ } else {
58
+ router.add(import_router.METHOD_NAME_ALL, rule.path, true);
59
+ }
60
+ }
61
+ }
62
+ function shouldIgnore(method, path) {
63
+ if (safeMethods.has(method)) {
64
+ return true;
65
+ }
66
+ const [matchedAll] = router.match(import_router.METHOD_NAME_ALL, path);
67
+ if (matchedAll.length > 0) {
68
+ return true;
69
+ }
70
+ const [matchedMethod] = router.match(method, path);
71
+ return matchedMethod.length > 0;
72
+ }
73
+ return async (c, next) => {
74
+ const method = c.req.method;
75
+ const path = c.req.path;
76
+ if (shouldIgnore(method, path)) {
77
+ await next();
78
+ return;
79
+ }
80
+ const cookieToken = (0, import_cookie.getCookie)(c, cookieName);
81
+ const headerToken = c.req.header(headerName);
82
+ if (!cookieToken || !headerToken) {
83
+ throw import_status.Status.permissionDenied(errorMessage).error();
84
+ }
85
+ if (!safeCompare(cookieToken, headerToken)) {
86
+ throw import_status.Status.permissionDenied(errorMessage).error();
87
+ }
88
+ await next();
89
+ };
90
+ }
91
+ // Annotate the CommonJS export names for ESM import in node:
92
+ 0 && (module.exports = {
93
+ csrf
94
+ });
95
+ //# sourceMappingURL=csrf.cjs.map