@guren/server 2.2.0 → 2.3.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.
@@ -2,10 +2,10 @@ import {
2
2
  DOCS_VIEWER_PATH,
3
3
  createDocsViewerAccessGuard,
4
4
  isDocsViewerEnabled
5
- } from "./chunk-WIXGT4TN.js";
5
+ } from "./chunk-A5JJ7XTH.js";
6
6
  import {
7
7
  ServiceProvider
8
- } from "./chunk-BZMZEFRG.js";
8
+ } from "./chunk-LHR6OHI7.js";
9
9
 
10
10
  // src/docs-viewer/DocsViewerServiceProvider.ts
11
11
  import { createRequire } from "module";
@@ -0,0 +1,8 @@
1
+ import {
2
+ McpServiceProvider
3
+ } from "./chunk-5WL2FTC4.js";
4
+ import "./chunk-Q2P6YLRR.js";
5
+ import "./chunk-LHR6OHI7.js";
6
+ export {
7
+ McpServiceProvider
8
+ };
@@ -56,7 +56,8 @@ import {
56
56
  verifyEmailToken,
57
57
  verifyOAuthState,
58
58
  verifyPasswordResetToken
59
- } from "../chunk-BUQXOZCT.js";
59
+ } from "../chunk-TVV5YNEC.js";
60
+ import "../chunk-3KV5X2FL.js";
60
61
  import "../chunk-DAQKYKLH.js";
61
62
  import "../chunk-SFQP6O52.js";
62
63
  import "../chunk-QQKTH5KX.js";
@@ -0,0 +1,31 @@
1
+ // src/support/expiry.ts
2
+ function toDate(value) {
3
+ const date = coerceDate(value);
4
+ return date !== null && !Number.isNaN(date.getTime()) ? date : null;
5
+ }
6
+ function coerceDate(value) {
7
+ if (value == null) return null;
8
+ if (value instanceof Date) return value;
9
+ if (typeof value === "number" || typeof value === "bigint") return new Date(Number(value));
10
+ if (typeof value === "string") return new Date(/^\d+$/.test(value) ? Number(value) : value);
11
+ return null;
12
+ }
13
+ function isExpired(value, now = Date.now()) {
14
+ const date = toDate(value);
15
+ return date === null || date.getTime() <= now;
16
+ }
17
+ function isOptionalExpiryPast(value, now = Date.now()) {
18
+ if (value == null) return false;
19
+ return isExpired(value, now);
20
+ }
21
+ function toOptionalExpiry(value) {
22
+ if (value == null) return null;
23
+ return toDate(value) ?? /* @__PURE__ */ new Date(0);
24
+ }
25
+
26
+ export {
27
+ toDate,
28
+ isExpired,
29
+ isOptionalExpiryPast,
30
+ toOptionalExpiry
31
+ };
@@ -2,10 +2,10 @@ import {
2
2
  MCP_ENDPOINT_PATH,
3
3
  createMcpAccessGuard,
4
4
  isMcpEndpointEnabled
5
- } from "./chunk-JBG4AR24.js";
5
+ } from "./chunk-Q2P6YLRR.js";
6
6
  import {
7
7
  ServiceProvider
8
- } from "./chunk-BZMZEFRG.js";
8
+ } from "./chunk-LHR6OHI7.js";
9
9
 
10
10
  // src/mcp/create-mcp-server.ts
11
11
  import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
@@ -195,7 +195,7 @@ function createMcpServer(options) {
195
195
  try {
196
196
  const result = await generate();
197
197
  if (result?.outputPath === "") {
198
- skipped.push({ artifacts, reason: "nothing to generate" });
198
+ skipped.push({ artifacts, reason: result.skipped?.message ?? "nothing to generate" });
199
199
  } else {
200
200
  generated.push(...artifacts);
201
201
  }
@@ -6,7 +6,7 @@ import standard from "figlet/importable-fonts/Standard.js";
6
6
  // package.json
7
7
  var package_default = {
8
8
  name: "@guren/server",
9
- version: "2.2.0",
9
+ version: "2.3.0",
10
10
  type: "module",
11
11
  license: "MIT",
12
12
  repository: {
@@ -106,6 +106,10 @@ var package_default = {
106
106
  "./redis": {
107
107
  types: "./dist/redis/index.d.ts",
108
108
  default: "./dist/redis/index.js"
109
+ },
110
+ "./support/expiry": {
111
+ types: "./dist/support/expiry.d.ts",
112
+ default: "./dist/support/expiry.js"
109
113
  }
110
114
  },
111
115
  scripts: {
@@ -115,7 +119,7 @@ var package_default = {
115
119
  test: "bun test"
116
120
  },
117
121
  dependencies: {
118
- "@guren/orm": "^2.2.0",
122
+ "@guren/orm": "^2.2.1",
119
123
  "@modelcontextprotocol/sdk": "^1.30.0",
120
124
  chalk: "^5.3.0",
121
125
  consola: "^3.4.2",
@@ -1,11 +1,17 @@
1
1
  import {
2
2
  createLoopbackGuard
3
- } from "./chunk-BZMZEFRG.js";
3
+ } from "./chunk-LHR6OHI7.js";
4
4
 
5
5
  // src/docs-viewer/endpoint.ts
6
6
  var DOCS_VIEWER_PATH = "/_guren/docs";
7
7
  function isDocsViewerEnabled() {
8
- return typeof process !== "undefined" && process.env?.NODE_ENV !== "production" && process.env?.GUREN_DOCS === "1";
8
+ if (typeof process === "undefined") {
9
+ return false;
10
+ }
11
+ if (process.env.NODE_ENV === "production") {
12
+ return false;
13
+ }
14
+ return process.env.GUREN_DOCS === "1";
9
15
  }
10
16
  function createDocsViewerAccessGuard() {
11
17
  return createLoopbackGuard("the docs viewer");
@@ -157,6 +157,9 @@ function clientAddress(ctx) {
157
157
  }
158
158
  return env.server.requestIP(ctx.req.raw)?.address;
159
159
  }
160
+ function allowsUnverifiedPeer() {
161
+ return typeof process !== "undefined" && process.env.GUREN_ALLOW_UNVERIFIED_PEER === "1";
162
+ }
160
163
  function createLoopbackGuard(resource) {
161
164
  return async (ctx, next) => {
162
165
  const origin = ctx.req.header("origin");
@@ -167,6 +170,14 @@ function createLoopbackGuard(resource) {
167
170
  if (address !== void 0 && !isLoopbackAddress(address)) {
168
171
  return ctx.json({ message: `Forbidden: remote request to ${resource}` }, 403);
169
172
  }
173
+ if (address === void 0 && !allowsUnverifiedPeer()) {
174
+ return ctx.json(
175
+ {
176
+ message: `Forbidden: this runtime does not report the peer address, so ${resource} cannot confirm the request came from this machine. Serve the app with Application.listen() on Bun, or set GUREN_ALLOW_UNVERIFIED_PEER=1 to accept requests from anywhere the process is reachable.`
177
+ },
178
+ 403
179
+ );
180
+ }
170
181
  await next();
171
182
  };
172
183
  }
@@ -1,11 +1,17 @@
1
1
  import {
2
2
  createLoopbackGuard
3
- } from "./chunk-BZMZEFRG.js";
3
+ } from "./chunk-LHR6OHI7.js";
4
4
 
5
5
  // src/mcp/endpoint.ts
6
6
  var MCP_ENDPOINT_PATH = "/_guren/mcp";
7
7
  function isMcpEndpointEnabled() {
8
- return typeof process !== "undefined" && process.env?.NODE_ENV !== "production" && process.env?.GUREN_MCP === "1";
8
+ if (typeof process === "undefined") {
9
+ return false;
10
+ }
11
+ if (process.env.NODE_ENV === "production") {
12
+ return false;
13
+ }
14
+ return process.env.GUREN_MCP === "1";
9
15
  }
10
16
  function createMcpAccessGuard() {
11
17
  return createLoopbackGuard("the MCP endpoint");
@@ -1,3 +1,7 @@
1
+ import {
2
+ isExpired,
3
+ isOptionalExpiryPast
4
+ } from "./chunk-3KV5X2FL.js";
1
5
  import {
2
6
  AuthenticationException
3
7
  } from "./chunk-DAQKYKLH.js";
@@ -1259,7 +1263,7 @@ async function verifyApiToken(plainTextToken, store, options = {}) {
1259
1263
  const token = await store.findByHashedToken(hashedToken);
1260
1264
  if (!token) return null;
1261
1265
  if (token.id !== parsed.id) return null;
1262
- if (token.expiresAt && /* @__PURE__ */ new Date() > token.expiresAt) {
1266
+ if (isOptionalExpiryPast(token.expiresAt)) {
1263
1267
  return null;
1264
1268
  }
1265
1269
  if (!secureCompare(token.hashedToken, hashedToken)) {
@@ -1444,7 +1448,7 @@ var MemoryOAuthStateStore = class {
1444
1448
  sweepExpired() {
1445
1449
  const now = Date.now();
1446
1450
  for (const [hash, payload] of this.states) {
1447
- if (payload.expiresAt.getTime() <= now) {
1451
+ if (isExpired(payload.expiresAt, now)) {
1448
1452
  this.states.delete(hash);
1449
1453
  }
1450
1454
  }
@@ -1452,7 +1456,7 @@ var MemoryOAuthStateStore = class {
1452
1456
  async find(stateHash) {
1453
1457
  const payload = this.states.get(stateHash);
1454
1458
  if (!payload) return null;
1455
- if (payload.expiresAt.getTime() <= Date.now()) {
1459
+ if (isExpired(payload.expiresAt)) {
1456
1460
  this.states.delete(stateHash);
1457
1461
  return null;
1458
1462
  }
@@ -1465,7 +1469,7 @@ var MemoryOAuthStateStore = class {
1465
1469
  const payload = this.states.get(stateHash);
1466
1470
  if (!payload) return null;
1467
1471
  this.states.delete(stateHash);
1468
- if (payload.expiresAt.getTime() <= Date.now()) return null;
1472
+ if (isExpired(payload.expiresAt)) return null;
1469
1473
  return payload;
1470
1474
  }
1471
1475
  clear() {
@@ -13,7 +13,17 @@ export declare const DOCS_VIEWER_PATH = "/_guren/docs";
13
13
  * Opt-in via `GUREN_DOCS=1` and never active in production: the viewer
14
14
  * renders the project's private knowledge bundle, so it must not be
15
15
  * reachable unless the developer asked for it.
16
+ *
17
+ * The environment reads use plain member access so that the deploy plugins'
18
+ * `--define 'process.env.NODE_ENV="production"'` settles the production
19
+ * branch at bundle time; an optional chain is a different expression and no
20
+ * define matches it. See `mcp/endpoint.ts` for the full reasoning — and do
21
+ * not add optional chaining back, a test reads this file for it.
16
22
  */
17
23
  export declare function isDocsViewerEnabled(): boolean;
18
- /** Restricts the docs viewer to the developer's own machine. */
24
+ /**
25
+ * Restricts the docs viewer to the developer's own machine: cross-origin
26
+ * browser requests are rejected, and so is any request whose socket peer
27
+ * is not loopback — including one whose peer the runtime cannot report.
28
+ */
19
29
  export declare function createDocsViewerAccessGuard(): MiddlewareHandler;
@@ -125,6 +125,7 @@ export declare class Application {
125
125
  private bunTeardownRegistered;
126
126
  private autoSessionAttached;
127
127
  private routesRegistered;
128
+ private bootPromise?;
128
129
  constructor(options?: ApplicationOptions);
129
130
  get auth(): AuthManager;
130
131
  get authOptions(): AuthPluginOptions | undefined;
@@ -141,10 +142,21 @@ export declare class Application {
141
142
  use(path: string, ...middleware: MiddlewareHandler[]): void;
142
143
  /**
143
144
  * Executes provider registration, boot callback, mounts routes, and boots providers.
145
+ *
146
+ * Booting twice is a no-op: the first call's promise is reused, so providers
147
+ * and routes are never mounted a second time — including when two callers
148
+ * boot concurrently, before the first has finished. A boot that throws is not
149
+ * remembered, so a later call attempts boot again (it resumes on a partially
150
+ * mounted app rather than starting clean). The security defaults are mounted
151
+ * by the constructor and so are outside this entirely.
144
152
  */
145
153
  boot(): Promise<void>;
154
+ private bootOnce;
146
155
  /**
147
156
  * Registers default security middleware (headers + host authorization).
157
+ *
158
+ * Called once, from the constructor — see the note there for why it does
159
+ * not belong in boot().
148
160
  */
149
161
  private mountSecurityDefaults;
150
162
  private mountHostAuthorization;
@@ -42,6 +42,17 @@ export interface DevAssetsOptions {
42
42
  /** Serve selected files from the public directory without the `/public` prefix. */
43
43
  rootPublicAssets?: RootPublicAssetsConfig;
44
44
  }
45
+ /**
46
+ * Absolute path to `@guren/inertia-client`'s build output, the directory
47
+ * production serves the vendored client and its chunks from.
48
+ *
49
+ * Unlike {@link resolveGurenInertiaClient}, this must not follow a tsconfig
50
+ * `paths` mapping to the package's TypeScript sources — production serves
51
+ * files, it cannot transpile them. So it anchors on `./package.json`, a
52
+ * subpath such a mapping misses (there is no `src/package.json`) and real
53
+ * package resolution answers with the package root.
54
+ */
55
+ export declare function resolveInertiaClientDir(): string;
45
56
  /**
46
57
  * Registers development asset serving middleware.
47
58
  * @param app
@@ -19,4 +19,13 @@ export interface AutoConfigureInertiaOptions extends InertiaAssetsOptions {
19
19
  enableSsr?: boolean;
20
20
  }
21
21
  export declare function configureInertiaAssets(app: Application, options: InertiaAssetsOptions): void;
22
+ /**
23
+ * Serves the built Inertia client and the chunks it imports out of the
24
+ * resolved package directory.
25
+ *
26
+ * Split out of {@link configureInertiaAssets} so it can be pointed at a
27
+ * directory: the caller derives `inertiaClientDir` from `import.meta.resolve`,
28
+ * which no test can redirect at a fixture.
29
+ */
30
+ export declare function registerBuiltInertiaClient(app: Application, inertiaClientDir: string, inertiaClientPath: string): void;
22
31
  export declare function autoConfigureInertiaAssets(app: Application, options: AutoConfigureInertiaOptions): void;
@@ -9,6 +9,14 @@
9
9
  * templates bind `0.0.0.0` and `Host` is trivially forged, so host
10
10
  * authorization does not help, and a client that sends no `Origin` is
11
11
  * otherwise indistinguishable from a local process.
12
+ *
13
+ * The guard fails closed. A request is served only once the runtime has
14
+ * reported a loopback peer; if it reports no peer at all, the request is
15
+ * denied rather than waved through, because "no `Origin` and no peer" is
16
+ * exactly the shape of a remote `curl`. Runtimes that cannot report a peer
17
+ * (Node, or any host calling `app.fetch()` directly instead of
18
+ * `Application.listen()`) need `GUREN_ALLOW_UNVERIFIED_PEER=1`, which the
19
+ * denial names.
12
20
  */
13
21
  import type { MiddlewareHandler } from 'hono';
14
22
  /**
@@ -18,6 +26,10 @@ import type { MiddlewareHandler } from 'hono';
18
26
  * web page made the request. Restricting those to loopback blocks both
19
27
  * ordinary cross-site requests and DNS rebinding, where an attacker's
20
28
  * domain resolves to 127.0.0.1 so the browser skips preflight.
29
+ *
30
+ * This is a *negative* filter only. A loopback `Origin` is never proof that
31
+ * the caller is local: browsers set the header honestly, but any other
32
+ * client sets it with one flag. Never use it to satisfy the peer check.
21
33
  */
22
34
  export declare function isLoopbackOrigin(origin: string): boolean;
23
35
  /**
@@ -31,8 +43,9 @@ export declare function isLoopbackAddress(address: string): boolean;
31
43
  * Restricts an endpoint to the developer's own machine. `resource` names
32
44
  * the endpoint in the 403 body (e.g. "the MCP endpoint").
33
45
  *
34
- * When the runtime cannot report a peer address (non-Bun hosts, in-process
35
- * test requests) the address check is skipped and the origin check stands
36
- * alone.
46
+ * Three outcomes, and the two denials say different things on purpose:
47
+ * a peer that is present and not loopback is a remote caller, while a peer
48
+ * the runtime never reported is a deployment the guard cannot vouch for —
49
+ * the developer needs to know which one they are looking at.
37
50
  */
38
51
  export declare function createLoopbackGuard(resource: string): MiddlewareHandler;
@@ -0,0 +1,18 @@
1
+ import type { Context } from 'hono';
2
+ export type ResponseHeader = readonly [string, string];
3
+ /**
4
+ * Sets each header on the response unless it already carries that header.
5
+ *
6
+ * Use this instead of `ctx.header()` for any header that must reach *every*
7
+ * response. `ctx.header()` writes into Hono's prepared headers, which are only
8
+ * merged when the handler answers through the context (`ctx.text`/`json`/`html`);
9
+ * a handler returning a raw `new Response(...)` replaces `ctx.res` outright and
10
+ * drops them. That is every asset response the framework itself serves, so a
11
+ * header written the other way is simply absent from them.
12
+ *
13
+ * First writer wins, which preserves the precedence the prepared-header form
14
+ * had: anything registered closer to the handler — a route deliberately
15
+ * relaxing `X-Frame-Options` so it can be embedded, or an inner middleware's
16
+ * stronger `Strict-Transport-Security` — overwrote these before and still does.
17
+ */
18
+ export declare function applyResponseHeaders(ctx: Context, headers: readonly ResponseHeader[]): void;
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  logDevServerBanner,
3
3
  parseImportMap,
4
4
  startViteDevServer
5
- } from "./chunk-PZKUDFMW.js";
5
+ } from "./chunk-6IGN233M.js";
6
6
  import {
7
7
  PendingSchedule,
8
8
  Schedule,
@@ -29,7 +29,7 @@ import {
29
29
  } from "./chunk-AZOYI43J.js";
30
30
  import {
31
31
  isDocsViewerEnabled
32
- } from "./chunk-WIXGT4TN.js";
32
+ } from "./chunk-A5JJ7XTH.js";
33
33
  import {
34
34
  I18nManager,
35
35
  JsonLoader,
@@ -72,11 +72,11 @@ import {
72
72
  import {
73
73
  MCP_ENDPOINT_PATH,
74
74
  isMcpEndpointEnabled
75
- } from "./chunk-JBG4AR24.js";
75
+ } from "./chunk-Q2P6YLRR.js";
76
76
  import {
77
77
  ProviderManager,
78
78
  ServiceProvider
79
- } from "./chunk-BZMZEFRG.js";
79
+ } from "./chunk-LHR6OHI7.js";
80
80
  import {
81
81
  DatabaseChannel,
82
82
  MailChannel,
@@ -180,7 +180,8 @@ import {
180
180
  verifyEmailToken,
181
181
  verifyOAuthState,
182
182
  verifyPasswordResetToken
183
- } from "./chunk-BUQXOZCT.js";
183
+ } from "./chunk-TVV5YNEC.js";
184
+ import "./chunk-3KV5X2FL.js";
184
185
  import {
185
186
  Gate,
186
187
  Policy,
@@ -1475,6 +1476,31 @@ var SlidingWindowRateLimitStore = class extends BaseMemoryStore {
1475
1476
  }
1476
1477
  };
1477
1478
 
1479
+ // src/http/middleware/response-headers.ts
1480
+ function applyResponseHeaders(ctx, headers) {
1481
+ const response = ctx.res;
1482
+ try {
1483
+ for (const [name, value] of headers) {
1484
+ if (!response.headers.has(name)) response.headers.set(name, value);
1485
+ }
1486
+ return;
1487
+ } catch (error) {
1488
+ if (!isImmutableHeadersError(error)) throw error;
1489
+ }
1490
+ const merged = new Headers(response.headers);
1491
+ for (const [name, value] of headers) {
1492
+ if (!merged.has(name)) merged.set(name, value);
1493
+ }
1494
+ ctx.res = new Response(response.body, {
1495
+ status: response.status,
1496
+ statusText: response.statusText,
1497
+ headers: merged
1498
+ });
1499
+ }
1500
+ function isImmutableHeadersError(error) {
1501
+ return error instanceof TypeError && /immutable/i.test(error.message);
1502
+ }
1503
+
1478
1504
  // src/http/middleware/security-headers.ts
1479
1505
  function createSecurityHeaders(options = {}) {
1480
1506
  const {
@@ -1486,26 +1512,21 @@ function createSecurityHeaders(options = {}) {
1486
1512
  hsts = process.env.NODE_ENV === "production" ? { maxAge: 31536e3 } : false
1487
1513
  } = options;
1488
1514
  const hstsValue = hsts !== false ? buildHstsValue(hsts) : null;
1515
+ const headers = [];
1516
+ if (frameOptions !== false) headers.push(["X-Frame-Options", frameOptions]);
1517
+ if (contentTypeOptions !== false) headers.push(["X-Content-Type-Options", contentTypeOptions]);
1518
+ if (xssProtection !== false) headers.push(["X-XSS-Protection", xssProtection]);
1519
+ if (referrerPolicy !== false) headers.push(["Referrer-Policy", referrerPolicy]);
1520
+ if (crossDomainPolicies !== false) {
1521
+ headers.push(["X-Permitted-Cross-Domain-Policies", crossDomainPolicies]);
1522
+ }
1523
+ if (hstsValue) headers.push(["Strict-Transport-Security", hstsValue]);
1489
1524
  return async (ctx, next) => {
1490
- if (frameOptions !== false) {
1491
- ctx.header("X-Frame-Options", frameOptions);
1492
- }
1493
- if (contentTypeOptions !== false) {
1494
- ctx.header("X-Content-Type-Options", contentTypeOptions);
1495
- }
1496
- if (xssProtection !== false) {
1497
- ctx.header("X-XSS-Protection", xssProtection);
1498
- }
1499
- if (referrerPolicy !== false) {
1500
- ctx.header("Referrer-Policy", referrerPolicy);
1501
- }
1502
- if (crossDomainPolicies !== false) {
1503
- ctx.header("X-Permitted-Cross-Domain-Policies", crossDomainPolicies);
1504
- }
1505
- if (hstsValue) {
1506
- ctx.header("Strict-Transport-Security", hstsValue);
1525
+ try {
1526
+ await next();
1527
+ } finally {
1528
+ applyResponseHeaders(ctx, headers);
1507
1529
  }
1508
- await next();
1509
1530
  };
1510
1531
  }
1511
1532
  function buildHstsValue(options) {
@@ -1542,10 +1563,11 @@ function createCspMiddleware(options = {}) {
1542
1563
  ctx.set(CSP_NONCE_KEY, nonce);
1543
1564
  }
1544
1565
  const headerValue = buildCspHeader(directives, nonce, reportUri);
1545
- if (headerValue) {
1546
- ctx.header(headerName, headerValue);
1566
+ try {
1567
+ await next();
1568
+ } finally {
1569
+ if (headerValue) applyResponseHeaders(ctx, [[headerName, headerValue]]);
1547
1570
  }
1548
- await next();
1549
1571
  };
1550
1572
  }
1551
1573
  function camelToKebab(str) {
@@ -1725,8 +1747,11 @@ function createForceHttpsMiddleware(options = {}) {
1725
1747
  url2.protocol = "https:";
1726
1748
  return ctx.redirect(url2.toString(), 301);
1727
1749
  }
1728
- ctx.header("Strict-Transport-Security", hstsValue);
1729
- await next();
1750
+ try {
1751
+ await next();
1752
+ } finally {
1753
+ applyResponseHeaders(ctx, [["Strict-Transport-Security", hstsValue]]);
1754
+ }
1730
1755
  };
1731
1756
  }
1732
1757
 
@@ -2625,6 +2650,7 @@ var Application = class {
2625
2650
  this.router = new Router();
2626
2651
  this.authManager = new AuthManager();
2627
2652
  this.providerManager = new ProviderManager(this.container);
2653
+ this.mountSecurityDefaults();
2628
2654
  this.container.instance("app", this);
2629
2655
  this.container.instance("hono", this.hono);
2630
2656
  this.container.instance("auth", this.authManager);
@@ -2678,6 +2704,7 @@ var Application = class {
2678
2704
  bunTeardownRegistered = false;
2679
2705
  autoSessionAttached = false;
2680
2706
  routesRegistered = false;
2707
+ bootPromise;
2681
2708
  get auth() {
2682
2709
  return this.authManager;
2683
2710
  }
@@ -2716,26 +2743,44 @@ var Application = class {
2716
2743
  }
2717
2744
  /**
2718
2745
  * Executes provider registration, boot callback, mounts routes, and boots providers.
2746
+ *
2747
+ * Booting twice is a no-op: the first call's promise is reused, so providers
2748
+ * and routes are never mounted a second time — including when two callers
2749
+ * boot concurrently, before the first has finished. A boot that throws is not
2750
+ * remembered, so a later call attempts boot again (it resumes on a partially
2751
+ * mounted app rather than starting clean). The security defaults are mounted
2752
+ * by the constructor and so are outside this entirely.
2719
2753
  */
2720
2754
  async boot() {
2721
- this.mountSecurityDefaults();
2755
+ this.bootPromise ??= this.bootOnce();
2756
+ try {
2757
+ await this.bootPromise;
2758
+ } catch (error) {
2759
+ this.bootPromise = void 0;
2760
+ throw error;
2761
+ }
2762
+ }
2763
+ async bootOnce() {
2722
2764
  await this.providerManager.registerAll();
2723
2765
  await this.options.boot?.(this.hono);
2724
2766
  await this.mountRoutes();
2725
2767
  await this.mountDevEndpoint(
2726
2768
  isMcpEndpointEnabled(),
2727
- async () => (await import("./McpServiceProvider-GRDYNEQG.js")).McpServiceProvider,
2769
+ async () => (await import("./McpServiceProvider-FRJ5O7LT.js")).McpServiceProvider,
2728
2770
  "GUREN_MCP=1 but the MCP endpoint could not load \u2014 is @modelcontextprotocol/sdk installed?"
2729
2771
  );
2730
2772
  await this.mountDevEndpoint(
2731
2773
  isDocsViewerEnabled(),
2732
- async () => (await import("./DocsViewerServiceProvider-D7RGJPGM.js")).DocsViewerServiceProvider,
2774
+ async () => (await import("./DocsViewerServiceProvider-RUYDFBMW.js")).DocsViewerServiceProvider,
2733
2775
  "GUREN_DOCS=1 but the docs viewer could not load \u2014 is @guren/cli resolvable from this app?"
2734
2776
  );
2735
2777
  await this.providerManager.bootAll();
2736
2778
  }
2737
2779
  /**
2738
2780
  * Registers default security middleware (headers + host authorization).
2781
+ *
2782
+ * Called once, from the constructor — see the note there for why it does
2783
+ * not belong in boot().
2739
2784
  */
2740
2785
  mountSecurityDefaults() {
2741
2786
  const { securityHeaders } = this.options;
@@ -22,6 +22,11 @@ export interface ScaffoldOptions {
22
22
  * found nothing to describe and wrote no file (a project with no page
23
23
  * components, for instance).
24
24
  *
25
+ * `skipped` is an optional sentence explaining that empty `outputPath` when
26
+ * "nothing to describe" would be wrong — the pages generator declines to write
27
+ * a manifest into an app that cannot compile one, and an agent reading this
28
+ * result is exactly who needs to hear that a page it just wrote was ignored.
29
+ *
25
30
  * `definitions` is the route manifest `generateRouteTypes` builds. It stays
26
31
  * opaque here — this package only carries it from one CLI call to the next
27
32
  * (`generateApiClientTypes` consumes it) and never reads inside it, so
@@ -30,6 +35,9 @@ export interface ScaffoldOptions {
30
35
  export interface CodegenResult {
31
36
  outputPath?: string;
32
37
  definitions?: unknown[];
38
+ skipped?: {
39
+ message: string;
40
+ } | null;
33
41
  }
34
42
  /**
35
43
  * CLI functions that the MCP server wraps.
@@ -16,6 +16,22 @@ export declare const MCP_ENDPOINT_PATH = "/_guren/mcp";
16
16
  * Opt-in via `GUREN_MCP=1` and never active in production: the endpoint
17
17
  * exposes project introspection and code generation, so it must not be
18
18
  * reachable unless the developer asked for it.
19
+ *
20
+ * The environment reads below are deliberately written as plain member
21
+ * access. Do not "harden" them with optional chaining: the deploy plugins
22
+ * bundle server code with `--define 'process.env.NODE_ENV="production"'`,
23
+ * and a define matches one exact expression. Inserting `?.` produces a
24
+ * different expression that no define touches, leaving this gate a runtime
25
+ * read — and on hosts where the platform's environment is not in
26
+ * `process.env` by the time the module graph evaluates (workerd is the
27
+ * documented case; see the comment on the Cloudflare plugin's `define`),
28
+ * that runtime read answers "not production" and the gate silently reopens.
29
+ * A test in `tests/mcp/endpoint.test.ts` reads this file and fails on any
30
+ * optional chain after `process.env`, because nothing observable at runtime
31
+ * distinguishes the two forms.
32
+ *
33
+ * The `typeof process` check covers the only runtimes without `process`;
34
+ * every runtime the framework supports that has `process` has `process.env`.
19
35
  */
20
36
  export declare function isMcpEndpointEnabled(): boolean;
21
37
  /**
@@ -24,6 +40,8 @@ export declare function isMcpEndpointEnabled(): boolean;
24
40
  * The endpoint is exempt from CSRF — agent clients carry no token — so
25
41
  * the loopback guard takes over that job: web pages are rejected unless
26
42
  * their `Origin` is loopback (the check the MCP specification asks local
27
- * servers for), and non-browser clients unless their socket peer is.
43
+ * servers for), and every caller is rejected unless its socket peer is
44
+ * loopback. The guard fails closed when the runtime reports no peer at
45
+ * all; see `http/middleware/loopback-guard.ts` for the opt-out.
28
46
  */
29
47
  export declare function createMcpAccessGuard(): MiddlewareHandler;
package/dist/mcp/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  McpServiceProvider,
3
3
  createMcpServer
4
- } from "../chunk-CDZUNKI6.js";
5
- import "../chunk-JBG4AR24.js";
6
- import "../chunk-BZMZEFRG.js";
4
+ } from "../chunk-5WL2FTC4.js";
5
+ import "../chunk-Q2P6YLRR.js";
6
+ import "../chunk-LHR6OHI7.js";
7
7
  export {
8
8
  McpServiceProvider,
9
9
  createMcpServer
@@ -2,6 +2,10 @@ import {
2
2
  Redis,
3
3
  createRedisClient
4
4
  } from "../chunk-UY3AZSYL.js";
5
+ import {
6
+ toDate,
7
+ toOptionalExpiry
8
+ } from "../chunk-3KV5X2FL.js";
5
9
 
6
10
  // src/redis/scan-keys.ts
7
11
  async function scanKeys(redis, pattern) {
@@ -230,6 +234,20 @@ var RedisSlidingWindowRateLimitStore = class {
230
234
  }
231
235
  };
232
236
 
237
+ // src/redis/redis-values.ts
238
+ function decodeAbilities(value) {
239
+ if (value == null || value === "") return [];
240
+ let parsed = value;
241
+ if (typeof value === "string") {
242
+ try {
243
+ parsed = JSON.parse(value);
244
+ } catch {
245
+ return [];
246
+ }
247
+ }
248
+ return Array.isArray(parsed) ? parsed.filter((ability) => typeof ability === "string") : [];
249
+ }
250
+
233
251
  // src/redis/RedisApiTokenStore.ts
234
252
  var RedisApiTokenStore = class {
235
253
  constructor(redis, options = {}) {
@@ -353,10 +371,13 @@ var RedisApiTokenStore = class {
353
371
  name: data.name,
354
372
  hashedToken: data.hashedToken,
355
373
  userId: data.userId,
356
- abilities: JSON.parse(data.abilities),
357
- lastUsedAt: data.lastUsedAt ? new Date(data.lastUsedAt) : null,
358
- expiresAt: data.expiresAt ? new Date(data.expiresAt) : null,
359
- createdAt: new Date(data.createdAt)
374
+ abilities: decodeAbilities(data.abilities),
375
+ lastUsedAt: toDate(data.lastUsedAt),
376
+ // Absent means "never expires"; present-but-unparseable means a corrupt
377
+ // record, which must not read as immortal — `verifyApiToken` skips its
378
+ // expiry check entirely when this is null.
379
+ expiresAt: toOptionalExpiry(data.expiresAt),
380
+ createdAt: toDate(data.createdAt) ?? /* @__PURE__ */ new Date(0)
360
381
  };
361
382
  }
362
383
  /**
@@ -406,9 +427,13 @@ var RedisPasswordResetStore = class {
406
427
  }
407
428
  try {
408
429
  const parsed = JSON.parse(data);
430
+ const expiresAt = toDate(parsed.expiresAt);
431
+ if (expiresAt === null) {
432
+ return null;
433
+ }
409
434
  return {
410
435
  email: parsed.email,
411
- expiresAt: new Date(parsed.expiresAt)
436
+ expiresAt
412
437
  };
413
438
  } catch {
414
439
  return null;
@@ -495,11 +520,15 @@ var RedisEmailVerificationStore = class {
495
520
  }
496
521
  try {
497
522
  const parsed = JSON.parse(data);
523
+ const expiresAt = toDate(parsed.expiresAt);
524
+ if (expiresAt === null) {
525
+ return null;
526
+ }
498
527
  return {
499
528
  tokenId: parsed.tokenId,
500
529
  email: parsed.email,
501
- expiresAt: new Date(parsed.expiresAt),
502
- createdAt: new Date(parsed.createdAt)
530
+ expiresAt,
531
+ createdAt: toDate(parsed.createdAt) ?? /* @__PURE__ */ new Date(0)
503
532
  };
504
533
  } catch {
505
534
  return null;
@@ -607,10 +636,14 @@ var RedisOAuthStateStore = class {
607
636
  parsePayload(data) {
608
637
  try {
609
638
  const parsed = JSON.parse(data);
639
+ const expiresAt = toDate(parsed.expiresAt);
640
+ if (expiresAt === null) {
641
+ return null;
642
+ }
610
643
  return {
611
644
  provider: parsed.provider,
612
645
  redirectTo: parsed.redirectTo,
613
- expiresAt: new Date(parsed.expiresAt),
646
+ expiresAt,
614
647
  binding: parsed.binding
615
648
  };
616
649
  } catch {
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Decoding rules shared by the Redis-backed stores.
3
+ *
4
+ * Expiry coercion lives in `../support/expiry` — every store reads its expiry
5
+ * through `toDate`/`toOptionalExpiry`/`isExpired` there, so there is one rule
6
+ * rather than one per store.
7
+ */
8
+ /**
9
+ * Decode a JSON-encoded ability list.
10
+ *
11
+ * Corrupt text degrades to no abilities (deny-by-default) instead of throwing
12
+ * on every verification of the affected token. A value that decodes to
13
+ * something other than a list of strings degrades the same way: `tokenCan`
14
+ * would otherwise run `String.prototype.includes` on it, so a stored `'"*"'`
15
+ * would grant every ability.
16
+ */
17
+ export declare function decodeAbilities(value: unknown): string[];
@@ -3,7 +3,7 @@ import {
3
3
  logDevServerBanner,
4
4
  parseImportMap,
5
5
  startViteDevServer
6
- } from "../chunk-PZKUDFMW.js";
6
+ } from "../chunk-6IGN233M.js";
7
7
  import {
8
8
  trimTrailingSlashes
9
9
  } from "../chunk-AZOYI43J.js";
@@ -13,12 +13,38 @@ import {
13
13
 
14
14
  // src/http/dev-assets.ts
15
15
  import { serveStatic } from "hono/bun";
16
- import { dirname, extname as extname2, resolve as resolve2 } from "path";
16
+ import { dirname, extname as extname2, join, resolve as resolve2 } from "path";
17
17
  import { fileURLToPath } from "url";
18
18
  import { createRequire } from "module";
19
19
 
20
20
  // src/http/public-assets.ts
21
- import { extname, resolve, sep } from "path";
21
+ import { extname, resolve } from "path";
22
+
23
+ // src/support/contained-path.ts
24
+ import { realpath } from "fs/promises";
25
+ import { sep } from "path";
26
+ function isPathWithin(root, candidate) {
27
+ return candidate.startsWith(root.endsWith(sep) ? root : root + sep);
28
+ }
29
+ async function isRealPathWithin(root, candidate) {
30
+ if (!isPathWithin(root, candidate)) {
31
+ return false;
32
+ }
33
+ const [realRoot, realCandidate] = await Promise.all([canonicalize(root), canonicalize(candidate)]);
34
+ if (!realRoot || !realCandidate) {
35
+ return false;
36
+ }
37
+ return isPathWithin(realRoot, realCandidate);
38
+ }
39
+ async function canonicalize(path) {
40
+ try {
41
+ return await realpath(path);
42
+ } catch {
43
+ return void 0;
44
+ }
45
+ }
46
+
47
+ // src/http/public-assets.ts
22
48
  var DEFAULT_CACHE_CONTROL = "public, max-age=31536000, immutable";
23
49
  var DEFAULT_EXTENSIONS = [".svg", ".png", ".jpg", ".jpeg", ".gif", ".ico", ".webp", ".avif", ".webmanifest", ".txt"];
24
50
  var DEFAULT_CONTENT_TYPES = {
@@ -61,13 +87,16 @@ function registerRootPublicAssets(app, publicDir, config) {
61
87
  return next();
62
88
  }
63
89
  const candidatePath = resolve(publicDir, relativePath);
64
- if (!candidatePath.startsWith(publicDir + sep) && candidatePath !== publicDir) {
90
+ if (!isPathWithin(publicDir, candidatePath) && candidatePath !== publicDir) {
65
91
  return next();
66
92
  }
67
93
  const file = Bun.file(candidatePath);
68
94
  if (!await file.exists()) {
69
95
  return next();
70
96
  }
97
+ if (!await isRealPathWithin(publicDir, candidatePath)) {
98
+ return next();
99
+ }
71
100
  const headers = new Headers({
72
101
  "Cache-Control": cacheControlHeader,
73
102
  "Content-Type": contentTypeMap?.[extension] ?? DEFAULT_CONTENT_TYPES[extension] ?? "application/octet-stream"
@@ -112,6 +141,7 @@ function normalizeExtension(value) {
112
141
  var DEFAULT_PREFIX = "/resources/js";
113
142
  var DEFAULT_VENDOR_PATH = "/vendor/inertia-client.tsx";
114
143
  var DEFAULT_JSX_RUNTIME = "https://esm.sh/react@19.0.0/jsx-dev-runtime?dev";
144
+ var REACT_IMPORT_PATTERN = /from\s+['"]react['"]/u;
115
145
  function resolveInertiaClientRoute(inertiaClientPath) {
116
146
  const base = inertiaClientPath.slice(0, inertiaClientPath.lastIndexOf("/") + 1) || "/";
117
147
  return {
@@ -124,6 +154,9 @@ var require2 = createRequire(import.meta.url);
124
154
  function resolveGurenInertiaClient() {
125
155
  return require2.resolve("@guren/inertia-client/app");
126
156
  }
157
+ function resolveInertiaClientDir() {
158
+ return join(dirname(require2.resolve("@guren/inertia-client/package.json")), "dist");
159
+ }
127
160
  function registerDevAssets(app, options) {
128
161
  if (typeof Bun === "undefined") {
129
162
  throw new Error("Bun runtime is required for dev asset serving.");
@@ -140,7 +173,6 @@ function registerDevAssets(app, options) {
140
173
  const inertiaClientSource = options.inertiaClientSource ?? resolveGurenInertiaClient();
141
174
  const jsxRuntimeUrl = options.jsxRuntimeUrl ?? DEFAULT_JSX_RUNTIME;
142
175
  const resourcesJsDir = resolve2(resourcesDir, "js");
143
- const reactImportPattern = /from\s+['"]react['"]/u;
144
176
  const transpilerOptions = {
145
177
  target: "browser",
146
178
  jsx: "transform",
@@ -150,9 +182,12 @@ function registerDevAssets(app, options) {
150
182
  "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV ?? "development")
151
183
  }
152
184
  };
153
- const tsxTranspiler = new Bun.Transpiler({ loader: "tsx", ...transpilerOptions });
154
- const tsTranspiler = new Bun.Transpiler({ loader: "ts", ...transpilerOptions });
155
- app.hono.get(`${prefix}/*`, (ctx) => handleTranspileRequest(ctx, resourcesJsDir, prefix, reactImportPattern, tsxTranspiler, tsTranspiler, jsxRuntimeUrl));
185
+ const transpile = {
186
+ tsx: new Bun.Transpiler({ loader: "tsx", ...transpilerOptions }),
187
+ ts: new Bun.Transpiler({ loader: "ts", ...transpilerOptions }),
188
+ jsxRuntimeUrl
189
+ };
190
+ app.hono.get(`${prefix}/*`, (ctx) => handleTranspileRequest(ctx, resourcesJsDir, prefix, transpile));
156
191
  if (cssDir) {
157
192
  const cssRewrite = createStaticRewrite(cssRoute);
158
193
  app.use(
@@ -173,13 +208,13 @@ function registerDevAssets(app, options) {
173
208
  app.hono.get(inertiaClientPattern, (ctx) => {
174
209
  const relativeRequest = ctx.req.path.slice(inertiaClientBase.length) || inertiaClientRequestPath;
175
210
  if (relativeRequest === inertiaClientRequestPath) {
176
- return transpileFile(inertiaClientSource, reactImportPattern, tsxTranspiler, tsTranspiler, jsxRuntimeUrl);
211
+ return transpileFile(inertiaClientSource, transpile);
177
212
  }
178
213
  const candidatePath = resolve2(inertiaClientDir, relativeRequest);
179
- if (!candidatePath.startsWith(inertiaClientDir)) {
214
+ if (!isPathWithin(inertiaClientDir, candidatePath)) {
180
215
  return ctx.notFound();
181
216
  }
182
- return transpileFile(candidatePath, reactImportPattern, tsxTranspiler, tsTranspiler, jsxRuntimeUrl);
217
+ return transpileFile(candidatePath, transpile, inertiaClientDir);
183
218
  });
184
219
  }
185
220
  const publicPathOption = options.publicPath === void 0 ? "../public" : options.publicPath;
@@ -219,15 +254,15 @@ function createStaticRewrite(route) {
219
254
  return remainder.startsWith("/") ? remainder : `/${remainder}`;
220
255
  };
221
256
  }
222
- async function handleTranspileRequest(ctx, resourcesJsDir, prefix, reactImportPattern, tsxTranspiler, tsTranspiler, jsxRuntimeUrl) {
257
+ async function handleTranspileRequest(ctx, resourcesJsDir, prefix, transpile) {
223
258
  const relative = ctx.req.path.slice(prefix.length + 1);
224
259
  const fsPath = resolve2(resourcesJsDir, relative);
225
- if (!fsPath.startsWith(resourcesJsDir)) {
260
+ if (!isPathWithin(resourcesJsDir, fsPath)) {
226
261
  return ctx.notFound();
227
262
  }
228
- return transpileFile(fsPath, reactImportPattern, tsxTranspiler, tsTranspiler, jsxRuntimeUrl);
263
+ return transpileFile(fsPath, transpile, resourcesJsDir);
229
264
  }
230
- async function transpileFile(fsPath, reactImportPattern, tsxTranspiler, tsTranspiler, jsxRuntimeUrl) {
265
+ async function transpileFile(fsPath, transpile, containmentRoot) {
231
266
  const candidates = buildCandidatePaths(fsPath);
232
267
  let filePath;
233
268
  let file;
@@ -242,23 +277,23 @@ async function transpileFile(fsPath, reactImportPattern, tsxTranspiler, tsTransp
242
277
  if (!file || !filePath) {
243
278
  return new Response("Not Found", { status: 404 });
244
279
  }
280
+ if (containmentRoot && !await isRealPathWithin(containmentRoot, filePath)) {
281
+ return new Response("Not Found", { status: 404 });
282
+ }
245
283
  const ext = extname2(filePath);
246
284
  let source = await file.text();
247
- if (ext === ".tsx" && !reactImportPattern.test(source)) {
285
+ if (ext === ".tsx" && !REACT_IMPORT_PATTERN.test(source)) {
248
286
  source = "import React from 'react'\n" + source;
249
287
  }
250
288
  if (ext === ".tsx" || ext === ".ts") {
251
- const transpiled = ext === ".tsx" ? tsxTranspiler.transformSync(source, {
252
- loader: "tsx",
253
- sourceMap: isDev() ? "inline" : false,
254
- filename: filePath
255
- }) : tsTranspiler.transformSync(source, {
256
- loader: "ts",
289
+ const loader = ext === ".tsx" ? "tsx" : "ts";
290
+ const transpiled = transpile[loader].transformSync(source, {
291
+ loader,
257
292
  sourceMap: isDev() ? "inline" : false,
258
293
  filename: filePath
259
294
  });
260
295
  const helpers = collectJsxHelpers(transpiled);
261
- const runtimeShim = helpers.size ? createJsxRuntimeShim(helpers, jsxRuntimeUrl) : "";
296
+ const runtimeShim = helpers.size ? createJsxRuntimeShim(helpers, transpile.jsxRuntimeUrl) : "";
262
297
  return new Response(runtimeShim + transpiled, {
263
298
  headers: {
264
299
  "Content-Type": "application/javascript; charset=utf-8",
@@ -315,7 +350,7 @@ function deriveCssRoute(prefix) {
315
350
 
316
351
  // src/http/inertia-assets.ts
317
352
  import { serveStatic as serveStatic2 } from "hono/bun";
318
- import { dirname as dirname2, resolve as resolve3, join } from "path";
353
+ import { dirname as dirname2, resolve as resolve3, join as join2 } from "path";
319
354
  import { fileURLToPath as fileURLToPath2 } from "url";
320
355
  import { readFileSync } from "fs";
321
356
  var DEFAULT_STYLES_ENTRY = "/public/assets/app.css";
@@ -366,55 +401,53 @@ function configureInertiaAssets(app, options) {
366
401
  app.hono.get("/favicon.ico", () => new Response(null, { status: 204 }));
367
402
  }
368
403
  registerRootPublicAssets(app, publicDir, options.rootPublicAssets);
369
- if (isProduction && options.inertiaClient !== false) {
404
+ if (options.inertiaClient !== false) {
370
405
  try {
371
- let inertiaClientEntry;
372
- if (typeof import.meta.resolve === "function") {
373
- try {
374
- const resolved = import.meta.resolve("@guren/inertia-client/app", import.meta.url);
375
- inertiaClientEntry = fileURLToPath2(new URL(resolved));
376
- } catch {
377
- inertiaClientEntry = void 0;
378
- }
379
- }
380
- if (!inertiaClientEntry) {
381
- throw new Error("Unable to resolve @guren/inertia-client entry");
382
- }
383
- const inertiaClientDir = dirname2(inertiaClientEntry);
384
- const inertiaClientPath = options.inertiaClientPath ?? DEFAULT_VENDOR_CLIENT_PATH;
385
- const {
386
- base: inertiaClientBase,
387
- pattern: inertiaClientPattern,
388
- requestPath: inertiaClientRequestPath
389
- } = resolveInertiaClientRoute(inertiaClientPath);
390
- app.hono.get(inertiaClientPattern, async (ctx) => {
391
- const relativeRequest = ctx.req.path.slice(inertiaClientBase.length) || inertiaClientRequestPath;
392
- let targetPath;
393
- if (relativeRequest === inertiaClientRequestPath) {
394
- targetPath = join(inertiaClientDir, "app.js");
395
- } else {
396
- targetPath = resolve3(inertiaClientDir, relativeRequest);
397
- if (!targetPath.startsWith(inertiaClientDir)) {
398
- return ctx.notFound();
399
- }
400
- }
401
- const file = Bun.file(targetPath);
402
- if (!await file.exists()) {
403
- return ctx.notFound();
404
- }
405
- const contentType = file.type || "application/javascript; charset=utf-8";
406
- return new Response(file, {
407
- headers: {
408
- "Content-Type": contentType,
409
- "Cache-Control": "public, max-age=31536000"
410
- }
411
- });
412
- });
406
+ registerBuiltInertiaClient(
407
+ app,
408
+ resolveInertiaClientDir(),
409
+ options.inertiaClientPath ?? DEFAULT_VENDOR_CLIENT_PATH
410
+ );
413
411
  } catch (error) {
414
- console.warn("Unable to resolve @guren/inertia-client/app for production serving.", error);
412
+ console.warn("Unable to resolve @guren/inertia-client for production serving.", error);
415
413
  }
416
414
  }
417
415
  }
416
+ function registerBuiltInertiaClient(app, inertiaClientDir, inertiaClientPath) {
417
+ const {
418
+ base: inertiaClientBase,
419
+ pattern: inertiaClientPattern,
420
+ requestPath: inertiaClientRequestPath
421
+ } = resolveInertiaClientRoute(inertiaClientPath);
422
+ app.hono.get(inertiaClientPattern, async (ctx) => {
423
+ const relativeRequest = ctx.req.path.slice(inertiaClientBase.length) || inertiaClientRequestPath;
424
+ let targetPath;
425
+ let containmentRoot;
426
+ if (relativeRequest === inertiaClientRequestPath) {
427
+ targetPath = join2(inertiaClientDir, "app.js");
428
+ } else {
429
+ targetPath = resolve3(inertiaClientDir, relativeRequest);
430
+ containmentRoot = inertiaClientDir;
431
+ if (!isPathWithin(containmentRoot, targetPath)) {
432
+ return ctx.notFound();
433
+ }
434
+ }
435
+ const file = Bun.file(targetPath);
436
+ if (!await file.exists()) {
437
+ return ctx.notFound();
438
+ }
439
+ if (containmentRoot && !await isRealPathWithin(containmentRoot, targetPath)) {
440
+ return ctx.notFound();
441
+ }
442
+ const contentType = file.type || "application/javascript; charset=utf-8";
443
+ return new Response(file, {
444
+ headers: {
445
+ "Content-Type": contentType,
446
+ "Cache-Control": "public, max-age=31536000"
447
+ }
448
+ });
449
+ });
450
+ }
418
451
  function autoConfigureInertiaAssets(app, options) {
419
452
  const providedEnv = captureInertiaEnvFlags();
420
453
  configureInertiaAssets(app, options);
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Is `candidate` a path strictly below `root`, judged lexically?
3
+ *
4
+ * The trailing separator is what keeps out a sibling directory whose name
5
+ * merely extends the root's (`…/inertia` vs `…/inertia-secrets`), and what
6
+ * rejects an absolute `candidate` — which `resolve()` returns verbatim when a
7
+ * doubled slash in the request path left the relative part rooted.
8
+ *
9
+ * Cheap, but not sufficient on its own: `resolve()` collapses `..` without
10
+ * following symlinks. Use {@link isRealPathWithin} before reading the file.
11
+ */
12
+ export declare function isPathWithin(root: string, candidate: string): boolean;
13
+ /**
14
+ * Is `candidate` a path strictly below `root` once both are canonicalized?
15
+ *
16
+ * Every reader downstream of these checks (`Bun.file().text()`,
17
+ * `.arrayBuffer()`, `new Response(file)`) follows symlinks, so a lexical check
18
+ * alone accepts `<root>/link/secret` where `link` points out of the tree.
19
+ * *Both* sides are canonicalized: a root reached through a symlink itself is
20
+ * routine (workspace and pnpm layouts, macOS `/var` → `/private/var`), and
21
+ * canonicalizing only the candidate would 404 every asset such an app serves.
22
+ *
23
+ * Call this on a path already known to exist — a path that does not exist
24
+ * cannot be read, and `realpath` rejects it, so either way this fails closed.
25
+ */
26
+ export declare function isRealPathWithin(root: string, candidate: string): Promise<boolean>;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Expiry coercion and the one predicate that decides whether a stored expiry
3
+ * has passed.
4
+ *
5
+ * This is the single copy. `packages/core/src/store-utils.ts` re-exports
6
+ * `toDate`/`isExpired`/`toOptionalExpiry` from here through the
7
+ * `@guren/server/support/expiry` subpath, so the database-backed stores and
8
+ * the Redis ones decide expiry with the same code. It lives in this package
9
+ * because `@guren/core` depends on `@guren/server` and not the other way
10
+ * around — core is unreachable from here without a dependency cycle.
11
+ *
12
+ * Not part of the public API: the subpath exists for that re-export, and
13
+ * neither package's index exposes these.
14
+ */
15
+ /**
16
+ * Coerce a stored timestamp, rejecting anything unparseable.
17
+ *
18
+ * Accepts every shape a driver or a Redis value can hand back: Date, number,
19
+ * bigint (MySQL / postgres.js BIGINT), digit-only strings as epoch
20
+ * milliseconds, and ISO strings. A Date wrapping garbage is a parse failure,
21
+ * not a value — `new Date(garbage)` yields an Invalid Date whose comparisons
22
+ * are all false, which is exactly how a corrupt expiry reads as "not past".
23
+ */
24
+ export declare function toDate(value: unknown): Date | null;
25
+ /**
26
+ * Whether an expiry that is required to be present has passed.
27
+ *
28
+ * Missing or unparseable counts as expired, so a malformed record can never be
29
+ * accepted indefinitely. Use for sessions and OAuth state, whose writers always
30
+ * supply an expiry.
31
+ */
32
+ export declare function isExpired(value: unknown, now?: number): boolean;
33
+ /**
34
+ * Whether an expiry that is allowed to be absent has passed.
35
+ *
36
+ * Absent means "never expires" and is never past. Present-but-unparseable is a
37
+ * malformed record and counts as expired — collapsing the two is the fail-open
38
+ * this exists to close. Use at the point of comparison, so the check holds for
39
+ * every store implementation including ones this package never sees.
40
+ */
41
+ export declare function isOptionalExpiryPast(value: unknown, now?: number): boolean;
42
+ /**
43
+ * Coerce an expiry that is allowed to be absent into a value callers can
44
+ * compare directly: absent stays null, present-but-unparseable degrades to a
45
+ * long-past date rather than to null, which would read as "never expires".
46
+ */
47
+ export declare function toOptionalExpiry(value: unknown): Date | null;
@@ -0,0 +1,12 @@
1
+ import {
2
+ isExpired,
3
+ isOptionalExpiryPast,
4
+ toDate,
5
+ toOptionalExpiry
6
+ } from "../chunk-3KV5X2FL.js";
7
+ export {
8
+ isExpired,
9
+ isOptionalExpiryPast,
10
+ toDate,
11
+ toOptionalExpiry
12
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/server",
3
- "version": "2.2.0",
3
+ "version": "2.3.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -100,6 +100,10 @@
100
100
  "./redis": {
101
101
  "types": "./dist/redis/index.d.ts",
102
102
  "default": "./dist/redis/index.js"
103
+ },
104
+ "./support/expiry": {
105
+ "types": "./dist/support/expiry.d.ts",
106
+ "default": "./dist/support/expiry.js"
103
107
  }
104
108
  },
105
109
  "scripts": {
@@ -109,7 +113,7 @@
109
113
  "test": "bun test"
110
114
  },
111
115
  "dependencies": {
112
- "@guren/orm": "^2.2.0",
116
+ "@guren/orm": "^2.2.1",
113
117
  "@modelcontextprotocol/sdk": "^1.30.0",
114
118
  "chalk": "^5.3.0",
115
119
  "consola": "^3.4.2",
@@ -1,8 +0,0 @@
1
- import {
2
- McpServiceProvider
3
- } from "./chunk-CDZUNKI6.js";
4
- import "./chunk-JBG4AR24.js";
5
- import "./chunk-BZMZEFRG.js";
6
- export {
7
- McpServiceProvider
8
- };