gencow 0.1.299 → 0.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 (149) hide show
  1. package/bin/gencow.mjs +0 -6
  2. package/core/package.json +1 -1
  3. package/docs/packaging.md +14 -4
  4. package/lib/cli-artifact-guard.mjs +53 -3
  5. package/lib/cli-dev-runtime.mjs +1 -0
  6. package/lib/cli-project-runtime.mjs +26 -14
  7. package/lib/codegen-command.mjs +16 -0
  8. package/lib/coding-guardrails.mjs +2 -0
  9. package/lib/dashboard-artifact.mjs +65 -0
  10. package/lib/dashboard-assets.mjs +20 -0
  11. package/lib/db-command.mjs +121 -80
  12. package/lib/db-migration-command-steps.mjs +19 -16
  13. package/lib/db-push-command.mjs +1 -1
  14. package/lib/deploy-codegen-preflight.mjs +1 -0
  15. package/lib/dev-cloud-command.mjs +1 -1
  16. package/lib/dev-local-command.mjs +19 -56
  17. package/lib/document-local-converter.mjs +11 -0
  18. package/lib/local-dashboard-plan.mjs +60 -0
  19. package/lib/local-database-commands.mjs +127 -0
  20. package/lib/local-development-migrations.mjs +157 -0
  21. package/lib/local-drizzle-database.config.mjs +10 -0
  22. package/lib/local-runtime-features.mjs +12 -0
  23. package/lib/rag-selection.mjs +7 -0
  24. package/lib/runtime-local-worker.mjs +116 -0
  25. package/lib/runtime-mode.mjs +3 -0
  26. package/lib/standalone-codegen-adapter.mjs +91 -0
  27. package/lib/ts-codegen-import-extension.mjs +228 -19
  28. package/package.json +16 -9
  29. package/runtime/config.mjs +218 -2
  30. package/runtime/engine/chunk-2HA4CUMS.mjs +90 -0
  31. package/runtime/engine/chunk-2JLO3KMM.mjs +305 -0
  32. package/runtime/engine/chunk-2SR2M7SR.mjs +1045 -0
  33. package/runtime/engine/chunk-3D7MHEUC.mjs +253 -0
  34. package/runtime/engine/chunk-3R7COBWG.mjs +309 -0
  35. package/runtime/engine/chunk-3ZKA54UW.mjs +1560 -0
  36. package/runtime/engine/chunk-45I4YR2J.mjs +9 -0
  37. package/runtime/engine/chunk-4MLRXO7F.mjs +74 -0
  38. package/runtime/engine/chunk-5575APCJ.mjs +215 -0
  39. package/runtime/engine/chunk-5GUJZQF3.mjs +114 -0
  40. package/runtime/engine/chunk-5MXY3T75.mjs +428 -0
  41. package/runtime/engine/chunk-5TACQ2US.mjs +44 -0
  42. package/runtime/engine/chunk-66G4YEDT.mjs +3104 -0
  43. package/runtime/engine/chunk-67YO53WW.mjs +1426 -0
  44. package/runtime/engine/chunk-6GQRM7XY.mjs +87 -0
  45. package/runtime/engine/chunk-6JO72SPP.mjs +68 -0
  46. package/runtime/engine/chunk-6W653LXI.mjs +13 -0
  47. package/runtime/engine/chunk-7ITSMI3S.mjs +69 -0
  48. package/runtime/engine/chunk-7KUJ2H2S.mjs +128 -0
  49. package/runtime/engine/chunk-A5BMQ5IC.mjs +45 -0
  50. package/runtime/engine/chunk-ADF3UR6L.mjs +428 -0
  51. package/runtime/engine/chunk-AEBW7XZJ.mjs +4510 -0
  52. package/runtime/engine/chunk-AGPQ5XIV.mjs +156 -0
  53. package/runtime/engine/chunk-CPU4OZSX.mjs +753 -0
  54. package/runtime/engine/chunk-CSWPPWBL.mjs +50 -0
  55. package/runtime/engine/chunk-DPWXSMWO.mjs +53 -0
  56. package/runtime/engine/chunk-EAIELFKU.mjs +151 -0
  57. package/runtime/engine/chunk-EDU5CBKT.mjs +10 -0
  58. package/runtime/engine/chunk-EQCTAET7.mjs +173 -0
  59. package/runtime/engine/chunk-EQCXDF2Z.mjs +70 -0
  60. package/runtime/engine/chunk-F3G4UGV4.mjs +330 -0
  61. package/runtime/engine/chunk-F62NUNOO.mjs +26 -0
  62. package/runtime/engine/chunk-FKPNIFRP.mjs +2492 -0
  63. package/runtime/engine/chunk-FM23RGVI.mjs +81 -0
  64. package/runtime/engine/chunk-FW5AK4YP.mjs +1041 -0
  65. package/runtime/engine/chunk-GDWYAGWV.mjs +23 -0
  66. package/runtime/engine/chunk-GO5PZUYW.mjs +53 -0
  67. package/runtime/engine/chunk-GOLP7OSG.mjs +340 -0
  68. package/runtime/engine/chunk-GSLM44EF.mjs +242 -0
  69. package/runtime/engine/chunk-GYAJ7OX2.mjs +125 -0
  70. package/runtime/engine/chunk-I3GWR43K.mjs +14 -0
  71. package/runtime/engine/chunk-IFMOTJNU.mjs +106 -0
  72. package/runtime/engine/chunk-IKQKBE2G.mjs +128 -0
  73. package/runtime/engine/chunk-ITH2NEKM.mjs +282 -0
  74. package/runtime/engine/chunk-J6SDRCG4.mjs +96 -0
  75. package/runtime/engine/chunk-JODRNM3S.mjs +29596 -0
  76. package/runtime/engine/chunk-JUDKX53X.mjs +137 -0
  77. package/runtime/engine/chunk-K2YZVPJ4.mjs +827 -0
  78. package/runtime/engine/chunk-KEZJUXEE.mjs +151 -0
  79. package/runtime/engine/chunk-KVLTJFCH.mjs +234 -0
  80. package/runtime/engine/chunk-KX2PRQPS.mjs +126 -0
  81. package/runtime/engine/chunk-LEW5ZMLR.mjs +76 -0
  82. package/runtime/engine/chunk-LINVSJEM.mjs +175 -0
  83. package/runtime/engine/chunk-M7K2ICSM.mjs +11 -0
  84. package/runtime/engine/chunk-MZXDXSDC.mjs +292 -0
  85. package/runtime/engine/chunk-N2TA2IK2.mjs +678 -0
  86. package/runtime/engine/chunk-N4LTCKJP.mjs +695 -0
  87. package/runtime/engine/chunk-N6GCLOUX.mjs +13 -0
  88. package/runtime/engine/chunk-NAG2OXS5.mjs +37 -0
  89. package/runtime/engine/chunk-NNZ2QJUG.mjs +381 -0
  90. package/runtime/engine/chunk-NZPPLDNW.mjs +15 -0
  91. package/runtime/engine/chunk-ODWM57W6.mjs +138 -0
  92. package/runtime/engine/chunk-P5IIXAIE.mjs +23 -0
  93. package/runtime/engine/chunk-PBOXB2BV.mjs +6 -0
  94. package/runtime/engine/chunk-PMOJLN2P.mjs +8 -0
  95. package/runtime/engine/chunk-PZFMKFHO.mjs +180 -0
  96. package/runtime/engine/chunk-QL2TQX2N.mjs +114 -0
  97. package/runtime/engine/chunk-RITT2RSJ.mjs +258 -0
  98. package/runtime/engine/chunk-RODBVJ5M.mjs +135 -0
  99. package/runtime/engine/chunk-RW65MPVY.mjs +261 -0
  100. package/runtime/engine/chunk-S67UYPB6.mjs +25 -0
  101. package/runtime/engine/chunk-SVJCOUI3.mjs +47 -0
  102. package/runtime/engine/chunk-TCN3ZASV.mjs +957 -0
  103. package/runtime/engine/chunk-U2NRG6KC.mjs +32 -0
  104. package/runtime/engine/chunk-UM3F7HUV.mjs +432 -0
  105. package/runtime/engine/chunk-VWU7JJ3P.mjs +146 -0
  106. package/runtime/engine/chunk-WDTKPPMU.mjs +310 -0
  107. package/runtime/engine/chunk-WJOO4XTB.mjs +31 -0
  108. package/runtime/engine/chunk-XNFVL2OY.mjs +63 -0
  109. package/runtime/engine/chunk-XPWJXP2J.mjs +58 -0
  110. package/runtime/engine/chunk-Y3HSBJ3I.mjs +1132 -0
  111. package/runtime/engine/chunk-YMH4RYSX.mjs +317 -0
  112. package/runtime/engine/chunk-YNOMPSGS.mjs +8 -0
  113. package/runtime/engine/chunk-YRBAYTEZ.mjs +251 -0
  114. package/runtime/engine/chunk-YRHM272W.mjs +528 -0
  115. package/runtime/engine/chunk-ZQUZAGIQ.mjs +149 -0
  116. package/runtime/engine/chunk-ZXMM7QFP.mjs +176 -0
  117. package/runtime/engine/chunk-ZZJSIPV2.mjs +262 -0
  118. package/runtime/engine/composition.mjs +325 -0
  119. package/runtime/engine/document-local.mjs +504 -0
  120. package/runtime/engine/graph.json +4134 -0
  121. package/runtime/engine/index.mjs +265 -0
  122. package/runtime/engine/local-postgres-support.mjs +69 -0
  123. package/runtime/engine/local.mjs +3275 -0
  124. package/runtime/engine/pglite-directory-lock.mjs +8 -0
  125. package/runtime/engine/rag.mjs +11 -0
  126. package/runtime/engine/search.mjs +18 -0
  127. package/runtime/framework-migrations/foundation-bootstrap/rag.sql +115 -0
  128. package/runtime/framework-migrations/foundation-bootstrap/workflow.sql +194 -0
  129. package/runtime/framework-migrations/journal-bootstrap/migration.sql +26 -0
  130. package/runtime/framework-migrations/manifest.json +56 -0
  131. package/runtime/framework-migrations/rag/20261006111509_mushy_warhawk/migration.sql +121 -0
  132. package/runtime/framework-migrations/rag/20261013234621_rag_v2_lifecycle_markers/migration.sql +6 -0
  133. package/runtime/framework-migrations/workflow/20261006111508_perpetual_star_brand/migration.sql +31 -0
  134. package/runtime/runtime-metadata.json +27 -0
  135. package/runtime/tooling.mjs +10399 -8951
  136. package/scripts/bundle-runtime-config.mjs +23 -0
  137. package/scripts/bundle-runtime.mjs +100 -0
  138. package/scripts/bundle-runtime.test.mjs +33 -0
  139. package/scripts/bundle-shared.mjs +3 -0
  140. package/scripts/copy-dashboard.mjs +16 -0
  141. package/scripts/pre-publish-check.mjs +23 -11
  142. package/templateFeature/sso/sso-auth-callback.tsx +37 -5
  143. package/templateFeature/tools/manifest.json +2 -1
  144. package/templateFeature/tools/tools.ts +3 -3
  145. package/runtime/server.mjs +0 -14389
  146. package/scripts/bundle-server.mjs +0 -223
  147. package/server/config.js +0 -1
  148. package/server/index.js +0 -1
  149. package/server/package.json +0 -6
@@ -0,0 +1,1426 @@
1
+ import {
2
+ runtimeStartupError
3
+ } from "./chunk-IFMOTJNU.mjs";
4
+ import {
5
+ RuntimeDiagnosticError
6
+ } from "./chunk-AEBW7XZJ.mjs";
7
+
8
+ // ../../node_modules/.pnpm/hono@4.13.17/node_modules/hono/dist/middleware/cors/index.js
9
+ var cors = (options) => {
10
+ const opts = {
11
+ origin: "*",
12
+ allowMethods: [
13
+ "GET",
14
+ "HEAD",
15
+ "PUT",
16
+ "POST",
17
+ "DELETE",
18
+ "PATCH",
19
+ "QUERY"
20
+ ],
21
+ allowHeaders: [],
22
+ exposeHeaders: [],
23
+ ...options
24
+ };
25
+ const exposeHeadersStr = opts.exposeHeaders?.length ? opts.exposeHeaders.join(",") : void 0;
26
+ const allowHeadersStr = opts.allowHeaders?.length ? opts.allowHeaders.join(",") : void 0;
27
+ const findAllowOrigin = ((optsOrigin) => {
28
+ if (typeof optsOrigin === "string") {
29
+ if (optsOrigin === "*") return () => optsOrigin;
30
+ else return (origin) => optsOrigin === origin ? origin : null;
31
+ } else if (typeof optsOrigin === "function") return optsOrigin;
32
+ else return (origin) => optsOrigin.includes(origin) ? origin : null;
33
+ })(opts.origin);
34
+ const findAllowMethods = ((optsAllowMethods) => {
35
+ if (typeof optsAllowMethods === "function") return async (origin, c) => (await optsAllowMethods(origin, c)).join(",");
36
+ else if (Array.isArray(optsAllowMethods)) {
37
+ const methodsStr = optsAllowMethods.join(",");
38
+ return () => methodsStr;
39
+ } else return () => "";
40
+ })(opts.allowMethods);
41
+ return async function cors2(c, next) {
42
+ function set(key, value) {
43
+ c.res.headers.set(key, value);
44
+ }
45
+ const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
46
+ if (allowOrigin) set("Access-Control-Allow-Origin", allowOrigin);
47
+ if (opts.credentials) set("Access-Control-Allow-Credentials", "true");
48
+ if (exposeHeadersStr) set("Access-Control-Expose-Headers", exposeHeadersStr);
49
+ if (c.req.method === "OPTIONS") {
50
+ if (opts.origin !== "*") c.res.headers.append("Vary", "Origin");
51
+ if (opts.maxAge != null) set("Access-Control-Max-Age", opts.maxAge.toString());
52
+ const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
53
+ if (allowMethods) set("Access-Control-Allow-Methods", allowMethods);
54
+ let headersStr = allowHeadersStr;
55
+ if (!headersStr) {
56
+ const requestHeaders = c.req.header("Access-Control-Request-Headers");
57
+ if (requestHeaders) headersStr = requestHeaders.split(",").map((h) => h.trim()).join(",");
58
+ }
59
+ if (headersStr) {
60
+ set("Access-Control-Allow-Headers", headersStr);
61
+ c.res.headers.append("Vary", "Access-Control-Request-Headers");
62
+ }
63
+ c.res.headers.delete("Content-Length");
64
+ c.res.headers.delete("Content-Type");
65
+ return new Response(null, {
66
+ headers: c.res.headers,
67
+ status: 204,
68
+ statusText: "No Content"
69
+ });
70
+ }
71
+ await next();
72
+ if (opts.origin !== "*") c.header("Vary", "Origin", { append: true });
73
+ };
74
+ };
75
+
76
+ // ../runtime/dist/app/browser-policy.js
77
+ var LOCALHOST_WILDCARD = /^https?:\/\/localhost:\*$/u;
78
+ function invalid() {
79
+ throw runtimeStartupError("RUNTIME_BROWSER_ORIGIN_INVALID", "Configure exact HTTPS frontendOrigins, or local http://localhost:<port>/http://127.0.0.1:<port> development origins, without credentials, paths or wildcards. Legacy trustedOrigins may use bare domains or http(s)://localhost:*. Check auth callback URLs too: use HTTP(S) URLs or a relative route against the configured backend origin. Correct trusted bootstrap configuration and restart.", "none");
80
+ }
81
+ function frontendRuntimeOrigin(value) {
82
+ const origin = exactRuntimeOrigin(value);
83
+ if (!origin)
84
+ return;
85
+ const url = new URL(origin);
86
+ return url.protocol === "https:" || ["localhost", "127.0.0.1"].includes(url.hostname) && url.port !== "" ? origin : void 0;
87
+ }
88
+ function exactRuntimeOrigin(value) {
89
+ if (typeof value !== "string")
90
+ return;
91
+ try {
92
+ const url = new URL(value.trim());
93
+ if (!/^https?:$/u.test(url.protocol) || url.username || url.password || url.pathname !== "/" || url.search || url.hash || url.hostname.includes("*"))
94
+ return;
95
+ return url.origin;
96
+ } catch {
97
+ return;
98
+ }
99
+ }
100
+ function trustedRuntimeOrigin(value) {
101
+ return typeof value === "string" && LOCALHOST_WILDCARD.test(value.trim()) ? value.trim() : exactRuntimeOrigin(value);
102
+ }
103
+ function isRuntimeOriginAllowed(origin, allowed) {
104
+ if (exactRuntimeOrigin(origin) !== origin)
105
+ return false;
106
+ return allowed.some((value) => {
107
+ if (value === origin)
108
+ return true;
109
+ if (!LOCALHOST_WILDCARD.test(value))
110
+ return false;
111
+ const url = new URL(origin);
112
+ return url.hostname === "localhost" && url.protocol === value.split("//")[0];
113
+ });
114
+ }
115
+ function captureRuntimeBrowserConfiguration(input = {}) {
116
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((key) => !["origin", "frontendOrigins", "trustedOrigins"].includes(key)))
117
+ invalid();
118
+ const frontend = input.frontendOrigins ?? [];
119
+ const trusted = input.trustedOrigins ?? [];
120
+ if (!Array.isArray(frontend) || !Array.isArray(trusted) || frontend.some((value) => !frontendRuntimeOrigin(value)) || trusted.some((value) => typeof value !== "string" || !value.trim()))
121
+ invalid();
122
+ if (input.origin !== void 0 && !exactRuntimeOrigin(input.origin))
123
+ invalid();
124
+ const captured = Object.freeze({
125
+ ...input.origin ? { origin: exactRuntimeOrigin(input.origin) } : {},
126
+ frontendOrigins: Object.freeze(frontend.map((value) => frontendRuntimeOrigin(value))),
127
+ trustedOrigins: Object.freeze(trusted.map((value) => value.trim()))
128
+ });
129
+ resolveRuntimeBrowserPolicy(captured);
130
+ return captured;
131
+ }
132
+ function resolveRuntimeBrowserPolicy(input = {}, auth) {
133
+ const publicOrigins = /* @__PURE__ */ new Set();
134
+ if (input.origin !== void 0) {
135
+ const origin = exactRuntimeOrigin(input.origin);
136
+ if (!origin)
137
+ invalid();
138
+ publicOrigins.add(origin);
139
+ }
140
+ for (const value of input.frontendOrigins ?? []) {
141
+ const origin = frontendRuntimeOrigin(value);
142
+ if (!origin)
143
+ invalid();
144
+ publicOrigins.add(origin);
145
+ }
146
+ for (const value of input.trustedOrigins ?? []) {
147
+ const origin = trustedRuntimeOrigin(value);
148
+ if (origin) {
149
+ publicOrigins.add(origin);
150
+ continue;
151
+ }
152
+ if (typeof value !== "string" || /[\s/*?#@]/u.test(value))
153
+ invalid();
154
+ const host = exactRuntimeOrigin(`https://${value}`);
155
+ if (!host)
156
+ invalid();
157
+ publicOrigins.add(host);
158
+ publicOrigins.add(new URL(host.replace("https:", "http:")).origin);
159
+ const canonical = new URL(host);
160
+ if (!canonical.hostname.startsWith("www.") && !value.includes(":")) {
161
+ canonical.hostname = `www.${canonical.hostname}`;
162
+ publicOrigins.add(canonical.origin);
163
+ canonical.protocol = "http:";
164
+ publicOrigins.add(canonical.origin);
165
+ }
166
+ }
167
+ const authOrigins = new Set(publicOrigins);
168
+ for (const callback of [auth?.oauth?.callbackURL, ...auth?.oauth?.allowedCallbackURLs ?? []]) {
169
+ if (callback === void 0)
170
+ continue;
171
+ try {
172
+ const url = new URL(callback, input.origin);
173
+ const origin = exactRuntimeOrigin(url.origin);
174
+ if (!origin || url.username || url.password)
175
+ invalid();
176
+ authOrigins.add(origin);
177
+ } catch {
178
+ invalid();
179
+ }
180
+ }
181
+ return Object.freeze({
182
+ apiAllowedOrigins: Object.freeze([...publicOrigins]),
183
+ authTrustedOrigins: Object.freeze([...authOrigins])
184
+ });
185
+ }
186
+ function captureRuntimeBrowserPolicy(policy) {
187
+ if (!policy || typeof policy !== "object" || Array.isArray(policy))
188
+ invalid();
189
+ const capture = (values) => {
190
+ if (!Array.isArray(values) || values.some((value) => !trustedRuntimeOrigin(value)))
191
+ invalid();
192
+ return Object.freeze([...new Set(values.map((value) => trustedRuntimeOrigin(value)))]);
193
+ };
194
+ return Object.freeze({
195
+ apiAllowedOrigins: capture(policy.apiAllowedOrigins),
196
+ authTrustedOrigins: capture(policy.authTrustedOrigins)
197
+ });
198
+ }
199
+ function runtimeCorsMiddleware(policy) {
200
+ const middleware = cors({
201
+ origin: (origin) => isRuntimeOriginAllowed(origin, policy.apiAllowedOrigins) ? origin : "",
202
+ credentials: true
203
+ });
204
+ return async (context, next) => {
205
+ const result = await middleware(context, next);
206
+ applyCorsHeaders(context.req.raw, context.res.headers, policy);
207
+ if (result)
208
+ applyCorsHeaders(context.req.raw, result.headers, policy);
209
+ return result;
210
+ };
211
+ }
212
+ function applyCorsHeaders(request, headers, policy) {
213
+ headers.delete("access-control-allow-origin");
214
+ headers.delete("access-control-allow-credentials");
215
+ const origin = request.headers.get("origin");
216
+ if (origin && isRuntimeOriginAllowed(origin, policy.apiAllowedOrigins)) {
217
+ headers.set("access-control-allow-origin", origin);
218
+ headers.set("access-control-allow-credentials", "true");
219
+ }
220
+ const vary = headers.get("vary")?.split(",").map((value) => value.trim()) ?? [];
221
+ if (!vary.some((value) => value.toLowerCase() === "origin"))
222
+ headers.set("vary", [...vary, "Origin"].join(", "));
223
+ }
224
+ function runtimeCorsResponse(request, response, policy) {
225
+ if (!new URL(request.url).pathname.startsWith("/api/"))
226
+ return response;
227
+ const headers = new Headers(response.headers);
228
+ applyCorsHeaders(request, headers, policy);
229
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
230
+ }
231
+
232
+ // ../runtime/dist/app/request-body.js
233
+ async function captureRequestBody(request, work, maxBytes, abortedInput, cancellationSignal = request.signal) {
234
+ if (cancellationSignal.aborted) {
235
+ if (request.body)
236
+ work.track(request.body.cancel().catch(() => {
237
+ }));
238
+ throw abortedInput();
239
+ }
240
+ const length = Number(request.headers.get("content-length") ?? "0");
241
+ if (Number.isFinite(length) && length > maxBytes) {
242
+ if (request.body)
243
+ work.track(request.body.cancel().catch(() => {
244
+ }));
245
+ return void 0;
246
+ }
247
+ if (!request.body)
248
+ return request;
249
+ const reader = request.body.getReader();
250
+ let cancellation;
251
+ function cancelInput() {
252
+ cancellation ??= work.track(reader.cancel().catch(() => {
253
+ }));
254
+ }
255
+ cancellationSignal.addEventListener("abort", cancelInput, { once: true });
256
+ let body = new Uint8Array(0);
257
+ let bytes = 0;
258
+ try {
259
+ if (cancellationSignal.aborted)
260
+ cancelInput();
261
+ while (true) {
262
+ const chunk = await reader.read();
263
+ if (cancellationSignal.aborted)
264
+ throw abortedInput();
265
+ if (chunk.done)
266
+ break;
267
+ bytes += chunk.value.byteLength;
268
+ if (bytes > maxBytes) {
269
+ cancelInput();
270
+ return void 0;
271
+ }
272
+ if (body.length < bytes) {
273
+ const enlarged = new Uint8Array(Math.min(maxBytes, Math.max(bytes, body.length * 2, 1024)));
274
+ enlarged.set(body);
275
+ body = enlarged;
276
+ }
277
+ body.set(chunk.value, bytes - chunk.value.byteLength);
278
+ }
279
+ } catch (error) {
280
+ cancelInput();
281
+ throw error;
282
+ } finally {
283
+ cancellationSignal.removeEventListener("abort", cancelInput);
284
+ reader.releaseLock();
285
+ }
286
+ return new Request(request, { body: body.subarray(0, bytes) });
287
+ }
288
+
289
+ // ../runtime/dist/app/runtime-logging.js
290
+ var protectedScopeKeys = /* @__PURE__ */ new Set([
291
+ "runtime.component",
292
+ "runtime.capability",
293
+ "runtime.target",
294
+ "request.id"
295
+ ]);
296
+ var unsafeAttributeKey = /(?:authorization|cookie|credential|email|env(?:ironment)?|header|password|secret|sql|token|user|body|connection|string|path)/iu;
297
+ function isLogValue(value) {
298
+ return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || Array.isArray(value) && value.every((entry) => typeof entry === "string");
299
+ }
300
+ function safeAttributes(attributes) {
301
+ const entries = Object.entries(attributes ?? {}).filter(([key, value]) => !unsafeAttributeKey.test(key) && isLogValue(value)).map(([key, value]) => [key, Array.isArray(value) ? Object.freeze([...value]) : value]);
302
+ return Object.freeze(Object.fromEntries(entries));
303
+ }
304
+ function mergeAttributes(parent, child) {
305
+ const merged = { ...parent };
306
+ for (const [key, value] of Object.entries(safeAttributes(child))) {
307
+ if (protectedScopeKeys.has(key) && key in parent)
308
+ continue;
309
+ merged[key] = value;
310
+ }
311
+ return Object.freeze(merged);
312
+ }
313
+ var ScopedRuntimeLogger = class _ScopedRuntimeLogger {
314
+ sink;
315
+ attributes;
316
+ constructor(sink, attributes) {
317
+ this.sink = sink;
318
+ this.attributes = attributes;
319
+ }
320
+ child(attributes) {
321
+ return new _ScopedRuntimeLogger(this.sink, mergeAttributes(this.attributes, attributes));
322
+ }
323
+ debug(event, attributes) {
324
+ this.emit("debug", event, attributes);
325
+ }
326
+ info(event, attributes) {
327
+ this.emit("info", event, attributes);
328
+ }
329
+ warn(event, attributes) {
330
+ this.emit("warn", event, attributes);
331
+ }
332
+ error(event, attributes) {
333
+ this.emit("error", event, attributes);
334
+ }
335
+ emit(level, event, attributes) {
336
+ try {
337
+ this.sink.emit(Object.freeze({
338
+ timestamp: /* @__PURE__ */ new Date(),
339
+ level,
340
+ event,
341
+ attributes: mergeAttributes(this.attributes, attributes ?? {})
342
+ }));
343
+ } catch {
344
+ }
345
+ }
346
+ };
347
+ var runtimeNullLogSink = Object.freeze({ emit() {
348
+ } });
349
+ var runtimeNullLogger = new ScopedRuntimeLogger(runtimeNullLogSink, Object.freeze({}));
350
+ function createRuntimeLogger(sink, attributes = {}) {
351
+ return new ScopedRuntimeLogger(sink, safeAttributes(attributes));
352
+ }
353
+ function createRuntimeHostContext(sink, attributes = {}) {
354
+ return Object.freeze({ logger: createRuntimeLogger(sink, attributes) });
355
+ }
356
+ function createRecordingRuntimeLogSink(records) {
357
+ return { emit: (record3) => records.push(record3) };
358
+ }
359
+
360
+ // ../runtime/dist/adapters/auth/better-auth/errors.js
361
+ function authStartupError(code, nextAction, retryPrecondition = "Correct the documented Runtime auth configuration before restarting.") {
362
+ return new RuntimeDiagnosticError({
363
+ code,
364
+ stage: "startup",
365
+ servingStarted: false,
366
+ dataImpact: "none",
367
+ retryable: false,
368
+ retryPrecondition,
369
+ nextAction,
370
+ capability: "auth",
371
+ correlationId: crypto.randomUUID()
372
+ });
373
+ }
374
+
375
+ // ../runtime/dist/adapters/auth/better-auth/identity.js
376
+ var OMITTED = /* @__PURE__ */ new Set([
377
+ "password",
378
+ "hashedPassword",
379
+ "salt",
380
+ "iat",
381
+ "exp",
382
+ "iss",
383
+ "nbf",
384
+ "aud",
385
+ "jti",
386
+ "sub"
387
+ ]);
388
+ function scalar(value) {
389
+ return value === null || ["string", "number", "boolean"].includes(typeof value);
390
+ }
391
+ function toRuntimeIdentity(value) {
392
+ if (typeof value.id !== "string" || !value.id || typeof value.email !== "string" || !value.email)
393
+ return null;
394
+ const identity = {
395
+ id: value.id,
396
+ email: value.email,
397
+ ...typeof value.name === "string" ? { name: value.name } : {}
398
+ };
399
+ for (const [key, field] of Object.entries(value)) {
400
+ if (key === "id" || key === "email" || key === "name" || OMITTED.has(key))
401
+ continue;
402
+ if (scalar(field) || Array.isArray(field) && field.every(scalar))
403
+ identity[key] = field;
404
+ else if (field instanceof Date)
405
+ identity[key] = field.toISOString();
406
+ }
407
+ return identity;
408
+ }
409
+
410
+ // ../runtime/dist/adapters/auth/better-auth/token.js
411
+ import { createHash } from "node:crypto";
412
+ import { readFile } from "node:fs/promises";
413
+ import { isAbsolute, resolve } from "node:path";
414
+
415
+ // ../../node_modules/.pnpm/hono@4.13.17/node_modules/hono/dist/utils/jwt/jwa.js
416
+ var AlgorithmTypes = /* @__PURE__ */ (function(AlgorithmTypes2) {
417
+ AlgorithmTypes2["HS256"] = "HS256";
418
+ AlgorithmTypes2["HS384"] = "HS384";
419
+ AlgorithmTypes2["HS512"] = "HS512";
420
+ AlgorithmTypes2["RS256"] = "RS256";
421
+ AlgorithmTypes2["RS384"] = "RS384";
422
+ AlgorithmTypes2["RS512"] = "RS512";
423
+ AlgorithmTypes2["PS256"] = "PS256";
424
+ AlgorithmTypes2["PS384"] = "PS384";
425
+ AlgorithmTypes2["PS512"] = "PS512";
426
+ AlgorithmTypes2["ES256"] = "ES256";
427
+ AlgorithmTypes2["ES384"] = "ES384";
428
+ AlgorithmTypes2["ES512"] = "ES512";
429
+ AlgorithmTypes2["EdDSA"] = "EdDSA";
430
+ return AlgorithmTypes2;
431
+ })({});
432
+
433
+ // ../../node_modules/.pnpm/hono@4.13.17/node_modules/hono/dist/utils/url.js
434
+ var splitPath = (path) => {
435
+ const paths = path.split("/");
436
+ if (paths[0] === "") paths.shift();
437
+ return paths;
438
+ };
439
+ var splitRoutingPath = (routePath) => {
440
+ const { groups, path } = extractGroupsFromPath(routePath);
441
+ const paths = splitPath(path);
442
+ return replaceGroupMarks(paths, groups);
443
+ };
444
+ var extractGroupsFromPath = (path) => {
445
+ const groups = [];
446
+ path = path.replace(/\{[^}]+\}/g, (match, index) => {
447
+ const mark = `@${index}`;
448
+ groups.push([mark, match]);
449
+ return mark;
450
+ });
451
+ return {
452
+ groups,
453
+ path
454
+ };
455
+ };
456
+ var replaceGroupMarks = (paths, groups) => {
457
+ for (let i = groups.length - 1; i >= 0; i--) {
458
+ const [mark] = groups[i];
459
+ for (let j = paths.length - 1; j >= 0; j--) if (paths[j].includes(mark)) {
460
+ paths[j] = paths[j].replace(mark, groups[i][1]);
461
+ break;
462
+ }
463
+ }
464
+ return paths;
465
+ };
466
+ var patternCache = {};
467
+ var getPattern = (label, next) => {
468
+ if (label === "*") return "*";
469
+ const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
470
+ if (match) {
471
+ const cacheKey = `${label}#${next}`;
472
+ if (!patternCache[cacheKey]) {
473
+ if (match[2]) patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [
474
+ cacheKey,
475
+ match[1],
476
+ new RegExp(`^${match[2]}(?=/${next})`)
477
+ ] : [
478
+ label,
479
+ match[1],
480
+ new RegExp(`^${match[2]}$`)
481
+ ];
482
+ else patternCache[cacheKey] = [
483
+ label,
484
+ match[1],
485
+ true
486
+ ];
487
+ }
488
+ return patternCache[cacheKey];
489
+ }
490
+ return null;
491
+ };
492
+ var tryDecode = (str, decoder) => {
493
+ try {
494
+ return decoder(str);
495
+ } catch {
496
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
497
+ try {
498
+ return decoder(match);
499
+ } catch {
500
+ return match;
501
+ }
502
+ });
503
+ }
504
+ };
505
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
506
+ var getPath = (request) => {
507
+ const url = request.url;
508
+ const start = url.indexOf("/", url.indexOf(":") + 4);
509
+ let i = start;
510
+ for (; i < url.length; i++) {
511
+ const charCode = url.charCodeAt(i);
512
+ if (charCode === 37) {
513
+ const queryIndex = url.indexOf("?", i);
514
+ const hashIndex = url.indexOf("#", i);
515
+ const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
516
+ const path = url.slice(start, end);
517
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
518
+ } else if (charCode === 63 || charCode === 35) break;
519
+ }
520
+ return url.slice(start, i);
521
+ };
522
+ var getPathNoStrict = (request) => {
523
+ const result = getPath(request);
524
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
525
+ };
526
+ var stripPathPrefix = (rawPath, decodedPath, prefixLength) => {
527
+ if (rawPath.at(-1) === "/" && decodedPath.at(-1) !== "/") rawPath = rawPath.slice(0, -1);
528
+ let index = 0;
529
+ for (let i = decodedPath.indexOf("/"); i !== -1 && i < prefixLength; i = decodedPath.indexOf("/", i + 1)) {
530
+ index = rawPath.indexOf("/", index + 1);
531
+ if (index === -1) return "/";
532
+ }
533
+ return rawPath.slice(index) || "/";
534
+ };
535
+ var mergePath = (base, sub, ...rest) => {
536
+ if (rest.length) sub = mergePath(sub, ...rest);
537
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
538
+ };
539
+ var checkOptionalParameter = (path) => {
540
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) return null;
541
+ const segments = path.split("/");
542
+ const results = [];
543
+ let basePath = "";
544
+ segments.forEach((segment) => {
545
+ if (segment !== "" && !/\:/.test(segment)) basePath += "/" + segment;
546
+ else if (/\:/.test(segment)) {
547
+ if (segment.charCodeAt(segment.length - 1) === 63) {
548
+ if (results.length === 0 && basePath === "") results.push("/");
549
+ else results.push(basePath);
550
+ const optionalSegment = segment.slice(0, -1);
551
+ basePath += "/" + optionalSegment;
552
+ results.push(basePath);
553
+ } else basePath += "/" + segment;
554
+ }
555
+ });
556
+ return results.filter((v, i, a) => a.indexOf(v) === i);
557
+ };
558
+ var tryDecodeURIComponent = (str) => str.indexOf("%") !== -1 ? tryDecode(str, decodeURIComponent_) : str;
559
+ var _decodeURI = (value) => {
560
+ if (value.indexOf("+") !== -1) value = value.replace(/\+/g, " ");
561
+ return tryDecodeURIComponent(value);
562
+ };
563
+ var _getQueryParam = (url, key, multiple) => {
564
+ const hashIndex = url.indexOf("#", 8);
565
+ if (hashIndex !== -1) url = url.slice(0, hashIndex);
566
+ let encoded;
567
+ if (!multiple && key && !/[%+&=]/.test(key)) {
568
+ const queryIndex = url.indexOf("?", 8);
569
+ let keyIndex2 = queryIndex;
570
+ if (keyIndex2 === -1) return;
571
+ if (!url.startsWith(key, keyIndex2 + 1)) keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
572
+ while (keyIndex2 !== -1) {
573
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
574
+ if (trailingKeyCode === 61 || trailingKeyCode === 38 || isNaN(trailingKeyCode)) {
575
+ if (keyIndex2 > queryIndex && /(?:^|&)[^=&]*[%+]/.test(url.slice(queryIndex + 1, keyIndex2))) break;
576
+ if (trailingKeyCode === 61) {
577
+ const valueIndex = keyIndex2 + key.length + 2;
578
+ const endIndex = url.indexOf("&", valueIndex);
579
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
580
+ }
581
+ return "";
582
+ }
583
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
584
+ }
585
+ encoded = /[%+]/.test(url);
586
+ if (!encoded) return;
587
+ }
588
+ const results = /* @__PURE__ */ Object.create(null);
589
+ encoded ??= /[%+]/.test(url);
590
+ let keyIndex = url.indexOf("?", 8);
591
+ while (keyIndex !== -1) {
592
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
593
+ let valueIndex = url.indexOf("=", keyIndex);
594
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) valueIndex = -1;
595
+ let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex);
596
+ if (encoded) name = _decodeURI(name);
597
+ keyIndex = nextKeyIndex;
598
+ if (name === "") continue;
599
+ let value;
600
+ if (valueIndex === -1) value = "";
601
+ else {
602
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
603
+ if (encoded) value = _decodeURI(value);
604
+ }
605
+ if (multiple) {
606
+ if (!(results[name] && Array.isArray(results[name]))) results[name] = [];
607
+ results[name].push(value);
608
+ } else results[name] ??= value;
609
+ }
610
+ return key ? results[key] : results;
611
+ };
612
+ var getQueryParam = _getQueryParam;
613
+ var getQueryParams = (url, key) => {
614
+ return _getQueryParam(url, key, true);
615
+ };
616
+ var decodeURIComponent_ = decodeURIComponent;
617
+
618
+ // ../../node_modules/.pnpm/hono@4.13.17/node_modules/hono/dist/utils/encode.js
619
+ var decodeBase64Url = (str) => {
620
+ return decodeBase64(str.replace(/_|-/g, (m) => ({
621
+ _: "/",
622
+ "-": "+"
623
+ })[m] ?? m));
624
+ };
625
+ var encodeBase64Url = (buf) => encodeBase64(buf).replace(/\/|\+/g, (m) => ({
626
+ "/": "_",
627
+ "+": "-"
628
+ })[m] ?? m);
629
+ var encodeBase64 = (buf) => {
630
+ let binary = "";
631
+ const bytes = new Uint8Array(buf);
632
+ for (let i = 0, len = bytes.length; i < len; i++) binary += String.fromCharCode(bytes[i]);
633
+ return btoa(binary);
634
+ };
635
+ var decodeBase64 = (str) => {
636
+ const binary = atob(str);
637
+ const bytes = new Uint8Array(new ArrayBuffer(binary.length));
638
+ const half = binary.length / 2;
639
+ for (let i = 0, j = binary.length - 1; i <= half; i++, j--) {
640
+ bytes[i] = binary.charCodeAt(i);
641
+ bytes[j] = binary.charCodeAt(j);
642
+ }
643
+ return bytes;
644
+ };
645
+
646
+ // ../../node_modules/.pnpm/hono@4.13.17/node_modules/hono/dist/utils/jwt/types.js
647
+ var JwtAlgorithmNotImplemented = class extends Error {
648
+ constructor(alg) {
649
+ super(`${alg} is not an implemented algorithm`);
650
+ this.name = "JwtAlgorithmNotImplemented";
651
+ }
652
+ };
653
+ var JwtAlgorithmRequired = class extends Error {
654
+ constructor() {
655
+ super('JWT verification requires "alg" option to be specified');
656
+ this.name = "JwtAlgorithmRequired";
657
+ }
658
+ };
659
+ var JwtAlgorithmMismatch = class extends Error {
660
+ constructor(expected, actual) {
661
+ super(`JWT algorithm mismatch: expected "${expected}", got "${actual}"`);
662
+ this.name = "JwtAlgorithmMismatch";
663
+ }
664
+ };
665
+ var JwtTokenInvalid = class extends Error {
666
+ constructor(token) {
667
+ super(`invalid JWT token: ${token}`);
668
+ this.name = "JwtTokenInvalid";
669
+ }
670
+ };
671
+ var JwtTokenNotBefore = class extends Error {
672
+ constructor(token) {
673
+ super(`token (${token}) is being used before it's valid`);
674
+ this.name = "JwtTokenNotBefore";
675
+ }
676
+ };
677
+ var JwtTokenExpired = class extends Error {
678
+ constructor(token) {
679
+ super(`token (${token}) expired`);
680
+ this.name = "JwtTokenExpired";
681
+ }
682
+ };
683
+ var JwtTokenIssuedAt = class extends Error {
684
+ constructor(currentTimestamp, iat) {
685
+ super(`Invalid "iat" claim, must be a valid number lower than "${currentTimestamp}" (iat: "${iat}")`);
686
+ this.name = "JwtTokenIssuedAt";
687
+ }
688
+ };
689
+ var JwtTokenIssuer = class extends Error {
690
+ constructor(expected, iss) {
691
+ super(`expected issuer "${expected}", got ${iss ? `"${iss}"` : "none"} `);
692
+ this.name = "JwtTokenIssuer";
693
+ }
694
+ };
695
+ var JwtHeaderInvalid = class extends Error {
696
+ constructor(header) {
697
+ super(`jwt header is invalid: ${JSON.stringify(header)}`);
698
+ this.name = "JwtHeaderInvalid";
699
+ }
700
+ };
701
+ var JwtHeaderRequiresKid = class extends Error {
702
+ constructor(header) {
703
+ super(`required "kid" in jwt header: ${JSON.stringify(header)}`);
704
+ this.name = "JwtHeaderRequiresKid";
705
+ }
706
+ };
707
+ var JwtSymmetricAlgorithmNotAllowed = class extends Error {
708
+ constructor(alg) {
709
+ super(`symmetric algorithm "${alg}" is not allowed for JWK verification`);
710
+ this.name = "JwtSymmetricAlgorithmNotAllowed";
711
+ }
712
+ };
713
+ var JwtAlgorithmNotAllowed = class extends Error {
714
+ constructor(alg, allowedAlgorithms) {
715
+ super(`algorithm "${alg}" is not in the allowed list: [${allowedAlgorithms.join(", ")}]`);
716
+ this.name = "JwtAlgorithmNotAllowed";
717
+ }
718
+ };
719
+ var JwtTokenSignatureMismatched = class extends Error {
720
+ constructor(token) {
721
+ super(`token(${token}) signature mismatched`);
722
+ this.name = "JwtTokenSignatureMismatched";
723
+ }
724
+ };
725
+ var JwtPayloadRequiresAud = class extends Error {
726
+ constructor(payload) {
727
+ super(`required "aud" in jwt payload: ${JSON.stringify(payload)}`);
728
+ this.name = "JwtPayloadRequiresAud";
729
+ }
730
+ };
731
+ var JwtTokenAudience = class extends Error {
732
+ constructor(expected, aud) {
733
+ super(`expected audience "${Array.isArray(expected) ? expected.join(", ") : expected}", got "${aud}"`);
734
+ this.name = "JwtTokenAudience";
735
+ }
736
+ };
737
+
738
+ // ../../node_modules/.pnpm/hono@4.13.17/node_modules/hono/dist/utils/jwt/utf8.js
739
+ var utf8Encoder = new TextEncoder();
740
+ var utf8Decoder = new TextDecoder();
741
+
742
+ // ../../node_modules/.pnpm/hono@4.13.17/node_modules/hono/dist/helper/adapter/index.js
743
+ var knownUserAgents = {
744
+ deno: "Deno",
745
+ bun: "Bun",
746
+ workerd: "Cloudflare-Workers",
747
+ node: "Node.js"
748
+ };
749
+ var getRuntimeKey = () => {
750
+ const global = globalThis;
751
+ if (typeof navigator !== "undefined" && typeof navigator.userAgent === "string") {
752
+ for (const [runtimeKey, userAgent] of Object.entries(knownUserAgents)) if (checkUserAgentEquals(userAgent)) return runtimeKey;
753
+ }
754
+ if (typeof global?.EdgeRuntime === "string") return "edge-light";
755
+ if (global?.fastly !== void 0) return "fastly";
756
+ if (global?.process?.release?.name === "node") return "node";
757
+ return "other";
758
+ };
759
+ var checkUserAgentEquals = (platform) => {
760
+ return navigator.userAgent.startsWith(platform);
761
+ };
762
+
763
+ // ../../node_modules/.pnpm/hono@4.13.17/node_modules/hono/dist/utils/jwt/jws.js
764
+ async function signing(privateKey, alg, data) {
765
+ const algorithm = getKeyAlgorithm(alg);
766
+ const cryptoKey = await importPrivateKey(privateKey, algorithm);
767
+ return await crypto.subtle.sign(algorithm, cryptoKey, data);
768
+ }
769
+ async function verifying(publicKey, alg, signature, data) {
770
+ const algorithm = getKeyAlgorithm(alg);
771
+ const cryptoKey = await importPublicKey(publicKey, algorithm);
772
+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
773
+ }
774
+ function pemToBinary(pem) {
775
+ return decodeBase64(pem.replace(/-+(BEGIN|END).*?-+/g, "").replace(/\s/g, ""));
776
+ }
777
+ async function importPrivateKey(key, alg) {
778
+ if (!crypto.subtle || !crypto.subtle.importKey) throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.");
779
+ if (isCryptoKey(key)) {
780
+ if (key.type !== "private" && key.type !== "secret") throw new Error(`unexpected key type: CryptoKey.type is ${key.type}, expected private or secret`);
781
+ return key;
782
+ }
783
+ const usages = ["sign"];
784
+ if (typeof key === "object") return await crypto.subtle.importKey("jwk", key, alg, false, usages);
785
+ if (key.includes("PRIVATE")) return await crypto.subtle.importKey("pkcs8", pemToBinary(key), alg, false, usages);
786
+ return await crypto.subtle.importKey("raw", utf8Encoder.encode(key), alg, false, usages);
787
+ }
788
+ async function importPublicKey(key, alg) {
789
+ if (!crypto.subtle || !crypto.subtle.importKey) throw new Error("`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.");
790
+ if (isCryptoKey(key)) {
791
+ if (key.type === "public" || key.type === "secret") return key;
792
+ key = await exportPublicJwkFrom(key);
793
+ }
794
+ if (typeof key === "string" && key.includes("PRIVATE")) key = await exportPublicJwkFrom(await crypto.subtle.importKey("pkcs8", pemToBinary(key), alg, true, ["sign"]));
795
+ const usages = ["verify"];
796
+ if (typeof key === "object") return await crypto.subtle.importKey("jwk", key, alg, false, usages);
797
+ if (key.includes("PUBLIC")) return await crypto.subtle.importKey("spki", pemToBinary(key), alg, false, usages);
798
+ return await crypto.subtle.importKey("raw", utf8Encoder.encode(key), alg, false, usages);
799
+ }
800
+ async function exportPublicJwkFrom(privateKey) {
801
+ if (privateKey.type !== "private") throw new Error(`unexpected key type: ${privateKey.type}`);
802
+ if (!privateKey.extractable) throw new Error("unexpected private key is unextractable");
803
+ const jwk = await crypto.subtle.exportKey("jwk", privateKey);
804
+ const { kty } = jwk;
805
+ const { alg, e, n } = jwk;
806
+ const { crv, x, y } = jwk;
807
+ return {
808
+ kty,
809
+ alg,
810
+ e,
811
+ n,
812
+ crv,
813
+ x,
814
+ y,
815
+ key_ops: ["verify"]
816
+ };
817
+ }
818
+ function getKeyAlgorithm(name) {
819
+ switch (name) {
820
+ case "HS256":
821
+ return {
822
+ name: "HMAC",
823
+ hash: { name: "SHA-256" }
824
+ };
825
+ case "HS384":
826
+ return {
827
+ name: "HMAC",
828
+ hash: { name: "SHA-384" }
829
+ };
830
+ case "HS512":
831
+ return {
832
+ name: "HMAC",
833
+ hash: { name: "SHA-512" }
834
+ };
835
+ case "RS256":
836
+ return {
837
+ name: "RSASSA-PKCS1-v1_5",
838
+ hash: { name: "SHA-256" }
839
+ };
840
+ case "RS384":
841
+ return {
842
+ name: "RSASSA-PKCS1-v1_5",
843
+ hash: { name: "SHA-384" }
844
+ };
845
+ case "RS512":
846
+ return {
847
+ name: "RSASSA-PKCS1-v1_5",
848
+ hash: { name: "SHA-512" }
849
+ };
850
+ case "PS256":
851
+ return {
852
+ name: "RSA-PSS",
853
+ hash: { name: "SHA-256" },
854
+ saltLength: 32
855
+ };
856
+ case "PS384":
857
+ return {
858
+ name: "RSA-PSS",
859
+ hash: { name: "SHA-384" },
860
+ saltLength: 48
861
+ };
862
+ case "PS512":
863
+ return {
864
+ name: "RSA-PSS",
865
+ hash: { name: "SHA-512" },
866
+ saltLength: 64
867
+ };
868
+ case "ES256":
869
+ return {
870
+ name: "ECDSA",
871
+ hash: { name: "SHA-256" },
872
+ namedCurve: "P-256"
873
+ };
874
+ case "ES384":
875
+ return {
876
+ name: "ECDSA",
877
+ hash: { name: "SHA-384" },
878
+ namedCurve: "P-384"
879
+ };
880
+ case "ES512":
881
+ return {
882
+ name: "ECDSA",
883
+ hash: { name: "SHA-512" },
884
+ namedCurve: "P-521"
885
+ };
886
+ case "EdDSA":
887
+ return {
888
+ name: "Ed25519",
889
+ namedCurve: "Ed25519"
890
+ };
891
+ default:
892
+ throw new JwtAlgorithmNotImplemented(name);
893
+ }
894
+ }
895
+ function isCryptoKey(key) {
896
+ if (getRuntimeKey() === "node" && !!crypto.webcrypto) return key instanceof crypto.webcrypto.CryptoKey;
897
+ return key instanceof CryptoKey;
898
+ }
899
+
900
+ // ../../node_modules/.pnpm/hono@4.13.17/node_modules/hono/dist/utils/jwt/jwt.js
901
+ var encodeJwtPart = (part) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(part)).buffer).replace(/=/g, "");
902
+ var encodeSignaturePart = (buf) => encodeBase64Url(buf).replace(/=/g, "");
903
+ var decodeJwtPart = (part) => JSON.parse(utf8Decoder.decode(decodeBase64Url(part)));
904
+ function isTokenHeader(obj) {
905
+ if (typeof obj === "object" && obj !== null) {
906
+ const objWithAlg = obj;
907
+ return "alg" in objWithAlg && Object.values(AlgorithmTypes).includes(objWithAlg.alg) && (!("typ" in objWithAlg) || objWithAlg.typ === "JWT") && !("crit" in objWithAlg);
908
+ }
909
+ return false;
910
+ }
911
+ var sign = async (payload, privateKey, alg = "HS256") => {
912
+ const encodedPayload = encodeJwtPart(payload);
913
+ let encodedHeader;
914
+ if (typeof privateKey === "object" && "alg" in privateKey) {
915
+ alg = privateKey.alg;
916
+ encodedHeader = encodeJwtPart({
917
+ alg,
918
+ typ: "JWT",
919
+ kid: privateKey.kid
920
+ });
921
+ } else encodedHeader = encodeJwtPart({
922
+ alg,
923
+ typ: "JWT"
924
+ });
925
+ const partialToken = `${encodedHeader}.${encodedPayload}`;
926
+ const signaturePart = await signing(privateKey, alg, utf8Encoder.encode(partialToken));
927
+ return `${partialToken}.${encodeSignaturePart(signaturePart)}`;
928
+ };
929
+ var verify = async (token, publicKey, algOrOptions) => {
930
+ if (!algOrOptions) throw new JwtAlgorithmRequired();
931
+ const { alg, iss, nbf = true, exp = true, iat = true, aud } = typeof algOrOptions === "string" ? { alg: algOrOptions } : algOrOptions;
932
+ if (!alg) throw new JwtAlgorithmRequired();
933
+ const tokenParts = token.split(".");
934
+ if (tokenParts.length !== 3) throw new JwtTokenInvalid(token);
935
+ const { header, payload } = decode(token);
936
+ if (!isTokenHeader(header)) throw new JwtHeaderInvalid(header);
937
+ if (header.alg !== alg) throw new JwtAlgorithmMismatch(alg, header.alg);
938
+ const now = Math.floor(Date.now() / 1e3);
939
+ if (nbf && payload.nbf !== void 0) {
940
+ if (typeof payload.nbf !== "number" || !Number.isFinite(payload.nbf) || payload.nbf > now) throw new JwtTokenNotBefore(token);
941
+ }
942
+ if (exp && payload.exp !== void 0) {
943
+ if (typeof payload.exp !== "number" || !Number.isFinite(payload.exp) || payload.exp <= now) throw new JwtTokenExpired(token);
944
+ }
945
+ if (iat && payload.iat !== void 0) {
946
+ if (typeof payload.iat !== "number" || !Number.isFinite(payload.iat) || now < payload.iat) throw new JwtTokenIssuedAt(now, payload.iat);
947
+ }
948
+ if (iss) {
949
+ if (!payload.iss) throw new JwtTokenIssuer(iss, null);
950
+ if (typeof iss === "string" && payload.iss !== iss) throw new JwtTokenIssuer(iss, payload.iss);
951
+ if (iss instanceof RegExp && !iss.test(payload.iss)) throw new JwtTokenIssuer(iss, payload.iss);
952
+ }
953
+ if (aud) {
954
+ if (!payload.aud) throw new JwtPayloadRequiresAud(payload);
955
+ if (!(Array.isArray(payload.aud) ? payload.aud : [payload.aud]).some((payloadAud) => aud instanceof RegExp ? aud.test(payloadAud) : typeof aud === "string" ? payloadAud === aud : Array.isArray(aud) && aud.includes(payloadAud))) throw new JwtTokenAudience(aud, payload.aud);
956
+ }
957
+ const headerPayload = token.substring(0, token.lastIndexOf("."));
958
+ if (!/^[A-Za-z0-9_-]*={0,2}$/.test(tokenParts[2])) throw new JwtTokenInvalid(token);
959
+ let signature;
960
+ try {
961
+ signature = decodeBase64Url(tokenParts[2]);
962
+ } catch {
963
+ throw new JwtTokenInvalid(token);
964
+ }
965
+ if (!await verifying(publicKey, alg, signature, utf8Encoder.encode(headerPayload))) throw new JwtTokenSignatureMismatched(token);
966
+ return payload;
967
+ };
968
+ var symmetricAlgorithms = [
969
+ "HS256",
970
+ "HS384",
971
+ "HS512"
972
+ ];
973
+ var verifyWithJwks = async (token, options, init) => {
974
+ const verifyOpts = options.verification || {};
975
+ const header = decodeHeader(token);
976
+ if (!isTokenHeader(header)) throw new JwtHeaderInvalid(header);
977
+ if (!header.kid) throw new JwtHeaderRequiresKid(header);
978
+ if (symmetricAlgorithms.includes(header.alg)) throw new JwtSymmetricAlgorithmNotAllowed(header.alg);
979
+ if (!options.allowedAlgorithms.includes(header.alg)) throw new JwtAlgorithmNotAllowed(header.alg, options.allowedAlgorithms);
980
+ let verifyKeys = options.keys ? [...options.keys] : void 0;
981
+ if (options.jwks_uri) {
982
+ const response = await fetch(options.jwks_uri, init);
983
+ if (!response.ok) throw new Error(`failed to fetch JWKS from ${options.jwks_uri}`);
984
+ const data = await response.json();
985
+ if (!data.keys) throw new Error('invalid JWKS response. "keys" field is missing');
986
+ if (!Array.isArray(data.keys)) throw new Error('invalid JWKS response. "keys" field is not an array');
987
+ verifyKeys ??= [];
988
+ verifyKeys.push(...data.keys);
989
+ } else if (!verifyKeys) throw new Error('verifyWithJwks requires options for either "keys" or "jwks_uri" or both');
990
+ const matchingKey = verifyKeys.find((key) => key.kid === header.kid);
991
+ if (!matchingKey) throw new JwtTokenInvalid(token);
992
+ if (matchingKey.alg && matchingKey.alg !== header.alg) throw new JwtAlgorithmMismatch(matchingKey.alg, header.alg);
993
+ return await verify(token, matchingKey, {
994
+ alg: header.alg,
995
+ ...verifyOpts
996
+ });
997
+ };
998
+ var decode = (token) => {
999
+ const parts = token.split(".");
1000
+ if (parts.length !== 3) throw new JwtTokenInvalid(token);
1001
+ try {
1002
+ return {
1003
+ header: decodeJwtPart(parts[0]),
1004
+ payload: decodeJwtPart(parts[1])
1005
+ };
1006
+ } catch {
1007
+ throw new JwtTokenInvalid(token);
1008
+ }
1009
+ };
1010
+ var decodeHeader = (token) => {
1011
+ const parts = token.split(".");
1012
+ if (parts.length !== 3) throw new JwtTokenInvalid(token);
1013
+ try {
1014
+ return decodeJwtPart(parts[0]);
1015
+ } catch {
1016
+ throw new JwtTokenInvalid(token);
1017
+ }
1018
+ };
1019
+
1020
+ // ../../node_modules/.pnpm/hono@4.13.17/node_modules/hono/dist/utils/jwt/index.js
1021
+ var Jwt = {
1022
+ sign,
1023
+ verify,
1024
+ decode,
1025
+ verifyWithJwks
1026
+ };
1027
+
1028
+ // ../../node_modules/.pnpm/hono@4.13.17/node_modules/hono/dist/middleware/jwt/jwt.js
1029
+ var verifyWithJwks2 = Jwt.verifyWithJwks;
1030
+ var verify2 = Jwt.verify;
1031
+ var decode2 = Jwt.decode;
1032
+ var sign2 = Jwt.sign;
1033
+
1034
+ // ../runtime/dist/adapters/auth/better-auth/token.js
1035
+ var TOKEN_LIFETIME_SECONDS = 5 * 60;
1036
+ var verifiedDigestCacheLimit = 128;
1037
+ var inFlightProofLimit = 64;
1038
+ var allowedHonoAlgorithms = new Set(Object.values(AlgorithmTypes));
1039
+ async function resolveServerCompatibleAccessTokenKey(environment) {
1040
+ const internalToken = environment.GENCOW_INTERNAL_TOKEN;
1041
+ if (internalToken !== void 0) {
1042
+ if (!internalToken.trim()) {
1043
+ throw authStartupError("RUNTIME_AUTH_ACCESS_TOKEN_KEY_UNAVAILABLE", "Configure a nonblank GENCOW_INTERNAL_TOKEN, or omit it to use the explicitly configured existing key file.");
1044
+ }
1045
+ return createHash("sha256").update(`gencow-settings-key:${internalToken}`).digest().subarray(0, 32);
1046
+ }
1047
+ const root = environment.GENCOW_APP_DATA_DIR?.trim();
1048
+ const configured = environment.GENCOW_SECRET_KEY_PATH?.trim();
1049
+ const keyPath = configured ? isAbsolute(configured) ? configured : root && isAbsolute(root) ? resolve(root, configured) : null : root && isAbsolute(root) ? resolve(root, ".gencow", "secret.key") : null;
1050
+ if (!keyPath) {
1051
+ throw authStartupError("RUNTIME_AUTH_ACCESS_TOKEN_KEY_UNAVAILABLE", "Provide GENCOW_INTERNAL_TOKEN, an absolute GENCOW_SECRET_KEY_PATH, or an absolute GENCOW_APP_DATA_DIR with an existing key.");
1052
+ }
1053
+ const key = await readFile(keyPath).catch(() => null);
1054
+ if (!key || key.length !== 32) {
1055
+ throw authStartupError("RUNTIME_AUTH_ACCESS_TOKEN_KEY_UNAVAILABLE", "Provide an existing 32-byte Runtime access-token key before restarting.");
1056
+ }
1057
+ return key;
1058
+ }
1059
+ function secret(key) {
1060
+ return Buffer.from(key).toString("base64");
1061
+ }
1062
+ function normalizedVerifiedIdentity(payload) {
1063
+ if (payload.iss !== "gencow-auth" || typeof payload.sub !== "string")
1064
+ return null;
1065
+ return toRuntimeIdentity({ ...payload, id: payload.sub });
1066
+ }
1067
+ function decodeHonoVerifiedPayload(value) {
1068
+ try {
1069
+ const decoded = decode2(value);
1070
+ const header = decoded.header;
1071
+ if (header === null || typeof header !== "object" || !("alg" in header) || typeof header.alg !== "string" || !allowedHonoAlgorithms.has(header.alg) || "typ" in header && header.typ !== "JWT" || header.alg !== AlgorithmTypes.HS256)
1072
+ return void 0;
1073
+ const payload = decoded.payload;
1074
+ if (payload === null || payload === void 0)
1075
+ return void 0;
1076
+ const claims = payload;
1077
+ const now = Math.floor(Date.now() / 1e3);
1078
+ const notBefore = claims.nbf;
1079
+ if (notBefore !== void 0 && (typeof notBefore !== "number" || !Number.isFinite(notBefore) || notBefore > now))
1080
+ return void 0;
1081
+ const expiresAt = claims.exp;
1082
+ if (expiresAt !== void 0 && (typeof expiresAt !== "number" || !Number.isFinite(expiresAt) || expiresAt <= now))
1083
+ return void 0;
1084
+ const issuedAt = claims.iat;
1085
+ if (issuedAt !== void 0 && (typeof issuedAt !== "number" || !Number.isFinite(issuedAt) || now < issuedAt))
1086
+ return void 0;
1087
+ return decoded.payload;
1088
+ } catch {
1089
+ return void 0;
1090
+ }
1091
+ }
1092
+ async function issueAccessToken(identity, key) {
1093
+ const now = Math.floor(Date.now() / 1e3);
1094
+ const payload = {
1095
+ ...identity,
1096
+ sub: identity.id,
1097
+ iat: now,
1098
+ exp: now + TOKEN_LIFETIME_SECONDS,
1099
+ iss: "gencow-auth"
1100
+ };
1101
+ return { token: await sign2(payload, secret(key), "HS256"), expires_in: TOKEN_LIFETIME_SECONDS };
1102
+ }
1103
+ function createAuthGenerationAccessTokenVerifier(key) {
1104
+ const keyCopy = new Uint8Array(key);
1105
+ const secretBytes = new TextEncoder().encode(secret(keyCopy));
1106
+ let importedKey;
1107
+ const verifiedDigests = /* @__PURE__ */ new Map();
1108
+ const inFlightProofs = /* @__PURE__ */ new Map();
1109
+ function importVerificationKey() {
1110
+ if (!importedKey) {
1111
+ try {
1112
+ importedKey = globalThis.crypto.subtle.importKey("raw", secretBytes, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
1113
+ } catch (error) {
1114
+ importedKey = Promise.reject(error);
1115
+ }
1116
+ }
1117
+ return importedKey;
1118
+ }
1119
+ function rememberVerifiedDigest(digest) {
1120
+ verifiedDigests.delete(digest);
1121
+ verifiedDigests.set(digest, true);
1122
+ if (verifiedDigests.size > verifiedDigestCacheLimit) {
1123
+ const leastRecentlyUsed = verifiedDigests.keys().next().value;
1124
+ if (leastRecentlyUsed !== void 0)
1125
+ verifiedDigests.delete(leastRecentlyUsed);
1126
+ }
1127
+ }
1128
+ function touchVerifiedDigest(digest) {
1129
+ if (!verifiedDigests.has(digest))
1130
+ return false;
1131
+ verifiedDigests.delete(digest);
1132
+ verifiedDigests.set(digest, true);
1133
+ return true;
1134
+ }
1135
+ async function signatureOnlyVerify(value, verificationKey, payload) {
1136
+ try {
1137
+ await verify2(value, verificationKey, {
1138
+ alg: AlgorithmTypes.HS256,
1139
+ nbf: false,
1140
+ exp: false,
1141
+ iat: false
1142
+ });
1143
+ return normalizedVerifiedIdentity(payload);
1144
+ } catch {
1145
+ return null;
1146
+ }
1147
+ }
1148
+ return async (value) => {
1149
+ const payload = decodeHonoVerifiedPayload(value);
1150
+ if (payload === void 0) {
1151
+ const invalidDigest = createHash("sha256").update(value, "utf8").digest("hex");
1152
+ verifiedDigests.delete(invalidDigest);
1153
+ return null;
1154
+ }
1155
+ const digest = createHash("sha256").update(value, "utf8").digest("hex");
1156
+ if (touchVerifiedDigest(digest)) {
1157
+ const identity = normalizedVerifiedIdentity(payload);
1158
+ if (identity === null)
1159
+ verifiedDigests.delete(digest);
1160
+ return identity;
1161
+ }
1162
+ const existingProof = inFlightProofs.get(digest);
1163
+ if (existingProof) {
1164
+ if (!await existingProof) {
1165
+ try {
1166
+ return await signatureOnlyVerify(value, await importVerificationKey(), payload);
1167
+ } catch {
1168
+ return signatureOnlyVerify(value, secret(keyCopy), payload);
1169
+ }
1170
+ }
1171
+ return normalizedVerifiedIdentity(payload);
1172
+ }
1173
+ let cryptoKey;
1174
+ try {
1175
+ cryptoKey = await importVerificationKey();
1176
+ } catch {
1177
+ return signatureOnlyVerify(value, secret(keyCopy), payload);
1178
+ }
1179
+ if (touchVerifiedDigest(digest)) {
1180
+ const identity = normalizedVerifiedIdentity(payload);
1181
+ if (identity === null)
1182
+ verifiedDigests.delete(digest);
1183
+ return identity;
1184
+ }
1185
+ const proofAfterImport = inFlightProofs.get(digest);
1186
+ if (proofAfterImport) {
1187
+ if (!await proofAfterImport) {
1188
+ return signatureOnlyVerify(value, cryptoKey, payload);
1189
+ }
1190
+ return normalizedVerifiedIdentity(payload);
1191
+ }
1192
+ if (inFlightProofs.size >= inFlightProofLimit)
1193
+ return signatureOnlyVerify(value, cryptoKey, payload);
1194
+ let resolveProof;
1195
+ const proof = new Promise((resolve2) => {
1196
+ resolveProof = resolve2;
1197
+ });
1198
+ inFlightProofs.set(digest, proof);
1199
+ try {
1200
+ await verify2(value, cryptoKey, {
1201
+ alg: AlgorithmTypes.HS256,
1202
+ nbf: false,
1203
+ exp: false,
1204
+ iat: false
1205
+ });
1206
+ const identity = normalizedVerifiedIdentity(payload);
1207
+ if (identity !== null)
1208
+ rememberVerifiedDigest(digest);
1209
+ resolveProof(true);
1210
+ return identity;
1211
+ } catch {
1212
+ resolveProof(false);
1213
+ return null;
1214
+ } finally {
1215
+ if (inFlightProofs.get(digest) === proof)
1216
+ inFlightProofs.delete(digest);
1217
+ }
1218
+ };
1219
+ }
1220
+
1221
+ // ../runtime/dist/admin/auth-diagnostics.js
1222
+ function authAdministrationFailure(code) {
1223
+ const unknown = code === "RUNTIME_AUTH_PROFILE_DELETE_FAILED" || code === "RUNTIME_AUTH_PROFILE_UPDATE_FAILED" || code === "RUNTIME_AUTH_PROFILE_INPUT_REJECTED";
1224
+ return new RuntimeDiagnosticError({
1225
+ code,
1226
+ stage: "request",
1227
+ capability: "auth",
1228
+ servingStarted: "unchanged",
1229
+ dataImpact: unknown ? "unknown" : "none",
1230
+ retryable: false,
1231
+ retryPrecondition: unknown ? "Explicitly inspect the affected Auth profiles and configured hook/provider effects before a deliberate new action." : code === "RUNTIME_LOCAL_AUTH_INPUT_INVALID" ? "Correct the bounded query, current profile ID or allowed profile fields before trying again." : "Use a current profile and a selected provider that supports this Auth operation.",
1232
+ nextAction: code === "RUNTIME_AUTH_PROFILE_INPUT_REJECTED" ? "Correct the selected profile fields or configured Auth field validation, then explicitly refresh Auth and inspect prior callback effects before a deliberate new action. No rollback or automatic replay is claimed." : unknown ? "Refresh Auth and inspect the current profile before retrying. A provider hook or session update may have changed state; no rollback is claimed and writes are not replayed." : code === "RUNTIME_LOCAL_AUTH_INPUT_INVALID" ? "Use bounded page inputs and only name, email, image or email_verified for profile changes. Identity, timestamps, credentials and role fields cannot be edited. No profile was changed." : "Refresh Auth after checking the selected provider and current profile. If this operation is unsupported, use a supported view; generic Data SQL is never an Auth fallback. No profile was changed."
1233
+ });
1234
+ }
1235
+
1236
+ // ../runtime/dist/admin/auth-input.js
1237
+ function record(value) {
1238
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1239
+ }
1240
+ function validateAuthProfileId(id) {
1241
+ if (typeof id !== "string" || !id || id.length > 256 || /[\x00-\x1f/\\]/u.test(id))
1242
+ throw authAdministrationFailure("RUNTIME_LOCAL_AUTH_INPUT_INVALID");
1243
+ }
1244
+ function validateAuthProfileUpdate(input) {
1245
+ validateAuthProfileId(input.id);
1246
+ const patch = record(input.patch);
1247
+ if (!patch || !Object.keys(patch).length || Object.keys(patch).some((key) => !["name", "email", "image", "email_verified"].includes(key)))
1248
+ throw authAdministrationFailure("RUNTIME_LOCAL_AUTH_INPUT_INVALID");
1249
+ const captured = {};
1250
+ for (const [key, value] of Object.entries(patch)) {
1251
+ if (key === "email_verified") {
1252
+ if (typeof value !== "boolean")
1253
+ throw authAdministrationFailure("RUNTIME_LOCAL_AUTH_INPUT_INVALID");
1254
+ captured.email_verified = value;
1255
+ } else if (key === "image" && value === null)
1256
+ captured.image = null;
1257
+ else {
1258
+ if (typeof value !== "string" || !value.trim() || value.length > (key === "email" ? 320 : key === "image" ? 2048 : 512) || /[\x00-\x1f]/u.test(value))
1259
+ throw authAdministrationFailure("RUNTIME_LOCAL_AUTH_INPUT_INVALID");
1260
+ if (key === "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(value))
1261
+ throw authAdministrationFailure("RUNTIME_LOCAL_AUTH_INPUT_INVALID");
1262
+ if (key === "image") {
1263
+ let url;
1264
+ try {
1265
+ url = new URL(value);
1266
+ } catch {
1267
+ throw authAdministrationFailure("RUNTIME_LOCAL_AUTH_INPUT_INVALID");
1268
+ }
1269
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password)
1270
+ throw authAdministrationFailure("RUNTIME_LOCAL_AUTH_INPUT_INVALID");
1271
+ }
1272
+ captured[key] = key === "email" ? value.toLowerCase() : value;
1273
+ }
1274
+ }
1275
+ return Object.freeze({ id: input.id, patch: Object.freeze(captured), request: input.request });
1276
+ }
1277
+
1278
+ // ../shared/dist/src/auth-rate-limit-policy.js
1279
+ var GENCOW_AUTH_RATE_LIMIT = Object.freeze({
1280
+ enabled: true,
1281
+ storage: "database",
1282
+ window: 600,
1283
+ max: 120,
1284
+ customRules: Object.freeze({
1285
+ "/sign-in/email": Object.freeze({ window: 600, max: 10 }),
1286
+ "/sign-up/email": Object.freeze({ window: 600, max: 5 }),
1287
+ "/token": Object.freeze({ window: 300, max: 120 }),
1288
+ "/send-verification-email": Object.freeze({ window: 600, max: 5 })
1289
+ })
1290
+ });
1291
+ var GENCOW_AUTH_IP_ADDRESS = Object.freeze({
1292
+ ipAddressHeaders: Object.freeze(["x-real-ip"])
1293
+ });
1294
+
1295
+ // ../runtime/dist/adapters/auth/better-auth/rate-limit-policy.js
1296
+ function invalidRateLimitConfig(nextAction = "Correct defineAuth.local.rateLimit or defineAuth.local.advanced.ipAddress in auth.ts; regenerate and restart.") {
1297
+ throw authStartupError("RUNTIME_AUTH_RATE_LIMIT_CONFIG_INVALID", nextAction);
1298
+ }
1299
+ function record2(value, keys) {
1300
+ if (!value || typeof value !== "object" || Array.isArray(value) || keys && Object.keys(value).some((key) => !keys.includes(key)))
1301
+ invalidRateLimitConfig();
1302
+ return value;
1303
+ }
1304
+ function positive(value) {
1305
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0)
1306
+ invalidRateLimitConfig();
1307
+ }
1308
+ function strings(value, header = false) {
1309
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string" || !item.trim() || header && !/^[!#$%&'*+.^_`|~0-9a-z-]+$/iu.test(item)))
1310
+ invalidRateLimitConfig();
1311
+ const result = [...value];
1312
+ Object.freeze(result);
1313
+ return result;
1314
+ }
1315
+ function snapshotLocalAuthConfig(value) {
1316
+ if (value === void 0)
1317
+ return void 0;
1318
+ const local = record2(value, ["rateLimit", "advanced"]);
1319
+ const rate = local.rateLimit === void 0 ? void 0 : record2(local.rateLimit, ["enabled", "storage", "customStorage", "window", "max", "customRules"]);
1320
+ if (rate?.enabled !== void 0 && typeof rate.enabled !== "boolean")
1321
+ invalidRateLimitConfig();
1322
+ if (rate?.storage !== void 0 && (typeof rate.storage !== "string" || !["memory", "database"].includes(rate.storage)))
1323
+ invalidRateLimitConfig();
1324
+ if (rate?.customStorage !== void 0) {
1325
+ const provider = record2(rate.customStorage);
1326
+ if (typeof provider.consume !== "function")
1327
+ invalidRateLimitConfig("Implement defineAuth.local.rateLimit.customStorage.consume in auth.ts; get/set callbacks alone are unsupported. Run `gencow codegen` and restart after correcting the provider.");
1328
+ }
1329
+ for (const name of ["window", "max"])
1330
+ if (rate?.[name] !== void 0)
1331
+ positive(rate[name]);
1332
+ const rules = rate?.customRules === void 0 ? void 0 : record2(rate.customRules);
1333
+ const copiedRules = rules && Object.freeze(Object.fromEntries(Object.entries(rules).map(([path, rule]) => {
1334
+ if (!path.startsWith("/") || /[\r\n\0]/u.test(path))
1335
+ invalidRateLimitConfig();
1336
+ if (rule === false || typeof rule === "function")
1337
+ return [path, rule];
1338
+ const data = record2(rule, ["window", "max"]);
1339
+ positive(data.window);
1340
+ positive(data.max);
1341
+ return [path, Object.freeze({ window: data.window, max: data.max })];
1342
+ })));
1343
+ const advanced = local.advanced === void 0 ? void 0 : record2(local.advanced, ["ipAddress"]);
1344
+ const ip = advanced?.ipAddress === void 0 ? void 0 : record2(advanced.ipAddress, ["ipAddressHeaders", "disableIpTracking", "ipv6Subnet", "trustedProxies"]);
1345
+ if (ip?.disableIpTracking !== void 0 && typeof ip.disableIpTracking !== "boolean")
1346
+ invalidRateLimitConfig();
1347
+ if (ip?.ipv6Subnet !== void 0 && (typeof ip.ipv6Subnet !== "number" || !Number.isInteger(ip.ipv6Subnet) || ip.ipv6Subnet < 0 || ip.ipv6Subnet > 128))
1348
+ invalidRateLimitConfig();
1349
+ return Object.freeze({
1350
+ ...rate ? { rateLimit: Object.freeze({ ...rate, ...copiedRules ? { customRules: copiedRules } : {} }) } : {},
1351
+ ...advanced ? {
1352
+ advanced: Object.freeze({
1353
+ ...ip ? {
1354
+ ipAddress: Object.freeze({
1355
+ ...ip,
1356
+ ...ip.ipAddressHeaders === void 0 ? {} : { ipAddressHeaders: strings(ip.ipAddressHeaders, true) },
1357
+ ...ip.trustedProxies === void 0 ? {} : { trustedProxies: strings(ip.trustedProxies) }
1358
+ })
1359
+ } : {}
1360
+ })
1361
+ } : {}
1362
+ });
1363
+ }
1364
+ function resolveAuthRateLimitPolicy(config, schema, selection) {
1365
+ if (selection !== void 0) {
1366
+ record2(selection, ["context"]);
1367
+ if (!["local", "hosted"].includes(selection.context))
1368
+ invalidRateLimitConfig();
1369
+ }
1370
+ const context = selection?.context ?? "local";
1371
+ const local = context === "local" ? snapshotLocalAuthConfig(config.local) : void 0;
1372
+ const storage = context === "local" ? local?.rateLimit?.storage ?? "memory" : schema.rateLimit ? "database" : "memory";
1373
+ return Object.freeze({
1374
+ context,
1375
+ enabled: local?.rateLimit?.enabled ?? true,
1376
+ storage,
1377
+ ...local?.rateLimit?.customStorage ? { customStorage: local.rateLimit.customStorage } : {},
1378
+ window: local?.rateLimit?.window ?? GENCOW_AUTH_RATE_LIMIT.window,
1379
+ max: local?.rateLimit?.max ?? GENCOW_AUTH_RATE_LIMIT.max,
1380
+ // SDK takes the first matching custom rule. Keep the app's insertion order,
1381
+ // then append only unspecified defaults so native wildcards remain useful.
1382
+ customRules: Object.freeze({
1383
+ ...local?.rateLimit?.customRules,
1384
+ ...Object.fromEntries(Object.entries(GENCOW_AUTH_RATE_LIMIT.customRules).filter(([path]) => !Object.hasOwn(local?.rateLimit?.customRules ?? {}, path)))
1385
+ }),
1386
+ ...context === "hosted" ? { ipAddress: { ipAddressHeaders: ["x-real-ip"] } } : local?.advanced?.ipAddress ? { ipAddress: local.advanced.ipAddress } : {}
1387
+ });
1388
+ }
1389
+
1390
+ export {
1391
+ exactRuntimeOrigin,
1392
+ trustedRuntimeOrigin,
1393
+ isRuntimeOriginAllowed,
1394
+ captureRuntimeBrowserConfiguration,
1395
+ resolveRuntimeBrowserPolicy,
1396
+ captureRuntimeBrowserPolicy,
1397
+ runtimeCorsMiddleware,
1398
+ runtimeCorsResponse,
1399
+ captureRequestBody,
1400
+ runtimeNullLogSink,
1401
+ runtimeNullLogger,
1402
+ createRuntimeLogger,
1403
+ createRuntimeHostContext,
1404
+ createRecordingRuntimeLogSink,
1405
+ authAdministrationFailure,
1406
+ validateAuthProfileId,
1407
+ validateAuthProfileUpdate,
1408
+ splitPath,
1409
+ splitRoutingPath,
1410
+ getPattern,
1411
+ getPath,
1412
+ getPathNoStrict,
1413
+ stripPathPrefix,
1414
+ mergePath,
1415
+ checkOptionalParameter,
1416
+ tryDecodeURIComponent,
1417
+ getQueryParam,
1418
+ getQueryParams,
1419
+ authStartupError,
1420
+ toRuntimeIdentity,
1421
+ resolveServerCompatibleAccessTokenKey,
1422
+ issueAccessToken,
1423
+ createAuthGenerationAccessTokenVerifier,
1424
+ snapshotLocalAuthConfig,
1425
+ resolveAuthRateLimitPolicy
1426
+ };