@guren/server 2.10.0 → 2.11.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 (91) hide show
  1. package/dist/DocsViewerServiceProvider-qFCaeiUv.js +77 -0
  2. package/dist/Hash-CzrwKeDp.js +133 -0
  3. package/dist/HttpException-BkS3euNG.js +161 -0
  4. package/dist/Job-BVT813DO.js +441 -0
  5. package/dist/McpServiceProvider-BoAN-UcD.js +367 -0
  6. package/dist/MessageSigner-Bd25ZJAV.js +93 -0
  7. package/dist/Random-DbIJ22KQ.js +191 -0
  8. package/dist/address-D0Iq-XIH.js +20 -0
  9. package/dist/auth/index.js +2 -122
  10. package/dist/auth-C7sVmYgc.js +1954 -0
  11. package/dist/authorization/index.js +2 -38
  12. package/dist/authorization-Dbcuc5ZK.js +610 -0
  13. package/dist/broadcasting/index.js +2 -26
  14. package/dist/broadcasting-Dw-FhyjN.js +1055 -0
  15. package/dist/cache/index.js +2 -17
  16. package/dist/cache/types.d.ts +4 -4
  17. package/dist/cache-BYnZf2FR.js +812 -0
  18. package/dist/client-Dd7vLcqp.js +27 -0
  19. package/dist/console/Output.d.ts +18 -18
  20. package/dist/encryption/index.js +5 -96
  21. package/dist/encryption-fOWQaKqX.js +250 -0
  22. package/dist/endpoint-D-20PiHY.js +46 -0
  23. package/dist/endpoint-D6GIqOpe.js +31 -0
  24. package/dist/errors-quJOkkCn.js +81 -0
  25. package/dist/events/index.js +2 -28
  26. package/dist/events-aIH_bWRx.js +410 -0
  27. package/dist/health/index.js +2 -24
  28. package/dist/health-VWdWXRwh.js +345 -0
  29. package/dist/hot-disposables-WsTX2ySN.js +281 -0
  30. package/dist/hot-reload/testing.d.ts +1 -1
  31. package/dist/http/resources/Resource.d.ts +23 -3
  32. package/dist/i18n/index.js +2 -30
  33. package/dist/i18n-mcWi7LCd.js +617 -0
  34. package/dist/index.js +7515 -7276
  35. package/dist/lambda/index.js +114 -71
  36. package/dist/logging/index.js +2 -24
  37. package/dist/logging-CPaRMuPP.js +518 -0
  38. package/dist/loopback-guard-D0Kc7-xc.js +224 -0
  39. package/dist/mail/index.js +2 -27
  40. package/dist/mail-DfEfSQEr.js +699 -0
  41. package/dist/mcp/index.js +2 -10
  42. package/dist/notifications/index.js +2 -33
  43. package/dist/notifications-BGqmUNZ8.js +759 -0
  44. package/dist/queue/index.js +3 -42
  45. package/dist/queue-CXrRK85G.js +948 -0
  46. package/dist/redis/index.js +672 -642
  47. package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
  48. package/dist/runtime/index.js +472 -616
  49. package/dist/scheduling/index.js +2 -29
  50. package/dist/scheduling-CPiEdtQd.js +839 -0
  51. package/dist/storage/index.js +2 -15
  52. package/dist/storage-tWHMv2H_.js +841 -0
  53. package/dist/support/expiry.js +69 -12
  54. package/dist/trim-slashes-ZJ_VsY5s.js +25 -0
  55. package/dist/vite/index.js +118 -181
  56. package/dist/vite/plugin.d.ts +1 -1
  57. package/dist/vite-dev-server-BSJkduhZ.js +131 -0
  58. package/package.json +6 -5
  59. package/dist/DocsViewerServiceProvider-RUYDFBMW.js +0 -75
  60. package/dist/McpServiceProvider-SL7DUZ4G.js +0 -8
  61. package/dist/chunk-2SC566CD.js +0 -376
  62. package/dist/chunk-2V3YID4H.js +0 -20
  63. package/dist/chunk-3KV5X2FL.js +0 -31
  64. package/dist/chunk-63SKW5PS.js +0 -457
  65. package/dist/chunk-6J6B5KOB.js +0 -425
  66. package/dist/chunk-A5JJ7XTH.js +0 -24
  67. package/dist/chunk-AZOYI43J.js +0 -18
  68. package/dist/chunk-B5E5VBDI.js +0 -115
  69. package/dist/chunk-DAQKYKLH.js +0 -182
  70. package/dist/chunk-DRNPVBAA.js +0 -1002
  71. package/dist/chunk-EI5GYMAT.js +0 -853
  72. package/dist/chunk-H3B23O6T.js +0 -271
  73. package/dist/chunk-HPET6XY5.js +0 -853
  74. package/dist/chunk-HR2KZ3WL.js +0 -616
  75. package/dist/chunk-IOTWFHZU.js +0 -558
  76. package/dist/chunk-K6CUBJX6.js +0 -642
  77. package/dist/chunk-KTNJG7R7.js +0 -911
  78. package/dist/chunk-LAJQCSSF.js +0 -355
  79. package/dist/chunk-LHR6OHI7.js +0 -189
  80. package/dist/chunk-N7PLD7MB.js +0 -729
  81. package/dist/chunk-Q2P6YLRR.js +0 -24
  82. package/dist/chunk-QQKTH5KX.js +0 -114
  83. package/dist/chunk-SFQP6O52.js +0 -126
  84. package/dist/chunk-SQR7277M.js +0 -911
  85. package/dist/chunk-T2FFUU6J.js +0 -484
  86. package/dist/chunk-TVV5YNEC.js +0 -1842
  87. package/dist/chunk-UY3AZSYL.js +0 -14
  88. package/dist/chunk-V4DNC2ER.js +0 -114
  89. package/dist/chunk-VSA3QY5Q.js +0 -274
  90. package/dist/chunk-YSOJKAAU.js +0 -427
  91. package/dist/errors-PUNHAFL2.js +0 -34
@@ -0,0 +1,367 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
+ import { r as ServiceProvider } from "./loopback-guard-D0Kc7-xc.js";
3
+ import { n as createMcpAccessGuard, r as isMcpEndpointEnabled, t as MCP_ENDPOINT_PATH } from "./endpoint-D-20PiHY.js";
4
+ import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { z } from "zod";
6
+ //#region src/mcp/create-mcp-server.ts
7
+ function createMcpServer(options) {
8
+ const { cwd, cli, version = "0.2.0" } = options;
9
+ const server = new McpServer({
10
+ name: "guren",
11
+ version
12
+ });
13
+ server.tool("guren_get_context", "Get a complete project context map including models, routes, pages, controllers, resources, events, jobs, middleware, listeners, and validators.", { format: z.enum(["json", "markdown"]).default("json").describe("Output format") }, async ({ format }) => {
14
+ const ctx = await cli.generateContext({ cwd });
15
+ return { content: [{
16
+ type: "text",
17
+ text: format === "markdown" ? cli.renderContextMarkdown(ctx) : JSON.stringify(ctx, null, 2)
18
+ }] };
19
+ });
20
+ server.tool("guren_entity_context", "Get everything about one entity in a single bundle: model (table, columns, relationships, reverse references), routes with validation schemas, controller actions, Inertia pages with props, resource, policy, seeders, and tests. Prefer this over guren_get_context when working on a specific model.", {
21
+ entity: z.string().describe("Model class name (e.g., \"User\"). Case-insensitive."),
22
+ module: z.string().optional().describe("Module name to disambiguate same-named models across modules/; \"app\" selects the application root"),
23
+ format: z.enum(["json", "markdown"]).default("markdown").describe("Output format")
24
+ }, async ({ entity, module, format }) => {
25
+ try {
26
+ const ctx = await cli.generateEntityContext(entity, {
27
+ cwd,
28
+ module
29
+ });
30
+ return { content: [{
31
+ type: "text",
32
+ text: format === "markdown" ? cli.renderEntityContextMarkdown(ctx) : JSON.stringify(ctx, null, 2)
33
+ }] };
34
+ } catch (error) {
35
+ return {
36
+ content: [{
37
+ type: "text",
38
+ text: error instanceof Error ? error.message : String(error)
39
+ }],
40
+ isError: true
41
+ };
42
+ }
43
+ });
44
+ if (cli.buildDocsGraphReport && cli.renderDocsGraphMarkdown) {
45
+ const { buildDocsGraphReport, renderDocsGraphMarkdown } = cli;
46
+ server.tool("guren_docs_graph", "The OKF docs relation graph: documents, entities, and code paths as nodes, verified relations (governs, body links, spec-view derivation) as edges. Narrow with entity or path to answer \"which docs govern this, and which spec views regenerate from it?\" BEFORE renaming or editing a file — guren_check only reports the breakage afterwards.", {
47
+ entity: z.string().optional().describe("Narrow to the neighborhood of one model entity (case-insensitive)."),
48
+ path: z.string().optional().describe("Narrow to the neighborhood of one app-root-relative path (e.g. \"app/Http/Controllers/PostController.ts\")."),
49
+ format: z.enum(["json", "markdown"]).default("markdown").describe("Output format")
50
+ }, async ({ entity, path, format }) => {
51
+ const report = await buildDocsGraphReport({
52
+ cwd,
53
+ entity,
54
+ path
55
+ });
56
+ return { content: [{
57
+ type: "text",
58
+ text: format === "markdown" ? renderDocsGraphMarkdown(report) : JSON.stringify(report, null, 2)
59
+ }] };
60
+ });
61
+ }
62
+ server.tool("guren_check", "Validate route-to-controller-to-page consistency, check for empty controller methods, missing test files, and missing generated manifests.", {}, async () => {
63
+ const report = await cli.runCheck({ cwd });
64
+ return { content: [{
65
+ type: "text",
66
+ text: JSON.stringify(report, null, 2)
67
+ }] };
68
+ });
69
+ server.tool("guren_list_models", "List all models with their table names, relationships, authentication trait, and soft deletes status.", {}, async () => {
70
+ const models = await cli.listModels({ appRoot: cwd });
71
+ return { content: [{
72
+ type: "text",
73
+ text: JSON.stringify(models, null, 2)
74
+ }] };
75
+ });
76
+ server.tool("guren_generate_guidelines", "Generate project-specific coding guidelines based on the current project structure, naming conventions, auth setup, models, validation patterns, and middleware.", {}, async () => {
77
+ return { content: [{
78
+ type: "text",
79
+ text: await cli.generateGuidelines({ cwd })
80
+ }] };
81
+ });
82
+ server.tool("guren_doctor", "Run a comprehensive health check on the Guren project and optionally suggest actionable next steps.", { next: z.boolean().default(false).describe("Include actionable next steps") }, async ({ next }) => {
83
+ const report = await cli.runDoctor({ cwd });
84
+ let text = JSON.stringify(report, null, 2);
85
+ if (next) {
86
+ const steps = await cli.suggestNextSteps({ cwd });
87
+ text = JSON.stringify({
88
+ ...report,
89
+ nextSteps: steps
90
+ }, null, 2);
91
+ }
92
+ return { content: [{
93
+ type: "text",
94
+ text
95
+ }] };
96
+ });
97
+ server.tool("guren_make_feature", "Generate a complete CRUD feature: controller, model, views (Index, Show, New, Edit), validator, and resource. Optionally include test file.", {
98
+ name: z.string().describe("Resource name in PascalCase (e.g., \"Post\", \"BlogComment\")"),
99
+ fields: z.string().optional().describe("Comma-separated field definitions (e.g., \"title:string,body:text,published:boolean\")"),
100
+ withTest: z.boolean().default(false).describe("Generate test file"),
101
+ force: z.boolean().default(false).describe("Overwrite existing files")
102
+ }, async ({ name, fields, withTest, force }) => {
103
+ const createdFiles = await cli.makeFeature(name, {
104
+ fields,
105
+ withTest,
106
+ force,
107
+ cwd
108
+ });
109
+ return { content: [{
110
+ type: "text",
111
+ text: JSON.stringify({ created: createdFiles }, null, 2)
112
+ }] };
113
+ });
114
+ server.tool("guren_make_component", "Generate a single component: controller, model, middleware, event, job, listener, resource, view, test, mail, notification, seeder, factory, or migration.", {
115
+ type: z.enum([
116
+ "controller",
117
+ "model",
118
+ "middleware",
119
+ "event",
120
+ "job",
121
+ "listener",
122
+ "resource",
123
+ "view",
124
+ "test",
125
+ "mail",
126
+ "notification",
127
+ "seeder",
128
+ "factory",
129
+ "provider",
130
+ "exception",
131
+ "command",
132
+ "channel"
133
+ ]).describe("Component type to generate"),
134
+ name: z.string().describe("Component name in PascalCase"),
135
+ force: z.boolean().default(false).describe("Overwrite existing files")
136
+ }, async ({ type, name, force }) => {
137
+ const maker = {
138
+ controller: cli.makeController,
139
+ model: cli.makeModel,
140
+ view: cli.makeView,
141
+ test: cli.makeTest,
142
+ route: cli.makeRoute
143
+ }[type];
144
+ if (!maker) return {
145
+ content: [{
146
+ type: "text",
147
+ text: `Component type "${type}" is not yet supported via MCP. Use the CLI: bunx guren make:${type} ${name}`
148
+ }],
149
+ isError: true
150
+ };
151
+ const result = await maker(name, {
152
+ force,
153
+ cwd
154
+ });
155
+ return { content: [{
156
+ type: "text",
157
+ text: JSON.stringify({ created: Array.isArray(result) ? result : [result] }, null, 2)
158
+ }] };
159
+ });
160
+ server.tool("guren_codegen", "Generate the type-safe route, page, data, and channel manifests plus the API client (.guren/ and types/generated/).", {}, async () => {
161
+ const options = {
162
+ cwd,
163
+ force: true
164
+ };
165
+ const generated = [];
166
+ const skipped = [];
167
+ const warnings = [];
168
+ let failed = false;
169
+ /**
170
+ * Runs one generator and files its artifacts under `generated` or
171
+ * `skipped`. A generator that returns an empty `outputPath` had
172
+ * nothing to describe, which is a normal shape for a project rather
173
+ * than a failure; a throw is the opposite, and is what `isError`
174
+ * reports on.
175
+ */
176
+ const run = async (artifacts, generate) => {
177
+ try {
178
+ const result = await generate();
179
+ if (result?.outputPath === "") skipped.push({
180
+ artifacts,
181
+ reason: result.skipped?.message ?? "nothing to generate"
182
+ });
183
+ else generated.push(...artifacts);
184
+ if (result?.warnings) warnings.push(...result.warnings);
185
+ return result;
186
+ } catch (error) {
187
+ failed = true;
188
+ skipped.push({
189
+ artifacts,
190
+ reason: error instanceof Error ? error.message : String(error)
191
+ });
192
+ }
193
+ };
194
+ const routes = await run([".guren/routes.gen.ts", "types/generated/routes.d.ts"], () => cli.generateRouteTypes(options));
195
+ await run([".guren/pages.gen.ts"], () => cli.generatePageTypes(options));
196
+ const data = await run([".guren/data.gen.ts"], () => cli.generateDataTypes(options));
197
+ await run([".guren/channels.gen.ts"], () => cli.generateChannelTypes(options));
198
+ await run([".guren/api-client.gen.ts"], () => {
199
+ if (!routes?.definitions) throw new Error("route generation produced no manifest to build a client from");
200
+ return cli.generateApiClientTypes(routes.definitions, {
201
+ ...options,
202
+ resources: data?.definitions
203
+ });
204
+ });
205
+ return {
206
+ content: [{
207
+ type: "text",
208
+ text: JSON.stringify({
209
+ generated,
210
+ skipped,
211
+ warnings
212
+ }, null, 2)
213
+ }],
214
+ isError: failed
215
+ };
216
+ });
217
+ server.resource("context", "guren://context", {
218
+ description: "Current project structure map (models, routes, pages, controllers, etc.)",
219
+ mimeType: "application/json"
220
+ }, async (uri) => {
221
+ const ctx = await cli.generateContext({ cwd });
222
+ return { contents: [{
223
+ uri: uri.href,
224
+ mimeType: "application/json",
225
+ text: JSON.stringify(ctx, null, 2)
226
+ }] };
227
+ });
228
+ server.resource("entity-context", new ResourceTemplate("guren://context/{entity}", { list: void 0 }), {
229
+ description: "Entity-centric context bundle: model, routes, controller, pages, resource, policy. For same-named models across modules, use the guren_entity_context tool with its module argument instead.",
230
+ mimeType: "text/markdown"
231
+ }, async (uri, variables) => {
232
+ const ctx = await cli.generateEntityContext(String(variables.entity), { cwd });
233
+ return { contents: [{
234
+ uri: uri.href,
235
+ mimeType: "text/markdown",
236
+ text: cli.renderEntityContextMarkdown(ctx)
237
+ }] };
238
+ });
239
+ server.resource("guidelines", "guren://guidelines", {
240
+ description: "Auto-generated project-specific coding guidelines",
241
+ mimeType: "text/markdown"
242
+ }, async (uri) => {
243
+ const guidelines = await cli.generateGuidelines({ cwd });
244
+ return { contents: [{
245
+ uri: uri.href,
246
+ mimeType: "text/markdown",
247
+ text: guidelines
248
+ }] };
249
+ });
250
+ server.prompt("guren_review", "Review code changes against project conventions and patterns. Automatically fetches project context and runs integrity checks first.", async () => {
251
+ let contextSummary;
252
+ try {
253
+ const ctx = await cli.generateContext({ cwd });
254
+ const check = await cli.runCheck({ cwd });
255
+ contextSummary = [
256
+ "## Project Context",
257
+ `Framework: ${ctx.framework.name} v${ctx.framework.version}`,
258
+ `Models: ${ctx.models.map((m) => m.className).join(", ") || "none"}`,
259
+ `Controllers: ${ctx.controllers.join(", ") || "none"}`,
260
+ `Pages: ${ctx.pages.join(", ") || "none"}`,
261
+ "",
262
+ "## Integrity Check",
263
+ `Pass: ${check.passCount}, Warn: ${check.warnCount}, Fail: ${check.failCount}`,
264
+ ...check.checks.filter((c) => c.status !== "pass").map((c) => `- [${c.status}] ${c.title}: ${c.message}`)
265
+ ].join("\n");
266
+ } catch {
267
+ contextSummary = "Could not load project context.";
268
+ }
269
+ return { messages: [{
270
+ role: "user",
271
+ content: {
272
+ type: "text",
273
+ text: [
274
+ "Review the recent code changes in this Guren project.",
275
+ "Check for:",
276
+ "1. Adherence to project naming conventions and patterns",
277
+ "2. Route-controller-page consistency",
278
+ "3. Missing validation schemas",
279
+ "4. Missing tests for new controllers",
280
+ "5. Proper use of Model API (findOrFail, relationships)",
281
+ "",
282
+ contextSummary
283
+ ].join("\n")
284
+ }
285
+ }] };
286
+ });
287
+ server.prompt("guren_plan_feature", "Plan a new feature given the current project structure. Provide the feature description as an argument.", { feature: z.string().describe("Description of the feature to plan") }, async ({ feature }) => {
288
+ let contextSummary;
289
+ try {
290
+ const ctx = await cli.generateContext({ cwd });
291
+ const models = await cli.listModels({ appRoot: cwd });
292
+ contextSummary = [
293
+ "## Current Project State",
294
+ `Models: ${models.map((m) => `${m.className}${m.tableName ? ` (${m.tableName})` : ""}`).join(", ") || "none"}`,
295
+ `Controllers: ${ctx.controllers.join(", ") || "none"}`,
296
+ `Routes: ${ctx.routes.length} defined`,
297
+ `Pages: ${ctx.pages.join(", ") || "none"}`,
298
+ "",
299
+ "## Model Relationships",
300
+ ...models.flatMap((m) => m.relationships.length > 0 ? [`${m.className}: ${m.relationships.map((r) => `${r.type}(${r.name})`).join(", ")}`] : [])
301
+ ].join("\n");
302
+ } catch {
303
+ contextSummary = "Could not load project context.";
304
+ }
305
+ return { messages: [{
306
+ role: "user",
307
+ content: {
308
+ type: "text",
309
+ text: [
310
+ `Plan the implementation of: ${feature}`,
311
+ "",
312
+ "Provide:",
313
+ "1. Which files to create/modify",
314
+ "2. Database schema changes (migration)",
315
+ "3. Model definition with relationships",
316
+ "4. Controller actions and validation schemas",
317
+ "5. Inertia page components",
318
+ "6. Route definitions",
319
+ "7. Test plan",
320
+ "",
321
+ contextSummary
322
+ ].join("\n")
323
+ }
324
+ }] };
325
+ });
326
+ return server;
327
+ }
328
+ //#endregion
329
+ //#region src/mcp/McpServiceProvider.ts
330
+ var McpServiceProvider_exports = /* @__PURE__ */ __exportAll({ McpServiceProvider: () => McpServiceProvider });
331
+ /**
332
+ * Registers the MCP (Model Context Protocol) endpoint at /_guren/mcp.
333
+ *
334
+ * Only active while `isMcpEndpointEnabled()` holds, so registering this
335
+ * provider directly honours the same `GUREN_MCP=1` opt-in that `Application`
336
+ * gates on — and the same condition that exempts the endpoint from CSRF.
337
+ * It allows AI coding agents (Claude Code, Cursor, etc.) to introspect
338
+ * the project structure, run integrity checks, and scaffold code.
339
+ *
340
+ * @guren/cli is loaded via dynamic import to avoid circular dependencies
341
+ * (@guren/server -> @guren/cli -> @guren/core -> @guren/server).
342
+ */
343
+ var McpServiceProvider = class extends ServiceProvider {
344
+ register() {}
345
+ async boot() {
346
+ if (!isMcpEndpointEnabled()) return;
347
+ const hono = this.container.make("app").hono;
348
+ const cwd = process.cwd();
349
+ const [{ WebStandardStreamableHTTPServerTransport }, cli] = await Promise.all([import("@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"), import("@guren/cli")]);
350
+ const routeAwareCli = cli.createFreshContextApi ? {
351
+ ...cli,
352
+ ...cli.createFreshContextApi()
353
+ } : cli;
354
+ hono.use(MCP_ENDPOINT_PATH, createMcpAccessGuard());
355
+ hono.all(MCP_ENDPOINT_PATH, async (c) => {
356
+ const mcpServer = createMcpServer({
357
+ cwd,
358
+ cli: routeAwareCli
359
+ });
360
+ const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: void 0 });
361
+ await mcpServer.connect(transport);
362
+ return transport.handleRequest(c.req.raw);
363
+ });
364
+ }
365
+ };
366
+ //#endregion
367
+ export { McpServiceProvider_exports as n, createMcpServer as r, McpServiceProvider as t };
@@ -0,0 +1,93 @@
1
+ import { createHmac, hkdfSync, randomBytes, timingSafeEqual } from "node:crypto";
2
+ //#region src/encryption/app-key.ts
3
+ const APP_KEY_PREFIX = "base64:";
4
+ const APP_KEY_BYTES = 32;
5
+ function decodeAppKey(rawKey, envName) {
6
+ const trimmed = rawKey.trim();
7
+ if (!trimmed) throw new Error(`${envName} is required and must be a base64-encoded 32-byte key.`);
8
+ const encoded = trimmed.startsWith(APP_KEY_PREFIX) ? trimmed.slice(7) : trimmed;
9
+ const decoded = Buffer.from(encoded, "base64");
10
+ if (decoded.length !== APP_KEY_BYTES || decoded.toString("base64") !== encoded.replace(/\s+/gu, "")) throw new Error(`${envName} must be a base64-encoded 32-byte key.`);
11
+ return decoded;
12
+ }
13
+ function normalizeAppKey(rawKey, envName = "APP_KEY") {
14
+ return `${APP_KEY_PREFIX}${decodeAppKey(rawKey, envName).toString("base64")}`;
15
+ }
16
+ function parseAppKey(rawKey, envName = "APP_KEY") {
17
+ return decodeAppKey(rawKey, envName);
18
+ }
19
+ function parsePreviousAppKeys(rawKeys, envName = "APP_PREVIOUS_KEYS") {
20
+ if (!rawKeys) return [];
21
+ return rawKeys.split(",").map((value) => value.trim()).filter(Boolean).map((value, index) => decodeAppKey(value, `${envName}[${index}]`));
22
+ }
23
+ function getAppKeyringFromEnv(env = process.env) {
24
+ return {
25
+ current: parseAppKey(env.APP_KEY ?? "", "APP_KEY"),
26
+ previous: parsePreviousAppKeys(env.APP_PREVIOUS_KEYS)
27
+ };
28
+ }
29
+ function deriveAppKey(rootKey, purpose) {
30
+ return Buffer.from(hkdfSync("sha256", rootKey, Buffer.alloc(0), Buffer.from(`guren:${purpose}`, "utf8"), APP_KEY_BYTES));
31
+ }
32
+ function deriveAppKeyring(keyring, purpose) {
33
+ return {
34
+ current: deriveAppKey(keyring.current, purpose),
35
+ previous: keyring.previous.map((key) => deriveAppKey(key, purpose))
36
+ };
37
+ }
38
+ function encodeDerivedKey(key) {
39
+ return `${APP_KEY_PREFIX}${key.toString("base64")}`;
40
+ }
41
+ function generateAppKey() {
42
+ return `${APP_KEY_PREFIX}${randomBytes(APP_KEY_BYTES).toString("base64")}`;
43
+ }
44
+ //#endregion
45
+ //#region src/encryption/MessageSigner.ts
46
+ function encodeBase64Url(value) {
47
+ return Buffer.from(value).toString("base64url");
48
+ }
49
+ function decodeBase64Url(value) {
50
+ return Buffer.from(value, "base64url").toString("utf8");
51
+ }
52
+ function createSignature(input, key) {
53
+ return encodeBase64Url(createHmac("sha256", key).update(input).digest());
54
+ }
55
+ function signaturesMatch(actual, expected) {
56
+ const actualBuffer = Buffer.from(actual, "utf8");
57
+ const expectedBuffer = Buffer.from(expected, "utf8");
58
+ if (actualBuffer.length !== expectedBuffer.length) return false;
59
+ return timingSafeEqual(actualBuffer, expectedBuffer);
60
+ }
61
+ var MessageSigner = class {
62
+ keyring;
63
+ constructor(keyring) {
64
+ this.keyring = keyring;
65
+ }
66
+ sign(payload, options = {}) {
67
+ const now = Date.now();
68
+ const claims = {
69
+ ...payload,
70
+ iat: Math.floor(now / 1e3),
71
+ ...options.purpose ? { purpose: options.purpose } : {},
72
+ ...typeof options.expiresIn === "number" ? { exp: Math.floor((now + options.expiresIn) / 1e3) } : {}
73
+ };
74
+ const encodedPayload = encodeBase64Url(JSON.stringify(claims));
75
+ return `${encodedPayload}.${createSignature(encodedPayload, this.keyring.current)}`;
76
+ }
77
+ verify(token, options = {}) {
78
+ const [encodedPayload, signature, extra] = token.split(".");
79
+ if (!encodedPayload || !signature || extra) return null;
80
+ if (![this.keyring.current, ...this.keyring.previous].some((key) => signaturesMatch(signature, createSignature(encodedPayload, key)))) return null;
81
+ let payload;
82
+ try {
83
+ payload = JSON.parse(decodeBase64Url(encodedPayload));
84
+ } catch {
85
+ return null;
86
+ }
87
+ if (options.purpose && payload.purpose !== options.purpose) return null;
88
+ if (typeof payload.exp === "number" && Math.floor(Date.now() / 1e3) > payload.exp && options.allowExpired !== true) return null;
89
+ return payload;
90
+ }
91
+ };
92
+ //#endregion
93
+ export { generateAppKey as a, parseAppKey as c, encodeDerivedKey as i, parsePreviousAppKeys as l, deriveAppKey as n, getAppKeyringFromEnv as o, deriveAppKeyring as r, normalizeAppKey as s, MessageSigner as t };
@@ -0,0 +1,191 @@
1
+ import { randomBytes, randomInt, randomUUID } from "crypto";
2
+ //#region src/encryption/Random.ts
3
+ /**
4
+ * Character sets for random string generation.
5
+ */
6
+ const CHARSETS = {
7
+ alphanumeric: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
8
+ alphabetic: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
9
+ numeric: "0123456789",
10
+ hex: "0123456789abcdef",
11
+ "base64": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
12
+ "url-safe": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
13
+ };
14
+ /**
15
+ * Map random bytes onto a character set without modulo bias: bytes that fall
16
+ * into the truncated remainder of the 0-255 range are discarded and redrawn,
17
+ * so every character stays equally likely (a plain `byte % chars.length`
18
+ * skews toward the front of the set whenever 256 is not a multiple of it).
19
+ */
20
+ function unbiasedRandomChars(length, chars) {
21
+ if (!Number.isInteger(length) || length < 0) throw new RangeError(`Random string length must be a non-negative integer, received ${length}.`);
22
+ const limit = 256 - 256 % chars.length;
23
+ let result = "";
24
+ while (result.length < length) {
25
+ const remaining = length - result.length;
26
+ const bytes = randomBytes(Math.ceil(remaining * 256 / limit) + 8);
27
+ for (const byte of bytes) if (byte < limit) {
28
+ result += chars[byte % chars.length];
29
+ if (result.length === length) break;
30
+ }
31
+ }
32
+ return result;
33
+ }
34
+ /**
35
+ * Generate a cryptographically secure random string.
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * randomString(32) // 32-character alphanumeric string
40
+ * randomString(16, { charset: 'hex' }) // 16-character hex string
41
+ * randomString(24, { charset: 'url-safe' }) // URL-safe string
42
+ * ```
43
+ */
44
+ function randomString(length, options = {}) {
45
+ const { charset = "alphanumeric" } = options;
46
+ return unbiasedRandomChars(length, CHARSETS[charset]);
47
+ }
48
+ /**
49
+ * Generate random bytes.
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * const bytes = random(32) // 32 random bytes
54
+ * ```
55
+ */
56
+ function random(length) {
57
+ return randomBytes(length);
58
+ }
59
+ /**
60
+ * Generate random bytes as hex string.
61
+ */
62
+ function randomHex(length) {
63
+ return randomBytes(length).toString("hex");
64
+ }
65
+ /**
66
+ * Generate random bytes as base64 string.
67
+ */
68
+ function randomBase64(length) {
69
+ return randomBytes(length).toString("base64");
70
+ }
71
+ /**
72
+ * Generate random bytes as URL-safe base64 string.
73
+ */
74
+ function randomBase64Url(length) {
75
+ return randomBytes(length).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
76
+ }
77
+ /**
78
+ * Generate a UUID v4.
79
+ *
80
+ * @example
81
+ * ```typescript
82
+ * const id = uuid() // e.g., '550e8400-e29b-41d4-a716-446655440000'
83
+ * ```
84
+ */
85
+ function uuid() {
86
+ return randomUUID();
87
+ }
88
+ /**
89
+ * Generate a secure random integer.
90
+ *
91
+ * @example
92
+ * ```typescript
93
+ * randomInt(1, 100) // Random number between 1 and 100 (inclusive)
94
+ * ```
95
+ */
96
+ function randomInt$1(min, max) {
97
+ return randomInt(min, max + 1);
98
+ }
99
+ /**
100
+ * Generate a random token suitable for URLs.
101
+ *
102
+ * @example
103
+ * ```typescript
104
+ * const token = urlSafeToken(32) // URL-safe 32-character token
105
+ * ```
106
+ */
107
+ function urlSafeToken(length = 32) {
108
+ return randomBase64Url(Math.ceil(length * .75)).slice(0, length);
109
+ }
110
+ /**
111
+ * Generate a secure random password.
112
+ *
113
+ * @example
114
+ * ```typescript
115
+ * const password = generatePassword(16) // Random 16-character password
116
+ * ```
117
+ */
118
+ function generatePassword(length = 16, options = {}) {
119
+ const { uppercase = true, lowercase = true, numbers = true, symbols = true } = options;
120
+ let chars = "";
121
+ if (uppercase) chars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
122
+ if (lowercase) chars += "abcdefghijklmnopqrstuvwxyz";
123
+ if (numbers) chars += "0123456789";
124
+ if (symbols) chars += "!@#$%^&*()-_=+[]{}|;:,.<>?";
125
+ if (chars.length === 0) chars = CHARSETS.alphanumeric;
126
+ return unbiasedRandomChars(length, chars);
127
+ }
128
+ /**
129
+ * Generate a random OTP (One-Time Password).
130
+ *
131
+ * @example
132
+ * ```typescript
133
+ * const otp = generateOtp(6) // e.g., '482901'
134
+ * ```
135
+ */
136
+ function generateOtp(length = 6) {
137
+ return randomString(length, { charset: "numeric" });
138
+ }
139
+ /**
140
+ * Generate a random slug-friendly string.
141
+ *
142
+ * @example
143
+ * ```typescript
144
+ * const slug = generateSlug() // e.g., 'a8b2c4d6e8'
145
+ * ```
146
+ */
147
+ function generateSlug(length = 10) {
148
+ return randomString(length, { charset: "hex" });
149
+ }
150
+ /**
151
+ * Shuffle an array using Fisher-Yates algorithm with secure random.
152
+ *
153
+ * @example
154
+ * ```typescript
155
+ * const shuffled = shuffle([1, 2, 3, 4, 5])
156
+ * ```
157
+ */
158
+ function shuffle(array) {
159
+ const result = [...array];
160
+ for (let i = result.length - 1; i > 0; i--) {
161
+ const j = randomInt$1(0, i);
162
+ [result[i], result[j]] = [result[j], result[i]];
163
+ }
164
+ return result;
165
+ }
166
+ /**
167
+ * Pick a random element from an array.
168
+ *
169
+ * @example
170
+ * ```typescript
171
+ * const item = pick(['a', 'b', 'c']) // Random element
172
+ * ```
173
+ */
174
+ function pick(array) {
175
+ if (array.length === 0) throw new Error("Cannot pick from empty array.");
176
+ return array[randomInt$1(0, array.length - 1)];
177
+ }
178
+ /**
179
+ * Pick multiple random elements from an array.
180
+ *
181
+ * @example
182
+ * ```typescript
183
+ * const items = sample(['a', 'b', 'c', 'd'], 2) // Two random elements
184
+ * ```
185
+ */
186
+ function sample(array, count) {
187
+ if (count > array.length) throw new Error("Sample count exceeds array length.");
188
+ return shuffle(array).slice(0, count);
189
+ }
190
+ //#endregion
191
+ export { random as a, randomHex as c, sample as d, shuffle as f, pick as i, randomInt$1 as l, uuid as m, generatePassword as n, randomBase64 as o, urlSafeToken as p, generateSlug as r, randomBase64Url as s, generateOtp as t, randomString as u };
@@ -0,0 +1,20 @@
1
+ //#region src/mail/address.ts
2
+ /**
3
+ * Parse an email address string or object into MailAddress, supporting the
4
+ * `Name <email>` format. Parsed with string scanning — the previous
5
+ * `/^(.+)\s*<(.+)>$/` backtracks polynomially on crafted recipient strings,
6
+ * which can be request-derived (e.g. password reset forms).
7
+ */
8
+ function parseMailAddress(input) {
9
+ if (typeof input !== "string") return input;
10
+ if (input.endsWith(">") && !/[\r\n\u2028\u2029]/u.test(input)) {
11
+ const open = input.lastIndexOf("<");
12
+ if (open > 0 && open < input.length - 2) return {
13
+ name: input.slice(0, open).trim(),
14
+ email: input.slice(open + 1, -1).trim()
15
+ };
16
+ }
17
+ return { email: input };
18
+ }
19
+ //#endregion
20
+ export { parseMailAddress as t };