@guren/server 2.1.1 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{DocsViewerServiceProvider-D7RGJPGM.js → DocsViewerServiceProvider-RUYDFBMW.js} +2 -2
- package/dist/McpServiceProvider-FRJ5O7LT.js +8 -0
- package/dist/auth/AuthManager.d.ts +30 -0
- package/dist/auth/AuthenticatableModel.d.ts +25 -0
- package/dist/auth/RequestAuthContext.d.ts +24 -0
- package/dist/auth/SessionGuard.d.ts +31 -0
- package/dist/auth/api-token.d.ts +299 -0
- package/dist/auth/email-verification.d.ts +203 -0
- package/dist/auth/index.d.ts +18 -110
- package/dist/auth/index.js +4 -1
- package/dist/auth/oauth/index.d.ts +239 -0
- package/dist/auth/password/DefaultHasher.d.ts +13 -0
- package/dist/auth/password/NodeHasher.d.ts +22 -0
- package/dist/auth/password/PasswordHasher.d.ts +5 -0
- package/dist/auth/password/ScryptHasher.d.ts +26 -0
- package/dist/auth/password-reset.d.ts +91 -0
- package/dist/auth/providers/ModelUserProvider.d.ts +36 -0
- package/dist/auth/providers/UserProvider.d.ts +9 -0
- package/dist/auth/types.d.ts +102 -0
- package/dist/auth/utils.d.ts +39 -0
- package/dist/{Gate-CynjZCtS.d.ts → authorization/Gate.d.ts} +30 -111
- package/dist/authorization/Policy.d.ts +77 -0
- package/dist/authorization/index.d.ts +5 -129
- package/dist/authorization/index.js +3 -1
- package/dist/authorization/middleware.d.ts +49 -0
- package/dist/authorization/types.d.ts +108 -0
- package/dist/broadcasting/BroadcastManager.d.ts +205 -0
- package/dist/broadcasting/channels/Channel.d.ts +28 -0
- package/dist/broadcasting/channels/PresenceChannel.d.ts +72 -0
- package/dist/broadcasting/channels/PrivateChannel.d.ts +32 -0
- package/dist/broadcasting/channels/index.d.ts +3 -0
- package/dist/broadcasting/drivers/MemoryDriver.d.ts +93 -0
- package/dist/broadcasting/drivers/RedisDriver.d.ts +112 -0
- package/dist/broadcasting/drivers/index.d.ts +2 -0
- package/dist/broadcasting/index.d.ts +6 -233
- package/dist/broadcasting/index.js +1 -1
- package/dist/broadcasting/typed.d.ts +23 -0
- package/dist/broadcasting/types.d.ts +155 -0
- package/dist/cache/CacheManager.d.ts +87 -0
- package/dist/cache/TaggedCache.d.ts +62 -0
- package/dist/cache/index.d.ts +6 -233
- package/dist/cache/index.js +1 -1
- package/dist/cache/stores/FileStore.d.ts +64 -0
- package/dist/cache/stores/MemoryStore.d.ts +52 -0
- package/dist/cache/stores/RedisStore.d.ts +53 -0
- package/dist/{CacheManager-BmDzUKrF.d.ts → cache/types.d.ts} +26 -99
- package/dist/chunk-3KV5X2FL.js +31 -0
- package/dist/{chunk-TVY72CLV.js → chunk-4VE3LYOM.js} +3 -2
- package/dist/{chunk-DSDX3ASM.js → chunk-5WL2FTC4.js} +67 -85
- package/dist/{chunk-5SZTEZ22.js → chunk-6IGN233M.js} +15 -8
- package/dist/{chunk-FZD2AKJI.js → chunk-7OB2YXRE.js} +56 -28
- package/dist/{chunk-WIXGT4TN.js → chunk-A5JJ7XTH.js} +8 -2
- package/dist/{chunk-CWI4AJ47.js → chunk-HPET6XY5.js} +13 -9
- package/dist/{chunk-A3ISJVEV.js → chunk-HR2KZ3WL.js} +23 -5
- package/dist/{chunk-BZMZEFRG.js → chunk-LHR6OHI7.js} +11 -0
- package/dist/{chunk-JBG4AR24.js → chunk-Q2P6YLRR.js} +8 -2
- package/dist/{chunk-J6ETA476.js → chunk-TVV5YNEC.js} +101 -9
- package/dist/console/Command.d.ts +179 -0
- package/dist/{ConsoleKernel-CJg975mp.d.ts → console/ConsoleKernel.d.ts} +4 -6
- package/dist/console/Input.d.ts +140 -0
- package/dist/console/Output.d.ts +161 -0
- package/dist/console/index.d.ts +5 -0
- package/dist/console/types.d.ts +106 -0
- package/dist/container/Container.d.ts +148 -0
- package/dist/container/ServiceProvider.d.ts +103 -0
- package/dist/container/bindings.d.ts +55 -0
- package/dist/container/defineModule.d.ts +88 -0
- package/dist/container/definePlugin.d.ts +62 -0
- package/dist/container/index.d.ts +8 -0
- package/dist/container/types.d.ts +73 -0
- package/dist/database/Factory.d.ts +82 -0
- package/dist/database/Seeder.d.ts +35 -0
- package/dist/database/SeederRunner.d.ts +41 -0
- package/dist/database/index.d.ts +4 -0
- package/dist/database/types.d.ts +49 -0
- package/dist/discovery/AutoDiscovery.d.ts +113 -0
- package/dist/discovery/index.d.ts +2 -0
- package/dist/docs-viewer/DocsViewerServiceProvider.d.ts +12 -0
- package/dist/docs-viewer/endpoint.d.ts +29 -0
- package/dist/encryption/Encrypter.d.ts +96 -0
- package/dist/encryption/Hash.d.ts +69 -0
- package/dist/encryption/MessageSigner.d.ts +21 -0
- package/dist/encryption/Random.d.ts +119 -0
- package/dist/encryption/app-key.d.ts +12 -0
- package/dist/encryption/index.d.ts +10 -222
- package/dist/encryption/signed-url.d.ts +9 -0
- package/dist/encryption/types.d.ts +103 -0
- package/dist/errors/ExceptionHandler.d.ts +118 -0
- package/dist/errors/HttpException.d.ts +106 -0
- package/dist/errors/debug-page.d.ts +22 -0
- package/dist/errors/error-page.d.ts +1 -0
- package/dist/errors/exceptions/AuthenticationException.d.ts +32 -0
- package/dist/errors/exceptions/AuthorizationException.d.ts +32 -0
- package/dist/errors/exceptions/MethodNotAllowedException.d.ts +31 -0
- package/dist/errors/exceptions/NotFoundHttpException.d.ts +36 -0
- package/dist/errors/exceptions/ValidationException.d.ts +60 -0
- package/dist/errors/exceptions/index.d.ts +5 -0
- package/dist/errors/index.d.ts +5 -0
- package/dist/errors/types.d.ts +43 -0
- package/dist/events/Event.d.ts +33 -0
- package/dist/{EventManager-CmIoLt7r.d.ts → events/EventManager.d.ts} +4 -86
- package/dist/events/Listener.d.ts +79 -0
- package/dist/events/builtin.d.ts +73 -0
- package/dist/events/index.d.ts +6 -155
- package/dist/events/types.d.ts +48 -0
- package/dist/facades/index.d.ts +31 -0
- package/dist/health/HealthCheck.d.ts +34 -0
- package/dist/health/HealthManager.d.ts +53 -0
- package/dist/health/checks/CacheCheck.d.ts +35 -0
- package/dist/health/checks/CustomCheck.d.ts +23 -0
- package/dist/health/checks/DatabaseCheck.d.ts +33 -0
- package/dist/health/checks/MemoryCheck.d.ts +32 -0
- package/dist/health/checks/RedisCheck.d.ts +27 -0
- package/dist/health/checks/StorageCheck.d.ts +35 -0
- package/dist/health/checks/index.d.ts +12 -0
- package/dist/health/index.d.ts +5 -185
- package/dist/health/types.d.ts +52 -0
- package/dist/hot-reload/hot-disposables.d.ts +96 -0
- package/dist/hot-reload/testing.d.ts +14 -0
- package/dist/http/Application.d.ts +199 -0
- package/dist/http/FormRequest.d.ts +73 -0
- package/dist/http/dev-assets.d.ts +62 -0
- package/dist/http/dev-banner.d.ts +7 -0
- package/dist/http/inertia-assets.d.ts +31 -0
- package/dist/http/middleware/auth.d.ts +13 -0
- package/dist/http/middleware/capabilities.d.ts +22 -0
- package/dist/http/middleware/cors.d.ts +40 -0
- package/dist/http/middleware/csp.d.ts +59 -0
- package/dist/http/middleware/csrf.d.ts +121 -0
- package/dist/http/middleware/detect-locale.d.ts +65 -0
- package/dist/http/middleware/force-https.d.ts +34 -0
- package/dist/http/middleware/host-authorization.d.ts +24 -0
- package/dist/http/middleware/index.d.ts +19 -0
- package/dist/http/middleware/loopback-guard.d.ts +51 -0
- package/dist/{rate-limit-D9J2b4S1.d.ts → http/middleware/rate-limit.d.ts} +22 -50
- package/dist/http/middleware/redirect-safety.d.ts +29 -0
- package/dist/http/middleware/request-id.d.ts +19 -0
- package/dist/http/middleware/request-logging.d.ts +16 -0
- package/dist/http/middleware/response-headers.d.ts +18 -0
- package/dist/http/middleware/security-headers.d.ts +49 -0
- package/dist/http/middleware/session.d.ts +93 -0
- package/dist/http/middleware/validation.d.ts +94 -0
- package/dist/http/public-assets.d.ts +15 -0
- package/dist/http/request.d.ts +24 -0
- package/dist/http/resources/CursorPaginator.d.ts +106 -0
- package/dist/http/resources/Paginator.d.ts +130 -0
- package/dist/http/resources/Resource.d.ts +67 -0
- package/dist/http/resources/ResourceCollection.d.ts +60 -0
- package/dist/http/resources/index.d.ts +6 -0
- package/dist/http/resources/types.d.ts +91 -0
- package/dist/http/validation/Validator.d.ts +128 -0
- package/dist/http/validation/index.d.ts +3 -0
- package/dist/http/validation/rules.d.ts +196 -0
- package/dist/http/validation/types.d.ts +96 -0
- package/dist/http/vite-dev-server.d.ts +27 -0
- package/dist/i18n/I18nManager.d.ts +114 -0
- package/dist/i18n/Translator.d.ts +80 -0
- package/dist/i18n/index.d.ts +6 -101
- package/dist/i18n/index.js +5 -3
- package/dist/i18n/loaders/JsonLoader.d.ts +47 -0
- package/dist/i18n/loaders/MemoryLoader.d.ts +37 -0
- package/dist/i18n/pluralization.d.ts +19 -0
- package/dist/i18n/types.d.ts +106 -0
- package/dist/index.d.ts +69 -2605
- package/dist/index.js +405 -180
- package/dist/lambda/index.d.ts +17 -37
- package/dist/logging/LogManager.d.ts +83 -0
- package/dist/logging/Logger.d.ts +76 -0
- package/dist/logging/channels/ConsoleChannel.d.ts +11 -0
- package/dist/logging/channels/DailyFileChannel.d.ts +20 -0
- package/dist/logging/channels/FileChannel.d.ts +15 -0
- package/dist/logging/index.d.ts +8 -50
- package/dist/logging/types.d.ts +96 -0
- package/dist/mail/Mail.d.ts +138 -0
- package/dist/mail/MailManager.d.ts +79 -0
- package/dist/mail/address.d.ts +8 -0
- package/dist/mail/index.d.ts +7 -316
- package/dist/mail/transports/LogTransport.d.ts +19 -0
- package/dist/mail/transports/MemoryTransport.d.ts +84 -0
- package/dist/mail/transports/ResendTransport.d.ts +32 -0
- package/dist/mail/transports/SmtpTransport.d.ts +40 -0
- package/dist/{MailManager-DpMvYiP9.d.ts → mail/types.d.ts} +11 -92
- package/dist/mcp/McpServiceProvider.d.ts +17 -0
- package/dist/mcp/create-mcp-server.d.ts +152 -0
- package/dist/mcp/endpoint.d.ts +47 -0
- package/dist/mcp/index.d.ts +3 -185
- package/dist/mcp/index.js +3 -3
- package/dist/mvc/Controller.d.ts +326 -0
- package/dist/mvc/Router.d.ts +239 -0
- package/dist/mvc/ViewEngine.d.ts +11 -0
- package/dist/mvc/inertia/InertiaEngine.d.ts +114 -0
- package/dist/mvc/inertia/shared.d.ts +90 -0
- package/dist/mvc/mount-route.d.ts +10 -0
- package/dist/notifications/Notification.d.ts +99 -0
- package/dist/notifications/NotificationManager.d.ts +150 -0
- package/dist/notifications/channels/DatabaseChannel.d.ts +55 -0
- package/dist/notifications/channels/MailChannel.d.ts +45 -0
- package/dist/notifications/channels/MemoryChannel.d.ts +85 -0
- package/dist/notifications/channels/SlackChannel.d.ts +73 -0
- package/dist/notifications/channels/index.d.ts +4 -0
- package/dist/notifications/index.d.ts +6 -322
- package/dist/notifications/notifiable-type.d.ts +10 -0
- package/dist/notifications/registry.d.ts +39 -0
- package/dist/notifications/types.d.ts +162 -0
- package/dist/providers/AuthServiceProvider.d.ts +7 -0
- package/dist/providers/AuthorizationServiceProvider.d.ts +9 -0
- package/dist/providers/BroadcastServiceProvider.d.ts +7 -0
- package/dist/providers/CacheServiceProvider.d.ts +7 -0
- package/dist/providers/EncryptionServiceProvider.d.ts +7 -0
- package/dist/providers/ErrorServiceProvider.d.ts +9 -0
- package/dist/providers/EventServiceProvider.d.ts +7 -0
- package/dist/providers/HealthServiceProvider.d.ts +7 -0
- package/dist/providers/I18nServiceProvider.d.ts +27 -0
- package/dist/providers/InertiaServiceProvider.d.ts +20 -0
- package/dist/providers/LogServiceProvider.d.ts +7 -0
- package/dist/providers/MailServiceProvider.d.ts +7 -0
- package/dist/providers/NotificationServiceProvider.d.ts +8 -0
- package/dist/providers/OAuthServiceProvider.d.ts +7 -0
- package/dist/providers/QueueServiceProvider.d.ts +7 -0
- package/dist/providers/SchedulingServiceProvider.d.ts +7 -0
- package/dist/providers/StorageServiceProvider.d.ts +7 -0
- package/dist/providers/index.d.ts +17 -0
- package/dist/queue/FailedJobReporter.d.ts +40 -0
- package/dist/queue/Job.d.ts +140 -0
- package/dist/queue/QueueManager.d.ts +79 -0
- package/dist/queue/Worker.d.ts +99 -0
- package/dist/queue/drivers/MemoryDriver.d.ts +60 -0
- package/dist/queue/drivers/RedisDriver.d.ts +96 -0
- package/dist/queue/drivers/SqsDriver.d.ts +108 -0
- package/dist/queue/drivers/SyncDriver.d.ts +28 -0
- package/dist/queue/index.d.ts +9 -453
- package/dist/queue/types.d.ts +171 -0
- package/dist/redis/RedisApiTokenStore.d.ts +78 -0
- package/dist/redis/RedisEmailVerificationStore.d.ts +54 -0
- package/dist/redis/RedisOAuthStateStore.d.ts +26 -0
- package/dist/redis/RedisPasswordResetStore.d.ts +57 -0
- package/dist/redis/RedisRateLimitStore.d.ts +77 -0
- package/dist/redis/RedisSessionStore.d.ts +61 -0
- package/dist/redis/client.d.ts +41 -0
- package/dist/redis/index.d.ts +14 -356
- package/dist/redis/index.js +45 -9
- package/dist/redis/redis-values.d.ts +17 -0
- package/dist/redis/scan-keys.d.ts +6 -0
- package/dist/runtime/index.d.ts +8 -95
- package/dist/runtime/index.js +101 -68
- package/dist/scheduling/CronParser.d.ts +37 -0
- package/dist/scheduling/Schedule.d.ts +229 -0
- package/dist/scheduling/ScheduledTask.d.ts +47 -0
- package/dist/scheduling/Scheduler.d.ts +99 -0
- package/dist/scheduling/index.d.ts +5 -41
- package/dist/scheduling/types.d.ts +97 -0
- package/dist/storage/StorageManager.d.ts +65 -0
- package/dist/storage/drivers/LocalDriver.d.ts +55 -0
- package/dist/storage/drivers/MemoryDriver.d.ts +66 -0
- package/dist/storage/drivers/S3Driver.d.ts +72 -0
- package/dist/storage/index.d.ts +5 -197
- package/dist/{StorageManager-oZTHqaza.d.ts → storage/types.d.ts} +10 -77
- package/dist/support/contained-path.d.ts +26 -0
- package/dist/support/error-polyfill.d.ts +9 -0
- package/dist/support/expiry.d.ts +47 -0
- package/dist/support/expiry.js +12 -0
- package/dist/support/import-map.d.ts +13 -0
- package/dist/support/redirect-target.d.ts +11 -0
- package/dist/support/stack-frames.d.ts +56 -0
- package/dist/support/trim-slashes.d.ts +11 -0
- package/dist/vite/index.d.ts +2 -35
- package/dist/vite/index.js +0 -3
- package/dist/vite/plugin.d.ts +34 -0
- package/package.json +7 -3
- package/dist/AuthManager-DBP4KYsx.d.ts +0 -79
- package/dist/BroadcastManager-D8KoJxiV.d.ts +0 -492
- package/dist/HealthManager-DUyMIzsZ.d.ts +0 -141
- package/dist/I18nManager-BiSoczfV.d.ts +0 -275
- package/dist/LogManager-7mxnkaPM.d.ts +0 -256
- package/dist/McpServiceProvider-7BB5FPF3.js +0 -8
- package/dist/Scheduler-pZiT8i57.d.ts +0 -471
- package/dist/api-token-D24VPr_E.d.ts +0 -663
- package/dist/app-key-CsBfRC_Q.d.ts +0 -214
- package/dist/email-verification-Dx426KLn.d.ts +0 -336
- package/dist/index-9_Jzj5jo.d.ts +0 -7
- package/dist/validation-yAL53e1S.d.ts +0 -2610
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
2
|
+
import { type I18nManager, type Translator } from '../../i18n/index.js';
|
|
3
|
+
/** Context key for the resolved request locale (read by Inertia for `<html lang>`). */
|
|
4
|
+
export declare const LOCALE_CONTEXT_KEY = "locale";
|
|
5
|
+
/** Request-scoped translator surface bound by {@link detectLocaleMiddleware}. */
|
|
6
|
+
export type TranslatorBinding = {
|
|
7
|
+
t: Translator['t'];
|
|
8
|
+
tc: Translator['tc'];
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Read the request locale resolved by {@link detectLocaleMiddleware} (or any
|
|
12
|
+
* middleware that sets the `locale` context variable).
|
|
13
|
+
*/
|
|
14
|
+
export declare function getRequestLocale(c: Context): string | undefined;
|
|
15
|
+
/**
|
|
16
|
+
* Read the request-scoped `t`/`tc` translator bound by
|
|
17
|
+
* {@link detectLocaleMiddleware}, when present.
|
|
18
|
+
*/
|
|
19
|
+
export declare function getRequestTranslator(c: Context): TranslatorBinding | undefined;
|
|
20
|
+
export type LocaleSource = 'query' | 'cookie' | 'header';
|
|
21
|
+
/** Context variables set by {@link detectLocaleMiddleware}, for typing Hono apps. */
|
|
22
|
+
export type DetectLocaleVariables = {
|
|
23
|
+
locale: string;
|
|
24
|
+
t?: Translator['t'];
|
|
25
|
+
tc?: Translator['tc'];
|
|
26
|
+
};
|
|
27
|
+
export interface DetectLocaleOptions {
|
|
28
|
+
/** Locales the app supports. Detection only ever resolves to one of these. */
|
|
29
|
+
supported: readonly string[];
|
|
30
|
+
/** Locale used when no source matches (defaults to the first supported locale). */
|
|
31
|
+
fallback?: string;
|
|
32
|
+
/** Detection order (defaults to `['query', 'cookie', 'header']`). */
|
|
33
|
+
sources?: readonly LocaleSource[];
|
|
34
|
+
/** Query parameter to read (defaults to `locale`). */
|
|
35
|
+
queryParam?: string;
|
|
36
|
+
/** Cookie to read (defaults to `locale`). */
|
|
37
|
+
cookieName?: string;
|
|
38
|
+
/**
|
|
39
|
+
* i18n manager used to bind request-scoped `t`/`tc` translator helpers.
|
|
40
|
+
* Defaults to the global manager when one was registered via `setI18n()`;
|
|
41
|
+
* pass a manager explicitly (e.g. `app.container.make('i18n')`), or `false`
|
|
42
|
+
* to skip the translator binding entirely.
|
|
43
|
+
*/
|
|
44
|
+
i18n?: I18nManager | false;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Middleware that resolves the request locale from the query string, a cookie,
|
|
48
|
+
* or the `Accept-Language` header — in that order by default — restricted to
|
|
49
|
+
* the `supported` allowlist.
|
|
50
|
+
*
|
|
51
|
+
* The result is stored as the `locale` context variable, which Inertia
|
|
52
|
+
* responses pick up for the root `<html lang>` attribute. When an i18n manager
|
|
53
|
+
* is available (see the `i18n` option), request-scoped `t`/`tc` translator
|
|
54
|
+
* helpers are attached as well.
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* ```ts
|
|
58
|
+
* import { detectLocaleMiddleware } from '@guren/core'
|
|
59
|
+
*
|
|
60
|
+
* app.use('*', detectLocaleMiddleware({ supported: ['en', 'ja'] }))
|
|
61
|
+
* ```
|
|
62
|
+
*/
|
|
63
|
+
export declare function detectLocaleMiddleware(options: DetectLocaleOptions): import("hono").MiddlewareHandler<{
|
|
64
|
+
Variables: DetectLocaleVariables;
|
|
65
|
+
}, string, {}, Response>;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { MiddlewareHandler } from 'hono';
|
|
2
|
+
export interface ForceHttpsOptions {
|
|
3
|
+
/**
|
|
4
|
+
* HSTS max-age in seconds. Default: 31536000 (1 year).
|
|
5
|
+
*/
|
|
6
|
+
hstsMaxAge?: number;
|
|
7
|
+
/**
|
|
8
|
+
* Include subdomains in HSTS. Default: true.
|
|
9
|
+
*/
|
|
10
|
+
hstsIncludeSubDomains?: boolean;
|
|
11
|
+
/**
|
|
12
|
+
* Enable HSTS preload. Default: false.
|
|
13
|
+
*/
|
|
14
|
+
hstsPreload?: boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Paths to exclude from HTTPS redirect (e.g., health checks).
|
|
17
|
+
*/
|
|
18
|
+
exclude?: string[];
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Middleware that redirects HTTP requests to HTTPS and sets the
|
|
22
|
+
* Strict-Transport-Security header. Equivalent to Rails' `force_ssl`.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```ts
|
|
26
|
+
* import { createForceHttpsMiddleware } from '@guren/core'
|
|
27
|
+
*
|
|
28
|
+
* // In production only
|
|
29
|
+
* if (process.env.NODE_ENV === 'production') {
|
|
30
|
+
* app.use('*', createForceHttpsMiddleware())
|
|
31
|
+
* }
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
export declare function createForceHttpsMiddleware(options?: ForceHttpsOptions): MiddlewareHandler;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { Context, MiddlewareHandler } from 'hono';
|
|
2
|
+
export interface HostAuthorizationOptions {
|
|
3
|
+
/** Allowed hosts. Supports exact matches and wildcard subdomains (e.g., '*.example.com'). */
|
|
4
|
+
allowedHosts: string[];
|
|
5
|
+
/** Paths to exclude from host checking (e.g., ['/healthcheck', '/up']). */
|
|
6
|
+
exclude?: string[];
|
|
7
|
+
/** Custom response when host is not authorized. Default: 403 Forbidden. */
|
|
8
|
+
onError?: (ctx: Context) => Response | Promise<Response>;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Middleware that validates the Host header against an allowed list.
|
|
12
|
+
* Protects against DNS rebinding and host header attacks.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* import { createHostAuthorizationMiddleware } from '@guren/core'
|
|
17
|
+
*
|
|
18
|
+
* app.use('*', createHostAuthorizationMiddleware({
|
|
19
|
+
* allowedHosts: ['example.com', '*.example.com', 'localhost:3000'],
|
|
20
|
+
* exclude: ['/healthcheck'],
|
|
21
|
+
* }))
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export declare function createHostAuthorizationMiddleware(options: HostAuthorizationOptions): MiddlewareHandler;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { MiddlewareHandler } from 'hono';
|
|
2
|
+
export type Middleware = MiddlewareHandler;
|
|
3
|
+
export declare function defineMiddleware(handler: MiddlewareHandler): MiddlewareHandler;
|
|
4
|
+
export declare function jsonResponse(data: unknown, status?: number): Response;
|
|
5
|
+
export { createSessionMiddleware, MemorySessionStore, getSessionFromContext } from './session.js';
|
|
6
|
+
export type { Session, SessionData, SessionStore } from './session.js';
|
|
7
|
+
export { requireAuthenticated, requireGuest, attachAuthContext, type AuthContext, type RequireAuthOptions, } from './auth.js';
|
|
8
|
+
export { createCsrfMiddleware, getCsrfToken, csrfField, verifyCsrfToken, CSRF_TOKEN_KEY, CSRF_HEADER_NAME, CSRF_FORM_FIELD, XSRF_HEADER_NAME, XSRF_COOKIE_NAME, type CsrfOptions, } from './csrf.js';
|
|
9
|
+
export { validateRequest, validateRequestWith, getValidatedData, validate, validateSafe, VALIDATED_DATA_KEY, type ValidationSchema, type ValidateRequestOptions, } from './validation.js';
|
|
10
|
+
export { createRateLimitMiddleware, getRateLimitInfo, resetRateLimit, MemoryRateLimitStore, SlidingWindowRateLimitStore, type RateLimitOptions, type RateLimitStore, type RateLimitEntry, type RateLimitInfo, } from './rate-limit.js';
|
|
11
|
+
export { createSecurityHeaders, type SecurityHeadersOptions, type HstsOptions, } from './security-headers.js';
|
|
12
|
+
export { createCspMiddleware, getCspNonce, CSP_NONCE_KEY, type CspOptions, type CspDirectives, } from './csp.js';
|
|
13
|
+
export { createHostAuthorizationMiddleware, type HostAuthorizationOptions, } from './host-authorization.js';
|
|
14
|
+
export { createCorsMiddleware, type CorsOptions, } from './cors.js';
|
|
15
|
+
export { createRedirectSafetyMiddleware, isSafeRedirectUrl, type RedirectSafetyOptions, } from './redirect-safety.js';
|
|
16
|
+
export { createForceHttpsMiddleware, type ForceHttpsOptions, } from './force-https.js';
|
|
17
|
+
export { requestIdMiddleware } from './request-id.js';
|
|
18
|
+
export { requestLoggingMiddleware } from './request-logging.js';
|
|
19
|
+
export { detectLocaleMiddleware, LOCALE_CONTEXT_KEY, getRequestLocale, getRequestTranslator, type TranslatorBinding, type DetectLocaleOptions, type DetectLocaleVariables, type LocaleSource, } from './detect-locale.js';
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loopback-only access guard shared by the dev-only framework endpoints
|
|
3
|
+
* (`/_guren/mcp`, `/_guren/docs`).
|
|
4
|
+
*
|
|
5
|
+
* Two classes of caller have to be stopped (see
|
|
6
|
+
* `.claude/rules/common-pitfalls.md`): browser pages, rejected unless
|
|
7
|
+
* their `Origin` is loopback (which also defeats DNS rebinding), and
|
|
8
|
+
* non-browser clients, rejected unless the socket peer is loopback —
|
|
9
|
+
* templates bind `0.0.0.0` and `Host` is trivially forged, so host
|
|
10
|
+
* authorization does not help, and a client that sends no `Origin` is
|
|
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.
|
|
20
|
+
*/
|
|
21
|
+
import type { MiddlewareHandler } from 'hono';
|
|
22
|
+
/**
|
|
23
|
+
* Whether an `Origin` header value belongs to the developer's own machine.
|
|
24
|
+
*
|
|
25
|
+
* Non-browser clients send no `Origin` at all; a value only appears when a
|
|
26
|
+
* web page made the request. Restricting those to loopback blocks both
|
|
27
|
+
* ordinary cross-site requests and DNS rebinding, where an attacker's
|
|
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.
|
|
33
|
+
*/
|
|
34
|
+
export declare function isLoopbackOrigin(origin: string): boolean;
|
|
35
|
+
/**
|
|
36
|
+
* Whether a socket peer address belongs to this machine.
|
|
37
|
+
*
|
|
38
|
+
* Bun reports IPv4-mapped peers as `::ffff:127.0.0.1`, so unwrap that prefix
|
|
39
|
+
* before matching.
|
|
40
|
+
*/
|
|
41
|
+
export declare function isLoopbackAddress(address: string): boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Restricts an endpoint to the developer's own machine. `resource` names
|
|
44
|
+
* the endpoint in the 403 body (e.g. "the MCP endpoint").
|
|
45
|
+
*
|
|
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.
|
|
50
|
+
*/
|
|
51
|
+
export declare function createLoopbackGuard(resource: string): MiddlewareHandler;
|
|
@@ -1,45 +1,8 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { Context, MiddlewareHandler } from 'hono';
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Options for creating a Redis client.
|
|
6
|
-
*/
|
|
7
|
-
interface RedisClientOptions extends RedisOptions {
|
|
8
|
-
/**
|
|
9
|
-
* Redis connection URL (e.g., 'redis://localhost:6379').
|
|
10
|
-
* If provided, overrides host/port/password.
|
|
11
|
-
*/
|
|
12
|
-
url?: string;
|
|
13
|
-
/**
|
|
14
|
-
* Key prefix for all operations.
|
|
15
|
-
* @default ''
|
|
16
|
-
*/
|
|
17
|
-
keyPrefix?: string;
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* Create a Redis client with the given options.
|
|
21
|
-
*
|
|
22
|
-
* @example
|
|
23
|
-
* ```ts
|
|
24
|
-
* // Using URL
|
|
25
|
-
* const redis = createRedisClient({ url: 'redis://localhost:6379' })
|
|
26
|
-
*
|
|
27
|
-
* // Using host/port
|
|
28
|
-
* const redis = createRedisClient({ host: 'localhost', port: 6379 })
|
|
29
|
-
*
|
|
30
|
-
* // With key prefix
|
|
31
|
-
* const redis = createRedisClient({
|
|
32
|
-
* url: process.env.REDIS_URL,
|
|
33
|
-
* keyPrefix: 'myapp:',
|
|
34
|
-
* })
|
|
35
|
-
* ```
|
|
36
|
-
*/
|
|
37
|
-
declare function createRedisClient(options?: RedisClientOptions): Redis;
|
|
38
|
-
|
|
1
|
+
import type { MiddlewareHandler, Context } from 'hono';
|
|
39
2
|
/**
|
|
40
3
|
* Rate limit entry stored in the backing store.
|
|
41
4
|
*/
|
|
42
|
-
interface RateLimitEntry {
|
|
5
|
+
export interface RateLimitEntry {
|
|
43
6
|
count: number;
|
|
44
7
|
resetAt: number;
|
|
45
8
|
}
|
|
@@ -47,7 +10,7 @@ interface RateLimitEntry {
|
|
|
47
10
|
* Store interface for rate limit data.
|
|
48
11
|
* Implement this for Redis or database-backed storage.
|
|
49
12
|
*/
|
|
50
|
-
interface RateLimitStore {
|
|
13
|
+
export interface RateLimitStore {
|
|
51
14
|
/**
|
|
52
15
|
* Get the current rate limit entry for a key.
|
|
53
16
|
*/
|
|
@@ -66,6 +29,7 @@ interface RateLimitStore {
|
|
|
66
29
|
* Base class for in-memory rate limit stores with automatic cleanup.
|
|
67
30
|
*/
|
|
68
31
|
declare abstract class BaseMemoryStore implements RateLimitStore {
|
|
32
|
+
protected readonly now: () => number;
|
|
69
33
|
protected cleanupInterval?: ReturnType<typeof setInterval>;
|
|
70
34
|
/**
|
|
71
35
|
* This store's claim on its hot-reload slot, if it holds one.
|
|
@@ -74,7 +38,7 @@ declare abstract class BaseMemoryStore implements RateLimitStore {
|
|
|
74
38
|
* both duplicates work and keeps the process alive on its own.
|
|
75
39
|
*/
|
|
76
40
|
private readonly hotReloadClaim;
|
|
77
|
-
constructor(cleanupIntervalMs?: number);
|
|
41
|
+
constructor(cleanupIntervalMs?: number, now?: () => number);
|
|
78
42
|
abstract get(key: string): Promise<RateLimitEntry | null>;
|
|
79
43
|
abstract increment(key: string, windowMs: number): Promise<RateLimitEntry>;
|
|
80
44
|
abstract reset(key: string): Promise<void>;
|
|
@@ -87,7 +51,7 @@ declare abstract class BaseMemoryStore implements RateLimitStore {
|
|
|
87
51
|
* In-memory rate limit store.
|
|
88
52
|
* Suitable for single-process development, not for production clusters.
|
|
89
53
|
*/
|
|
90
|
-
declare class MemoryRateLimitStore extends BaseMemoryStore {
|
|
54
|
+
export declare class MemoryRateLimitStore extends BaseMemoryStore {
|
|
91
55
|
private entries;
|
|
92
56
|
get(key: string): Promise<RateLimitEntry | null>;
|
|
93
57
|
increment(key: string, windowMs: number): Promise<RateLimitEntry>;
|
|
@@ -99,7 +63,7 @@ declare class MemoryRateLimitStore extends BaseMemoryStore {
|
|
|
99
63
|
/**
|
|
100
64
|
* Configuration options for rate limiting.
|
|
101
65
|
*/
|
|
102
|
-
interface RateLimitOptions {
|
|
66
|
+
export interface RateLimitOptions {
|
|
103
67
|
/**
|
|
104
68
|
* Maximum number of requests allowed in the time window.
|
|
105
69
|
* @default 100
|
|
@@ -148,6 +112,15 @@ interface RateLimitOptions {
|
|
|
148
112
|
* @default 'rl:'
|
|
149
113
|
*/
|
|
150
114
|
keyPrefix?: string;
|
|
115
|
+
/**
|
|
116
|
+
* Clock returning the current time in epoch milliseconds. Injectable so
|
|
117
|
+
* tests can advance time synchronously instead of sleeping. Drives the
|
|
118
|
+
* middleware's own calculations (Retry-After) and, when no `store` is
|
|
119
|
+
* supplied, the store created for this middleware. A custom store keeps
|
|
120
|
+
* its own clock — construct it with the same `now` to stay coherent.
|
|
121
|
+
* @default () => Date.now()
|
|
122
|
+
*/
|
|
123
|
+
now?: () => number;
|
|
151
124
|
/**
|
|
152
125
|
* Trust reverse-proxy headers for client IP resolution, checked in order:
|
|
153
126
|
* `CF-Connecting-IP`, `True-Client-IP`, `X-Real-IP`, then the first entry
|
|
@@ -187,11 +160,11 @@ interface RateLimitOptions {
|
|
|
187
160
|
* }))
|
|
188
161
|
* ```
|
|
189
162
|
*/
|
|
190
|
-
declare function createRateLimitMiddleware(options?: RateLimitOptions): MiddlewareHandler;
|
|
163
|
+
export declare function createRateLimitMiddleware(options?: RateLimitOptions): MiddlewareHandler;
|
|
191
164
|
/**
|
|
192
165
|
* Rate limit result information.
|
|
193
166
|
*/
|
|
194
|
-
interface RateLimitInfo {
|
|
167
|
+
export interface RateLimitInfo {
|
|
195
168
|
limit: number;
|
|
196
169
|
remaining: number;
|
|
197
170
|
resetAt: Date;
|
|
@@ -206,7 +179,7 @@ interface RateLimitInfo {
|
|
|
206
179
|
* console.log(`${info.remaining} requests remaining`)
|
|
207
180
|
* ```
|
|
208
181
|
*/
|
|
209
|
-
declare function getRateLimitInfo(key: string, store: RateLimitStore, options?: {
|
|
182
|
+
export declare function getRateLimitInfo(key: string, store: RateLimitStore, options?: {
|
|
210
183
|
limit: number;
|
|
211
184
|
keyPrefix?: string;
|
|
212
185
|
}): Promise<RateLimitInfo>;
|
|
@@ -219,14 +192,14 @@ declare function getRateLimitInfo(key: string, store: RateLimitStore, options?:
|
|
|
219
192
|
* await resetRateLimit(clientIp, store)
|
|
220
193
|
* ```
|
|
221
194
|
*/
|
|
222
|
-
declare function resetRateLimit(key: string, store: RateLimitStore, options?: {
|
|
195
|
+
export declare function resetRateLimit(key: string, store: RateLimitStore, options?: {
|
|
223
196
|
keyPrefix?: string;
|
|
224
197
|
}): Promise<void>;
|
|
225
198
|
/**
|
|
226
199
|
* Sliding window rate limit store.
|
|
227
200
|
* More accurate than fixed window but uses more memory.
|
|
228
201
|
*/
|
|
229
|
-
declare class SlidingWindowRateLimitStore extends BaseMemoryStore {
|
|
202
|
+
export declare class SlidingWindowRateLimitStore extends BaseMemoryStore {
|
|
230
203
|
private requests;
|
|
231
204
|
get(key: string): Promise<RateLimitEntry | null>;
|
|
232
205
|
increment(key: string, windowMs: number): Promise<RateLimitEntry>;
|
|
@@ -235,5 +208,4 @@ declare class SlidingWindowRateLimitStore extends BaseMemoryStore {
|
|
|
235
208
|
clear(): void;
|
|
236
209
|
get size(): number;
|
|
237
210
|
}
|
|
238
|
-
|
|
239
|
-
export { MemoryRateLimitStore as M, type RateLimitStore as R, SlidingWindowRateLimitStore as S, type RateLimitEntry as a, type RedisClientOptions as b, createRedisClient as c, type RateLimitInfo as d, type RateLimitOptions as e, createRateLimitMiddleware as f, getRateLimitInfo as g, resetRateLimit as r };
|
|
211
|
+
export {};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { MiddlewareHandler } from 'hono';
|
|
2
|
+
export interface RedirectSafetyOptions {
|
|
3
|
+
/** Additional external hosts allowed as redirect targets. */
|
|
4
|
+
allowedHosts?: string[];
|
|
5
|
+
/** Fallback URL when an unsafe redirect is blocked. Default: '/' */
|
|
6
|
+
fallbackUrl?: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Middleware that prevents open redirect attacks by validating
|
|
10
|
+
* redirect destinations in 3xx responses.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { createRedirectSafetyMiddleware } from '@guren/core'
|
|
15
|
+
*
|
|
16
|
+
* app.use('*', createRedirectSafetyMiddleware({
|
|
17
|
+
* allowedHosts: ['accounts.google.com'],
|
|
18
|
+
* }))
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
export declare function createRedirectSafetyMiddleware(options?: RedirectSafetyOptions): MiddlewareHandler;
|
|
22
|
+
/**
|
|
23
|
+
* Check whether a redirect URL is safe (same-origin or in the allowed list).
|
|
24
|
+
*
|
|
25
|
+
* @param url - The redirect target URL
|
|
26
|
+
* @param requestUrl - The current request URL (used to determine the origin)
|
|
27
|
+
* @param allowedHosts - Additional allowed external hosts
|
|
28
|
+
*/
|
|
29
|
+
export declare function isSafeRedirectUrl(url: string, requestUrl: string, allowedHosts?: string[]): boolean;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Middleware that generates a unique request ID for each request.
|
|
3
|
+
* Reads from the `X-Request-ID` header if present, otherwise generates one
|
|
4
|
+
* using `crypto.randomUUID()`.
|
|
5
|
+
* Attaches the ID to the Hono context (`c.get('requestId')`) and sets it
|
|
6
|
+
* on the response header.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { requestIdMiddleware } from '@guren/core'
|
|
11
|
+
*
|
|
12
|
+
* app.use('*', requestIdMiddleware())
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
export declare function requestIdMiddleware(): import("hono").MiddlewareHandler<{
|
|
16
|
+
Variables: {
|
|
17
|
+
requestId: string;
|
|
18
|
+
};
|
|
19
|
+
}, string, {}, Response>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Middleware that logs HTTP requests with method, path, status, and duration.
|
|
3
|
+
* Uses structured JSON format suitable for production monitoring and log collectors.
|
|
4
|
+
*
|
|
5
|
+
* Pairs well with {@link requestIdMiddleware} — if a `requestId` is set on the
|
|
6
|
+
* context, it will be included in the log entry.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { requestIdMiddleware, requestLoggingMiddleware } from '@guren/core'
|
|
11
|
+
*
|
|
12
|
+
* app.use('*', requestIdMiddleware())
|
|
13
|
+
* app.use('*', requestLoggingMiddleware())
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
export declare function requestLoggingMiddleware(): import("hono").MiddlewareHandler<any, string, {}, Response>;
|
|
@@ -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,49 @@
|
|
|
1
|
+
import type { MiddlewareHandler } from 'hono';
|
|
2
|
+
export interface HstsOptions {
|
|
3
|
+
/** Max age in seconds. */
|
|
4
|
+
maxAge: number;
|
|
5
|
+
/** Include subdomains. Default: false */
|
|
6
|
+
includeSubDomains?: boolean;
|
|
7
|
+
/** Enable HSTS preload. Default: false */
|
|
8
|
+
preload?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface SecurityHeadersOptions {
|
|
11
|
+
/** X-Frame-Options header. Set to false to disable. Default: 'SAMEORIGIN' */
|
|
12
|
+
frameOptions?: string | false;
|
|
13
|
+
/** X-Content-Type-Options header. Set to false to disable. Default: 'nosniff' */
|
|
14
|
+
contentTypeOptions?: string | false;
|
|
15
|
+
/** X-XSS-Protection header. Set to false to disable. Default: '0' */
|
|
16
|
+
xssProtection?: string | false;
|
|
17
|
+
/** Referrer-Policy header. Set to false to disable. Default: 'strict-origin-when-cross-origin' */
|
|
18
|
+
referrerPolicy?: string | false;
|
|
19
|
+
/** X-Permitted-Cross-Domain-Policies header. Set to false to disable. Default: 'none' */
|
|
20
|
+
crossDomainPolicies?: string | false;
|
|
21
|
+
/**
|
|
22
|
+
* Strict-Transport-Security header.
|
|
23
|
+
* Default: `{ maxAge: 31536000 }` (1 year) when NODE_ENV is 'production', false otherwise.
|
|
24
|
+
* Browsers ignore HSTS on plain-HTTP responses, so the production default is safe behind TLS terminators.
|
|
25
|
+
*/
|
|
26
|
+
hsts?: HstsOptions | false;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Middleware that sets common HTTP security headers on every response.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```ts
|
|
33
|
+
* import { createSecurityHeaders } from '@guren/core'
|
|
34
|
+
*
|
|
35
|
+
* app.use('*', createSecurityHeaders())
|
|
36
|
+
*
|
|
37
|
+
* // With HSTS enabled
|
|
38
|
+
* app.use('*', createSecurityHeaders({
|
|
39
|
+
* hsts: { maxAge: 31536000, includeSubDomains: true },
|
|
40
|
+
* }))
|
|
41
|
+
*
|
|
42
|
+
* // Disable specific headers
|
|
43
|
+
* app.use('*', createSecurityHeaders({
|
|
44
|
+
* frameOptions: false,
|
|
45
|
+
* xssProtection: false,
|
|
46
|
+
* }))
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
export declare function createSecurityHeaders(options?: SecurityHeadersOptions): MiddlewareHandler;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import type { MiddlewareHandler } from 'hono';
|
|
2
|
+
export type SessionData = Record<string, unknown>;
|
|
3
|
+
export interface SessionStore {
|
|
4
|
+
/**
|
|
5
|
+
* Read a session by its opaque identifier.
|
|
6
|
+
* Returns undefined when the session does not exist or has expired.
|
|
7
|
+
*/
|
|
8
|
+
read(id: string): Promise<SessionData | undefined>;
|
|
9
|
+
/**
|
|
10
|
+
* Persist a session using upsert semantics for the given opaque identifier.
|
|
11
|
+
*/
|
|
12
|
+
write(id: string, data: SessionData, ttlSeconds: number): Promise<void>;
|
|
13
|
+
/**
|
|
14
|
+
* Destroy a session. Implementations must treat repeated calls as safe.
|
|
15
|
+
*/
|
|
16
|
+
destroy(id: string): Promise<void>;
|
|
17
|
+
/**
|
|
18
|
+
* Optional: refresh an existing session's TTL without rewriting its data.
|
|
19
|
+
* The middleware uses this for unchanged sessions (rolling expiry); stores
|
|
20
|
+
* that omit it fall back to a full `write`. Refreshing a session that no
|
|
21
|
+
* longer exists — including one that has expired but not yet been swept
|
|
22
|
+
* from storage — must be a no-op, not a resurrection.
|
|
23
|
+
*/
|
|
24
|
+
touch?(id: string, ttlSeconds: number): Promise<void>;
|
|
25
|
+
}
|
|
26
|
+
export declare class MemorySessionStore implements SessionStore {
|
|
27
|
+
private readonly now;
|
|
28
|
+
private readonly store;
|
|
29
|
+
constructor(now?: () => number);
|
|
30
|
+
read(id: string): Promise<SessionData | undefined>;
|
|
31
|
+
write(id: string, data: SessionData, ttlSeconds: number): Promise<void>;
|
|
32
|
+
destroy(id: string): Promise<void>;
|
|
33
|
+
touch(id: string, ttlSeconds: number): Promise<void>;
|
|
34
|
+
}
|
|
35
|
+
export interface SessionOptions {
|
|
36
|
+
cookieName?: string;
|
|
37
|
+
cookiePath?: string;
|
|
38
|
+
cookieDomain?: string;
|
|
39
|
+
cookieSecure?: boolean;
|
|
40
|
+
cookieSameSite?: 'Strict' | 'Lax' | 'None';
|
|
41
|
+
cookieHttpOnly?: boolean;
|
|
42
|
+
cookieMaxAgeSeconds?: number;
|
|
43
|
+
ttlSeconds?: number;
|
|
44
|
+
store?: SessionStore;
|
|
45
|
+
}
|
|
46
|
+
declare const SESSION_CONTEXT_KEY = "guren:session";
|
|
47
|
+
export interface Session {
|
|
48
|
+
readonly id: string;
|
|
49
|
+
readonly isNew: boolean;
|
|
50
|
+
get<T = unknown>(key: string): T | undefined;
|
|
51
|
+
set<T = unknown>(key: string, value: T): void;
|
|
52
|
+
has(key: string): boolean;
|
|
53
|
+
forget(key: string): void;
|
|
54
|
+
flush(): void;
|
|
55
|
+
all(): SessionData;
|
|
56
|
+
/**
|
|
57
|
+
* Rotate the session id (call after login to mitigate session fixation).
|
|
58
|
+
* The new id is persisted and the old one destroyed at request end. Known
|
|
59
|
+
* limitation shared by every multi-process store: a concurrent request
|
|
60
|
+
* still carrying the old cookie can re-persist the old id afterwards; the
|
|
61
|
+
* resurrected row holds only pre-rotation data (no auth state), so
|
|
62
|
+
* fixation does not escalate, but the row can linger until it expires.
|
|
63
|
+
*/
|
|
64
|
+
regenerate(): void;
|
|
65
|
+
invalidate(): void;
|
|
66
|
+
/**
|
|
67
|
+
* Whether this session survives the current response under `id`.
|
|
68
|
+
*
|
|
69
|
+
* `isNew` alone cannot answer this: a session created *during* this
|
|
70
|
+
* request stays `isNew` for its whole lifetime, yet once a handler
|
|
71
|
+
* writes to it (logging a user in) it is persisted under `id` and every
|
|
72
|
+
* later request finds it. Anything anchoring a value to the session id —
|
|
73
|
+
* CSRF token binding — has to ask this rather than `!isNew`, or it
|
|
74
|
+
* anchors to nothing across the login response.
|
|
75
|
+
*
|
|
76
|
+
* Optional only so a custom `Session` predating it still type-checks.
|
|
77
|
+
* Callers fall back to `!isNew`, which for that implementation reproduces
|
|
78
|
+
* the bug this method exists to prevent — a login response anchors to
|
|
79
|
+
* nothing, and the next mutation is rejected. Implement it.
|
|
80
|
+
*/
|
|
81
|
+
willPersist?(): boolean;
|
|
82
|
+
flash(key: string, value: unknown): void;
|
|
83
|
+
getFlash<T = unknown>(key: string): T | undefined;
|
|
84
|
+
reflash(): void;
|
|
85
|
+
keep(...keys: string[]): void;
|
|
86
|
+
}
|
|
87
|
+
export interface CreateSessionMiddlewareOptions extends SessionOptions {
|
|
88
|
+
}
|
|
89
|
+
export declare function createSessionMiddleware(options?: CreateSessionMiddlewareOptions): MiddlewareHandler;
|
|
90
|
+
export declare function getSessionFromContext<T extends Session = Session>(ctx: {
|
|
91
|
+
get: (key: string) => unknown;
|
|
92
|
+
}): T | undefined;
|
|
93
|
+
export { SESSION_CONTEXT_KEY };
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { Context, MiddlewareHandler } from 'hono';
|
|
2
|
+
import { type ValidationErrorLike } from '../request.js';
|
|
3
|
+
export declare const VALIDATED_DATA_KEY = "guren:validated";
|
|
4
|
+
export interface ValidationSchema<T = unknown> {
|
|
5
|
+
parse(data: unknown): T;
|
|
6
|
+
safeParse(data: unknown): {
|
|
7
|
+
success: true;
|
|
8
|
+
data: T;
|
|
9
|
+
} | {
|
|
10
|
+
success: false;
|
|
11
|
+
error: ValidationErrorLike;
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export interface ValidateRequestOptions {
|
|
15
|
+
/**
|
|
16
|
+
* Custom error handler when validation fails.
|
|
17
|
+
* Defaults to returning a 422 JSON response with formatted errors.
|
|
18
|
+
*/
|
|
19
|
+
onError?: (ctx: Context, errors: Record<string, string>) => Response | Promise<Response>;
|
|
20
|
+
/**
|
|
21
|
+
* HTTP status code for validation errors.
|
|
22
|
+
* Defaults to 422 (Unprocessable Entity).
|
|
23
|
+
*/
|
|
24
|
+
status?: number;
|
|
25
|
+
/**
|
|
26
|
+
* Fallback message when no field-specific errors are available.
|
|
27
|
+
*/
|
|
28
|
+
fallbackMessage?: string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Get validated data from the request context.
|
|
32
|
+
* Returns undefined if validation middleware hasn't run or validation failed.
|
|
33
|
+
*/
|
|
34
|
+
export declare function getValidatedData<T = Record<string, unknown>>(ctx: Context): T | undefined;
|
|
35
|
+
/**
|
|
36
|
+
* Creates a validation middleware that validates the request body against a Zod schema.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```ts
|
|
40
|
+
* import { z } from 'zod'
|
|
41
|
+
* import { validateRequest, getValidatedData } from '@guren/server'
|
|
42
|
+
*
|
|
43
|
+
* const CreateUserSchema = z.object({
|
|
44
|
+
* name: z.string().min(1),
|
|
45
|
+
* email: z.email(),
|
|
46
|
+
* })
|
|
47
|
+
*
|
|
48
|
+
* app.post('/users', validateRequest(CreateUserSchema), (c) => {
|
|
49
|
+
* const data = getValidatedData<z.infer<typeof CreateUserSchema>>(c)
|
|
50
|
+
* // data is typed and validated
|
|
51
|
+
* return c.json({ user: data })
|
|
52
|
+
* })
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
export declare function validateRequest<T>(schema: ValidationSchema<T>, options?: ValidateRequestOptions): MiddlewareHandler;
|
|
56
|
+
/**
|
|
57
|
+
* Creates a validation middleware from a schema factory function.
|
|
58
|
+
* Useful when the schema depends on request context.
|
|
59
|
+
*
|
|
60
|
+
* @example
|
|
61
|
+
* ```ts
|
|
62
|
+
* app.post('/users/:role', validateRequestWith((ctx) => {
|
|
63
|
+
* const role = ctx.req.param('role')
|
|
64
|
+
* return role === 'admin' ? AdminSchema : UserSchema
|
|
65
|
+
* }), handler)
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
export declare function validateRequestWith<T>(schemaFactory: (ctx: Context) => ValidationSchema<T>, options?: ValidateRequestOptions): MiddlewareHandler;
|
|
69
|
+
/**
|
|
70
|
+
* Validates data against a schema and throws if invalid.
|
|
71
|
+
* Useful for manual validation in handlers.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* ```ts
|
|
75
|
+
* app.post('/data', async (c) => {
|
|
76
|
+
* const payload = await parseRequestPayload(c)
|
|
77
|
+
* const data = validate(MySchema, payload)
|
|
78
|
+
* // throws ValidationError if invalid
|
|
79
|
+
* return c.json(data)
|
|
80
|
+
* })
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
export declare function validate<T>(schema: ValidationSchema<T>, data: unknown): T;
|
|
84
|
+
/**
|
|
85
|
+
* Validates data against a schema and returns a result object.
|
|
86
|
+
* Does not throw on validation failure.
|
|
87
|
+
*/
|
|
88
|
+
export declare function validateSafe<T>(schema: ValidationSchema<T>, data: unknown): {
|
|
89
|
+
success: true;
|
|
90
|
+
data: T;
|
|
91
|
+
} | {
|
|
92
|
+
success: false;
|
|
93
|
+
errors: Record<string, string>;
|
|
94
|
+
};
|