@ghuri/core 0.1.0-alpha.1 → 0.1.0-alpha.3

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/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Context, Hono, HonoRequest } from 'hono';
2
- import { U as UrlResolver, G as GhuriSettings, a as GhuriContext, E as Env, b as ExecutionContextLike, S as SettingsFactory, A as AppConfig, c as GhuriError, P as PermissionDenied, V as ViewFunction } from './context-Du2IsGtO.js';
3
- export { d as AppConfigClass, e as AppRegistry, f as AppRegistryNotReady, B as BadRequest, C as CSRF_EXEMPT_MARKER, g as Cache, h as CacheBackend, i as CacheConfig, j as CacheOptions, k as CommandClassLike, l as CommonMiddleware, m as CompiledRoute, n as Converter, o as CorsMiddleware, p as CorsOptions, q as CsrfMiddleware, D as DisallowedHost, r as GZipMiddleware, H as HonoApp, s as Http404, t as HttpError, I as ImproperlyConfigured, u as Includable, L as LookupError, M as MethodNotAllowed, v as Middleware, w as MiddlewareClass, x as MiddlewareEntry, y as MiddlewareLike, z as MultipleObjectsReturned, N as NoReverseMatch, O as ObjectDoesNotExist, F as PathOptions, J as PathTarget, R as Resolver404, K as ResolverMatch, Q as ReverseOptions, T as SecurityMiddleware, W as SuspiciousOperation, X as UrlEntry, Y as UrlInclude, Z as UrlPatterns, _ as UrlPatternsLike, $ as ValidationError, a0 as ValidationMessages, a1 as ViewClassLike, a2 as XFrameOptionsMiddleware, a3 as apps, a4 as cache, a5 as caches, a6 as cfCache, a7 as converters, a8 as createContext, a9 as defineSettings, aa as ensureAppsReady, ab as getContext, ac as getEnv, ad as getResolver, ae as getSettings, af as include, ag as isAllowedHost, ah as isSettingsFactory, ai as kvCache, aj as kwargs, ak as memoryCache, al as path, am as rePath, an as registerConverter, ao as resolve, ap as resolverMatch, aq as reverse, ar as runWithContext, as as setGlobalContext, at as setting, au as toHonoMiddleware, av as tryGetContext, aw as urlpatterns, ax as validateHost } from './context-Du2IsGtO.js';
2
+ import { U as UrlResolver, G as GhuriSettings, a as GhuriContext, E as Env, b as ExecutionContextLike, S as SettingsFactory, A as AppConfig, c as GhuriError, P as PermissionDenied, V as ViewFunction } from './context-mL1PriMt.js';
3
+ export { d as AppConfigClass, e as AppRegistry, f as AppRegistryNotReady, B as BadRequest, C as CSRF_EXEMPT_MARKER, g as Cache, h as CacheBackend, i as CacheConfig, j as CacheOptions, k as CommandClassLike, l as CommonMiddleware, m as CompiledRoute, n as Converter, o as CorsMiddleware, p as CorsOptions, q as CsrfMiddleware, D as DisallowedHost, r as ErrorView, s as GZipMiddleware, H as HonoApp, t as Http404, u as HttpError, I as ImproperlyConfigured, v as Includable, L as LookupError, M as MethodNotAllowed, w as Middleware, x as MiddlewareClass, y as MiddlewareEntry, z as MiddlewareLike, F as MultipleObjectsReturned, N as NoReverseMatch, O as ObjectDoesNotExist, J as PathOptions, K as PathTarget, R as Resolver404, Q as ResolverMatch, T as ReverseOptions, W as SecurityMiddleware, X as SuspiciousOperation, Y as UrlEntry, Z as UrlInclude, _ as UrlPatterns, $ as UrlPatternsLike, a0 as ValidationError, a1 as ValidationMessages, a2 as ViewClassLike, a3 as XFRAME_OPTIONS_EXEMPT_MARKER, a4 as XFrameOptionsMiddleware, a5 as apps, a6 as cache, a7 as caches, a8 as cfCache, a9 as converters, aa as createContext, ab as defineSettings, ac as ensureAppsReady, ad as getContext, ae as getEnv, af as getResolver, ag as getSettings, ah as include, ai as isAllowedHost, aj as isSettingsFactory, ak as kvCache, al as kwargs, am as memoryCache, an as path, ao as rePath, ap as registerConverter, aq as resolve, ar as resolverMatch, as as reverse, at as runWithContext, au as setGlobalContext, av as setting, aw as toHonoMiddleware, ax as tryGetContext, ay as urlpatterns, az as validateHost } from './context-mL1PriMt.js';
4
4
 
5
5
  type ExceptionHandler = (err: any, c: Context) => Response | undefined | null | void | Promise<Response | undefined | null | void>;
6
6
  type Matcher = ((err: unknown) => boolean) | (abstract new (...args: any[]) => unknown);
@@ -24,18 +24,26 @@ declare function settingsFor(c?: Context): GhuriSettings | undefined;
24
24
  declare function wantsJson(c: Context): boolean;
25
25
  /** Settings with secrets masked (debug pages). */
26
26
  declare function cleansedSettings(settings: GhuriSettings | undefined): Array<[string, string]>;
27
- /** Render a 404 for a path no pattern matched (DEBUG lists the URL patterns, like Django). */
27
+ /**
28
+ * The built-in 404 for a path no pattern matched (DEBUG lists the URL patterns, like Django). It never
29
+ * calls `HANDLER_404`, so a custom handler can return it, e.g. for JSON clients.
30
+ */
28
31
  declare function notFoundResponse(c: Context, message?: string): Response;
29
32
  /**
30
33
  * Turn any thrown value into a Response: registered handlers first, then `HttpError` subclasses,
31
34
  * `ValidationError` (400), `ObjectDoesNotExist` (404), Hono's `HTTPException`, and finally 500.
35
+ * With `DEBUG` off, 404s go through `HANDLER_404` and uncaught errors through `HANDLER_500` when set.
32
36
  */
33
37
  declare function handleException(err: unknown, c: Context): Promise<Response>;
34
38
  /** Hono `onError` handler. */
35
39
  declare const errorHandler: (err: Error, c: Context) => Promise<Response>;
36
40
  /** Redirect `/x` → `/x/` (301) when APPEND_SLASH applies (GET/HEAD, path unmatched, slashed path matches). */
37
41
  declare function appendSlashRedirect(c: Context, urlconf?: UrlResolver): Response | null;
38
- /** Hono `notFound` handler: APPEND_SLASH, 405 for method-restricted routes, then 404. */
42
+ /**
43
+ * Hono `notFound` handler: APPEND_SLASH, 405 for method-restricted routes, then 404 (the project's
44
+ * `HANDLER_404` when set and `DEBUG` is off). It runs at the end of the middleware chain, so the request
45
+ * context and values set by MIDDLEWARE are available to `HANDLER_404`.
46
+ */
39
47
  declare function notFoundHandler(urlconf?: UrlResolver): (c: Context) => Response | Promise<Response>;
40
48
 
41
49
  /** Cloudflare `ScheduledController` (structural). */
@@ -183,6 +191,20 @@ interface RunChecksOptions {
183
191
  /** Run registered checks. Uses the current context's settings unless given. */
184
192
  declare function runChecks(opts?: RunChecksOptions): Promise<CheckMessage[]>;
185
193
 
194
+ /**
195
+ * Mark a view (or a mounted Hono app) as exempt from `XFrameOptionsMiddleware` (Django's
196
+ * `xframe_options_exempt`): its responses get no `X-Frame-Options` header from the middleware, so other
197
+ * sites can frame it. A header the view sets itself is always kept. For class views, set
198
+ * `static xframeOptionsExempt = true`.
199
+ *
200
+ * ```ts
201
+ * path('embed/', xframeOptionsExempt(embedView))
202
+ * ```
203
+ */
204
+ declare function xframeOptionsExempt<T extends object>(view: T): T;
205
+ /** Is the request's view exempt from `XFrameOptionsMiddleware`? */
206
+ declare function isXFrameOptionsExempt(c: Context): boolean;
207
+
186
208
  declare class CommandError extends GhuriError {
187
209
  readonly returncode: number;
188
210
  constructor(message: string, returncode?: number);
@@ -292,6 +314,23 @@ declare function enforceCsrf(c: Context): Promise<void>;
292
314
  /** Send the CSRF cookie if the token was created or rotated during this request. */
293
315
  declare function setCsrfCookieIfNeeded(c: Context): void;
294
316
 
317
+ /**
318
+ * Record the peer address of an incoming request (what `getRemoteAddr()` returns for it). `serve()` from
319
+ * `@ghuri/core/node` calls this with the socket address; call it yourself from a custom server (Bun, Deno, …)
320
+ * before passing the request to `app.fetch()`.
321
+ */
322
+ declare function setRemoteAddr(request: Request, addr: string): void;
323
+ /** Is this request served by Cloudflare (Workers, or `wrangler dev`/Miniflare)? */
324
+ declare function isCloudflareRequest(c: Context): boolean;
325
+ /**
326
+ * The client's network address (Django's `request.META['REMOTE_ADDR']`), from sources a client cannot forge:
327
+ * `CF-Connecting-IP` on Cloudflare (Cloudflare sets it and overwrites any client copy), else the socket
328
+ * address recorded by `serve()` / `setRemoteAddr()`, else `c.env.incoming` when the app is served by
329
+ * `@hono/node-server` directly, else `''`. `X-Forwarded-For` is never read here: behind a reverse proxy this
330
+ * is the proxy's address (REST throttles read the header with `NUM_PROXIES`).
331
+ */
332
+ declare function getRemoteAddr(c: Context): string;
333
+
295
334
  type Receiver<A> = (args: A & {
296
335
  sender: unknown;
297
336
  }) => void | Promise<void>;
@@ -389,6 +428,8 @@ declare abstract class View {
389
428
  static httpMethodNames: HttpMethodName[];
390
429
  /** Mark every view produced by `asView()` as CSRF exempt. */
391
430
  static csrfExempt: boolean;
431
+ /** Mark every view produced by `asView()` as exempt from `XFrameOptionsMiddleware`. */
432
+ static xframeOptionsExempt: boolean;
392
433
  /** The Hono context of the current request. */
393
434
  c: Context;
394
435
  /** The Hono request (Django's `self.request`). */
@@ -482,4 +523,4 @@ declare function redirect(c: Context, to: string | {
482
523
  status?: number;
483
524
  }): Response;
484
525
 
485
- export { AnonymousUser, AppConfig, ArgumentParser, type ArgumentSpec, type AsViewFunction, BaseCommand, SAFE_METHODS as CSRF_SAFE_METHODS, CSRF_SECRET_LENGTH, CSRF_TOKEN_LENGTH, type CheckContext, type CheckFunction, CheckLevel, CheckMessage, type CommandClass, CommandError, type CommandIO, CommandRegistry, type CommandStyle, type CreateAppOptions, CsrfFailure, Env, type ExceptionHandler, ExecutionContextLike, type GhuriApp, GhuriContext, GhuriError, GhuriSettings, type HttpMethodName, type MessageBatchLike, type OptionSpec, PermissionDenied, type QueueHandler, type QueueMessageLike, type Receiver, RedirectView, type RenderOptions, type Renderable, type RequestUser, type RunChecksOptions, type ScheduledEventLike, type ScheduledHandler, SettingsFactory, Signal, type Template, TemplateView, UrlResolver, type UserLoader, View, ViewFunction, anonymousUser, appendSlashRedirect, bufferIO, callCommand, checkCsrf, checks, cleansedSettings, commandRegistry, createApp, csrfExempt, enforceCsrf, ensureCsrfCookie, errorHandler, escapeHtml, generateCsrfSecret, getCsrfToken, getHost, getUser, handleException, hostMatches, isCsrfExempt, isSecure, json, loadUser, maskCsrfSecret, notFoundHandler, notFoundResponse, onQueue, onSchedule, plainStyle, receiver, redirect, registerExceptionHandler, registerUserLoader, render, requestFinished, requestStarted, resolveUrl, rotateCsrfToken, runChecks, setCsrfCookieIfNeeded, setUser, settingsFor, statusText, taskHandlers, toJson, unmaskCsrfToken, wantsJson };
526
+ export { AnonymousUser, AppConfig, ArgumentParser, type ArgumentSpec, type AsViewFunction, BaseCommand, SAFE_METHODS as CSRF_SAFE_METHODS, CSRF_SECRET_LENGTH, CSRF_TOKEN_LENGTH, type CheckContext, type CheckFunction, CheckLevel, CheckMessage, type CommandClass, CommandError, type CommandIO, CommandRegistry, type CommandStyle, type CreateAppOptions, CsrfFailure, Env, type ExceptionHandler, ExecutionContextLike, type GhuriApp, GhuriContext, GhuriError, GhuriSettings, type HttpMethodName, type MessageBatchLike, type OptionSpec, PermissionDenied, type QueueHandler, type QueueMessageLike, type Receiver, RedirectView, type RenderOptions, type Renderable, type RequestUser, type RunChecksOptions, type ScheduledEventLike, type ScheduledHandler, SettingsFactory, Signal, type Template, TemplateView, UrlResolver, type UserLoader, View, ViewFunction, anonymousUser, appendSlashRedirect, bufferIO, callCommand, checkCsrf, checks, cleansedSettings, commandRegistry, createApp, csrfExempt, enforceCsrf, ensureCsrfCookie, errorHandler, escapeHtml, generateCsrfSecret, getCsrfToken, getHost, getRemoteAddr, getUser, handleException, hostMatches, isCloudflareRequest, isCsrfExempt, isSecure, isXFrameOptionsExempt, json, loadUser, maskCsrfSecret, notFoundHandler, notFoundResponse, onQueue, onSchedule, plainStyle, receiver, redirect, registerExceptionHandler, registerUserLoader, render, requestFinished, requestStarted, resolveUrl, rotateCsrfToken, runChecks, setCsrfCookieIfNeeded, setRemoteAddr, setUser, settingsFor, statusText, taskHandlers, toJson, unmaskCsrfToken, wantsJson, xframeOptionsExempt };
package/dist/index.js CHANGED
@@ -1,3 +1,8 @@
1
+ import {
2
+ getRemoteAddr,
3
+ isCloudflareRequest,
4
+ setRemoteAddr
5
+ } from "./chunk-YJ7DTR2K.js";
1
6
  import {
2
7
  AppRegistryNotReady,
3
8
  BadRequest,
@@ -20,6 +25,7 @@ import {
20
25
  SuspiciousOperation,
21
26
  UrlResolver,
22
27
  ValidationError,
28
+ XFRAME_OPTIONS_EXEMPT_MARKER,
23
29
  appendSlashRedirect,
24
30
  checkCsrf,
25
31
  cleansedSettings,
@@ -61,8 +67,9 @@ import {
61
67
  tryGetContext,
62
68
  unmaskCsrfToken,
63
69
  urlpatterns,
70
+ viewHasMarker,
64
71
  wantsJson
65
- } from "./chunk-BQBV57DI.js";
72
+ } from "./chunk-54KUWCC4.js";
66
73
 
67
74
  // src/app.ts
68
75
  import { Hono } from "hono";
@@ -457,6 +464,18 @@ checks.register(checkSecurity, { tags: ["security"], deploy: true });
457
464
  // src/middleware.ts
458
465
  import { compress } from "hono/compress";
459
466
  import { cors } from "hono/cors";
467
+
468
+ // src/clickjacking.ts
469
+ function xframeOptionsExempt(view) {
470
+ ;
471
+ view[XFRAME_OPTIONS_EXEMPT_MARKER] = true;
472
+ return view;
473
+ }
474
+ function isXFrameOptionsExempt(c) {
475
+ return viewHasMarker(c, XFRAME_OPTIONS_EXEMPT_MARKER);
476
+ }
477
+
478
+ // src/middleware.ts
460
479
  var Middleware = class {
461
480
  };
462
481
  function isMiddlewareClass(v) {
@@ -543,6 +562,7 @@ var SecurityMiddleware = class extends Middleware {
543
562
  var XFrameOptionsMiddleware = class extends Middleware {
544
563
  async handle(c, next) {
545
564
  await next();
565
+ if (isXFrameOptionsExempt(c)) return;
546
566
  const v = settings(c).X_FRAME_OPTIONS ?? "DENY";
547
567
  if (v) setIfMissing(c, "X-Frame-Options", v.toUpperCase());
548
568
  }
@@ -655,6 +675,11 @@ function validateSettings(s) {
655
675
  if (!Array.isArray(s.INSTALLED_APPS)) throw new ImproperlyConfigured("INSTALLED_APPS must be an array.");
656
676
  if (!Array.isArray(s.ROOT_URLCONF))
657
677
  throw new ImproperlyConfigured("ROOT_URLCONF must be an array of url patterns.");
678
+ for (const key of ["HANDLER_404", "HANDLER_500"]) {
679
+ if (s[key] !== void 0 && s[key] !== null && typeof s[key] !== "function") {
680
+ throw new ImproperlyConfigured(`${key} must be a view function (c, exception) => Response.`);
681
+ }
682
+ }
658
683
  }
659
684
  function getSettings() {
660
685
  return getContext().settings;
@@ -1193,6 +1218,8 @@ var View = class {
1193
1218
  ];
1194
1219
  /** Mark every view produced by `asView()` as CSRF exempt. */
1195
1220
  static csrfExempt = false;
1221
+ /** Mark every view produced by `asView()` as exempt from `XFrameOptionsMiddleware`. */
1222
+ static xframeOptionsExempt = false;
1196
1223
  /** The Hono context of the current request. */
1197
1224
  c;
1198
1225
  /** The Hono request (Django's `self.request`). */
@@ -1219,6 +1246,7 @@ var View = class {
1219
1246
  view.viewInitkwargs = initkwargs;
1220
1247
  Object.defineProperty(view, "name", { value: cls.name });
1221
1248
  if (cls.csrfExempt) view[CSRF_EXEMPT_MARKER] = true;
1249
+ if (cls.xframeOptionsExempt) view[XFRAME_OPTIONS_EXEMPT_MARKER] = true;
1222
1250
  return view;
1223
1251
  }
1224
1252
  /** Initialize attributes shared by all handlers (Django's `setup()`). */
@@ -1404,6 +1432,7 @@ export {
1404
1432
  UrlResolver,
1405
1433
  ValidationError,
1406
1434
  View,
1435
+ XFRAME_OPTIONS_EXEMPT_MARKER,
1407
1436
  XFrameOptionsMiddleware,
1408
1437
  anonymousUser,
1409
1438
  appendSlashRedirect,
@@ -1432,6 +1461,7 @@ export {
1432
1461
  getCsrfToken,
1433
1462
  getEnv,
1434
1463
  getHost,
1464
+ getRemoteAddr,
1435
1465
  getResolver,
1436
1466
  getSettings,
1437
1467
  getUser,
@@ -1439,9 +1469,11 @@ export {
1439
1469
  hostMatches,
1440
1470
  include,
1441
1471
  isAllowedHost,
1472
+ isCloudflareRequest,
1442
1473
  isCsrfExempt,
1443
1474
  isSecure,
1444
1475
  isSettingsFactory,
1476
+ isXFrameOptionsExempt,
1445
1477
  json,
1446
1478
  kvCache,
1447
1479
  kwargs,
@@ -1472,6 +1504,7 @@ export {
1472
1504
  runWithContext,
1473
1505
  setCsrfCookieIfNeeded,
1474
1506
  setGlobalContext,
1507
+ setRemoteAddr,
1475
1508
  setUser,
1476
1509
  setting,
1477
1510
  settingsFor,
@@ -1483,6 +1516,7 @@ export {
1483
1516
  unmaskCsrfToken,
1484
1517
  urlpatterns,
1485
1518
  validateHost,
1486
- wantsJson
1519
+ wantsJson,
1520
+ xframeOptionsExempt
1487
1521
  };
1488
1522
  //# sourceMappingURL=index.js.map