@thexjs/core 0.1.3 → 0.1.5

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.
package/README.md CHANGED
@@ -172,6 +172,41 @@ await build({ pagesDir: "./src/pages", outDir: "./.x" });
172
172
 
173
173
  `build()` writes prerendered `static` pages (and copies `public/`) to `<outDir>/client` — that output is a plain static site, deployable anywhere (Vercel, Netlify, any CDN). Any page left in the default `server` mode requires a running Bun process (`x start`) and **is not included in the static output** — it needs a Bun-capable host (Fly.io, a VPS, Docker, etc.), not a static host or a Node-only serverless platform.
174
174
 
175
+ ## Enterprise readiness: security & observability
176
+
177
+ `createApp` accepts optional `security` and `observability` config, all on by sane defaults:
178
+
179
+ ```ts
180
+ import { createApp, createSentryReporter } from "@thexjs/core";
181
+
182
+ const app = createApp({
183
+ pagesDir: "./src/pages",
184
+ actionsDir: "./src/actions",
185
+ security: {
186
+ // Origin/Referer verification on /__x/actions/* is always on; add explicit
187
+ // cross-subdomain origins here, or requireToken for double-submit CSRF cookies.
188
+ csrf: { allowedOrigins: ["https://app.example.com"] },
189
+ // CSP, HSTS, X-Frame-Options, etc. Pass `false` to disable entirely, or
190
+ // override individual fields (see SecurityHeadersOptions).
191
+ headers: { contentSecurityPolicy: "default-src 'self'" },
192
+ // In-memory fixed-window limiter, keyed by client IP by default.
193
+ rateLimit: { limit: 100, windowMs: 60_000 },
194
+ },
195
+ observability: {
196
+ // Structured JSON request logs (timestamp, requestId, route, status, durationMs). Default: true.
197
+ logging: true,
198
+ // Forward SSR/action/API exceptions to Sentry, OpenTelemetry, or both — see
199
+ // createSentryReporter / createOtelReporter / combineReporters.
200
+ errorReporter: createSentryReporter(Sentry),
201
+ // /healthz (liveness) and /readyz (readiness) are always served, ahead of all
202
+ // other routing. Add named checks (e.g. a DB ping) for /readyz.
203
+ health: { checks: { database: () => db.ping() } },
204
+ },
205
+ });
206
+ ```
207
+
208
+ Only variables prefixed `THEXJS_PUBLIC_` may reach the browser — `@thexjs/env`'s `createEnv` defaults `clientPrefix` to that, and the build step throws an `EnvLeakageError` if any client bundle references a server-only `process.env`/`Bun.env`/`import.meta.env` variable, so a secret like `STRIPE_SECRET_KEY` can never round-trip into shipped JS.
209
+
175
210
  ## Exports reference
176
211
 
177
212
  | Export | Purpose |
@@ -186,6 +221,13 @@ await build({ pagesDir: "./src/pages", outDir: "./.x" });
186
221
  | `registerServerFunctions`, `generateServerFunctionClient`, `getServerFunctionHandler`, `resetServerFunctions` | Server functions/actions internals |
187
222
  | `connectSQLite`, `connectPostgres`, `runSQLiteMigrations`, `runPostgresMigrations` | Data layer |
188
223
  | `DefaultNotFound`, `renderErrorOverlay`, `CLIENT_NAV_SCRIPT` | Defaults / dev tooling |
224
+ | `checkCsrf`, `verifyOrigin`, `verifyCsrfToken`, `generateCsrfToken`, `withCsrfCookie`, `CsrfOptions`, `CsrfResult` | CSRF protection |
225
+ | `buildSecurityHeaders`, `applySecurityHeaders`, `SecurityHeadersOptions` | Security response headers (CSP/HSTS/etc.) |
226
+ | `createRateLimiter`, `rateLimitMiddleware`, `RateLimitOptions`, `RateLimitResult` | Rate limiting |
227
+ | `findLeakedEnvKeys`, `assertNoEnvLeakage`, `EnvLeakageError`, `PUBLIC_ENV_PREFIX` | Server/client env var isolation |
228
+ | `logger`, `withRequestLogging`, `Logger`, `LogFields` | Structured JSON logging |
229
+ | `setErrorReporter`, `getErrorReporter`, `reportException`, `createSentryReporter`, `createOtelReporter`, `combineReporters`, `noopReporter`, `ErrorReporter` | Error reporting (Sentry/OpenTelemetry hook) |
230
+ | `createHealthCheckHandler`, `HealthCheckOptions`, `HealthCheck`, `ReadinessResult` | `/healthz` and `/readyz` |
189
231
 
190
232
  ## License
191
233
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as react from 'react';
2
- import { ReactNode } from 'react';
2
+ import { ReactNode, AnchorHTMLAttributes } from 'react';
3
3
  import { Database } from 'bun:sqlite';
4
4
 
5
5
  interface RouteEntry {
@@ -41,6 +41,182 @@ declare function findMiddlewareChain(routeFilePath: string, middleware: Middlewa
41
41
  declare function generateManifestSource(routes: RouteEntry[]): string;
42
42
  declare function writeManifest(routes: RouteEntry[], routesDir: string): string;
43
43
 
44
+ /**
45
+ * Built-in `/healthz` and `/readyz` endpoints for container orchestrators
46
+ * (Kubernetes, Docker Swarm, Railway, Fly.io) to probe process health and
47
+ * downstream readiness (e.g. database connectivity) before routing traffic.
48
+ */
49
+ type HealthCheck = () => Promise<boolean> | boolean;
50
+ interface HealthCheckOptions {
51
+ /** Named readiness checks, e.g. { database: () => pingDb() }. All must pass for /readyz to return 200. */
52
+ checks?: Record<string, HealthCheck>;
53
+ }
54
+ interface ReadinessResult {
55
+ status: "ok" | "error";
56
+ checks: Record<string, "ok" | "error">;
57
+ }
58
+ /**
59
+ * Returns a request handler that answers `/healthz` (liveness — the Bun
60
+ * process is up and serving) and `/readyz` (readiness — all configured
61
+ * checks pass, e.g. DB connectivity). Returns null for any other path so it
62
+ * can be composed ahead of normal routing.
63
+ */
64
+ declare function createHealthCheckHandler(options?: HealthCheckOptions): (req: Request) => Promise<Response | null>;
65
+
66
+ /**
67
+ * Plugin hook for capturing unhandled exceptions during SSR and server
68
+ * action execution, and exporting them to an APM provider. `@thexjs/core`
69
+ * has no hard dependency on Sentry or OpenTelemetry — apps opt in by
70
+ * installing the relevant package and constructing a reporter; everything
71
+ * here degrades to a no-op if nothing is configured.
72
+ */
73
+ interface ErrorContext {
74
+ route?: string;
75
+ requestId?: string;
76
+ phase: "ssr" | "action" | "api" | "loader";
77
+ }
78
+ interface ErrorReporter {
79
+ captureException(error: unknown, context: ErrorContext): void;
80
+ /** Optional: flush buffered events, e.g. on graceful shutdown. */
81
+ flush?(): Promise<void>;
82
+ }
83
+ /** No-op reporter used when no APM integration is configured. */
84
+ declare const noopReporter: ErrorReporter;
85
+ declare function setErrorReporter(reporter: ErrorReporter): void;
86
+ declare function getErrorReporter(): ErrorReporter;
87
+ declare function reportException(error: unknown, context: ErrorContext): void;
88
+ /**
89
+ * Minimal shape of the Sentry Node/Bun SDK surface this integration needs.
90
+ * Avoids a hard dependency on `@sentry/*` — pass in the SDK's `Sentry` object
91
+ * after calling `Sentry.init(...)` yourself.
92
+ */
93
+ interface SentryLike {
94
+ captureException(error: unknown, hint?: {
95
+ extra?: Record<string, unknown>;
96
+ }): string;
97
+ flush?(timeoutMs?: number): Promise<boolean>;
98
+ }
99
+ declare function createSentryReporter(sentry: SentryLike): ErrorReporter;
100
+ /**
101
+ * Minimal shape of an OpenTelemetry tracer's span-recording surface this
102
+ * integration needs. Pass in a tracer obtained from your own OTel SDK setup
103
+ * (`trace.getTracer(...)`) — `@thexjs/core` never initializes OTel itself.
104
+ */
105
+ interface OtelSpanLike {
106
+ recordException(error: unknown): void;
107
+ setStatus(status: {
108
+ code: number;
109
+ message?: string;
110
+ }): void;
111
+ end(): void;
112
+ }
113
+ interface OtelTracerLike {
114
+ startSpan(name: string): OtelSpanLike;
115
+ }
116
+ declare function createOtelReporter(tracer: OtelTracerLike): ErrorReporter;
117
+ /** Combines multiple reporters — useful for sending to Sentry and OTel at once. */
118
+ declare function combineReporters(...reporters: ErrorReporter[]): ErrorReporter;
119
+
120
+ /**
121
+ * CSRF protection for server actions (`/__x/actions/*`) and other mutating
122
+ * endpoints. Two independent checks are provided and both run by default:
123
+ *
124
+ * 1. Origin/Referer verification — rejects cross-site `POST` requests whose
125
+ * `Origin` (or, failing that, `Referer`) header doesn't match one of the
126
+ * app's own origins. This alone stops the vast majority of CSRF attempts
127
+ * from a browser, with zero setup required.
128
+ * 2. Double-submit CSRF token — for apps that want defense in depth, a
129
+ * random token is issued in a cookie and must be echoed back in the
130
+ * `x-csrf-token` request header on mutating requests.
131
+ */
132
+ interface CsrfOptions {
133
+ /** Origins considered same-site, e.g. ["https://example.com"]. */
134
+ allowedOrigins?: string[];
135
+ /** Require the double-submit token header in addition to origin checks. Default: false. */
136
+ requireToken?: boolean;
137
+ /** Skip CSRF checks entirely. Only use for local tooling/tests. Default: false. */
138
+ disabled?: boolean;
139
+ }
140
+ interface CsrfResult {
141
+ ok: boolean;
142
+ reason?: string;
143
+ }
144
+ /**
145
+ * Verifies the Origin/Referer of a mutating request against the app's own
146
+ * origin plus any explicitly allowed origins. Requests with no Origin or
147
+ * Referer header at all (same-origin requests from older browsers, curl,
148
+ * server-to-server calls with an explicit bypass) are rejected unless the
149
+ * method is safe.
150
+ */
151
+ declare function verifyOrigin(req: Request, allowedOrigins?: string[]): CsrfResult;
152
+ declare function generateCsrfToken(): string;
153
+ /** Double-submit check: the cookie value and the request header must match and be non-empty. */
154
+ declare function verifyCsrfToken(req: Request): CsrfResult;
155
+ /** Sets the double-submit CSRF cookie on a response if it isn't already present on the request. */
156
+ declare function withCsrfCookie(req: Request, res: Response): Response;
157
+ /** Runs the configured CSRF checks against a request. Returns ok:true when disabled. */
158
+ declare function checkCsrf(req: Request, options?: CsrfOptions): CsrfResult;
159
+
160
+ /**
161
+ * Security headers helper. Applies sane, overridable defaults for
162
+ * Content-Security-Policy, Strict-Transport-Security and X-Frame-Options
163
+ * (plus a couple of low-risk extras) to every response.
164
+ */
165
+ interface SecurityHeadersOptions {
166
+ /** Full CSP value, or false to disable. Default: a conservative same-origin policy. */
167
+ contentSecurityPolicy?: string | false;
168
+ /** HSTS max-age in seconds, or false to disable. Default: 15552000 (180 days). */
169
+ hstsMaxAge?: number | false;
170
+ /** Include subdomains in HSTS. Default: true. */
171
+ hstsIncludeSubDomains?: boolean;
172
+ /** X-Frame-Options value, or false to disable. Default: "DENY". */
173
+ frameOptions?: string | false;
174
+ /** X-Content-Type-Options. Default: "nosniff". Set false to disable. */
175
+ contentTypeOptions?: string | false;
176
+ /** Referrer-Policy. Default: "strict-origin-when-cross-origin". Set false to disable. */
177
+ referrerPolicy?: string | false;
178
+ }
179
+ declare function buildSecurityHeaders(options?: SecurityHeadersOptions): Headers;
180
+ /** Returns a new Response with security headers merged onto the original response's headers. */
181
+ declare function applySecurityHeaders(res: Response, options?: SecurityHeadersOptions): Response;
182
+
183
+ /**
184
+ * Lightweight in-memory rate limiter. Fixed-window counter keyed by client
185
+ * IP by default. Good enough for a single-process Bun deployment or as a
186
+ * first line of defense in front of brute-force/DDoS traffic; for multi-instance
187
+ * deployments, front this with a shared store (Redis, etc.) via a custom `keyFn`
188
+ * and store — this implementation intentionally has no external dependencies.
189
+ */
190
+ interface RateLimitOptions {
191
+ /** Max requests allowed per window per key. Default: 60. */
192
+ limit?: number;
193
+ /** Window size in milliseconds. Default: 60_000 (1 minute). */
194
+ windowMs?: number;
195
+ /** Derives the rate-limit bucket key from a request. Default: client IP from standard headers. */
196
+ keyFn?: (req: Request) => string;
197
+ }
198
+ interface RateLimitResult {
199
+ ok: boolean;
200
+ limit: number;
201
+ remaining: number;
202
+ resetAt: number;
203
+ }
204
+ interface Bucket {
205
+ count: number;
206
+ resetAt: number;
207
+ }
208
+ /** Creates an independent rate limiter with its own bucket store. */
209
+ declare function createRateLimiter(options?: RateLimitOptions): {
210
+ check: (req: Request) => RateLimitResult;
211
+ sweep: () => void;
212
+ buckets: Map<string, Bucket>;
213
+ };
214
+ /**
215
+ * Convenience middleware-style handler: returns a 429 Response when the
216
+ * limit is exceeded, or null when the request should proceed.
217
+ */
218
+ declare function rateLimitMiddleware(limiter: ReturnType<typeof createRateLimiter>, req: Request): Response | null;
219
+
44
220
  interface RouteProps {
45
221
  params: Record<string, string>;
46
222
  loaderData?: Record<string, unknown>;
@@ -58,6 +234,22 @@ interface CreateAppOptions {
58
234
  actionsDir?: string;
59
235
  port?: number;
60
236
  development?: boolean;
237
+ security?: {
238
+ /** CSRF protection for /__x/actions/* requests. Origin/Referer verification is always on unless disabled. */
239
+ csrf?: CsrfOptions;
240
+ /** Security response headers (CSP, HSTS, X-Frame-Options, ...). Pass false to disable entirely. */
241
+ headers?: SecurityHeadersOptions | false;
242
+ /** Rate limiting applied ahead of all routing. Pass false to disable entirely. */
243
+ rateLimit?: RateLimitOptions | false;
244
+ };
245
+ observability?: {
246
+ /** Structured JSON request logging. Default: true. */
247
+ logging?: boolean;
248
+ /** Plugin hook for exceptions during SSR/actions/API — see createSentryReporter/createOtelReporter. */
249
+ errorReporter?: ErrorReporter;
250
+ /** /healthz and /readyz endpoints, served ahead of all other routing. */
251
+ health?: HealthCheckOptions;
252
+ };
61
253
  }
62
254
  interface AppServeOptions {
63
255
  routes: Record<string, (req: Request) => Promise<Response> | Response>;
@@ -100,8 +292,12 @@ declare function renderStreamingPage(node: ReactNode, options?: RenderOptions):
100
292
  * Intercepts same-origin <a> clicks, fetches the destination page, and swaps
101
293
  * the #root element's content in place. Includes hover-prefetch and popstate
102
294
  * (back/forward) support.
295
+ *
296
+ * Opt-out attributes on <a> / <Link />:
297
+ * - data-no-nav — skip client navigation (full page load)
298
+ * - data-no-prefetch — skip hover prefetch (navigation still works)
103
299
  */
104
- declare const CLIENT_NAV_SCRIPT = "!function(){if(!window.__xNav){window.__xNav=!0;var t=new Map;document.addEventListener(\"click\",function(t){if(!t.defaultPrevented&&0===t.button&&!(t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)){var e=n(t.target&&t.target.closest?t.target.closest(\"a[href]\"):null);e&&(t.preventDefault(),e.href!==location.href&&i(e,!0))}}),document.addEventListener(\"mouseover\",function(e){var r=n(e.target&&e.target.closest?e.target.closest(\"a[href]\"):null);r&&function(e){t.has(e.href)||a(e).catch(function(){})}(r)},{passive:!0}),window.addEventListener(\"popstate\",function(){i(new URL(location.href),!1)});var e=document.createElement(\"style\");e.textContent=[\".x-nav-loading{cursor:progress}\",\".x-nav-loading::after{content:'';position:fixed;top:0;left:0;height:2px;width:100%;\",\"background:var(--x-accent,#6ab0ff);z-index:9999;animation:x-nav-progress .8s ease-in-out infinite}\",\"@keyframes x-nav-progress{0%{transform:translateX(-100%)}50%{transform:translateX(0)}100%{transform:translateX(100%)}}\"].join(\"\"),document.head.appendChild(e)}function n(t){if(!t)return null;if(t.hasAttribute(\"data-no-nav\"))return null;if(t.target&&\"_self\"!==t.target)return null;if(t.hasAttribute(\"download\"))return null;var e,n=t.getAttribute(\"href\");if(!n)return null;if(/^(#|mailto:|tel:|javascript:)/i.test(n))return null;try{e=new URL(n,location.href)}catch(t){return null}if(e.origin!==location.origin)return null;var r=new URL(location.href);return e.pathname===r.pathname&&e.search===r.search&&e.hash?null:e}function r(t){document.documentElement.classList.toggle(\"x-nav-loading\",t)}function a(e){var n=e.href;if(t.has(n))return t.get(n);var r=fetch(e.href,{headers:{\"X-X-Nav\":\"1\"}}).then(function(t){return t.text().then(function(n){var r=t.headers.get(\"content-type\")||\"\";return{html:n,ok:t.ok,finalUrl:t.url||e.href,isHtml:-1!==r.indexOf(\"text/html\")}})}).catch(function(e){throw t.delete(n),e});return function(){if(!(t.size<30)){var e=t.keys().next().value;void 0!==e&&t.delete(e)}}(),t.set(n,r),r}function i(t,e){return r(!0),a(t).then(function(n){if(n.isHtml){var r=(new DOMParser).parseFromString(n.html,\"text/html\"),a=r.getElementById(\"root\"),i=document.getElementById(\"root\");if(a&&i){if(e&&history.pushState({xNav:!0},\"\",n.finalUrl),r.title&&(document.title=r.title),i.innerHTML=a.innerHTML,function(t){for(var e=t.querySelectorAll(\"script\"),n=0;n<e.length;n++){for(var r=e[n],a=document.createElement(\"script\"),i=0;i<r.attributes.length;i++){var o=r.attributes[i];a.setAttribute(o.name,o.value)}a.textContent=r.textContent,r.replaceWith(a)}}(i),t.hash){var o=document.getElementById(t.hash.slice(1));if(o)return void o.scrollIntoView()}window.scrollTo(0,0)}else location.href=t.href}else location.href=t.href}).catch(function(){location.href=t.href}).finally(function(){r(!1)})}}();";
300
+ declare const CLIENT_NAV_SCRIPT: string;
105
301
 
106
302
  type RouteMode = "static" | "server";
107
303
  interface BuildOptions {
@@ -112,6 +308,14 @@ interface BuildOptions {
112
308
  actionsDir?: string;
113
309
  contentDir?: string;
114
310
  outDir?: string;
311
+ /**
312
+ * Absolute path to the project's x.config.ts/js/mjs, if any. When set, the
313
+ * generated production server entry re-imports it at startup and forwards
314
+ * its `security`/`observability` fields into `createApp()` — those fields
315
+ * can hold live values (rate-limit key functions, error reporters, health
316
+ * checks) that can't be serialized into the generated file directly.
317
+ */
318
+ configPath?: string;
115
319
  }
116
320
  declare function build(options: BuildOptions): Promise<void>;
117
321
 
@@ -147,6 +351,20 @@ declare function Island({ name, client, children, }: {
147
351
  children: ReactNode;
148
352
  }): react.JSX.Element;
149
353
 
354
+ interface LinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href"> {
355
+ href: string;
356
+ children: ReactNode;
357
+ /** Use client-side navigation instead of a full page load (default: true). */
358
+ clientNav?: boolean;
359
+ /** Prefetch the destination on hover/focus (default: true). Requires client nav. */
360
+ prefetch?: boolean;
361
+ }
362
+ /**
363
+ * Framework `<Link />` — renders an anchor wired for the inline client nav script
364
+ * (SPA transitions + hover prefetch). Opt out with `clientNav={false}` or `prefetch={false}`.
365
+ */
366
+ declare function Link({ href, children, clientNav, prefetch, ...rest }: LinkProps): react.JSX.Element;
367
+
150
368
  interface MiddlewareContext {
151
369
  params: Record<string, string>;
152
370
  request: Request;
@@ -158,10 +376,53 @@ declare function composeMiddleware(fns: MiddlewareFn[], handler: (ctx: Middlewar
158
376
  declare function generateServerFunctionClient(routeFilePath: string, fnNames: string[], endpointBase: string): string;
159
377
  declare function resetServerFunctions(): void;
160
378
  declare function registerServerFunctions(routePath: string, paramNames: string[], fns: Record<string, (...args: unknown[]) => Promise<unknown>>): void;
161
- declare function getServerFunctionHandler(): (req: Request) => Promise<Response | null>;
379
+ declare function getServerFunctionHandler(csrfOptions?: CsrfOptions): (req: Request) => Promise<Response | null>;
162
380
 
163
381
  declare function renderErrorOverlay(error: unknown): string;
164
382
 
383
+ /**
384
+ * Compiler boundary between server-only environment variables and the
385
+ * client bundle. Convention: only variables prefixed with `THEXJS_PUBLIC_`
386
+ * may ever reach browser code. Anything else read via `process.env.*`,
387
+ * `Bun.env.*`, or `import.meta.env.*` inside a file that ends up in a client
388
+ * bundle is a build error, not a warning — secrets like `STRIPE_SECRET_KEY`
389
+ * or `DATABASE_URL` must never round-trip through the bundler into
390
+ * browser-shipped JS.
391
+ */
392
+ declare const PUBLIC_ENV_PREFIX = "THEXJS_PUBLIC_";
393
+ /**
394
+ * Scans bundled JS/TS source for references to environment variables that
395
+ * are not public (`THEXJS_PUBLIC_`-prefixed). Returns the offending variable
396
+ * names, deduplicated. An empty array means the code is clean.
397
+ */
398
+ declare function findLeakedEnvKeys(code: string): string[];
399
+ declare class EnvLeakageError extends Error {
400
+ readonly file: string;
401
+ readonly keys: string[];
402
+ constructor(file: string, keys: string[]);
403
+ }
404
+ /** Throws EnvLeakageError if the given bundle source references non-public env vars. */
405
+ declare function assertNoEnvLeakage(code: string, file: string): void;
406
+
407
+ /**
408
+ * Structured JSON logging. Replaces ad-hoc `console.log` with one JSON
409
+ * object per line — easy to ingest into Datadog, Grafana Loki, Kibana, etc.
410
+ */
411
+ interface LogFields {
412
+ [key: string]: unknown;
413
+ }
414
+ interface Logger {
415
+ info(message: string, fields?: LogFields): void;
416
+ warn(message: string, fields?: LogFields): void;
417
+ error(message: string, fields?: LogFields): void;
418
+ }
419
+ declare const logger: Logger;
420
+ /**
421
+ * Wraps a fetch handler so every request is logged as one structured JSON
422
+ * line with `timestamp`, `requestId`, `route`, `status`, and `durationMs`.
423
+ */
424
+ declare function withRequestLogging(handler: (req: Request) => Response | Promise<Response>): (req: Request) => Promise<Response>;
425
+
165
426
  interface SQLiteOptions {
166
427
  path?: string;
167
428
  wal?: boolean;
@@ -189,4 +450,4 @@ interface PostgresMigrationResult {
189
450
  }
190
451
  declare function runPostgresMigrations(client: PostgresClient, migrationsDir: string): Promise<PostgresMigrationResult>;
191
452
 
192
- export { type BuildOptions, CLIENT_NAV_SCRIPT, type ContentEntry, type CreateAppOptions, DefaultNotFound, type Frontmatter, Island, type IslandEntry, type IslandMode, IslandProvider, type LayoutEntry, type LoaderArgs, type LoaderReturn, type MiddlewareContext, type MiddlewareEntry, type MiddlewareFn, type MiddlewareNext, type NotFoundEntry, type RevalidateOptions, type RouteEntry, type RouteMode, type RouteProps, build, composeMiddleware, connectPostgres, connectSQLite, createApp, defineConfig, escapeHtml, findLayoutChain, findMiddlewareChain, generateManifestSource, generateServerFunctionClient, getServerFunctionHandler, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, resetServerFunctions, runPostgresMigrations, runSQLiteMigrations, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, writeManifest };
453
+ export { type BuildOptions, CLIENT_NAV_SCRIPT, type ContentEntry, type CreateAppOptions, type CsrfOptions, type CsrfResult, DefaultNotFound, EnvLeakageError, type ErrorContext, type ErrorReporter, type Frontmatter, type HealthCheck, type HealthCheckOptions, Island, type IslandEntry, type IslandMode, IslandProvider, type LayoutEntry, Link, type LinkProps, type LoaderArgs, type LoaderReturn, type LogFields, type Logger, type MiddlewareContext, type MiddlewareEntry, type MiddlewareFn, type MiddlewareNext, type NotFoundEntry, type OtelTracerLike, PUBLIC_ENV_PREFIX, type RateLimitOptions, type RateLimitResult, type ReadinessResult, type RevalidateOptions, type RouteEntry, type RouteMode, type RouteProps, type SecurityHeadersOptions, type SentryLike, applySecurityHeaders, assertNoEnvLeakage, build, buildSecurityHeaders, checkCsrf, combineReporters, composeMiddleware, connectPostgres, connectSQLite, createApp, createHealthCheckHandler, createOtelReporter, createRateLimiter, createSentryReporter, defineConfig, escapeHtml, findLayoutChain, findLeakedEnvKeys, findMiddlewareChain, generateCsrfToken, generateManifestSource, generateServerFunctionClient, getErrorReporter, getServerFunctionHandler, logger, noopReporter, rateLimitMiddleware, registerServerFunctions, renderErrorOverlay, renderMarkdown, renderPage, renderStaticPage, renderStreamingPage, reportException, resetServerFunctions, runPostgresMigrations, runSQLiteMigrations, scanApiDir, scanContent, scanLayouts, scanLayoutsDir, scanMiddleware, scanNotFound, scanPages, scanRoutes, setErrorReporter, verifyCsrfToken, verifyOrigin, withCsrfCookie, withRequestLogging, writeManifest };
package/dist/index.js CHANGED
@@ -234,12 +234,175 @@ function DefaultNotFound(_props) {
234
234
  import { renderToReadableStream, renderToStaticMarkup, renderToString } from "react-dom/server";
235
235
 
236
236
  // src/client-nav.ts
237
- var CLIENT_NAV_SCRIPT = `!function(){if(!window.__xNav){window.__xNav=!0;var t=new Map;document.addEventListener("click",function(t){if(!t.defaultPrevented&&0===t.button&&!(t.metaKey||t.ctrlKey||t.shiftKey||t.altKey)){var e=n(t.target&&t.target.closest?t.target.closest("a[href]"):null);e&&(t.preventDefault(),e.href!==location.href&&i(e,!0))}}),document.addEventListener("mouseover",function(e){var r=n(e.target&&e.target.closest?e.target.closest("a[href]"):null);r&&function(e){t.has(e.href)||a(e).catch(function(){})}(r)},{passive:!0}),window.addEventListener("popstate",function(){i(new URL(location.href),!1)});var e=document.createElement("style");e.textContent=[".x-nav-loading{cursor:progress}",".x-nav-loading::after{content:'';position:fixed;top:0;left:0;height:2px;width:100%;","background:var(--x-accent,#6ab0ff);z-index:9999;animation:x-nav-progress .8s ease-in-out infinite}","@keyframes x-nav-progress{0%{transform:translateX(-100%)}50%{transform:translateX(0)}100%{transform:translateX(100%)}}"].join(""),document.head.appendChild(e)}function n(t){if(!t)return null;if(t.hasAttribute("data-no-nav"))return null;if(t.target&&"_self"!==t.target)return null;if(t.hasAttribute("download"))return null;var e,n=t.getAttribute("href");if(!n)return null;if(/^(#|mailto:|tel:|javascript:)/i.test(n))return null;try{e=new URL(n,location.href)}catch(t){return null}if(e.origin!==location.origin)return null;var r=new URL(location.href);return e.pathname===r.pathname&&e.search===r.search&&e.hash?null:e}function r(t){document.documentElement.classList.toggle("x-nav-loading",t)}function a(e){var n=e.href;if(t.has(n))return t.get(n);var r=fetch(e.href,{headers:{"X-X-Nav":"1"}}).then(function(t){return t.text().then(function(n){var r=t.headers.get("content-type")||"";return{html:n,ok:t.ok,finalUrl:t.url||e.href,isHtml:-1!==r.indexOf("text/html")}})}).catch(function(e){throw t.delete(n),e});return function(){if(!(t.size<30)){var e=t.keys().next().value;void 0!==e&&t.delete(e)}}(),t.set(n,r),r}function i(t,e){return r(!0),a(t).then(function(n){if(n.isHtml){var r=(new DOMParser).parseFromString(n.html,"text/html"),a=r.getElementById("root"),i=document.getElementById("root");if(a&&i){if(e&&history.pushState({xNav:!0},"",n.finalUrl),r.title&&(document.title=r.title),i.innerHTML=a.innerHTML,function(t){for(var e=t.querySelectorAll("script"),n=0;n<e.length;n++){for(var r=e[n],a=document.createElement("script"),i=0;i<r.attributes.length;i++){var o=r.attributes[i];a.setAttribute(o.name,o.value)}a.textContent=r.textContent,r.replaceWith(a)}}(i),t.hash){var o=document.getElementById(t.hash.slice(1));if(o)return void o.scrollIntoView()}window.scrollTo(0,0)}else location.href=t.href}else location.href=t.href}).catch(function(){location.href=t.href}).finally(function(){r(!1)})}}();`;
237
+ var CLIENT_NAV_SCRIPT = `
238
+ (function () {
239
+ if (window.__xNav) return;
240
+ window.__xNav = true;
241
+
242
+ var cache = new Map();
243
+
244
+ document.addEventListener("click", function (ev) {
245
+ if (ev.defaultPrevented || ev.button !== 0) return;
246
+ if (ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) return;
247
+ var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
248
+ if (!anchor) return;
249
+ ev.preventDefault();
250
+ if (anchor.href !== location.href) navigate(anchor, true);
251
+ });
252
+
253
+ document.addEventListener(
254
+ "mouseover",
255
+ function (ev) {
256
+ var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
257
+ if (!anchor || anchor.hasAttribute("data-no-prefetch")) return;
258
+ prefetch(anchor);
259
+ },
260
+ { passive: true },
261
+ );
262
+
263
+ document.addEventListener(
264
+ "focusin",
265
+ function (ev) {
266
+ var anchor = resolveLink(ev.target && ev.target.closest ? ev.target.closest("a[href]") : null);
267
+ if (!anchor || anchor.hasAttribute("data-no-prefetch")) return;
268
+ prefetch(anchor);
269
+ },
270
+ { passive: true },
271
+ );
272
+
273
+ window.addEventListener("popstate", function () {
274
+ navigate(new URL(location.href), false);
275
+ });
276
+
277
+ var style = document.createElement("style");
278
+ style.textContent = [
279
+ ".x-nav-loading{cursor:progress}",
280
+ ".x-nav-loading::after{content:'';position:fixed;top:0;left:0;height:2px;width:100%;",
281
+ "background:var(--x-accent,#6ab0ff);z-index:9999;animation:x-nav-progress .8s ease-in-out infinite}",
282
+ "@keyframes x-nav-progress{0%{transform:translateX(-100%)}50%{transform:translateX(0)}100%{transform:translateX(100%)}}",
283
+ ].join("");
284
+ document.head.appendChild(style);
285
+
286
+ function resolveLink(anchor) {
287
+ if (!anchor) return null;
288
+ if (anchor.hasAttribute("data-no-nav")) return null;
289
+ if (anchor.target && anchor.target !== "_self") return null;
290
+ if (anchor.hasAttribute("download")) return null;
291
+ var href = anchor.getAttribute("href");
292
+ if (!href) return null;
293
+ if (/^(#|mailto:|tel:|javascript:)/i.test(href)) return null;
294
+ var url;
295
+ try {
296
+ url = new URL(href, location.href);
297
+ } catch (_) {
298
+ return null;
299
+ }
300
+ if (url.origin !== location.origin) return null;
301
+ var here = new URL(location.href);
302
+ if (url.pathname === here.pathname && url.search === here.search && url.hash) return null;
303
+ return anchor;
304
+ }
305
+
306
+ function setLoading(on) {
307
+ document.documentElement.classList.toggle("x-nav-loading", on);
308
+ }
309
+
310
+ function prefetch(url) {
311
+ if (cache.has(url.href)) return cache.get(url.href);
312
+ var promise = fetch(url.href, { headers: { "X-X-Nav": "1" } })
313
+ .then(function (res) {
314
+ return res.text().then(function (html) {
315
+ var ct = res.headers.get("content-type") || "";
316
+ return { html: html, ok: res.ok, finalUrl: res.url || url.href, isHtml: ct.indexOf("text/html") !== -1 };
317
+ });
318
+ })
319
+ .catch(function (err) {
320
+ cache.delete(url.href);
321
+ throw err;
322
+ });
323
+ if (cache.size >= 30) {
324
+ var first = cache.keys().next().value;
325
+ if (first !== undefined) cache.delete(first);
326
+ }
327
+ cache.set(url.href, promise);
328
+ return promise;
329
+ }
330
+
331
+ function navigate(url, push) {
332
+ setLoading(true);
333
+ prefetch(url)
334
+ .then(function (payload) {
335
+ if (!payload.isHtml) {
336
+ location.href = url.href;
337
+ return;
338
+ }
339
+ var doc = new DOMParser().parseFromString(payload.html, "text/html");
340
+ var next = doc.getElementById("root");
341
+ var root = document.getElementById("root");
342
+ if (!next || !root) {
343
+ location.href = url.href;
344
+ return;
345
+ }
346
+ if (push) history.pushState({ xNav: true }, "", payload.finalUrl);
347
+ if (doc.title) document.title = doc.title;
348
+ root.innerHTML = next.innerHTML;
349
+ reexecuteScripts(root);
350
+ if (url.hash) {
351
+ var target = document.getElementById(url.hash.slice(1));
352
+ if (target) {
353
+ target.scrollIntoView();
354
+ return;
355
+ }
356
+ }
357
+ window.scrollTo(0, 0);
358
+ })
359
+ .catch(function () {
360
+ location.href = url.href;
361
+ })
362
+ .finally(function () {
363
+ setLoading(false);
364
+ });
365
+ }
366
+
367
+ function reexecuteScripts(root) {
368
+ var scripts = root.querySelectorAll("script");
369
+ for (var i = 0; i < scripts.length; i++) {
370
+ var old = scripts[i];
371
+ var el = document.createElement("script");
372
+ for (var j = 0; j < old.attributes.length; j++) {
373
+ var attr = old.attributes[j];
374
+ el.setAttribute(attr.name, attr.value);
375
+ }
376
+ el.textContent = old.textContent;
377
+ old.replaceWith(el);
378
+ }
379
+ }
380
+
381
+ /** Soft reload current page without a full document reload (used by dev live-reload). */
382
+ window.__xSoftReload = function () {
383
+ navigate(new URL(location.href), false);
384
+ };
385
+ })();
386
+ `.trim();
238
387
 
239
388
  // src/live-reload.ts
240
389
  var LIVE_RELOAD_SCRIPT = `
241
- (function(){var s=new EventSource("/__x/reload");s.addEventListener("reload",function(){s.close();window.location.reload()});s.addEventListener("hb",function(){});s.onerror=function(){s.close()}})();
242
- `;
390
+ (function () {
391
+ var es = new EventSource("/__x/reload");
392
+ es.addEventListener("reload", function () {
393
+ es.close();
394
+ if (typeof window.__xSoftReload === "function") {
395
+ window.__xSoftReload();
396
+ } else {
397
+ window.location.reload();
398
+ }
399
+ });
400
+ es.addEventListener("hb", function () {});
401
+ es.onerror = function () {
402
+ es.close();
403
+ };
404
+ })();
405
+ `.trim();
243
406
 
244
407
  // src/render.ts
245
408
  function escapeHtml(s) {
@@ -607,9 +770,309 @@ function composeMiddleware(fns, handler) {
607
770
  };
608
771
  }
609
772
 
773
+ // src/observability/health.ts
774
+ async function runChecks(checks) {
775
+ const results = {};
776
+ let allOk = true;
777
+ await Promise.all(
778
+ Object.entries(checks).map(async ([name, check]) => {
779
+ try {
780
+ const ok = await check();
781
+ results[name] = ok ? "ok" : "error";
782
+ if (!ok) allOk = false;
783
+ } catch {
784
+ results[name] = "error";
785
+ allOk = false;
786
+ }
787
+ })
788
+ );
789
+ return { status: allOk ? "ok" : "error", checks: results };
790
+ }
791
+ function createHealthCheckHandler(options = {}) {
792
+ const checks = options.checks ?? {};
793
+ return async (req) => {
794
+ const pathname = new URL(req.url).pathname;
795
+ if (pathname === "/healthz") {
796
+ return Response.json({ status: "ok" }, { status: 200 });
797
+ }
798
+ if (pathname === "/readyz") {
799
+ const result = await runChecks(checks);
800
+ return Response.json(result, { status: result.status === "ok" ? 200 : 503 });
801
+ }
802
+ return null;
803
+ };
804
+ }
805
+
806
+ // src/observability/logger.ts
807
+ function write(level, message, fields) {
808
+ const entry = {
809
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
810
+ level,
811
+ message,
812
+ ...fields
813
+ };
814
+ const line = JSON.stringify(entry);
815
+ if (level === "error") {
816
+ console.error(line);
817
+ } else if (level === "warn") {
818
+ console.warn(line);
819
+ } else {
820
+ console.log(line);
821
+ }
822
+ }
823
+ var logger = {
824
+ info: (message, fields) => write("info", message, fields),
825
+ warn: (message, fields) => write("warn", message, fields),
826
+ error: (message, fields) => write("error", message, fields)
827
+ };
828
+ function withRequestLogging(handler) {
829
+ return async (req) => {
830
+ const start = performance.now();
831
+ const requestId = req.headers.get("x-request-id") ?? crypto.randomUUID();
832
+ const route = new URL(req.url).pathname;
833
+ try {
834
+ const res = await handler(req);
835
+ write("info", "request completed", {
836
+ requestId,
837
+ route,
838
+ method: req.method,
839
+ status: res.status,
840
+ durationMs: Math.round(performance.now() - start)
841
+ });
842
+ if (!res.headers.has("x-request-id")) {
843
+ const headers = new Headers(res.headers);
844
+ headers.set("x-request-id", requestId);
845
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
846
+ }
847
+ return res;
848
+ } catch (err) {
849
+ write("error", "request failed", {
850
+ requestId,
851
+ route,
852
+ method: req.method,
853
+ status: 500,
854
+ durationMs: Math.round(performance.now() - start),
855
+ error: err instanceof Error ? err.message : String(err)
856
+ });
857
+ throw err;
858
+ }
859
+ };
860
+ }
861
+
862
+ // src/observability/monitoring.ts
863
+ var noopReporter = {
864
+ captureException: () => {
865
+ }
866
+ };
867
+ var activeReporter = noopReporter;
868
+ function setErrorReporter(reporter) {
869
+ activeReporter = reporter;
870
+ }
871
+ function getErrorReporter() {
872
+ return activeReporter;
873
+ }
874
+ function reportException(error, context) {
875
+ try {
876
+ activeReporter.captureException(error, context);
877
+ } catch (reportingError) {
878
+ console.error("[x] error reporter threw while handling an exception:", reportingError);
879
+ }
880
+ }
881
+ function createSentryReporter(sentry) {
882
+ return {
883
+ captureException(error, context) {
884
+ sentry.captureException(error, { extra: { ...context } });
885
+ },
886
+ async flush() {
887
+ await sentry.flush?.(2e3);
888
+ }
889
+ };
890
+ }
891
+ var OTEL_ERROR_STATUS_CODE = 2;
892
+ function createOtelReporter(tracer) {
893
+ return {
894
+ captureException(error, context) {
895
+ const span = tracer.startSpan(`x.${context.phase}.error`);
896
+ span.recordException(error);
897
+ span.setStatus({
898
+ code: OTEL_ERROR_STATUS_CODE,
899
+ message: error instanceof Error ? error.message : String(error)
900
+ });
901
+ span.end();
902
+ }
903
+ };
904
+ }
905
+ function combineReporters(...reporters) {
906
+ return {
907
+ captureException(error, context) {
908
+ for (const reporter of reporters) {
909
+ try {
910
+ reporter.captureException(error, context);
911
+ } catch (err) {
912
+ console.error("[x] error reporter threw while handling an exception:", err);
913
+ }
914
+ }
915
+ },
916
+ async flush() {
917
+ await Promise.all(reporters.map((r) => r.flush?.()));
918
+ }
919
+ };
920
+ }
921
+
922
+ // src/security/headers.ts
923
+ var DEFAULT_CSP = "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'";
924
+ function buildSecurityHeaders(options = {}) {
925
+ const headers = new Headers();
926
+ const csp = options.contentSecurityPolicy ?? DEFAULT_CSP;
927
+ if (csp !== false) headers.set("Content-Security-Policy", csp);
928
+ const hstsMaxAge = options.hstsMaxAge ?? 15552e3;
929
+ if (hstsMaxAge !== false) {
930
+ const includeSub = options.hstsIncludeSubDomains ?? true;
931
+ headers.set(
932
+ "Strict-Transport-Security",
933
+ `max-age=${hstsMaxAge}${includeSub ? "; includeSubDomains" : ""}`
934
+ );
935
+ }
936
+ const frameOptions = options.frameOptions ?? "DENY";
937
+ if (frameOptions !== false) headers.set("X-Frame-Options", frameOptions);
938
+ const contentTypeOptions = options.contentTypeOptions ?? "nosniff";
939
+ if (contentTypeOptions !== false) headers.set("X-Content-Type-Options", contentTypeOptions);
940
+ const referrerPolicy = options.referrerPolicy ?? "strict-origin-when-cross-origin";
941
+ if (referrerPolicy !== false) headers.set("Referrer-Policy", referrerPolicy);
942
+ return headers;
943
+ }
944
+ function applySecurityHeaders(res, options = {}) {
945
+ const extra = buildSecurityHeaders(options);
946
+ const headers = new Headers(res.headers);
947
+ for (const [key, value] of extra.entries()) {
948
+ if (!headers.has(key)) headers.set(key, value);
949
+ }
950
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
951
+ }
952
+
953
+ // src/security/rate-limit.ts
954
+ function defaultKeyFn(req) {
955
+ const headers = req.headers;
956
+ const forwarded = headers.get("x-forwarded-for");
957
+ if (forwarded) return forwarded.split(",")[0]?.trim() ?? "unknown";
958
+ return headers.get("x-real-ip") ?? "unknown";
959
+ }
960
+ function createRateLimiter(options = {}) {
961
+ const limit = options.limit ?? 60;
962
+ const windowMs = options.windowMs ?? 6e4;
963
+ const keyFn = options.keyFn ?? defaultKeyFn;
964
+ const buckets = /* @__PURE__ */ new Map();
965
+ function check(req) {
966
+ const key = keyFn(req);
967
+ const now = Date.now();
968
+ let bucket = buckets.get(key);
969
+ if (!bucket || bucket.resetAt <= now) {
970
+ bucket = { count: 0, resetAt: now + windowMs };
971
+ buckets.set(key, bucket);
972
+ }
973
+ bucket.count += 1;
974
+ const ok = bucket.count <= limit;
975
+ return { ok, limit, remaining: Math.max(0, limit - bucket.count), resetAt: bucket.resetAt };
976
+ }
977
+ function sweep() {
978
+ const now = Date.now();
979
+ for (const [key, bucket] of buckets) {
980
+ if (bucket.resetAt <= now) buckets.delete(key);
981
+ }
982
+ }
983
+ return { check, sweep, buckets };
984
+ }
985
+ function rateLimitMiddleware(limiter, req) {
986
+ const result = limiter.check(req);
987
+ if (result.ok) return null;
988
+ const retryAfterSeconds = Math.max(1, Math.ceil((result.resetAt - Date.now()) / 1e3));
989
+ return new Response("Too Many Requests", {
990
+ status: 429,
991
+ headers: {
992
+ "Retry-After": String(retryAfterSeconds),
993
+ "X-RateLimit-Limit": String(result.limit),
994
+ "X-RateLimit-Remaining": String(result.remaining)
995
+ }
996
+ });
997
+ }
998
+
610
999
  // src/server-functions.ts
611
1000
  import { writeFileSync as writeFileSync2 } from "fs";
612
1001
  import { join as join3 } from "path";
1002
+
1003
+ // src/security/csrf.ts
1004
+ var CSRF_COOKIE_NAME = "x_csrf_token";
1005
+ var CSRF_HEADER_NAME = "x-csrf-token";
1006
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
1007
+ function originFromHeader(value) {
1008
+ if (!value) return null;
1009
+ try {
1010
+ return new URL(value).origin;
1011
+ } catch {
1012
+ return null;
1013
+ }
1014
+ }
1015
+ function requestOrigin(req) {
1016
+ const url = new URL(req.url);
1017
+ return `${url.protocol}//${url.host}`;
1018
+ }
1019
+ function verifyOrigin(req, allowedOrigins = []) {
1020
+ if (SAFE_METHODS.has(req.method)) return { ok: true };
1021
+ const selfOrigin = requestOrigin(req);
1022
+ const allowed = new Set([selfOrigin, ...allowedOrigins].filter(Boolean));
1023
+ const origin = originFromHeader(req.headers.get("origin"));
1024
+ if (origin) {
1025
+ return allowed.has(origin) ? { ok: true } : { ok: false, reason: `origin "${origin}" is not an allowed origin` };
1026
+ }
1027
+ const referer = originFromHeader(req.headers.get("referer"));
1028
+ if (referer) {
1029
+ return allowed.has(referer) ? { ok: true } : { ok: false, reason: `referer origin "${referer}" is not an allowed origin` };
1030
+ }
1031
+ return { ok: false, reason: "missing Origin and Referer headers on a mutating request" };
1032
+ }
1033
+ function generateCsrfToken() {
1034
+ return crypto.randomUUID().replace(/-/g, "") + crypto.randomUUID().replace(/-/g, "");
1035
+ }
1036
+ function readCookie(req, name) {
1037
+ const header = req.headers.get("cookie");
1038
+ if (!header) return null;
1039
+ for (const part of header.split(";")) {
1040
+ const [key, ...rest] = part.trim().split("=");
1041
+ if (key === name) return rest.join("=");
1042
+ }
1043
+ return null;
1044
+ }
1045
+ function verifyCsrfToken(req) {
1046
+ if (SAFE_METHODS.has(req.method)) return { ok: true };
1047
+ const cookieToken = readCookie(req, CSRF_COOKIE_NAME);
1048
+ const headerToken = req.headers.get(CSRF_HEADER_NAME);
1049
+ if (!cookieToken || !headerToken) {
1050
+ return { ok: false, reason: `missing CSRF cookie or "${CSRF_HEADER_NAME}" header` };
1051
+ }
1052
+ if (cookieToken !== headerToken) {
1053
+ return { ok: false, reason: "CSRF token mismatch" };
1054
+ }
1055
+ return { ok: true };
1056
+ }
1057
+ function withCsrfCookie(req, res) {
1058
+ if (readCookie(req, CSRF_COOKIE_NAME)) return res;
1059
+ const token = generateCsrfToken();
1060
+ const headers = new Headers(res.headers);
1061
+ headers.append("Set-Cookie", `${CSRF_COOKIE_NAME}=${token}; Path=/; SameSite=Lax`);
1062
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
1063
+ }
1064
+ function checkCsrf(req, options = {}) {
1065
+ if (options.disabled) return { ok: true };
1066
+ const originResult = verifyOrigin(req, options.allowedOrigins ?? []);
1067
+ if (!originResult.ok) return originResult;
1068
+ if (options.requireToken) {
1069
+ const tokenResult = verifyCsrfToken(req);
1070
+ if (!tokenResult.ok) return tokenResult;
1071
+ }
1072
+ return { ok: true };
1073
+ }
1074
+
1075
+ // src/server-functions.ts
613
1076
  function generateServerFunctionClient(routeFilePath, fnNames, endpointBase) {
614
1077
  const fnCalls = fnNames.map(
615
1078
  (name) => `
@@ -644,11 +1107,15 @@ function registerServerFunctions(routePath, paramNames, fns) {
644
1107
  ACTION_ROUTES.push({ routePath, paramNames, fns: fnMap });
645
1108
  }
646
1109
  }
647
- function getServerFunctionHandler() {
1110
+ function getServerFunctionHandler(csrfOptions) {
648
1111
  return async (req) => {
649
1112
  if (req.method !== "POST") return null;
650
1113
  const url = new URL(req.url);
651
1114
  if (!url.pathname.startsWith("/__x/actions/")) return null;
1115
+ const csrfResult = checkCsrf(req, csrfOptions);
1116
+ if (!csrfResult.ok) {
1117
+ return new Response(`Forbidden: ${csrfResult.reason}`, { status: 403 });
1118
+ }
652
1119
  const parts = url.pathname.replace("/__x/actions/", "").split("/");
653
1120
  if (parts.length < 2) return null;
654
1121
  const actionName = parts.pop();
@@ -670,6 +1137,7 @@ function getServerFunctionHandler() {
670
1137
  const result = await fn(...args);
671
1138
  return Response.json(result);
672
1139
  } catch (err) {
1140
+ reportException(err, { route: concretePath, phase: "action" });
673
1141
  const message = err instanceof Error ? err.message : "Internal error";
674
1142
  return new Response(message, { status: 500 });
675
1143
  }
@@ -760,8 +1228,18 @@ async function createApp(options) {
760
1228
  let stylesheetHref;
761
1229
  let notFoundComponent = DefaultNotFound;
762
1230
  let notFoundLayout;
763
- const serverFnHandler = getServerFunctionHandler();
1231
+ const serverFnHandler = getServerFunctionHandler(options.security?.csrf);
764
1232
  const staticCache = /* @__PURE__ */ new Map();
1233
+ if (options.observability?.errorReporter) {
1234
+ setErrorReporter(options.observability.errorReporter);
1235
+ }
1236
+ const healthHandler = createHealthCheckHandler(options.observability?.health ?? {});
1237
+ const rateLimiter = options.security?.rateLimit === false ? null : createRateLimiter(options.security?.rateLimit ?? {});
1238
+ const securityHeadersOptions = options.security?.headers;
1239
+ const loggingEnabled = options.observability?.logging ?? true;
1240
+ function withResponseHardening(res) {
1241
+ return securityHeadersOptions === false ? res : applySecurityHeaders(res, securityHeadersOptions);
1242
+ }
765
1243
  async function renderNotFound(req) {
766
1244
  const content = notFoundLayout ? createElement(notFoundLayout, null, createElement(notFoundComponent, { params: {} })) : createElement(notFoundComponent, { params: {} });
767
1245
  const html = renderPage(content, {
@@ -866,6 +1344,7 @@ async function createApp(options) {
866
1344
  }
867
1345
  return new Response(`Method ${method} not allowed`, { status: 405 });
868
1346
  } catch (err) {
1347
+ reportException(err, { route: route.routePath, phase: "api" });
869
1348
  console.error("[x] API handler error:", err);
870
1349
  if (options.development) {
871
1350
  return new Response(renderErrorOverlay(err), {
@@ -968,6 +1447,7 @@ async function createApp(options) {
968
1447
  }
969
1448
  return baseHandler({ params, request: req });
970
1449
  } catch (err) {
1450
+ reportException(err, { route: route.routePath, phase: "ssr" });
971
1451
  console.error("[x] route handler error:", err);
972
1452
  if (options.development) {
973
1453
  return new Response(renderErrorOverlay(err), {
@@ -1069,8 +1549,14 @@ async function createApp(options) {
1069
1549
  } catch {
1070
1550
  console.warn("[x] file watching not available on this platform");
1071
1551
  }
1072
- const devFetch = async (req) => {
1552
+ const devFetchInner = async (req) => {
1073
1553
  const url = new URL(req.url).pathname;
1554
+ const healthResult = await healthHandler(req);
1555
+ if (healthResult !== null) return healthResult;
1556
+ if (rateLimiter) {
1557
+ const limited = rateLimitMiddleware(rateLimiter, req);
1558
+ if (limited !== null) return limited;
1559
+ }
1074
1560
  if (url === "/__x/reload") {
1075
1561
  const body = new ReadableStream({
1076
1562
  start(controller) {
@@ -1113,6 +1599,8 @@ data: ${data}
1113
1599
  }
1114
1600
  return renderNotFound(req);
1115
1601
  };
1602
+ const devFetchHardened = async (req) => withResponseHardening(await devFetchInner(req));
1603
+ const devFetch = loggingEnabled ? withRequestLogging(devFetchHardened) : devFetchHardened;
1116
1604
  return {
1117
1605
  routes: {},
1118
1606
  development: true,
@@ -1120,8 +1608,14 @@ data: ${data}
1120
1608
  fetch: devFetch
1121
1609
  };
1122
1610
  }
1123
- const prodFetch = async (req) => {
1611
+ const prodFetchInner = async (req) => {
1124
1612
  const url = new URL(req.url).pathname;
1613
+ const healthResult = await healthHandler(req);
1614
+ if (healthResult !== null) return healthResult;
1615
+ if (rateLimiter) {
1616
+ const limited = rateLimitMiddleware(rateLimiter, req);
1617
+ if (limited !== null) return limited;
1618
+ }
1125
1619
  const revalidationResult = await handleRevalidation(req);
1126
1620
  if (revalidationResult !== null) return revalidationResult;
1127
1621
  const serverFnResult = await serverFnHandler(req);
@@ -1141,6 +1635,8 @@ data: ${data}
1141
1635
  }
1142
1636
  return renderNotFound(req);
1143
1637
  };
1638
+ const prodFetchHardened = async (req) => withResponseHardening(await prodFetchInner(req));
1639
+ const prodFetch = loggingEnabled ? withRequestLogging(prodFetchHardened) : prodFetchHardened;
1144
1640
  return {
1145
1641
  routes: {},
1146
1642
  development: false,
@@ -1181,6 +1677,46 @@ function Island({
1181
1677
  return /* @__PURE__ */ jsx2("div", { "data-island": name, "data-island-id": id, "data-island-client": client, children });
1182
1678
  }
1183
1679
 
1680
+ // src/security/env-isolation.ts
1681
+ var PUBLIC_ENV_PREFIX = "THEXJS_PUBLIC_";
1682
+ var ENV_ACCESS_PATTERNS = [
1683
+ /\bprocess\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
1684
+ /\bprocess\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g,
1685
+ /\bBun\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,
1686
+ /\bBun\.env\[["']([A-Za-z_][A-Za-z0-9_]*)["']\]/g,
1687
+ /\bimport\.meta\.env\.([A-Za-z_][A-Za-z0-9_]*)/g
1688
+ ];
1689
+ function findLeakedEnvKeys(code) {
1690
+ const found = /* @__PURE__ */ new Set();
1691
+ for (const pattern of ENV_ACCESS_PATTERNS) {
1692
+ for (const match of code.matchAll(pattern)) {
1693
+ const key = match[1];
1694
+ if (key && !key.startsWith(PUBLIC_ENV_PREFIX)) {
1695
+ found.add(key);
1696
+ }
1697
+ }
1698
+ }
1699
+ return [...found];
1700
+ }
1701
+ var EnvLeakageError = class extends Error {
1702
+ constructor(file, keys) {
1703
+ super(
1704
+ `[x] server-only environment variable(s) leaked into client bundle "${file}": ${keys.join(", ")}. Only "${PUBLIC_ENV_PREFIX}*" variables may be referenced in client-shipped code \u2014 move this access into a loader, server function, or API route.`
1705
+ );
1706
+ this.file = file;
1707
+ this.keys = keys;
1708
+ this.name = "EnvLeakageError";
1709
+ }
1710
+ file;
1711
+ keys;
1712
+ };
1713
+ function assertNoEnvLeakage(code, file) {
1714
+ const leaked = findLeakedEnvKeys(code);
1715
+ if (leaked.length > 0) {
1716
+ throw new EnvLeakageError(file, leaked);
1717
+ }
1718
+ }
1719
+
1184
1720
  // src/build.ts
1185
1721
  async function build(options) {
1186
1722
  const outDir = options.outDir ?? join5(process.cwd(), ".x");
@@ -1213,18 +1749,27 @@ async function build(options) {
1213
1749
  if (legacyApiDir && existsSync2(legacyApiDir) && legacyApiDir !== apiDir) {
1214
1750
  routeEntries.push(...scanApiDir(legacyApiDir));
1215
1751
  }
1752
+ const actionModules = /* @__PURE__ */ new Map();
1216
1753
  if (actionsDir && existsSync2(actionsDir)) {
1217
1754
  for (const actionFile of scanRoutes(actionsDir)) {
1218
1755
  const mod = await import(actionFile.filePath);
1219
1756
  const segments = actionFile.routePath.split("/").filter(Boolean);
1220
1757
  const parentPath = `/${segments.slice(0, -1).join("/")}`;
1758
+ const fnNames = [];
1221
1759
  const actions = mod.actions;
1222
- if (actions) registerServerFunctions(parentPath, actionFile.paramNames, actions);
1760
+ if (actions) {
1761
+ registerServerFunctions(parentPath, actionFile.paramNames, actions);
1762
+ fnNames.push(...Object.keys(actions));
1763
+ }
1223
1764
  for (const [key, value] of Object.entries(mod)) {
1224
1765
  if (key === "default" || key === "actions" || typeof value !== "function") continue;
1225
1766
  registerServerFunctions(parentPath, actionFile.paramNames, {
1226
1767
  [key]: value
1227
1768
  });
1769
+ fnNames.push(key);
1770
+ }
1771
+ if (fnNames.length > 0) {
1772
+ actionModules.set(actionFile.filePath, { parentPath, fnNames });
1228
1773
  }
1229
1774
  }
1230
1775
  }
@@ -1288,7 +1833,7 @@ async function build(options) {
1288
1833
  let islandScripts = [];
1289
1834
  if (registry.entries.length > 0) {
1290
1835
  const uniqueNames = [...new Set(registry.entries.map((e) => e.name))];
1291
- islandScripts = await bundleRouteIslands(page.filePath, uniqueNames, islandsDir);
1836
+ islandScripts = await bundleRouteIslands(page.filePath, uniqueNames, islandsDir, actionModules);
1292
1837
  console.log(
1293
1838
  ` [islands] ${uniqueNames.length} island(s) on ${page.entry.routePath} -> ${islandScripts.join(", ")}`
1294
1839
  );
@@ -1327,8 +1872,10 @@ async function build(options) {
1327
1872
  if (options.layoutsDir) srvOpts.layoutsDir = options.layoutsDir;
1328
1873
  if (options.actionsDir) srvOpts.actionsDir = options.actionsDir;
1329
1874
  if (options.contentDir) srvOpts.contentDir = options.contentDir;
1875
+ const configImportPath = options.configPath ? relativeImportPath(serverDir, options.configPath) : void 0;
1330
1876
  const serverEntry = buildServerEntry(
1331
- srvOpts
1877
+ srvOpts,
1878
+ configImportPath
1332
1879
  );
1333
1880
  const serverEntryPath = join5(serverDir, "index.ts");
1334
1881
  writeFileSync3(serverEntryPath, serverEntry, "utf-8");
@@ -1338,7 +1885,7 @@ async function build(options) {
1338
1885
  }
1339
1886
  console.log(`[x] build complete -> ${outDir}`);
1340
1887
  }
1341
- async function bundleRouteIslands(routeFilePath, islandNames, islandsDir) {
1888
+ async function bundleRouteIslands(routeFilePath, islandNames, islandsDir, actionModules) {
1342
1889
  const entryId = `${basename(routeFilePath).replace(/\.(tsx|ts)$/, "")}-${hash(routeFilePath)}`;
1343
1890
  const outdir = join5(islandsDir, entryId);
1344
1891
  mkdirSync(outdir, { recursive: true });
@@ -1347,33 +1894,57 @@ async function bundleRouteIslands(routeFilePath, islandNames, islandsDir) {
1347
1894
  const hydrateEntry = generateHydrateEntry(routeRel, islandNames);
1348
1895
  const entryPath = join5(outdir, `${entryId}.tsx`);
1349
1896
  writeFileSync3(entryPath, hydrateEntry, "utf-8");
1350
- const result = Bun.spawnSync([
1351
- "bun",
1352
- "build",
1353
- "--target=browser",
1354
- "--external",
1355
- "react",
1356
- "--external",
1357
- "react-dom",
1358
- "--outdir",
1359
- outdir,
1360
- entryPath
1361
- ]);
1362
- if (result.success) {
1363
- return [`/_islands/${entryId}/${entryId}.js`];
1897
+ try {
1898
+ const result = await Bun.build({
1899
+ entrypoints: [entryPath],
1900
+ target: "browser",
1901
+ external: ["react", "react-dom"],
1902
+ plugins: [actionsRewritePlugin(actionModules)]
1903
+ });
1904
+ if (result.success) {
1905
+ const outputs = result.outputs.filter((o) => o.kind === "entry-point");
1906
+ const built = outputs[0] ?? result.outputs[0];
1907
+ if (!built) throw new Error("bun build produced no output");
1908
+ const code = await built.text();
1909
+ assertNoEnvLeakage(code, bundlePath);
1910
+ writeFileSync3(bundlePath, code, "utf-8");
1911
+ return [`/_islands/${entryId}/${entryId}.js`];
1912
+ }
1913
+ for (const log of result.logs) {
1914
+ console.warn(` [islands] build error: ${log.message}`);
1915
+ }
1916
+ } catch (err) {
1917
+ console.warn(` [islands] build failed for ${routeFilePath}:`, err);
1364
1918
  }
1365
1919
  writeFileSync3(bundlePath, generateFallbackHydration(islandNames), "utf-8");
1366
1920
  return [`/_islands/${entryId}/${entryId}.js`];
1367
1921
  }
1368
- function generateHydrateEntry(routeRelPath, islandNames) {
1369
- return `import * as Route from "${routeRelPath}";
1922
+ function actionsRewritePlugin(actionModules) {
1923
+ return {
1924
+ name: "x-actions-rewrite",
1925
+ setup(build2) {
1926
+ if (actionModules.size === 0) return;
1927
+ build2.onLoad({ filter: /\.(ts|tsx)$/ }, (args) => {
1928
+ const info = actionModules.get(args.path);
1929
+ if (!info) return void 0;
1930
+ const endpointBase = info.parentPath === "/" ? "/__x/actions" : `/__x/actions${info.parentPath}`;
1931
+ const contents = generateServerFunctionClient(args.path, info.fnNames, endpointBase);
1932
+ return { contents, loader: "ts" };
1933
+ });
1934
+ }
1935
+ };
1936
+ }
1937
+ function generateHydrateEntry(routeRelPath, _islandNames) {
1938
+ return `import React from "react";
1939
+ import { hydrateRoot } from "react-dom/client";
1940
+ import * as Route from "${routeRelPath}";
1370
1941
 
1371
1942
  document.querySelectorAll("[data-island]").forEach((el) => {
1372
1943
  const name = el.getAttribute("data-island");
1373
1944
  if (!name) return;
1374
1945
  const Component = Route.islands?.[name];
1375
1946
  if (!Component) return;
1376
- const root = ReactDOM.hydrateRoot(el, React.createElement(Component));
1947
+ hydrateRoot(el, React.createElement(Component));
1377
1948
  });
1378
1949
  `;
1379
1950
  }
@@ -1405,21 +1976,35 @@ function StaticContentPage({
1405
1976
  })
1406
1977
  );
1407
1978
  }
1408
- function buildServerEntry(opts) {
1979
+ function buildServerEntry(opts, configImportPath) {
1409
1980
  const dirKeys = ["pagesDir", "apiDir", "layoutsDir", "actionsDir", "contentDir"];
1410
1981
  const lines = [
1411
1982
  "// Auto-generated by @thexjs/core build",
1412
- 'import { createApp } from "@thexjs/core";',
1413
- "",
1414
- "const app = await createApp({"
1983
+ 'import { createApp } from "@thexjs/core";'
1415
1984
  ];
1985
+ if (configImportPath) {
1986
+ lines.push("", "let userConfig = {};", "try {");
1987
+ lines.push(` const mod = await import(${JSON.stringify(configImportPath)});`);
1988
+ lines.push(" userConfig = mod.default ?? {};");
1989
+ lines.push("} catch (err) {");
1990
+ lines.push(
1991
+ ' console.warn("[x] failed to load x.config for security/observability options:", err);'
1992
+ );
1993
+ lines.push("}");
1994
+ }
1995
+ lines.push("", "const app = await createApp({");
1416
1996
  for (const key of dirKeys) {
1417
1997
  const val = opts[key];
1418
1998
  if (val) lines.push(` ${key}: ${JSON.stringify(val)},`);
1419
1999
  }
2000
+ lines.push(' port: parseInt(process.env.PORT || "3000", 10),', " development: false,");
2001
+ if (configImportPath) {
2002
+ lines.push(" ...(userConfig.security ? { security: userConfig.security } : {}),");
2003
+ lines.push(
2004
+ " ...(userConfig.observability ? { observability: userConfig.observability } : {}),"
2005
+ );
2006
+ }
1420
2007
  lines.push(
1421
- ' port: parseInt(process.env.PORT || "3000", 10),',
1422
- " development: false,",
1423
2008
  "});",
1424
2009
  "",
1425
2010
  "const server = Bun.serve(app);",
@@ -1428,6 +2013,10 @@ function buildServerEntry(opts) {
1428
2013
  );
1429
2014
  return lines.join("\n");
1430
2015
  }
2016
+ function relativeImportPath(fromDir, toFile) {
2017
+ const rel = relative3(fromDir, toFile).replace(/\\/g, "/").replace(/\.(ts|js|mjs)$/, "");
2018
+ return rel.startsWith(".") ? rel : `./${rel}`;
2019
+ }
1431
2020
  function hash(str) {
1432
2021
  let h = 0;
1433
2022
  for (let i = 0; i < str.length; i++) {
@@ -1436,6 +2025,21 @@ function hash(str) {
1436
2025
  return Math.abs(h).toString(36);
1437
2026
  }
1438
2027
 
2028
+ // src/link.tsx
2029
+ import { jsx as jsx3 } from "react/jsx-runtime";
2030
+ function Link({ href, children, clientNav = true, prefetch = true, ...rest }) {
2031
+ return /* @__PURE__ */ jsx3(
2032
+ "a",
2033
+ {
2034
+ href,
2035
+ ...rest,
2036
+ ...!clientNav ? { "data-no-nav": "" } : {},
2037
+ ...!prefetch ? { "data-no-prefetch": "" } : {},
2038
+ children
2039
+ }
2040
+ );
2041
+ }
2042
+
1439
2043
  // src/data/sqlite.ts
1440
2044
  import { Database } from "bun:sqlite";
1441
2045
  function connectSQLite(options) {
@@ -1461,7 +2065,7 @@ function connectPostgres(options) {
1461
2065
  }
1462
2066
 
1463
2067
  // src/data/migrate.ts
1464
- import { readFileSync as readFileSync2, readdirSync as readdirSync3 } from "fs";
2068
+ import { readFileSync as readFileSync3, readdirSync as readdirSync3 } from "fs";
1465
2069
  import { join as join6 } from "path";
1466
2070
  function runSQLiteMigrations(db, migrationsDir) {
1467
2071
  db.run(`CREATE TABLE IF NOT EXISTS _x_migrations (
@@ -1482,7 +2086,7 @@ function runSQLiteMigrations(db, migrationsDir) {
1482
2086
  result.skipped.push(file);
1483
2087
  continue;
1484
2088
  }
1485
- const sql = readFileSync2(join6(migrationsDir, file), "utf-8");
2089
+ const sql = readFileSync3(join6(migrationsDir, file), "utf-8");
1486
2090
  db.run(sql);
1487
2091
  db.run("INSERT INTO _x_migrations (name) VALUES (?1)", [file]);
1488
2092
  console.log(`[x] migration applied: ${file}`);
@@ -1509,7 +2113,7 @@ async function runPostgresMigrations(client, migrationsDir) {
1509
2113
  result.skipped.push(file);
1510
2114
  continue;
1511
2115
  }
1512
- const raw = readFileSync2(join6(migrationsDir, file), "utf-8");
2116
+ const raw = readFileSync3(join6(migrationsDir, file), "utf-8");
1513
2117
  await client.unsafe(raw);
1514
2118
  await client.unsafe(`INSERT INTO _x_migrations (name) VALUES ('${file}')`);
1515
2119
  console.log(`[x] migration applied: ${file}`);
@@ -1520,26 +2124,45 @@ async function runPostgresMigrations(client, migrationsDir) {
1520
2124
  export {
1521
2125
  CLIENT_NAV_SCRIPT,
1522
2126
  DefaultNotFound,
2127
+ EnvLeakageError,
1523
2128
  Island,
1524
2129
  IslandProvider,
2130
+ Link,
2131
+ PUBLIC_ENV_PREFIX,
2132
+ applySecurityHeaders,
2133
+ assertNoEnvLeakage,
1525
2134
  build,
2135
+ buildSecurityHeaders,
2136
+ checkCsrf,
2137
+ combineReporters,
1526
2138
  composeMiddleware,
1527
2139
  connectPostgres,
1528
2140
  connectSQLite,
1529
2141
  createApp,
2142
+ createHealthCheckHandler,
2143
+ createOtelReporter,
2144
+ createRateLimiter,
2145
+ createSentryReporter,
1530
2146
  defineConfig,
1531
2147
  escapeHtml2 as escapeHtml,
1532
2148
  findLayoutChain,
2149
+ findLeakedEnvKeys,
1533
2150
  findMiddlewareChain,
2151
+ generateCsrfToken,
1534
2152
  generateManifestSource,
1535
2153
  generateServerFunctionClient,
2154
+ getErrorReporter,
1536
2155
  getServerFunctionHandler,
2156
+ logger,
2157
+ noopReporter,
2158
+ rateLimitMiddleware,
1537
2159
  registerServerFunctions,
1538
2160
  renderErrorOverlay,
1539
2161
  renderMarkdown,
1540
2162
  renderPage,
1541
2163
  renderStaticPage,
1542
2164
  renderStreamingPage,
2165
+ reportException,
1543
2166
  resetServerFunctions,
1544
2167
  runPostgresMigrations,
1545
2168
  runSQLiteMigrations,
@@ -1551,5 +2174,10 @@ export {
1551
2174
  scanNotFound,
1552
2175
  scanPages,
1553
2176
  scanRoutes,
2177
+ setErrorReporter,
2178
+ verifyCsrfToken,
2179
+ verifyOrigin,
2180
+ withCsrfCookie,
2181
+ withRequestLogging,
1554
2182
  writeManifest
1555
2183
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thexjs/core",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "Full-stack React framework core (router, SSR/SSG renderer, islands, server functions) for the x framework, built on Bun.",
5
5
  "keywords": [
6
6
  "react",
@@ -27,16 +27,12 @@
27
27
  "import": "./dist/index.js"
28
28
  }
29
29
  },
30
- "files": [
31
- "dist",
32
- "README.md",
33
- "LICENSE"
34
- ],
30
+ "files": ["dist", "README.md", "LICENSE"],
35
31
  "publishConfig": {
36
32
  "access": "public"
37
33
  },
38
34
  "scripts": {
39
- "build": "tsup src/index.ts --format esm --dts --clean --target node18 --external bun:sqlite",
35
+ "build": "tsup src/index.ts --format esm --dts --clean --target node18 --external bun:sqlite --external react --external react-dom --external react/jsx-runtime",
40
36
  "prepublishOnly": "bun run build"
41
37
  },
42
38
  "peerDependencies": {