@guren/server 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (270) hide show
  1. package/dist/{McpServiceProvider-7BB5FPF3.js → McpServiceProvider-GRDYNEQG.js} +1 -1
  2. package/dist/auth/AuthManager.d.ts +30 -0
  3. package/dist/auth/AuthenticatableModel.d.ts +25 -0
  4. package/dist/auth/RequestAuthContext.d.ts +24 -0
  5. package/dist/auth/SessionGuard.d.ts +31 -0
  6. package/dist/auth/api-token.d.ts +299 -0
  7. package/dist/auth/email-verification.d.ts +203 -0
  8. package/dist/auth/index.d.ts +18 -110
  9. package/dist/auth/index.js +3 -1
  10. package/dist/auth/oauth/index.d.ts +239 -0
  11. package/dist/auth/password/DefaultHasher.d.ts +13 -0
  12. package/dist/auth/password/NodeHasher.d.ts +22 -0
  13. package/dist/auth/password/PasswordHasher.d.ts +5 -0
  14. package/dist/auth/password/ScryptHasher.d.ts +26 -0
  15. package/dist/auth/password-reset.d.ts +91 -0
  16. package/dist/auth/providers/ModelUserProvider.d.ts +36 -0
  17. package/dist/auth/providers/UserProvider.d.ts +9 -0
  18. package/dist/auth/types.d.ts +102 -0
  19. package/dist/auth/utils.d.ts +39 -0
  20. package/dist/{Gate-CynjZCtS.d.ts → authorization/Gate.d.ts} +30 -111
  21. package/dist/authorization/Policy.d.ts +77 -0
  22. package/dist/authorization/index.d.ts +5 -129
  23. package/dist/authorization/index.js +3 -1
  24. package/dist/authorization/middleware.d.ts +49 -0
  25. package/dist/authorization/types.d.ts +108 -0
  26. package/dist/broadcasting/BroadcastManager.d.ts +205 -0
  27. package/dist/broadcasting/channels/Channel.d.ts +28 -0
  28. package/dist/broadcasting/channels/PresenceChannel.d.ts +72 -0
  29. package/dist/broadcasting/channels/PrivateChannel.d.ts +32 -0
  30. package/dist/broadcasting/channels/index.d.ts +3 -0
  31. package/dist/broadcasting/drivers/MemoryDriver.d.ts +93 -0
  32. package/dist/broadcasting/drivers/RedisDriver.d.ts +112 -0
  33. package/dist/broadcasting/drivers/index.d.ts +2 -0
  34. package/dist/broadcasting/index.d.ts +6 -233
  35. package/dist/broadcasting/index.js +1 -1
  36. package/dist/broadcasting/typed.d.ts +23 -0
  37. package/dist/broadcasting/types.d.ts +155 -0
  38. package/dist/cache/CacheManager.d.ts +87 -0
  39. package/dist/cache/TaggedCache.d.ts +62 -0
  40. package/dist/cache/index.d.ts +6 -233
  41. package/dist/cache/index.js +1 -1
  42. package/dist/cache/stores/FileStore.d.ts +64 -0
  43. package/dist/cache/stores/MemoryStore.d.ts +52 -0
  44. package/dist/cache/stores/RedisStore.d.ts +53 -0
  45. package/dist/{CacheManager-BmDzUKrF.d.ts → cache/types.d.ts} +26 -99
  46. package/dist/{chunk-TVY72CLV.js → chunk-4VE3LYOM.js} +3 -2
  47. package/dist/{chunk-FZD2AKJI.js → chunk-7OB2YXRE.js} +56 -28
  48. package/dist/{chunk-HONCNQXZ.js → chunk-BUQXOZCT.js} +97 -10
  49. package/dist/{chunk-DSDX3ASM.js → chunk-CDZUNKI6.js} +65 -83
  50. package/dist/{chunk-CWI4AJ47.js → chunk-HPET6XY5.js} +13 -9
  51. package/dist/{chunk-A3ISJVEV.js → chunk-HR2KZ3WL.js} +23 -5
  52. package/dist/{chunk-EARA7JM4.js → chunk-PZKUDFMW.js} +11 -8
  53. package/dist/console/Command.d.ts +179 -0
  54. package/dist/{ConsoleKernel-CJg975mp.d.ts → console/ConsoleKernel.d.ts} +4 -6
  55. package/dist/console/Input.d.ts +140 -0
  56. package/dist/console/Output.d.ts +161 -0
  57. package/dist/console/index.d.ts +5 -0
  58. package/dist/console/types.d.ts +106 -0
  59. package/dist/container/Container.d.ts +148 -0
  60. package/dist/container/ServiceProvider.d.ts +103 -0
  61. package/dist/container/bindings.d.ts +55 -0
  62. package/dist/container/defineModule.d.ts +88 -0
  63. package/dist/container/definePlugin.d.ts +62 -0
  64. package/dist/container/index.d.ts +8 -0
  65. package/dist/container/types.d.ts +73 -0
  66. package/dist/database/Factory.d.ts +82 -0
  67. package/dist/database/Seeder.d.ts +35 -0
  68. package/dist/database/SeederRunner.d.ts +41 -0
  69. package/dist/database/index.d.ts +4 -0
  70. package/dist/database/types.d.ts +49 -0
  71. package/dist/discovery/AutoDiscovery.d.ts +113 -0
  72. package/dist/discovery/index.d.ts +2 -0
  73. package/dist/docs-viewer/DocsViewerServiceProvider.d.ts +12 -0
  74. package/dist/docs-viewer/endpoint.d.ts +19 -0
  75. package/dist/encryption/Encrypter.d.ts +96 -0
  76. package/dist/encryption/Hash.d.ts +69 -0
  77. package/dist/encryption/MessageSigner.d.ts +21 -0
  78. package/dist/encryption/Random.d.ts +119 -0
  79. package/dist/encryption/app-key.d.ts +12 -0
  80. package/dist/encryption/index.d.ts +10 -222
  81. package/dist/encryption/signed-url.d.ts +9 -0
  82. package/dist/encryption/types.d.ts +103 -0
  83. package/dist/errors/ExceptionHandler.d.ts +118 -0
  84. package/dist/errors/HttpException.d.ts +106 -0
  85. package/dist/errors/debug-page.d.ts +22 -0
  86. package/dist/errors/error-page.d.ts +1 -0
  87. package/dist/errors/exceptions/AuthenticationException.d.ts +32 -0
  88. package/dist/errors/exceptions/AuthorizationException.d.ts +32 -0
  89. package/dist/errors/exceptions/MethodNotAllowedException.d.ts +31 -0
  90. package/dist/errors/exceptions/NotFoundHttpException.d.ts +36 -0
  91. package/dist/errors/exceptions/ValidationException.d.ts +60 -0
  92. package/dist/errors/exceptions/index.d.ts +5 -0
  93. package/dist/errors/index.d.ts +5 -0
  94. package/dist/errors/types.d.ts +43 -0
  95. package/dist/events/Event.d.ts +33 -0
  96. package/dist/{EventManager-CmIoLt7r.d.ts → events/EventManager.d.ts} +4 -86
  97. package/dist/events/Listener.d.ts +79 -0
  98. package/dist/events/builtin.d.ts +73 -0
  99. package/dist/events/index.d.ts +6 -155
  100. package/dist/events/types.d.ts +48 -0
  101. package/dist/facades/index.d.ts +31 -0
  102. package/dist/health/HealthCheck.d.ts +34 -0
  103. package/dist/health/HealthManager.d.ts +53 -0
  104. package/dist/health/checks/CacheCheck.d.ts +35 -0
  105. package/dist/health/checks/CustomCheck.d.ts +23 -0
  106. package/dist/health/checks/DatabaseCheck.d.ts +33 -0
  107. package/dist/health/checks/MemoryCheck.d.ts +32 -0
  108. package/dist/health/checks/RedisCheck.d.ts +27 -0
  109. package/dist/health/checks/StorageCheck.d.ts +35 -0
  110. package/dist/health/checks/index.d.ts +12 -0
  111. package/dist/health/index.d.ts +5 -185
  112. package/dist/health/types.d.ts +52 -0
  113. package/dist/hot-reload/hot-disposables.d.ts +96 -0
  114. package/dist/hot-reload/testing.d.ts +14 -0
  115. package/dist/http/Application.d.ts +187 -0
  116. package/dist/http/FormRequest.d.ts +73 -0
  117. package/dist/http/dev-assets.d.ts +51 -0
  118. package/dist/http/dev-banner.d.ts +7 -0
  119. package/dist/http/inertia-assets.d.ts +22 -0
  120. package/dist/http/middleware/auth.d.ts +13 -0
  121. package/dist/http/middleware/capabilities.d.ts +22 -0
  122. package/dist/http/middleware/cors.d.ts +40 -0
  123. package/dist/http/middleware/csp.d.ts +59 -0
  124. package/dist/http/middleware/csrf.d.ts +121 -0
  125. package/dist/http/middleware/detect-locale.d.ts +65 -0
  126. package/dist/http/middleware/force-https.d.ts +34 -0
  127. package/dist/http/middleware/host-authorization.d.ts +24 -0
  128. package/dist/http/middleware/index.d.ts +19 -0
  129. package/dist/http/middleware/loopback-guard.d.ts +38 -0
  130. package/dist/{rate-limit-D9J2b4S1.d.ts → http/middleware/rate-limit.d.ts} +22 -50
  131. package/dist/http/middleware/redirect-safety.d.ts +29 -0
  132. package/dist/http/middleware/request-id.d.ts +19 -0
  133. package/dist/http/middleware/request-logging.d.ts +16 -0
  134. package/dist/http/middleware/security-headers.d.ts +49 -0
  135. package/dist/http/middleware/session.d.ts +93 -0
  136. package/dist/http/middleware/validation.d.ts +94 -0
  137. package/dist/http/public-assets.d.ts +15 -0
  138. package/dist/http/request.d.ts +24 -0
  139. package/dist/http/resources/CursorPaginator.d.ts +106 -0
  140. package/dist/http/resources/Paginator.d.ts +130 -0
  141. package/dist/http/resources/Resource.d.ts +67 -0
  142. package/dist/http/resources/ResourceCollection.d.ts +60 -0
  143. package/dist/http/resources/index.d.ts +6 -0
  144. package/dist/http/resources/types.d.ts +91 -0
  145. package/dist/http/validation/Validator.d.ts +128 -0
  146. package/dist/http/validation/index.d.ts +3 -0
  147. package/dist/http/validation/rules.d.ts +196 -0
  148. package/dist/http/validation/types.d.ts +96 -0
  149. package/dist/http/vite-dev-server.d.ts +27 -0
  150. package/dist/i18n/I18nManager.d.ts +114 -0
  151. package/dist/i18n/Translator.d.ts +80 -0
  152. package/dist/i18n/index.d.ts +6 -101
  153. package/dist/i18n/index.js +5 -3
  154. package/dist/i18n/loaders/JsonLoader.d.ts +47 -0
  155. package/dist/i18n/loaders/MemoryLoader.d.ts +37 -0
  156. package/dist/i18n/pluralization.d.ts +19 -0
  157. package/dist/i18n/types.d.ts +106 -0
  158. package/dist/index.d.ts +69 -2605
  159. package/dist/index.js +332 -152
  160. package/dist/lambda/index.d.ts +17 -37
  161. package/dist/logging/LogManager.d.ts +83 -0
  162. package/dist/logging/Logger.d.ts +76 -0
  163. package/dist/logging/channels/ConsoleChannel.d.ts +11 -0
  164. package/dist/logging/channels/DailyFileChannel.d.ts +20 -0
  165. package/dist/logging/channels/FileChannel.d.ts +15 -0
  166. package/dist/logging/index.d.ts +8 -50
  167. package/dist/logging/types.d.ts +96 -0
  168. package/dist/mail/Mail.d.ts +138 -0
  169. package/dist/mail/MailManager.d.ts +79 -0
  170. package/dist/mail/address.d.ts +8 -0
  171. package/dist/mail/index.d.ts +7 -316
  172. package/dist/mail/transports/LogTransport.d.ts +19 -0
  173. package/dist/mail/transports/MemoryTransport.d.ts +84 -0
  174. package/dist/mail/transports/ResendTransport.d.ts +32 -0
  175. package/dist/mail/transports/SmtpTransport.d.ts +40 -0
  176. package/dist/{MailManager-DpMvYiP9.d.ts → mail/types.d.ts} +11 -92
  177. package/dist/mcp/McpServiceProvider.d.ts +17 -0
  178. package/dist/mcp/create-mcp-server.d.ts +144 -0
  179. package/dist/mcp/endpoint.d.ts +29 -0
  180. package/dist/mcp/index.d.ts +3 -185
  181. package/dist/mcp/index.js +1 -1
  182. package/dist/mvc/Controller.d.ts +326 -0
  183. package/dist/mvc/Router.d.ts +239 -0
  184. package/dist/mvc/ViewEngine.d.ts +11 -0
  185. package/dist/mvc/inertia/InertiaEngine.d.ts +114 -0
  186. package/dist/mvc/inertia/shared.d.ts +90 -0
  187. package/dist/mvc/mount-route.d.ts +10 -0
  188. package/dist/notifications/Notification.d.ts +99 -0
  189. package/dist/notifications/NotificationManager.d.ts +150 -0
  190. package/dist/notifications/channels/DatabaseChannel.d.ts +55 -0
  191. package/dist/notifications/channels/MailChannel.d.ts +45 -0
  192. package/dist/notifications/channels/MemoryChannel.d.ts +85 -0
  193. package/dist/notifications/channels/SlackChannel.d.ts +73 -0
  194. package/dist/notifications/channels/index.d.ts +4 -0
  195. package/dist/notifications/index.d.ts +6 -322
  196. package/dist/notifications/notifiable-type.d.ts +10 -0
  197. package/dist/notifications/registry.d.ts +39 -0
  198. package/dist/notifications/types.d.ts +162 -0
  199. package/dist/providers/AuthServiceProvider.d.ts +7 -0
  200. package/dist/providers/AuthorizationServiceProvider.d.ts +9 -0
  201. package/dist/providers/BroadcastServiceProvider.d.ts +7 -0
  202. package/dist/providers/CacheServiceProvider.d.ts +7 -0
  203. package/dist/providers/EncryptionServiceProvider.d.ts +7 -0
  204. package/dist/providers/ErrorServiceProvider.d.ts +9 -0
  205. package/dist/providers/EventServiceProvider.d.ts +7 -0
  206. package/dist/providers/HealthServiceProvider.d.ts +7 -0
  207. package/dist/providers/I18nServiceProvider.d.ts +27 -0
  208. package/dist/providers/InertiaServiceProvider.d.ts +20 -0
  209. package/dist/providers/LogServiceProvider.d.ts +7 -0
  210. package/dist/providers/MailServiceProvider.d.ts +7 -0
  211. package/dist/providers/NotificationServiceProvider.d.ts +8 -0
  212. package/dist/providers/OAuthServiceProvider.d.ts +7 -0
  213. package/dist/providers/QueueServiceProvider.d.ts +7 -0
  214. package/dist/providers/SchedulingServiceProvider.d.ts +7 -0
  215. package/dist/providers/StorageServiceProvider.d.ts +7 -0
  216. package/dist/providers/index.d.ts +17 -0
  217. package/dist/queue/FailedJobReporter.d.ts +40 -0
  218. package/dist/queue/Job.d.ts +140 -0
  219. package/dist/queue/QueueManager.d.ts +79 -0
  220. package/dist/queue/Worker.d.ts +99 -0
  221. package/dist/queue/drivers/MemoryDriver.d.ts +60 -0
  222. package/dist/queue/drivers/RedisDriver.d.ts +96 -0
  223. package/dist/queue/drivers/SqsDriver.d.ts +108 -0
  224. package/dist/queue/drivers/SyncDriver.d.ts +28 -0
  225. package/dist/queue/index.d.ts +9 -453
  226. package/dist/queue/types.d.ts +171 -0
  227. package/dist/redis/RedisApiTokenStore.d.ts +78 -0
  228. package/dist/redis/RedisEmailVerificationStore.d.ts +54 -0
  229. package/dist/redis/RedisOAuthStateStore.d.ts +26 -0
  230. package/dist/redis/RedisPasswordResetStore.d.ts +57 -0
  231. package/dist/redis/RedisRateLimitStore.d.ts +77 -0
  232. package/dist/redis/RedisSessionStore.d.ts +61 -0
  233. package/dist/redis/client.d.ts +41 -0
  234. package/dist/redis/index.d.ts +14 -356
  235. package/dist/redis/index.js +5 -2
  236. package/dist/redis/scan-keys.d.ts +6 -0
  237. package/dist/runtime/index.d.ts +8 -95
  238. package/dist/runtime/index.js +1 -1
  239. package/dist/scheduling/CronParser.d.ts +37 -0
  240. package/dist/scheduling/Schedule.d.ts +229 -0
  241. package/dist/scheduling/ScheduledTask.d.ts +47 -0
  242. package/dist/scheduling/Scheduler.d.ts +99 -0
  243. package/dist/scheduling/index.d.ts +5 -41
  244. package/dist/scheduling/types.d.ts +97 -0
  245. package/dist/storage/StorageManager.d.ts +65 -0
  246. package/dist/storage/drivers/LocalDriver.d.ts +55 -0
  247. package/dist/storage/drivers/MemoryDriver.d.ts +66 -0
  248. package/dist/storage/drivers/S3Driver.d.ts +72 -0
  249. package/dist/storage/index.d.ts +5 -197
  250. package/dist/{StorageManager-oZTHqaza.d.ts → storage/types.d.ts} +10 -77
  251. package/dist/support/error-polyfill.d.ts +9 -0
  252. package/dist/support/import-map.d.ts +13 -0
  253. package/dist/support/redirect-target.d.ts +11 -0
  254. package/dist/support/stack-frames.d.ts +56 -0
  255. package/dist/support/trim-slashes.d.ts +11 -0
  256. package/dist/vite/index.d.ts +2 -35
  257. package/dist/vite/index.js +0 -3
  258. package/dist/vite/plugin.d.ts +34 -0
  259. package/package.json +3 -3
  260. package/dist/AuthManager-DBP4KYsx.d.ts +0 -79
  261. package/dist/BroadcastManager-D8KoJxiV.d.ts +0 -492
  262. package/dist/HealthManager-DUyMIzsZ.d.ts +0 -141
  263. package/dist/I18nManager-BiSoczfV.d.ts +0 -275
  264. package/dist/LogManager-7mxnkaPM.d.ts +0 -256
  265. package/dist/Scheduler-pZiT8i57.d.ts +0 -471
  266. package/dist/api-token-D24VPr_E.d.ts +0 -663
  267. package/dist/app-key-CsBfRC_Q.d.ts +0 -214
  268. package/dist/email-verification-D60YF2ZO.d.ts +0 -329
  269. package/dist/index-9_Jzj5jo.d.ts +0 -7
  270. package/dist/validation-yAL53e1S.d.ts +0 -2610
@@ -1,6 +1,9 @@
1
1
  import {
2
2
  AuthorizationException
3
3
  } from "./chunk-63SKW5PS.js";
4
+ import {
5
+ HttpException
6
+ } from "./chunk-DAQKYKLH.js";
4
7
 
5
8
  // src/authorization/Gate.ts
6
9
  var Response = {
@@ -17,6 +20,23 @@ var Response = {
17
20
  return { allowed: false, message: message ?? "Not found.", status: 404 };
18
21
  }
19
22
  };
23
+ function isAuthorizationResponse(value) {
24
+ return typeof value === "object" && value !== null && typeof value.allowed === "boolean";
25
+ }
26
+ function toAuthorizationResponse(value) {
27
+ if (isAuthorizationResponse(value)) {
28
+ return value;
29
+ }
30
+ return value === true ? Response.allow() : Response.deny();
31
+ }
32
+ function denialToException(response) {
33
+ const message = response.message ?? "This action is unauthorized.";
34
+ const status = response.status;
35
+ if (typeof status === "number" && status !== 403) {
36
+ return new HttpException(status, message);
37
+ }
38
+ return new AuthorizationException(message);
39
+ }
20
40
  var Gate = class {
21
41
  /**
22
42
  * Defined gates.
@@ -146,45 +166,55 @@ var Gate = class {
146
166
  * Authorize the ability or throw an exception.
147
167
  */
148
168
  async authorize(ability, ...args) {
149
- const allowed = await this.allows(ability, ...args);
150
- if (!allowed) {
151
- throw new AuthorizationException(`This action is unauthorized.`);
169
+ const response = await this.checkResponse(ability, this.currentUser, ...args);
170
+ if (!response.allowed) {
171
+ throw denialToException(response);
152
172
  }
153
173
  }
154
174
  /**
155
175
  * Get the authorization response.
156
176
  */
157
177
  async inspect(ability, ...args) {
158
- const allowed = await this.check(ability, this.currentUser, ...args);
159
- return allowed ? Response.allow() : Response.deny();
178
+ return this.checkResponse(ability, this.currentUser, ...args);
160
179
  }
161
180
  /**
162
181
  * Check the ability with a specific user.
163
182
  */
164
183
  async check(ability, user, ...args) {
184
+ const response = await this.checkResponse(ability, user, ...args);
185
+ return response.allowed;
186
+ }
187
+ /**
188
+ * Check the ability with a specific user and keep the full response.
189
+ *
190
+ * Policies may answer with a boolean or with a `Response` object. Both
191
+ * shapes are normalized here so no caller has to truthy-test a
192
+ * `{ allowed: false }` object.
193
+ */
194
+ async checkResponse(ability, user, ...args) {
165
195
  for (const beforeCallback of this.beforeCallbacks) {
166
196
  const result = await beforeCallback(user, ability, ...args);
167
- if (typeof result === "boolean") {
168
- await this.runAfterCallbacks(user, ability, result, args);
169
- return result;
197
+ if (result !== void 0) {
198
+ return this.settle(user, ability, toAuthorizationResponse(result), args);
170
199
  }
171
200
  }
172
201
  const model = args[0];
173
202
  if (model !== void 0 && model !== null) {
174
203
  const policyResult = await this.checkPolicy(ability, user, model, args.slice(1));
175
204
  if (policyResult !== void 0) {
176
- await this.runAfterCallbacks(user, ability, policyResult, args);
177
- return policyResult;
205
+ return this.settle(user, ability, toAuthorizationResponse(policyResult), args);
178
206
  }
179
207
  }
180
208
  const gate = this.gates.get(ability);
181
209
  if (gate) {
182
210
  const result = await gate.callback(user, ...args);
183
- await this.runAfterCallbacks(user, ability, result, args);
184
- return result;
211
+ return this.settle(user, ability, toAuthorizationResponse(result), args);
185
212
  }
186
- await this.runAfterCallbacks(user, ability, false, args);
187
- return false;
213
+ return this.settle(user, ability, Response.deny(), args);
214
+ }
215
+ async settle(user, ability, response, args) {
216
+ await this.runAfterCallbacks(user, ability, response.allowed, args);
217
+ return response;
188
218
  }
189
219
  /**
190
220
  * Check a policy for the given ability.
@@ -217,7 +247,7 @@ var Gate = class {
217
247
  const policy = this.getPolicyInstance(policyClass);
218
248
  if (policy.before) {
219
249
  const beforeResult = await policy.before(user, ability);
220
- if (typeof beforeResult === "boolean") {
250
+ if (beforeResult !== void 0) {
221
251
  return beforeResult;
222
252
  }
223
253
  }
@@ -361,16 +391,15 @@ function authorizeMiddleware(ability, modelResolver, options = {}) {
361
391
  const gateForUser = gate.forUser(user);
362
392
  const abilities = Array.isArray(ability) ? ability : [ability];
363
393
  const model = modelResolver ? await modelResolver(ctx) : void 0;
364
- let authorized = false;
365
394
  if (Array.isArray(ability)) {
366
- authorized = await gateForUser.any(abilities, model);
395
+ if (!await gateForUser.any(abilities, model)) {
396
+ throw new AuthorizationException(options.message ?? "This action is unauthorized.");
397
+ }
367
398
  } else {
368
- authorized = await gateForUser.allows(ability, model);
369
- }
370
- if (!authorized) {
371
- throw new AuthorizationException(
372
- options.message ?? "This action is unauthorized."
373
- );
399
+ const response = await gateForUser.checkResponse(ability, user, model);
400
+ if (!response.allowed) {
401
+ throw denialToException(options.message ? { ...response, message: options.message } : response);
402
+ }
374
403
  }
375
404
  await next();
376
405
  };
@@ -416,11 +445,9 @@ function authorizeResourceMiddleware(modelResolver, options = {}) {
416
445
  const user = await gate.resolveUser(ctx);
417
446
  const gateForUser = gate.forUser(user);
418
447
  const model = await modelResolver(ctx);
419
- const authorized = await gateForUser.allows(ability, model);
420
- if (!authorized) {
421
- throw new AuthorizationException(
422
- options.message ?? "This action is unauthorized."
423
- );
448
+ const response = await gateForUser.checkResponse(ability, user, model);
449
+ if (!response.allowed) {
450
+ throw denialToException(options.message ? { ...response, message: options.message } : response);
424
451
  }
425
452
  await next();
426
453
  };
@@ -445,6 +472,7 @@ function withAuthorization(gate) {
445
472
 
446
473
  export {
447
474
  Response,
475
+ isAuthorizationResponse,
448
476
  Gate,
449
477
  createGate,
450
478
  setGate,
@@ -158,6 +158,12 @@ var SessionImpl = class {
158
158
  shouldPersist() {
159
159
  return this.dirty || this.isNew && this.hasContent();
160
160
  }
161
+ willPersist() {
162
+ if (this.destroyed) {
163
+ return false;
164
+ }
165
+ return !this.isNew || this.shouldPersist();
166
+ }
161
167
  hasContent() {
162
168
  return Object.keys(this.data).length > 0 || this.hasFlash();
163
169
  }
@@ -561,11 +567,10 @@ function generateId() {
561
567
  }
562
568
  function secureCompare(a, b) {
563
569
  if (a.length !== b.length) return false;
564
- try {
565
- return timingSafeEqual2(Buffer.from(a, "hex"), Buffer.from(b, "hex"));
566
- } catch {
567
- return false;
568
- }
570
+ const bufA = Buffer.from(a, "hex");
571
+ const bufB = Buffer.from(b, "hex");
572
+ if (bufA.length !== a.length / 2 || bufB.length !== b.length / 2) return false;
573
+ return timingSafeEqual2(bufA, bufB);
569
574
  }
570
575
  function secureStringCompare(a, b) {
571
576
  const bufA = Buffer.from(a, "utf8");
@@ -1370,6 +1375,52 @@ function hostMatchesAllowlist(target, allowedHosts) {
1370
1375
  }
1371
1376
 
1372
1377
  // src/auth/oauth/index.ts
1378
+ var OAUTH_SESSION_BINDING_KEY = "guren:oauth.bindings";
1379
+ var MAX_PENDING_SESSION_BINDINGS = 5;
1380
+ var warnedAboutUnboundState = false;
1381
+ function warnOnceAboutUnboundState() {
1382
+ if (warnedAboutUnboundState) return;
1383
+ warnedAboutUnboundState = true;
1384
+ console.warn(
1385
+ "[guren] OAuth authorize() was called without `session` or `bindTo`, so `state` is not tied to the browser that started the flow. An attacker can then complete their own authorization in a victim's browser and log the victim into the attacker's account. Pass the current session (`this.auth.session()`) as `session` to both authorize() and handleCallback(), or manage a per-browser value yourself via `bindTo`. See: https://guren.dev/docs/guides/oauth"
1386
+ );
1387
+ }
1388
+ var warnedAboutDroppedBinding = false;
1389
+ function warnOnceAboutDroppedBinding() {
1390
+ if (warnedAboutDroppedBinding) return;
1391
+ warnedAboutDroppedBinding = true;
1392
+ console.warn(
1393
+ "[guren] An OAuth state was created with `bindTo` but came back from the state store without its binding, so the callback could not be tied to the browser that started the flow. The configured OAuthStateStore is dropping `OAuthStatePayload.binding` \u2014 for DatabaseOAuthStateStore this usually means the `oauth_states` table has no `binding` column. See: https://guren.dev/docs/guides/oauth"
1394
+ );
1395
+ }
1396
+ function readPendingBindings(session) {
1397
+ const stored = session.get(OAUTH_SESSION_BINDING_KEY);
1398
+ if (!Array.isArray(stored)) return [];
1399
+ const now = Date.now();
1400
+ return stored.filter(
1401
+ (entry) => typeof entry === "object" && entry !== null && typeof entry.stateHash === "string" && typeof entry.binding === "string" && typeof entry.expiresAt === "number" && entry.expiresAt > now
1402
+ );
1403
+ }
1404
+ function issueSessionBinding(session) {
1405
+ if (!session) return void 0;
1406
+ return generateToken(DEFAULT_STATE_LENGTH);
1407
+ }
1408
+ function rememberSessionBinding(session, stateHash, binding, expiresAt) {
1409
+ const pending = readPendingBindings(session);
1410
+ pending.push({ stateHash, binding, expiresAt: expiresAt.getTime() });
1411
+ session.set(
1412
+ OAUTH_SESSION_BINDING_KEY,
1413
+ pending.slice(Math.max(0, pending.length - MAX_PENDING_SESSION_BINDINGS))
1414
+ );
1415
+ }
1416
+ function consumeSessionBinding(session, stateHash) {
1417
+ if (!session) return void 0;
1418
+ const pending = readPendingBindings(session);
1419
+ if (pending.length === 0) return void 0;
1420
+ const match = pending.find((entry) => entry.stateHash === stateHash);
1421
+ session.set(OAUTH_SESSION_BINDING_KEY, pending.filter((entry) => entry.stateHash !== stateHash));
1422
+ return match?.binding;
1423
+ }
1373
1424
  var DEFAULT_STATE_EXPIRES_IN = 10 * 60 * 1e3;
1374
1425
  var DEFAULT_STATE_LENGTH = 24;
1375
1426
  var DEFAULT_STATE_HASH_ALGORITHM = "sha256";
@@ -1449,13 +1500,27 @@ var OAuthManager = class {
1449
1500
  }
1450
1501
  async authorize(providerName, options = {}) {
1451
1502
  const provider = this.getProvider(providerName);
1503
+ const sessionBinding = options.bindTo ? void 0 : issueSessionBinding(options.session);
1504
+ const bindTo = options.bindTo ?? sessionBinding;
1505
+ if (!bindTo) {
1506
+ warnOnceAboutUnboundState();
1507
+ }
1452
1508
  const { state, expiresAt } = await createOAuthState(
1453
1509
  providerName,
1454
1510
  this.stateStore,
1455
1511
  this.stateConfig,
1456
1512
  options.redirectTo,
1457
- options.state
1513
+ options.state,
1514
+ bindTo
1458
1515
  );
1516
+ if (sessionBinding && options.session) {
1517
+ rememberSessionBinding(
1518
+ options.session,
1519
+ hashToken(state, this.stateConfig.hashAlgorithm),
1520
+ sessionBinding,
1521
+ expiresAt
1522
+ );
1523
+ }
1459
1524
  const scope = options.scope ?? provider.scopes;
1460
1525
  const url = buildOAuthAuthorizeUrl(provider, state, { scope, extraParams: options.extraParams });
1461
1526
  return { url, state, expiresAt };
@@ -1472,7 +1537,16 @@ var OAuthManager = class {
1472
1537
  */
1473
1538
  async handleCallback(providerName, payload) {
1474
1539
  const provider = this.getProvider(providerName);
1475
- const verified = await verifyOAuthState(payload.state, providerName, this.stateStore, this.stateConfig);
1540
+ const verified = await verifyOAuthState(
1541
+ payload.state,
1542
+ providerName,
1543
+ this.stateStore,
1544
+ this.stateConfig,
1545
+ payload.bindTo ?? consumeSessionBinding(
1546
+ payload.session,
1547
+ hashToken(payload.state, this.stateConfig.hashAlgorithm)
1548
+ )
1549
+ );
1476
1550
  if (!verified) {
1477
1551
  throw new AuthenticationException("Invalid or expired OAuth state.");
1478
1552
  }
@@ -1484,7 +1558,7 @@ var OAuthManager = class {
1484
1558
  function createOAuthManager(options = {}) {
1485
1559
  return new OAuthManager(options);
1486
1560
  }
1487
- async function createOAuthState(provider, store, config = {}, redirectTo, fixedState) {
1561
+ async function createOAuthState(provider, store, config = {}, redirectTo, fixedState, bindTo) {
1488
1562
  const state = fixedState ?? generateToken(config.stateLength ?? DEFAULT_STATE_LENGTH);
1489
1563
  const hashAlgorithm = config.hashAlgorithm ?? DEFAULT_STATE_HASH_ALGORITHM;
1490
1564
  const expiresAt = new Date(Date.now() + (config.expiresIn ?? DEFAULT_STATE_EXPIRES_IN));
@@ -1492,18 +1566,30 @@ async function createOAuthState(provider, store, config = {}, redirectTo, fixedS
1492
1566
  await store.store(stateHash, {
1493
1567
  provider,
1494
1568
  redirectTo: sanitizeOAuthRedirect(redirectTo, config.allowedRedirectHosts),
1495
- expiresAt
1569
+ expiresAt,
1570
+ // Only the hash is stored, so a leaked state store does not hand out
1571
+ // session ids.
1572
+ binding: bindTo ? hashToken(bindTo, hashAlgorithm) : void 0
1496
1573
  });
1497
1574
  return { state, expiresAt };
1498
1575
  }
1499
- async function verifyOAuthState(state, provider, store, config = {}) {
1576
+ async function verifyOAuthState(state, provider, store, config = {}, bindTo) {
1500
1577
  const hashAlgorithm = config.hashAlgorithm ?? DEFAULT_STATE_HASH_ALGORITHM;
1501
1578
  const stateHash = hashToken(state, hashAlgorithm);
1502
1579
  const payload = typeof store.consume === "function" ? await store.consume(stateHash) : await findAndDeleteState(store, stateHash);
1503
1580
  if (!payload) return null;
1504
1581
  if (payload.provider !== provider) return null;
1582
+ if (!bindingMatches(payload.binding, bindTo, hashAlgorithm)) return null;
1505
1583
  return { ...payload, redirectTo: sanitizeOAuthRedirect(payload.redirectTo, config.allowedRedirectHosts) };
1506
1584
  }
1585
+ function bindingMatches(stored, presented, hashAlgorithm) {
1586
+ if (!stored) {
1587
+ if (presented) warnOnceAboutDroppedBinding();
1588
+ return true;
1589
+ }
1590
+ if (!presented) return false;
1591
+ return secureCompare(stored, hashToken(presented, hashAlgorithm));
1592
+ }
1507
1593
  async function findAndDeleteState(store, stateHash) {
1508
1594
  const payload = await store.find(stateHash);
1509
1595
  if (!payload) return null;
@@ -1718,6 +1804,7 @@ export {
1718
1804
  createBearerTokenMiddleware,
1719
1805
  getApiToken,
1720
1806
  getApiTokenOrFail,
1807
+ OAUTH_SESSION_BINDING_KEY,
1721
1808
  MemoryOAuthStateStore,
1722
1809
  OAuthManager,
1723
1810
  createOAuthManager,
@@ -123,16 +123,10 @@ function createMcpServer(options) {
123
123
  force: z.boolean().default(false).describe("Overwrite existing files")
124
124
  },
125
125
  async ({ name, fields, withTest, force }) => {
126
- const originalCwd = process.cwd();
127
- try {
128
- process.chdir(cwd);
129
- const createdFiles = await cli.makeFeature(name, { fields, withTest, force });
130
- return {
131
- content: [{ type: "text", text: JSON.stringify({ created: createdFiles }, null, 2) }]
132
- };
133
- } finally {
134
- process.chdir(originalCwd);
135
- }
126
+ const createdFiles = await cli.makeFeature(name, { fields, withTest, force, cwd });
127
+ return {
128
+ content: [{ type: "text", text: JSON.stringify({ created: createdFiles }, null, 2) }]
129
+ };
136
130
  }
137
131
  );
138
132
  server.tool(
@@ -162,36 +156,30 @@ function createMcpServer(options) {
162
156
  force: z.boolean().default(false).describe("Overwrite existing files")
163
157
  },
164
158
  async ({ type, name, force }) => {
165
- const originalCwd = process.cwd();
166
- try {
167
- process.chdir(cwd);
168
- const makers = {
169
- controller: cli.makeController,
170
- model: cli.makeModel,
171
- view: cli.makeView,
172
- test: cli.makeTest,
173
- route: cli.makeRoute
174
- };
175
- const maker = makers[type];
176
- if (!maker) {
177
- return {
178
- content: [
179
- {
180
- type: "text",
181
- text: `Component type "${type}" is not yet supported via MCP. Use the CLI: bunx guren make:${type} ${name}`
182
- }
183
- ],
184
- isError: true
185
- };
186
- }
187
- const result = await maker(name, { force });
188
- const created = Array.isArray(result) ? result : [result];
159
+ const makers = {
160
+ controller: cli.makeController,
161
+ model: cli.makeModel,
162
+ view: cli.makeView,
163
+ test: cli.makeTest,
164
+ route: cli.makeRoute
165
+ };
166
+ const maker = makers[type];
167
+ if (!maker) {
189
168
  return {
190
- content: [{ type: "text", text: JSON.stringify({ created }, null, 2) }]
169
+ content: [
170
+ {
171
+ type: "text",
172
+ text: `Component type "${type}" is not yet supported via MCP. Use the CLI: bunx guren make:${type} ${name}`
173
+ }
174
+ ],
175
+ isError: true
191
176
  };
192
- } finally {
193
- process.chdir(originalCwd);
194
177
  }
178
+ const result = await maker(name, { force, cwd });
179
+ const created = Array.isArray(result) ? result : [result];
180
+ return {
181
+ content: [{ type: "text", text: JSON.stringify({ created }, null, 2) }]
182
+ };
195
183
  }
196
184
  );
197
185
  server.tool(
@@ -199,53 +187,47 @@ function createMcpServer(options) {
199
187
  "Generate the type-safe route, page, data, and channel manifests plus the API client (.guren/ and types/generated/).",
200
188
  {},
201
189
  async () => {
202
- const originalCwd = process.cwd();
203
- try {
204
- process.chdir(cwd);
205
- const options2 = { cwd, force: true };
206
- const generated = [];
207
- const skipped = [];
208
- let failed = false;
209
- const run = async (artifacts, generate) => {
210
- try {
211
- const result = await generate();
212
- if (result?.outputPath === "") {
213
- skipped.push({ artifacts, reason: "nothing to generate" });
214
- } else {
215
- generated.push(...artifacts);
216
- }
217
- return result;
218
- } catch (error) {
219
- failed = true;
220
- skipped.push({
221
- artifacts,
222
- reason: error instanceof Error ? error.message : String(error)
223
- });
190
+ const options2 = { cwd, force: true };
191
+ const generated = [];
192
+ const skipped = [];
193
+ let failed = false;
194
+ const run = async (artifacts, generate) => {
195
+ try {
196
+ const result = await generate();
197
+ if (result?.outputPath === "") {
198
+ skipped.push({ artifacts, reason: "nothing to generate" });
199
+ } else {
200
+ generated.push(...artifacts);
224
201
  }
225
- };
226
- const routes = await run(
227
- [".guren/routes.gen.ts", "types/generated/routes.d.ts"],
228
- () => cli.generateRouteTypes(options2)
229
- );
230
- await run([".guren/pages.gen.ts"], () => cli.generatePageTypes(options2));
231
- await run([".guren/data.gen.ts"], () => cli.generateDataTypes(options2));
232
- await run([".guren/channels.gen.ts"], () => cli.generateChannelTypes(options2));
233
- await run([".guren/api-client.gen.ts"], () => {
234
- if (!routes?.definitions) {
235
- throw new Error("route generation produced no manifest to build a client from");
236
- }
237
- return cli.generateApiClientTypes(routes.definitions, options2);
238
- });
239
- return {
240
- content: [{ type: "text", text: JSON.stringify({ generated, skipped }, null, 2) }],
241
- // A generator that found nothing to describe is not a failure — an
242
- // app with no page components is a normal shape — so only a thrown
243
- // one makes the run an error, even when other artifacts landed.
244
- isError: failed
245
- };
246
- } finally {
247
- process.chdir(originalCwd);
248
- }
202
+ return result;
203
+ } catch (error) {
204
+ failed = true;
205
+ skipped.push({
206
+ artifacts,
207
+ reason: error instanceof Error ? error.message : String(error)
208
+ });
209
+ }
210
+ };
211
+ const routes = await run(
212
+ [".guren/routes.gen.ts", "types/generated/routes.d.ts"],
213
+ () => cli.generateRouteTypes(options2)
214
+ );
215
+ await run([".guren/pages.gen.ts"], () => cli.generatePageTypes(options2));
216
+ await run([".guren/data.gen.ts"], () => cli.generateDataTypes(options2));
217
+ await run([".guren/channels.gen.ts"], () => cli.generateChannelTypes(options2));
218
+ await run([".guren/api-client.gen.ts"], () => {
219
+ if (!routes?.definitions) {
220
+ throw new Error("route generation produced no manifest to build a client from");
221
+ }
222
+ return cli.generateApiClientTypes(routes.definitions, options2);
223
+ });
224
+ return {
225
+ content: [{ type: "text", text: JSON.stringify({ generated, skipped }, null, 2) }],
226
+ // A generator that found nothing to describe is not a failure — an
227
+ // app with no page components is a normal shape — so only a thrown
228
+ // one makes the run an error, even when other artifacts landed.
229
+ isError: failed
230
+ };
249
231
  }
250
232
  );
251
233
  server.resource(
@@ -7,9 +7,11 @@ import {
7
7
  var MemoryStore = class {
8
8
  cache = /* @__PURE__ */ new Map();
9
9
  maxSize;
10
+ now;
10
11
  checkInterval = null;
11
12
  constructor(options = {}) {
12
13
  this.maxSize = options.maxSize ?? Infinity;
14
+ this.now = options.now ?? Date.now;
13
15
  const checkPeriod = options.checkPeriod ?? 6e4;
14
16
  if (checkPeriod > 0) {
15
17
  this.checkInterval = setInterval(() => {
@@ -24,7 +26,7 @@ var MemoryStore = class {
24
26
  * Remove expired items from the cache.
25
27
  */
26
28
  removeExpired() {
27
- const now = Date.now();
29
+ const now = this.now();
28
30
  for (const [key, item] of this.cache) {
29
31
  if (item.expiresAt !== null && item.expiresAt <= now) {
30
32
  this.cache.delete(key);
@@ -35,7 +37,7 @@ var MemoryStore = class {
35
37
  * Check if an item is expired.
36
38
  */
37
39
  isExpired(item) {
38
- return item.expiresAt !== null && item.expiresAt <= Date.now();
40
+ return item.expiresAt !== null && item.expiresAt <= this.now();
39
41
  }
40
42
  /**
41
43
  * Evict items if cache is full.
@@ -61,7 +63,7 @@ var MemoryStore = class {
61
63
  }
62
64
  async set(key, value, ttl) {
63
65
  this.evictIfNeeded();
64
- const expiresAt = ttl ? Date.now() + ttl * 1e3 : null;
66
+ const expiresAt = ttl ? this.now() + ttl * 1e3 : null;
65
67
  this.cache.set(key, {
66
68
  value,
67
69
  expiresAt
@@ -88,7 +90,7 @@ var MemoryStore = class {
88
90
  const current = await this.get(key);
89
91
  const newValue = (current ?? 0) + value;
90
92
  const item = this.cache.get(key);
91
- const ttl = item?.expiresAt ? Math.max(0, Math.ceil((item.expiresAt - Date.now()) / 1e3)) : void 0;
93
+ const ttl = item?.expiresAt ? Math.max(0, Math.ceil((item.expiresAt - this.now()) / 1e3)) : void 0;
92
94
  await this.set(key, newValue, ttl);
93
95
  return newValue;
94
96
  }
@@ -146,7 +148,7 @@ var MemoryStore = class {
146
148
  if (item.expiresAt === null) {
147
149
  return -1;
148
150
  }
149
- return Math.max(0, Math.ceil((item.expiresAt - Date.now()) / 1e3));
151
+ return Math.max(0, Math.ceil((item.expiresAt - this.now()) / 1e3));
150
152
  }
151
153
  /**
152
154
  * Get the number of items in the cache.
@@ -313,9 +315,11 @@ import { createHash } from "crypto";
313
315
  var FileStore = class {
314
316
  basePath;
315
317
  extension;
318
+ now;
316
319
  constructor(options) {
317
320
  this.basePath = options.path;
318
321
  this.extension = options.extension ?? ".cache";
322
+ this.now = options.now ?? Date.now;
319
323
  }
320
324
  /**
321
325
  * Generate a hashed filename for a cache key.
@@ -367,7 +371,7 @@ var FileStore = class {
367
371
  * Check if a cached item is expired.
368
372
  */
369
373
  isExpired(item) {
370
- return item.expiresAt !== null && item.expiresAt <= Date.now();
374
+ return item.expiresAt !== null && item.expiresAt <= this.now();
371
375
  }
372
376
  async get(key) {
373
377
  const filePath = this.getFilePath(key);
@@ -383,7 +387,7 @@ var FileStore = class {
383
387
  }
384
388
  async set(key, value, ttl) {
385
389
  const filePath = this.getFilePath(key);
386
- const expiresAt = ttl ? Date.now() + ttl * 1e3 : null;
390
+ const expiresAt = ttl ? this.now() + ttl * 1e3 : null;
387
391
  await this.writeCacheFile(filePath, {
388
392
  value,
389
393
  expiresAt
@@ -409,7 +413,7 @@ var FileStore = class {
409
413
  const newValue = (current ?? 0) + value;
410
414
  const filePath = this.getFilePath(key);
411
415
  const item = await this.readCacheFile(filePath);
412
- const ttl = item?.expiresAt ? Math.max(0, Math.ceil((item.expiresAt - Date.now()) / 1e3)) : void 0;
416
+ const ttl = item?.expiresAt ? Math.max(0, Math.ceil((item.expiresAt - this.now()) / 1e3)) : void 0;
413
417
  await this.set(key, newValue, ttl);
414
418
  return newValue;
415
419
  }
@@ -470,7 +474,7 @@ var FileStore = class {
470
474
  if (item.expiresAt === null) {
471
475
  return -1;
472
476
  }
473
- return Math.max(0, Math.ceil((item.expiresAt - Date.now()) / 1e3));
477
+ return Math.max(0, Math.ceil((item.expiresAt - this.now()) / 1e3));
474
478
  }
475
479
  /**
476
480
  * Clean up expired cache files.
@@ -99,6 +99,7 @@ function selectPluralForm(translation, count, rule) {
99
99
  }
100
100
 
101
101
  // src/i18n/Translator.ts
102
+ var REGEXP_SPECIALS = /[.*+?^${}()|[\]\\]/g;
102
103
  var Translator = class {
103
104
  locale;
104
105
  fallbackLocale;
@@ -231,7 +232,9 @@ var Translator = class {
231
232
  if (!replacements) return translation;
232
233
  let result = translation;
233
234
  for (const [key, value] of Object.entries(replacements)) {
234
- result = result.replace(new RegExp(`:${key}`, "g"), String(value)).replace(new RegExp(`\\{${key}\\}`, "g"), String(value));
235
+ const escaped = key.replace(REGEXP_SPECIALS, "\\$&");
236
+ const replacement = () => String(value);
237
+ result = result.replace(new RegExp(`:${escaped}`, "g"), replacement).replace(new RegExp(`\\{${escaped}\\}`, "g"), replacement);
235
238
  }
236
239
  return result;
237
240
  }
@@ -496,12 +499,23 @@ var I18nManager = class {
496
499
  return new Translator({
497
500
  locale,
498
501
  fallbackLocale: this.config.fallbackLocale,
499
- messages: {
500
- [locale]: this.translator.getMessages(locale),
501
- ...this.config.fallbackLocale ? { [this.config.fallbackLocale]: this.translator.getMessages(this.config.fallbackLocale) } : {}
502
- }
502
+ messages: this.messagesForLocale(locale)
503
503
  });
504
504
  }
505
+ /**
506
+ * The message catalogs that accompany a locale: the fallback locale's
507
+ * (when it differs) plus the locale's own, in that order — so consumers
508
+ * that flatten the record let the active locale win on key collisions.
509
+ */
510
+ messagesForLocale(locale) {
511
+ const fallback = this.config.fallbackLocale;
512
+ const messages = {};
513
+ if (fallback && fallback !== locale) {
514
+ messages[fallback] = this.translator.getMessages(fallback);
515
+ }
516
+ messages[locale] = this.translator.getMessages(locale);
517
+ return messages;
518
+ }
505
519
  };
506
520
  var globalI18n = null;
507
521
  function createI18n(config) {
@@ -516,6 +530,9 @@ function getI18n() {
516
530
  }
517
531
  return globalI18n;
518
532
  }
533
+ function tryGetI18n() {
534
+ return globalI18n ?? void 0;
535
+ }
519
536
  function t(key, replacements) {
520
537
  return getI18n().t(key, replacements);
521
538
  }
@@ -592,6 +609,7 @@ export {
592
609
  createI18n,
593
610
  setI18n,
594
611
  getI18n,
612
+ tryGetI18n,
595
613
  t,
596
614
  tc,
597
615
  MemoryLoader