@guren/server 2.2.0 → 2.4.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 (40) hide show
  1. package/dist/{DocsViewerServiceProvider-D7RGJPGM.js → DocsViewerServiceProvider-RUYDFBMW.js} +2 -2
  2. package/dist/McpServiceProvider-FRJ5O7LT.js +8 -0
  3. package/dist/auth/index.js +2 -1
  4. package/dist/broadcasting/index.js +2 -1
  5. package/dist/{chunk-SIP34GBE.js → chunk-2SC566CD.js} +14 -18
  6. package/dist/chunk-3KV5X2FL.js +31 -0
  7. package/dist/{chunk-CDZUNKI6.js → chunk-5WL2FTC4.js} +3 -3
  8. package/dist/{chunk-WIXGT4TN.js → chunk-A5JJ7XTH.js} +8 -2
  9. package/dist/{chunk-4VE3LYOM.js → chunk-DRNPVBAA.js} +20 -5
  10. package/dist/{chunk-LVJCZCAV.js → chunk-H3B23O6T.js} +10 -118
  11. package/dist/{chunk-BZMZEFRG.js → chunk-LHR6OHI7.js} +11 -0
  12. package/dist/{chunk-PZKUDFMW.js → chunk-NENDACRP.js} +20 -4
  13. package/dist/{chunk-JBG4AR24.js → chunk-Q2P6YLRR.js} +8 -2
  14. package/dist/{chunk-BUQXOZCT.js → chunk-TVV5YNEC.js} +8 -4
  15. package/dist/chunk-V4DNC2ER.js +114 -0
  16. package/dist/docs-viewer/endpoint.d.ts +11 -1
  17. package/dist/encryption/index.js +17 -15
  18. package/dist/health/index.js +1 -1
  19. package/dist/http/Application.d.ts +67 -1
  20. package/dist/http/FormRequest.d.ts +10 -7
  21. package/dist/http/dev-assets.d.ts +11 -0
  22. package/dist/http/dev-banner.d.ts +11 -0
  23. package/dist/http/inertia-assets.d.ts +9 -0
  24. package/dist/http/middleware/loopback-guard.d.ts +16 -3
  25. package/dist/http/middleware/response-headers.d.ts +18 -0
  26. package/dist/http/middleware/validation-errors-cookie.d.ts +31 -0
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.js +376 -112
  29. package/dist/mcp/create-mcp-server.d.ts +8 -0
  30. package/dist/mcp/endpoint.d.ts +19 -1
  31. package/dist/mcp/index.js +3 -3
  32. package/dist/redis/index.js +43 -8
  33. package/dist/redis/redis-values.d.ts +17 -0
  34. package/dist/runtime/index.js +102 -69
  35. package/dist/support/contained-path.d.ts +26 -0
  36. package/dist/support/expiry.d.ts +47 -0
  37. package/dist/support/expiry.js +12 -0
  38. package/dist/support/inertia-defaults.d.ts +13 -0
  39. package/package.json +6 -2
  40. package/dist/McpServiceProvider-GRDYNEQG.js +0 -8
@@ -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;
@@ -4,25 +4,11 @@ import {
4
4
  decrypt,
5
5
  encrypt,
6
6
  generateKey,
7
- generateOtp,
8
- generatePassword,
9
- generateSlug,
10
7
  getEncrypter,
11
- pick,
12
- random,
13
- randomBase64,
14
- randomBase64Url,
15
- randomHex,
16
- randomInt,
17
- randomString,
18
- sample,
19
8
  setEncrypter,
20
- shuffle,
21
9
  signUrl,
22
- urlSafeToken,
23
- uuid,
24
10
  verifySignedUrl
25
- } from "../chunk-LVJCZCAV.js";
11
+ } from "../chunk-H3B23O6T.js";
26
12
  import {
27
13
  MessageSigner,
28
14
  deriveAppKey,
@@ -47,6 +33,22 @@ import {
47
33
  verifyHmac,
48
34
  verifyPassword
49
35
  } from "../chunk-QQKTH5KX.js";
36
+ import {
37
+ generateOtp,
38
+ generatePassword,
39
+ generateSlug,
40
+ pick,
41
+ random,
42
+ randomBase64,
43
+ randomBase64Url,
44
+ randomHex,
45
+ randomInt,
46
+ randomString,
47
+ sample,
48
+ shuffle,
49
+ urlSafeToken,
50
+ uuid
51
+ } from "../chunk-V4DNC2ER.js";
50
52
  export {
51
53
  Encrypter,
52
54
  MessageSigner,
@@ -9,7 +9,7 @@ import {
9
9
  StorageCheck,
10
10
  createHealthManager,
11
11
  customCheck
12
- } from "../chunk-SIP34GBE.js";
12
+ } from "../chunk-2SC566CD.js";
13
13
  export {
14
14
  CacheCheck,
15
15
  CustomCheck,
@@ -105,6 +105,40 @@ export interface ApplicationListenOptions {
105
105
  hostname?: string;
106
106
  assetsUrl?: string;
107
107
  vite?: StartViteDevServerOptions | false;
108
+ /**
109
+ * What to do when the requested port is already taken.
110
+ *
111
+ * `true` walks forward through the next 20 ports; `false` fails fast with
112
+ * the original EADDRINUSE. Unset walks outside production, matching the loop
113
+ * this option replaces.
114
+ *
115
+ * `GUREN_STRICT_PORT=1` forces fail-fast regardless, and `port: 0` never
116
+ * walks — the OS is already picking a free port.
117
+ */
118
+ portFallback?: boolean;
119
+ }
120
+ /**
121
+ * Where the server actually ended up listening.
122
+ *
123
+ * Returned by {@link Application.listen} so callers never have to infer the
124
+ * port from the port they asked for — with a port walk or `PORT=0` in play,
125
+ * those are different numbers, and scraping the human-readable dev banner is
126
+ * the only alternative.
127
+ *
128
+ * Read-only because {@link Application.address} hands back the very object
129
+ * `listen()` returned: a caller that adjusted its own copy would change what
130
+ * every later reader sees.
131
+ */
132
+ export interface ListenAddress {
133
+ /**
134
+ * The port the socket is bound to — what the runtime reports, falling back
135
+ * to the port the successful `Bun.serve` call was made with.
136
+ */
137
+ readonly port: number;
138
+ /** The hostname the socket is bound to. */
139
+ readonly hostname: string;
140
+ /** A URL that reaches the server, with a wildcard bind resolved to localhost. */
141
+ readonly url: string;
108
142
  }
109
143
  /**
110
144
  * Application wires an app-local router into a running Hono instance.
@@ -121,10 +155,12 @@ export declare class Application {
121
155
  private readonly authManager;
122
156
  private viteDevServer?;
123
157
  private bunServer?;
158
+ private boundAddress?;
124
159
  private viteTeardownRegistered;
125
160
  private bunTeardownRegistered;
126
161
  private autoSessionAttached;
127
162
  private routesRegistered;
163
+ private bootPromise?;
128
164
  constructor(options?: ApplicationOptions);
129
165
  get auth(): AuthManager;
130
166
  get authOptions(): AuthPluginOptions | undefined;
@@ -141,10 +177,21 @@ export declare class Application {
141
177
  use(path: string, ...middleware: MiddlewareHandler[]): void;
142
178
  /**
143
179
  * Executes provider registration, boot callback, mounts routes, and boots providers.
180
+ *
181
+ * Booting twice is a no-op: the first call's promise is reused, so providers
182
+ * and routes are never mounted a second time — including when two callers
183
+ * boot concurrently, before the first has finished. A boot that throws is not
184
+ * remembered, so a later call attempts boot again (it resumes on a partially
185
+ * mounted app rather than starting clean). The security defaults are mounted
186
+ * by the constructor and so are outside this entirely.
144
187
  */
145
188
  boot(): Promise<void>;
189
+ private bootOnce;
146
190
  /**
147
191
  * Registers default security middleware (headers + host authorization).
192
+ *
193
+ * Called once, from the constructor — see the note there for why it does
194
+ * not belong in boot().
148
195
  */
149
196
  private mountSecurityDefaults;
150
197
  private mountHostAuthorization;
@@ -166,7 +213,26 @@ export declare class Application {
166
213
  /**
167
214
  * Convenience helper to start a Bun server when available.
168
215
  */
169
- listen(options?: ApplicationListenOptions): Promise<void>;
216
+ listen(options?: ApplicationListenOptions): Promise<ListenAddress>;
217
+ /**
218
+ * The address {@link Application.listen} bound, or `undefined` before it has
219
+ * been called and once this app's server has been superseded or torn down.
220
+ *
221
+ * The same object `listen()` returned, so callers that need the address
222
+ * later — an OpenAPI `servers` entry, an absolute URL, a health report —
223
+ * read it here instead of threading it out of the entrypoint.
224
+ *
225
+ * The stored value is preferred over re-reading the live server, because
226
+ * `listen()` resolves the port through a fallback the socket no longer
227
+ * carries.
228
+ *
229
+ * Liveness is only as good as the signal available: a server stopped through
230
+ * the framework — a later `listen()`, the process-exit teardown — clears the
231
+ * slot this reads, but one stopped by calling `stop()` on the Bun server
232
+ * directly does not, and this keeps reporting its address. Treat it as
233
+ * "where `listen()` put this app", not as a health check.
234
+ */
235
+ get address(): ListenAddress | undefined;
170
236
  /**
171
237
  * Register a service provider.
172
238
  */
@@ -24,17 +24,16 @@ import type { ValidationRule } from './validation/types.js';
24
24
  * }
25
25
  * }
26
26
  *
27
- * authorize() {
28
- * return this.user() !== null
27
+ * async authorize() {
28
+ * return (await this.user()) !== null
29
29
  * }
30
30
  * }
31
31
  *
32
32
  * // In controller:
33
- * const data = await this.validate(StorePostRequest)
33
+ * const data = await new StorePostRequest().handle(this.ctx)
34
34
  * // data is typed as StorePostData
35
35
  * ```
36
- */
37
- /**
36
+ *
38
37
  * @deprecated Legacy compatibility layer — prefer schema-first validation
39
38
  * via `this.validateBody()` / `validateQuery()` / `validateParams()`.
40
39
  */
@@ -62,11 +61,15 @@ export declare abstract class FormRequest<T = Record<string, unknown>> {
62
61
  attributes(): Record<string, string>;
63
62
  /**
64
63
  * Get the authenticated user from the request context.
64
+ *
65
+ * Awaiting is load-bearing: `this.user() !== null` compiles and is always
66
+ * true, because an unawaited call is a pending promise.
65
67
  */
66
- protected user(): unknown;
68
+ protected user<TUser = unknown>(): Promise<TUser | null>;
67
69
  /**
68
70
  * Handle the form request: authorize, parse body, validate, return typed data.
69
- * @internal Called by Controller.validate()
71
+ * Call it from a controller with the request context:
72
+ * `const data = await new StorePostRequest().handle(this.ctx)`.
70
73
  */
71
74
  handle(ctx: Context): Promise<T>;
72
75
  private parseBody;
@@ -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
@@ -4,4 +4,15 @@ export interface DevBannerOptions {
4
4
  port: number;
5
5
  assetsUrl?: string;
6
6
  }
7
+ /**
8
+ * A wildcard bind answers on every interface but is not itself dialable on
9
+ * every platform.
10
+ *
11
+ * Lives here rather than beside its other caller because the banner and
12
+ * `Application.listen()`'s returned address are two renderings of one fact,
13
+ * and a platform caveat added to only one of them is the drift this replaces.
14
+ */
15
+ export declare function isWildcardHost(hostname: string): boolean;
16
+ /** `host:port`, bracketing an IPv6 literal so the result is dialable. */
17
+ export declare function formatHostPort(hostname: string, port: number): string;
7
18
  export declare function logDevServerBanner({ hostname, port, assetsUrl, }: DevBannerOptions): void;
@@ -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;
@@ -0,0 +1,31 @@
1
+ import type { Context, MiddlewareHandler } from 'hono';
2
+ /**
3
+ * Cookie flash for Inertia validation errors on apps with no session.
4
+ *
5
+ * The Laravel-style flow flashes errors to the session and redirects back,
6
+ * but sessions are only mounted when `createApp({ auth })` is configured — a
7
+ * fresh scaffold has none yet. Dropping the errors silently turns every
8
+ * validation failure into "the form did nothing", so without a session the
9
+ * flattened errors ride across the one redirect in a short-lived HttpOnly
10
+ * cookie instead: display-only data, no store required, working on every
11
+ * runtime (Bun, Workers, Lambda).
12
+ */
13
+ export declare const VALIDATION_ERRORS_COOKIE = "guren_validation_errors";
14
+ /**
15
+ * The `Set-Cookie` value that flashes `errors` across the next redirect.
16
+ */
17
+ export declare function validationErrorsSetCookie(errors: Record<string, string>): string;
18
+ /**
19
+ * The flashed errors carried by the current request, if any. Reading consumes
20
+ * the flash: the cleanup middleware expires the cookie on this response.
21
+ */
22
+ export declare function readValidationErrorsCookie(ctx: Context): Record<string, string> | undefined;
23
+ /**
24
+ * Expires the flash cookie on the response whose render consumed it,
25
+ * restoring the show-once semantics a session flash has. Runs post-`next()`,
26
+ * so a thrown `ValidationException` (whose renderer may be *setting* a fresh
27
+ * cookie on its 303) never reaches the deletion — and the `getSetCookie`
28
+ * guard covers any other path that just wrote the cookie on this same
29
+ * response.
30
+ */
31
+ export declare function createValidationErrorsCookieCleanup(): MiddlewareHandler;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { Application, createApp } from './http/Application.js';
2
- export type { Context, ApplicationListenOptions, ServiceProviderConstructor } from './http/Application.js';
2
+ export type { Context, ApplicationListenOptions, ListenAddress, ServiceProviderConstructor, } from './http/Application.js';
3
3
  export { parseRequestPayload, formatValidationErrors } from './http/request.js';
4
4
  export { Controller } from './mvc/Controller.js';
5
5
  export type { InertiaResponse, InferInertiaProps, ControllerInertiaProps, AuthPayload } from './mvc/Controller.js';