@guren/server 2.1.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (270) hide show
  1. package/dist/{McpServiceProvider-7BB5FPF3.js → McpServiceProvider-GRDYNEQG.js} +1 -1
  2. package/dist/auth/AuthManager.d.ts +30 -0
  3. package/dist/auth/AuthenticatableModel.d.ts +25 -0
  4. package/dist/auth/RequestAuthContext.d.ts +24 -0
  5. package/dist/auth/SessionGuard.d.ts +31 -0
  6. package/dist/auth/api-token.d.ts +299 -0
  7. package/dist/auth/email-verification.d.ts +203 -0
  8. package/dist/auth/index.d.ts +18 -110
  9. package/dist/auth/index.js +3 -1
  10. package/dist/auth/oauth/index.d.ts +239 -0
  11. package/dist/auth/password/DefaultHasher.d.ts +13 -0
  12. package/dist/auth/password/NodeHasher.d.ts +22 -0
  13. package/dist/auth/password/PasswordHasher.d.ts +5 -0
  14. package/dist/auth/password/ScryptHasher.d.ts +26 -0
  15. package/dist/auth/password-reset.d.ts +91 -0
  16. package/dist/auth/providers/ModelUserProvider.d.ts +36 -0
  17. package/dist/auth/providers/UserProvider.d.ts +9 -0
  18. package/dist/auth/types.d.ts +102 -0
  19. package/dist/auth/utils.d.ts +39 -0
  20. package/dist/{Gate-CynjZCtS.d.ts → authorization/Gate.d.ts} +30 -111
  21. package/dist/authorization/Policy.d.ts +77 -0
  22. package/dist/authorization/index.d.ts +5 -129
  23. package/dist/authorization/index.js +3 -1
  24. package/dist/authorization/middleware.d.ts +49 -0
  25. package/dist/authorization/types.d.ts +108 -0
  26. package/dist/broadcasting/BroadcastManager.d.ts +205 -0
  27. package/dist/broadcasting/channels/Channel.d.ts +28 -0
  28. package/dist/broadcasting/channels/PresenceChannel.d.ts +72 -0
  29. package/dist/broadcasting/channels/PrivateChannel.d.ts +32 -0
  30. package/dist/broadcasting/channels/index.d.ts +3 -0
  31. package/dist/broadcasting/drivers/MemoryDriver.d.ts +93 -0
  32. package/dist/broadcasting/drivers/RedisDriver.d.ts +112 -0
  33. package/dist/broadcasting/drivers/index.d.ts +2 -0
  34. package/dist/broadcasting/index.d.ts +6 -233
  35. package/dist/broadcasting/index.js +1 -1
  36. package/dist/broadcasting/typed.d.ts +23 -0
  37. package/dist/broadcasting/types.d.ts +155 -0
  38. package/dist/cache/CacheManager.d.ts +87 -0
  39. package/dist/cache/TaggedCache.d.ts +62 -0
  40. package/dist/cache/index.d.ts +6 -233
  41. package/dist/cache/index.js +1 -1
  42. package/dist/cache/stores/FileStore.d.ts +64 -0
  43. package/dist/cache/stores/MemoryStore.d.ts +52 -0
  44. package/dist/cache/stores/RedisStore.d.ts +53 -0
  45. package/dist/{CacheManager-BmDzUKrF.d.ts → cache/types.d.ts} +26 -99
  46. package/dist/{chunk-TVY72CLV.js → chunk-4VE3LYOM.js} +3 -2
  47. package/dist/{chunk-FZD2AKJI.js → chunk-7OB2YXRE.js} +56 -28
  48. package/dist/{chunk-J6ETA476.js → chunk-BUQXOZCT.js} +93 -5
  49. package/dist/{chunk-DSDX3ASM.js → chunk-CDZUNKI6.js} +65 -83
  50. package/dist/{chunk-CWI4AJ47.js → chunk-HPET6XY5.js} +13 -9
  51. package/dist/{chunk-A3ISJVEV.js → chunk-HR2KZ3WL.js} +23 -5
  52. package/dist/{chunk-5SZTEZ22.js → chunk-PZKUDFMW.js} +11 -8
  53. package/dist/console/Command.d.ts +179 -0
  54. package/dist/{ConsoleKernel-CJg975mp.d.ts → console/ConsoleKernel.d.ts} +4 -6
  55. package/dist/console/Input.d.ts +140 -0
  56. package/dist/console/Output.d.ts +161 -0
  57. package/dist/console/index.d.ts +5 -0
  58. package/dist/console/types.d.ts +106 -0
  59. package/dist/container/Container.d.ts +148 -0
  60. package/dist/container/ServiceProvider.d.ts +103 -0
  61. package/dist/container/bindings.d.ts +55 -0
  62. package/dist/container/defineModule.d.ts +88 -0
  63. package/dist/container/definePlugin.d.ts +62 -0
  64. package/dist/container/index.d.ts +8 -0
  65. package/dist/container/types.d.ts +73 -0
  66. package/dist/database/Factory.d.ts +82 -0
  67. package/dist/database/Seeder.d.ts +35 -0
  68. package/dist/database/SeederRunner.d.ts +41 -0
  69. package/dist/database/index.d.ts +4 -0
  70. package/dist/database/types.d.ts +49 -0
  71. package/dist/discovery/AutoDiscovery.d.ts +113 -0
  72. package/dist/discovery/index.d.ts +2 -0
  73. package/dist/docs-viewer/DocsViewerServiceProvider.d.ts +12 -0
  74. package/dist/docs-viewer/endpoint.d.ts +19 -0
  75. package/dist/encryption/Encrypter.d.ts +96 -0
  76. package/dist/encryption/Hash.d.ts +69 -0
  77. package/dist/encryption/MessageSigner.d.ts +21 -0
  78. package/dist/encryption/Random.d.ts +119 -0
  79. package/dist/encryption/app-key.d.ts +12 -0
  80. package/dist/encryption/index.d.ts +10 -222
  81. package/dist/encryption/signed-url.d.ts +9 -0
  82. package/dist/encryption/types.d.ts +103 -0
  83. package/dist/errors/ExceptionHandler.d.ts +118 -0
  84. package/dist/errors/HttpException.d.ts +106 -0
  85. package/dist/errors/debug-page.d.ts +22 -0
  86. package/dist/errors/error-page.d.ts +1 -0
  87. package/dist/errors/exceptions/AuthenticationException.d.ts +32 -0
  88. package/dist/errors/exceptions/AuthorizationException.d.ts +32 -0
  89. package/dist/errors/exceptions/MethodNotAllowedException.d.ts +31 -0
  90. package/dist/errors/exceptions/NotFoundHttpException.d.ts +36 -0
  91. package/dist/errors/exceptions/ValidationException.d.ts +60 -0
  92. package/dist/errors/exceptions/index.d.ts +5 -0
  93. package/dist/errors/index.d.ts +5 -0
  94. package/dist/errors/types.d.ts +43 -0
  95. package/dist/events/Event.d.ts +33 -0
  96. package/dist/{EventManager-CmIoLt7r.d.ts → events/EventManager.d.ts} +4 -86
  97. package/dist/events/Listener.d.ts +79 -0
  98. package/dist/events/builtin.d.ts +73 -0
  99. package/dist/events/index.d.ts +6 -155
  100. package/dist/events/types.d.ts +48 -0
  101. package/dist/facades/index.d.ts +31 -0
  102. package/dist/health/HealthCheck.d.ts +34 -0
  103. package/dist/health/HealthManager.d.ts +53 -0
  104. package/dist/health/checks/CacheCheck.d.ts +35 -0
  105. package/dist/health/checks/CustomCheck.d.ts +23 -0
  106. package/dist/health/checks/DatabaseCheck.d.ts +33 -0
  107. package/dist/health/checks/MemoryCheck.d.ts +32 -0
  108. package/dist/health/checks/RedisCheck.d.ts +27 -0
  109. package/dist/health/checks/StorageCheck.d.ts +35 -0
  110. package/dist/health/checks/index.d.ts +12 -0
  111. package/dist/health/index.d.ts +5 -185
  112. package/dist/health/types.d.ts +52 -0
  113. package/dist/hot-reload/hot-disposables.d.ts +96 -0
  114. package/dist/hot-reload/testing.d.ts +14 -0
  115. package/dist/http/Application.d.ts +187 -0
  116. package/dist/http/FormRequest.d.ts +73 -0
  117. package/dist/http/dev-assets.d.ts +51 -0
  118. package/dist/http/dev-banner.d.ts +7 -0
  119. package/dist/http/inertia-assets.d.ts +22 -0
  120. package/dist/http/middleware/auth.d.ts +13 -0
  121. package/dist/http/middleware/capabilities.d.ts +22 -0
  122. package/dist/http/middleware/cors.d.ts +40 -0
  123. package/dist/http/middleware/csp.d.ts +59 -0
  124. package/dist/http/middleware/csrf.d.ts +121 -0
  125. package/dist/http/middleware/detect-locale.d.ts +65 -0
  126. package/dist/http/middleware/force-https.d.ts +34 -0
  127. package/dist/http/middleware/host-authorization.d.ts +24 -0
  128. package/dist/http/middleware/index.d.ts +19 -0
  129. package/dist/http/middleware/loopback-guard.d.ts +38 -0
  130. package/dist/{rate-limit-D9J2b4S1.d.ts → http/middleware/rate-limit.d.ts} +22 -50
  131. package/dist/http/middleware/redirect-safety.d.ts +29 -0
  132. package/dist/http/middleware/request-id.d.ts +19 -0
  133. package/dist/http/middleware/request-logging.d.ts +16 -0
  134. package/dist/http/middleware/security-headers.d.ts +49 -0
  135. package/dist/http/middleware/session.d.ts +93 -0
  136. package/dist/http/middleware/validation.d.ts +94 -0
  137. package/dist/http/public-assets.d.ts +15 -0
  138. package/dist/http/request.d.ts +24 -0
  139. package/dist/http/resources/CursorPaginator.d.ts +106 -0
  140. package/dist/http/resources/Paginator.d.ts +130 -0
  141. package/dist/http/resources/Resource.d.ts +67 -0
  142. package/dist/http/resources/ResourceCollection.d.ts +60 -0
  143. package/dist/http/resources/index.d.ts +6 -0
  144. package/dist/http/resources/types.d.ts +91 -0
  145. package/dist/http/validation/Validator.d.ts +128 -0
  146. package/dist/http/validation/index.d.ts +3 -0
  147. package/dist/http/validation/rules.d.ts +196 -0
  148. package/dist/http/validation/types.d.ts +96 -0
  149. package/dist/http/vite-dev-server.d.ts +27 -0
  150. package/dist/i18n/I18nManager.d.ts +114 -0
  151. package/dist/i18n/Translator.d.ts +80 -0
  152. package/dist/i18n/index.d.ts +6 -101
  153. package/dist/i18n/index.js +5 -3
  154. package/dist/i18n/loaders/JsonLoader.d.ts +47 -0
  155. package/dist/i18n/loaders/MemoryLoader.d.ts +37 -0
  156. package/dist/i18n/pluralization.d.ts +19 -0
  157. package/dist/i18n/types.d.ts +106 -0
  158. package/dist/index.d.ts +69 -2605
  159. package/dist/index.js +332 -152
  160. package/dist/lambda/index.d.ts +17 -37
  161. package/dist/logging/LogManager.d.ts +83 -0
  162. package/dist/logging/Logger.d.ts +76 -0
  163. package/dist/logging/channels/ConsoleChannel.d.ts +11 -0
  164. package/dist/logging/channels/DailyFileChannel.d.ts +20 -0
  165. package/dist/logging/channels/FileChannel.d.ts +15 -0
  166. package/dist/logging/index.d.ts +8 -50
  167. package/dist/logging/types.d.ts +96 -0
  168. package/dist/mail/Mail.d.ts +138 -0
  169. package/dist/mail/MailManager.d.ts +79 -0
  170. package/dist/mail/address.d.ts +8 -0
  171. package/dist/mail/index.d.ts +7 -316
  172. package/dist/mail/transports/LogTransport.d.ts +19 -0
  173. package/dist/mail/transports/MemoryTransport.d.ts +84 -0
  174. package/dist/mail/transports/ResendTransport.d.ts +32 -0
  175. package/dist/mail/transports/SmtpTransport.d.ts +40 -0
  176. package/dist/{MailManager-DpMvYiP9.d.ts → mail/types.d.ts} +11 -92
  177. package/dist/mcp/McpServiceProvider.d.ts +17 -0
  178. package/dist/mcp/create-mcp-server.d.ts +144 -0
  179. package/dist/mcp/endpoint.d.ts +29 -0
  180. package/dist/mcp/index.d.ts +3 -185
  181. package/dist/mcp/index.js +1 -1
  182. package/dist/mvc/Controller.d.ts +326 -0
  183. package/dist/mvc/Router.d.ts +239 -0
  184. package/dist/mvc/ViewEngine.d.ts +11 -0
  185. package/dist/mvc/inertia/InertiaEngine.d.ts +114 -0
  186. package/dist/mvc/inertia/shared.d.ts +90 -0
  187. package/dist/mvc/mount-route.d.ts +10 -0
  188. package/dist/notifications/Notification.d.ts +99 -0
  189. package/dist/notifications/NotificationManager.d.ts +150 -0
  190. package/dist/notifications/channels/DatabaseChannel.d.ts +55 -0
  191. package/dist/notifications/channels/MailChannel.d.ts +45 -0
  192. package/dist/notifications/channels/MemoryChannel.d.ts +85 -0
  193. package/dist/notifications/channels/SlackChannel.d.ts +73 -0
  194. package/dist/notifications/channels/index.d.ts +4 -0
  195. package/dist/notifications/index.d.ts +6 -322
  196. package/dist/notifications/notifiable-type.d.ts +10 -0
  197. package/dist/notifications/registry.d.ts +39 -0
  198. package/dist/notifications/types.d.ts +162 -0
  199. package/dist/providers/AuthServiceProvider.d.ts +7 -0
  200. package/dist/providers/AuthorizationServiceProvider.d.ts +9 -0
  201. package/dist/providers/BroadcastServiceProvider.d.ts +7 -0
  202. package/dist/providers/CacheServiceProvider.d.ts +7 -0
  203. package/dist/providers/EncryptionServiceProvider.d.ts +7 -0
  204. package/dist/providers/ErrorServiceProvider.d.ts +9 -0
  205. package/dist/providers/EventServiceProvider.d.ts +7 -0
  206. package/dist/providers/HealthServiceProvider.d.ts +7 -0
  207. package/dist/providers/I18nServiceProvider.d.ts +27 -0
  208. package/dist/providers/InertiaServiceProvider.d.ts +20 -0
  209. package/dist/providers/LogServiceProvider.d.ts +7 -0
  210. package/dist/providers/MailServiceProvider.d.ts +7 -0
  211. package/dist/providers/NotificationServiceProvider.d.ts +8 -0
  212. package/dist/providers/OAuthServiceProvider.d.ts +7 -0
  213. package/dist/providers/QueueServiceProvider.d.ts +7 -0
  214. package/dist/providers/SchedulingServiceProvider.d.ts +7 -0
  215. package/dist/providers/StorageServiceProvider.d.ts +7 -0
  216. package/dist/providers/index.d.ts +17 -0
  217. package/dist/queue/FailedJobReporter.d.ts +40 -0
  218. package/dist/queue/Job.d.ts +140 -0
  219. package/dist/queue/QueueManager.d.ts +79 -0
  220. package/dist/queue/Worker.d.ts +99 -0
  221. package/dist/queue/drivers/MemoryDriver.d.ts +60 -0
  222. package/dist/queue/drivers/RedisDriver.d.ts +96 -0
  223. package/dist/queue/drivers/SqsDriver.d.ts +108 -0
  224. package/dist/queue/drivers/SyncDriver.d.ts +28 -0
  225. package/dist/queue/index.d.ts +9 -453
  226. package/dist/queue/types.d.ts +171 -0
  227. package/dist/redis/RedisApiTokenStore.d.ts +78 -0
  228. package/dist/redis/RedisEmailVerificationStore.d.ts +54 -0
  229. package/dist/redis/RedisOAuthStateStore.d.ts +26 -0
  230. package/dist/redis/RedisPasswordResetStore.d.ts +57 -0
  231. package/dist/redis/RedisRateLimitStore.d.ts +77 -0
  232. package/dist/redis/RedisSessionStore.d.ts +61 -0
  233. package/dist/redis/client.d.ts +41 -0
  234. package/dist/redis/index.d.ts +14 -356
  235. package/dist/redis/index.js +5 -2
  236. package/dist/redis/scan-keys.d.ts +6 -0
  237. package/dist/runtime/index.d.ts +8 -95
  238. package/dist/runtime/index.js +1 -1
  239. package/dist/scheduling/CronParser.d.ts +37 -0
  240. package/dist/scheduling/Schedule.d.ts +229 -0
  241. package/dist/scheduling/ScheduledTask.d.ts +47 -0
  242. package/dist/scheduling/Scheduler.d.ts +99 -0
  243. package/dist/scheduling/index.d.ts +5 -41
  244. package/dist/scheduling/types.d.ts +97 -0
  245. package/dist/storage/StorageManager.d.ts +65 -0
  246. package/dist/storage/drivers/LocalDriver.d.ts +55 -0
  247. package/dist/storage/drivers/MemoryDriver.d.ts +66 -0
  248. package/dist/storage/drivers/S3Driver.d.ts +72 -0
  249. package/dist/storage/index.d.ts +5 -197
  250. package/dist/{StorageManager-oZTHqaza.d.ts → storage/types.d.ts} +10 -77
  251. package/dist/support/error-polyfill.d.ts +9 -0
  252. package/dist/support/import-map.d.ts +13 -0
  253. package/dist/support/redirect-target.d.ts +11 -0
  254. package/dist/support/stack-frames.d.ts +56 -0
  255. package/dist/support/trim-slashes.d.ts +11 -0
  256. package/dist/vite/index.d.ts +2 -35
  257. package/dist/vite/index.js +0 -3
  258. package/dist/vite/plugin.d.ts +34 -0
  259. package/package.json +3 -3
  260. package/dist/AuthManager-DBP4KYsx.d.ts +0 -79
  261. package/dist/BroadcastManager-D8KoJxiV.d.ts +0 -492
  262. package/dist/HealthManager-DUyMIzsZ.d.ts +0 -141
  263. package/dist/I18nManager-BiSoczfV.d.ts +0 -275
  264. package/dist/LogManager-7mxnkaPM.d.ts +0 -256
  265. package/dist/Scheduler-pZiT8i57.d.ts +0 -471
  266. package/dist/api-token-D24VPr_E.d.ts +0 -663
  267. package/dist/app-key-CsBfRC_Q.d.ts +0 -214
  268. package/dist/email-verification-Dx426KLn.d.ts +0 -336
  269. package/dist/index-9_Jzj5jo.d.ts +0 -7
  270. package/dist/validation-yAL53e1S.d.ts +0 -2610
@@ -1,663 +0,0 @@
1
- import { MiddlewareHandler, Context } from 'hono';
2
-
3
- type SessionData = Record<string, unknown>;
4
- interface SessionStore {
5
- /**
6
- * Read a session by its opaque identifier.
7
- * Returns undefined when the session does not exist or has expired.
8
- */
9
- read(id: string): Promise<SessionData | undefined>;
10
- /**
11
- * Persist a session using upsert semantics for the given opaque identifier.
12
- */
13
- write(id: string, data: SessionData, ttlSeconds: number): Promise<void>;
14
- /**
15
- * Destroy a session. Implementations must treat repeated calls as safe.
16
- */
17
- destroy(id: string): Promise<void>;
18
- /**
19
- * Optional: refresh an existing session's TTL without rewriting its data.
20
- * The middleware uses this for unchanged sessions (rolling expiry); stores
21
- * that omit it fall back to a full `write`. Refreshing a session that no
22
- * longer exists — including one that has expired but not yet been swept
23
- * from storage — must be a no-op, not a resurrection.
24
- */
25
- touch?(id: string, ttlSeconds: number): Promise<void>;
26
- }
27
- declare class MemorySessionStore implements SessionStore {
28
- private readonly now;
29
- private readonly store;
30
- constructor(now?: () => number);
31
- read(id: string): Promise<SessionData | undefined>;
32
- write(id: string, data: SessionData, ttlSeconds: number): Promise<void>;
33
- destroy(id: string): Promise<void>;
34
- touch(id: string, ttlSeconds: number): Promise<void>;
35
- }
36
- interface SessionOptions {
37
- cookieName?: string;
38
- cookiePath?: string;
39
- cookieDomain?: string;
40
- cookieSecure?: boolean;
41
- cookieSameSite?: 'Strict' | 'Lax' | 'None';
42
- cookieHttpOnly?: boolean;
43
- cookieMaxAgeSeconds?: number;
44
- ttlSeconds?: number;
45
- store?: SessionStore;
46
- }
47
- 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
- flash(key: string, value: unknown): void;
67
- getFlash<T = unknown>(key: string): T | undefined;
68
- reflash(): void;
69
- keep(...keys: string[]): void;
70
- }
71
- interface CreateSessionMiddlewareOptions extends SessionOptions {
72
- }
73
- declare function createSessionMiddleware(options?: CreateSessionMiddlewareOptions): MiddlewareHandler;
74
- declare function getSessionFromContext<T extends Session = Session>(ctx: {
75
- get: (key: string) => unknown;
76
- }): T | undefined;
77
-
78
- interface OAuthProviderConfig {
79
- clientId: string;
80
- clientSecret: string;
81
- redirectUri: string;
82
- authorizeUrl: string;
83
- tokenUrl: string;
84
- userInfoUrl: string;
85
- scopes?: string[];
86
- tokenAuthMethod?: 'client_secret_post' | 'client_secret_basic';
87
- userInfoMethod?: 'GET' | 'POST';
88
- mapProfile?: (raw: Record<string, unknown>, token: OAuthTokenResult) => OAuthUserProfile;
89
- /**
90
- * Key in the userinfo response carrying the provider's own verification
91
- * signal for the email address — Discord returns `verified`, for example.
92
- * Defaults to OIDC's standard `email_verified` claim. Only boolean values
93
- * are read; anything else leaves `profile.emailVerified` undefined. Ignored
94
- * when `mapProfile` is set, since that owns the whole mapping.
95
- */
96
- emailVerifiedKey?: string;
97
- /**
98
- * Fallback used when the userinfo response carries no email — e.g. GitHub
99
- * returns `email: null` for accounts with a private email even when the
100
- * `user:email` scope was granted. Returns the email to use, or undefined
101
- * to leave the profile without one.
102
- *
103
- * The signal read via `emailVerifiedKey` does not carry over to a fallback
104
- * address — it was read against a response that had no email. A bare string
105
- * therefore makes no verification claim and leaves `profile.emailVerified`
106
- * undefined; return `{ email, emailVerified: true }` to assert one.
107
- */
108
- fetchFallbackEmail?: (token: OAuthTokenResult) => Promise<string | OAuthFallbackEmail | undefined>;
109
- }
110
- interface OAuthFallbackEmail {
111
- email: string;
112
- /**
113
- * Whether the provider verified this specific address. Omit it when the
114
- * lookup cannot tell — the profile then reports `emailVerified: undefined`
115
- * rather than an unfounded claim.
116
- */
117
- emailVerified?: boolean;
118
- }
119
- interface OAuthTokenResult {
120
- accessToken: string;
121
- tokenType?: string;
122
- refreshToken?: string;
123
- expiresIn?: number;
124
- scope?: string;
125
- raw: Record<string, unknown>;
126
- }
127
- interface OAuthUserProfile {
128
- id: string;
129
- email?: string;
130
- name?: string;
131
- avatar?: string;
132
- /**
133
- * Whether the provider itself verified `email`. Tri-state on purpose:
134
- * `true` — the provider asserts the address is verified; `false` — it
135
- * asserts it is not; `undefined` — the provider sends no such signal
136
- * (GitHub's `/user`, for instance), so the consumer decides its own policy.
137
- * Returning an email is not by itself a claim that it was checked, so
138
- * treating `undefined` as verified is a decision, not a default.
139
- */
140
- emailVerified?: boolean;
141
- token: OAuthTokenResult;
142
- raw: Record<string, unknown>;
143
- }
144
- interface OAuthStatePayload {
145
- provider: string;
146
- redirectTo?: string;
147
- expiresAt: Date;
148
- }
149
- interface OAuthStateStore {
150
- store(stateHash: string, payload: OAuthStatePayload): Promise<void>;
151
- find(stateHash: string): Promise<OAuthStatePayload | null>;
152
- delete(stateHash: string): Promise<void>;
153
- /**
154
- * Atomically fetch and delete a state in one step. Exactly one caller may
155
- * receive the payload; every other concurrent caller (and any later call)
156
- * must get null. Expired states must also return null, mirroring `find`.
157
- *
158
- * Optional for backward compatibility: `verifyOAuthState` prefers this
159
- * when present. Stores that only implement find/delete keep working, but
160
- * leave a window where two concurrent callbacks with the same state can
161
- * both pass verification.
162
- */
163
- consume?(stateHash: string): Promise<OAuthStatePayload | null>;
164
- }
165
- interface OAuthStateConfig {
166
- expiresIn?: number;
167
- stateLength?: number;
168
- hashAlgorithm?: 'sha256' | 'sha512';
169
- /**
170
- * External hosts allowed as `redirectTo` targets (supports `*.example.com`
171
- * wildcards). App-relative paths (`/dashboard`) are always allowed; anything
172
- * else is dropped to prevent open redirects.
173
- */
174
- allowedRedirectHosts?: string[];
175
- }
176
- interface OAuthAuthorizeOptions {
177
- scope?: string[];
178
- redirectTo?: string;
179
- state?: string;
180
- extraParams?: Record<string, string>;
181
- }
182
- interface OAuthCallbackPayload {
183
- code: string;
184
- state: string;
185
- }
186
- interface OAuthManagerOptions {
187
- stateStore?: OAuthStateStore;
188
- stateConfig?: OAuthStateConfig;
189
- }
190
- declare class MemoryOAuthStateStore implements OAuthStateStore {
191
- private readonly states;
192
- private readonly maxEntries;
193
- constructor(options?: {
194
- maxEntries?: number;
195
- });
196
- store(stateHash: string, payload: OAuthStatePayload): Promise<void>;
197
- private sweepExpired;
198
- find(stateHash: string): Promise<OAuthStatePayload | null>;
199
- delete(stateHash: string): Promise<void>;
200
- consume(stateHash: string): Promise<OAuthStatePayload | null>;
201
- clear(): void;
202
- }
203
- declare class OAuthManager {
204
- private readonly providers;
205
- private readonly stateStore;
206
- private readonly stateConfig;
207
- constructor(options?: OAuthManagerOptions);
208
- registerProvider(name: string, config: OAuthProviderConfig): void;
209
- providerNames(): string[];
210
- getProvider(name: string): OAuthProviderConfig;
211
- authorize(providerName: string, options?: OAuthAuthorizeOptions): Promise<{
212
- url: string;
213
- state: string;
214
- expiresAt: Date;
215
- }>;
216
- user(providerName: string, payload: OAuthCallbackPayload): Promise<OAuthUserProfile>;
217
- /**
218
- * Verify the callback and return the user profile together with the
219
- * sanitized `redirectTo` stored at authorize time. `redirectTo` is safe to
220
- * pass to a redirect response: app-relative paths and allowlisted hosts
221
- * only.
222
- */
223
- handleCallback(providerName: string, payload: OAuthCallbackPayload): Promise<{
224
- profile: OAuthUserProfile;
225
- redirectTo?: string;
226
- }>;
227
- }
228
- declare function createOAuthManager(options?: OAuthManagerOptions): OAuthManager;
229
- declare function createOAuthState(provider: string, store: OAuthStateStore, config?: OAuthStateConfig, redirectTo?: string, fixedState?: string): Promise<{
230
- state: string;
231
- expiresAt: Date;
232
- }>;
233
- declare function verifyOAuthState(state: string, provider: string, store: OAuthStateStore, config?: OAuthStateConfig): Promise<OAuthStatePayload | null>;
234
- /**
235
- * Reduce a `redirectTo` value to a safe target: app-relative paths always
236
- * pass; absolute http(s) URLs pass only when their host is in the allowlist
237
- * (supports `*.example.com` wildcards). Everything else — protocol-relative
238
- * URLs, backslash tricks, `javascript:` and other schemes — returns
239
- * `undefined`.
240
- */
241
- declare function sanitizeOAuthRedirect(redirectTo: string | undefined, allowedHosts?: string[]): string | undefined;
242
- declare function buildOAuthAuthorizeUrl(provider: OAuthProviderConfig, state: string, options?: {
243
- scope?: string[];
244
- extraParams?: Record<string, string>;
245
- }): string;
246
- declare function exchangeOAuthCode(provider: OAuthProviderConfig, code: string): Promise<OAuthTokenResult>;
247
- declare function fetchOAuthUserProfile(provider: OAuthProviderConfig, token: OAuthTokenResult): Promise<OAuthUserProfile>;
248
- interface OAuthProviderFactoryInput {
249
- clientId: string;
250
- clientSecret: string;
251
- redirectUri: string;
252
- scopes?: string[];
253
- }
254
- declare function createGitHubOAuthProviderConfig(input: OAuthProviderFactoryInput): OAuthProviderConfig;
255
- declare function createGoogleOAuthProviderConfig(input: OAuthProviderFactoryInput): OAuthProviderConfig;
256
- declare function createDiscordOAuthProviderConfig(input: OAuthProviderFactoryInput): OAuthProviderConfig;
257
- declare function buildOAuthRedirectUrl(baseUrl: string, token: string, email?: string): string;
258
- declare function parseOAuthRedirectUrl(url: string): {
259
- token: string | null;
260
- email: string | null;
261
- };
262
-
263
- type AuthCredentials = Record<string, unknown>;
264
- interface Authenticatable {
265
- getAuthIdentifier(): unknown;
266
- getAuthPassword(): string | null | undefined;
267
- getRememberToken?(): string | null | undefined;
268
- setRememberToken?(token: string | null): void | Promise<void>;
269
- }
270
- interface Guard<User = Authenticatable> {
271
- check(): Promise<boolean>;
272
- guest(): Promise<boolean>;
273
- user<T = User>(): Promise<T | null>;
274
- id(): Promise<unknown>;
275
- login<T = User>(user: T, remember?: boolean): Promise<void>;
276
- logout(): Promise<void>;
277
- attempt(credentials: AuthCredentials, remember?: boolean): Promise<boolean>;
278
- validate(credentials: AuthCredentials): Promise<User | null>;
279
- session<T extends Session = Session>(): T | undefined;
280
- }
281
- interface UserProvider<User = Authenticatable> {
282
- retrieveById(identifier: unknown): Promise<User | null>;
283
- retrieveByCredentials(credentials: AuthCredentials): Promise<User | null>;
284
- validateCredentials(user: User, credentials: AuthCredentials): Promise<boolean>;
285
- getId(user: User): unknown;
286
- setRememberToken?(user: User, token: string | null): Promise<void> | void;
287
- getRememberToken?(user: User): Promise<string | null> | string | null;
288
- /**
289
- * Strip fields that must never leave the auth layer (password hashes,
290
- * remember tokens, model `hidden` fields) from a user record before it
291
- * is cached or handed to application code via guard.user().
292
- */
293
- sanitize?(user: User): User;
294
- }
295
- /**
296
- * The conventional names for the credential columns that
297
- * `ModelUserProvider.sanitize()` strips: the password column (`password`
298
- * by default, commonly configured as `passwordHash`/`password_hash`) and
299
- * the remember-token column (`remember_token` by default, commonly
300
- * `rememberToken`).
301
- */
302
- type DefaultSanitizedKeys = 'password' | 'passwordHash' | 'password_hash' | 'rememberToken' | 'remember_token';
303
- /**
304
- * The shape of a user record after auth-layer sanitization — what
305
- * `auth.user()` returns at runtime when the provider's column names
306
- * follow the {@link DefaultSanitizedKeys} conventions. Removes those
307
- * conventional credential keys plus any extra keys passed as `Hidden`.
308
- *
309
- * The runtime strips exactly the *configured* password/remember-token
310
- * columns plus the model's `static hidden` — a static type cannot see
311
- * that configuration. If your columns use other names, or the model
312
- * hides additional fields, list them in `Hidden` explicitly. Only
313
- * meaningful for concrete record types (index-signature records like
314
- * `Record<string, string>` cannot have individual keys removed).
315
- *
316
- * @example
317
- * ```ts
318
- * const user = await this.auth.userOrFail<Sanitized<UserRecord>>()
319
- * user.passwordHash // compile error — stripped at runtime
320
- *
321
- * // With additional hidden fields or custom column names:
322
- * type SafeUser = Sanitized<UserRecord, 'twoFactorSecret' | 'credentialDigest'>
323
- * ```
324
- */
325
- type Sanitized<User, Hidden extends string = never> = User extends unknown ? Omit<User, Extract<keyof User, DefaultSanitizedKeys | Hidden>> : never;
326
- interface GuardContext {
327
- ctx: Context;
328
- session: Session | undefined;
329
- manager: AuthManagerContract;
330
- }
331
- type GuardFactory<User = Authenticatable> = (context: GuardContext) => Guard<User>;
332
- interface ProviderFactory<User = Authenticatable> {
333
- (manager: AuthManagerContract): UserProvider<User>;
334
- }
335
- interface AuthManagerOptions {
336
- defaultGuard?: string;
337
- }
338
- interface AttachContextOptions {
339
- guard?: string;
340
- }
341
- interface AuthContext<User = Authenticatable> {
342
- check(): Promise<boolean>;
343
- guest(): Promise<boolean>;
344
- user<T = User>(): Promise<T | null>;
345
- userOrFail<T = User>(): Promise<T>;
346
- id(): Promise<unknown>;
347
- login<T = User>(user: T, remember?: boolean): Promise<void>;
348
- attempt(credentials: AuthCredentials, remember?: boolean): Promise<boolean>;
349
- logout(): Promise<void>;
350
- guard<T = User>(name?: string): Guard<T>;
351
- session<T extends Session = Session>(): T | undefined;
352
- }
353
- interface AuthManagerContract {
354
- registerGuard<User = Authenticatable>(name: string, factory: GuardFactory<User>): void;
355
- registerProvider<User = Authenticatable>(name: string, factory: ProviderFactory<User>): void;
356
- getProvider<User = Authenticatable>(name: string): UserProvider<User>;
357
- createGuard<User = Authenticatable>(name: string, context: GuardContext): Guard<User>;
358
- guardNames(): string[];
359
- setDefaultGuard(name: string): void;
360
- getDefaultGuard(): string;
361
- createAuthContext(ctx: Context, options?: AttachContextOptions): AuthContext;
362
- }
363
-
364
- /**
365
- * API token data stored in the backing store.
366
- */
367
- interface ApiToken {
368
- id: string;
369
- name: string;
370
- hashedToken: string;
371
- userId: string | number;
372
- abilities: string[];
373
- lastUsedAt: Date | null;
374
- expiresAt: Date | null;
375
- createdAt: Date;
376
- }
377
- /**
378
- * Store interface for API tokens.
379
- * Implement this for database-backed storage.
380
- */
381
- interface ApiTokenStore {
382
- /**
383
- * Store a new API token.
384
- */
385
- store(token: ApiToken): Promise<void>;
386
- /**
387
- * Find a token by its hashed value.
388
- */
389
- findByHashedToken(hashedToken: string): Promise<ApiToken | null>;
390
- /**
391
- * Find all tokens for a user.
392
- */
393
- findByUserId(userId: string | number): Promise<ApiToken[]>;
394
- /**
395
- * Delete a token by its ID.
396
- */
397
- delete(id: string): Promise<void>;
398
- /**
399
- * Delete all tokens for a user.
400
- */
401
- deleteForUser(userId: string | number): Promise<void>;
402
- /**
403
- * Update the last used timestamp.
404
- */
405
- updateLastUsed(id: string, timestamp: Date): Promise<void>;
406
- }
407
- /**
408
- * In-memory token store for testing.
409
- * Do NOT use in production - tokens will be lost on restart.
410
- */
411
- declare class MemoryApiTokenStore implements ApiTokenStore {
412
- private tokens;
413
- private byHash;
414
- store(token: ApiToken): Promise<void>;
415
- findByHashedToken(hashedToken: string): Promise<ApiToken | null>;
416
- findByUserId(userId: string | number): Promise<ApiToken[]>;
417
- delete(id: string): Promise<void>;
418
- deleteForUser(userId: string | number): Promise<void>;
419
- updateLastUsed(id: string, timestamp: Date): Promise<void>;
420
- /**
421
- * Clear all tokens (useful for testing).
422
- */
423
- clear(): void;
424
- /**
425
- * Get the number of stored tokens.
426
- */
427
- get size(): number;
428
- }
429
- /**
430
- * Configuration for API token creation.
431
- */
432
- interface CreateApiTokenOptions {
433
- /**
434
- * Human-readable name for the token.
435
- */
436
- name: string;
437
- /**
438
- * User ID the token belongs to.
439
- */
440
- userId: string | number;
441
- /**
442
- * Token abilities/scopes.
443
- * @default ['*'] (all abilities)
444
- */
445
- abilities?: string[];
446
- /**
447
- * Token expiration time in milliseconds from now.
448
- * @default null (never expires)
449
- */
450
- expiresIn?: number | null;
451
- /**
452
- * Token byte length (before encoding).
453
- * @default 32
454
- */
455
- tokenLength?: number;
456
- }
457
- /**
458
- * Result of creating an API token.
459
- */
460
- interface CreateApiTokenResult {
461
- /**
462
- * The full token to give to the user.
463
- * Format: {id}|{plainToken}
464
- * This is the ONLY time the plain token is available.
465
- */
466
- plainTextToken: string;
467
- /**
468
- * The token record (without the plain token).
469
- */
470
- token: ApiToken;
471
- }
472
- /**
473
- * Create a new API token.
474
- *
475
- * @example
476
- * ```ts
477
- * const { plainTextToken, token } = await createApiToken(store, {
478
- * name: 'My App Token',
479
- * userId: user.id,
480
- * abilities: ['read', 'write'],
481
- * expiresIn: 30 * 24 * 60 * 60 * 1000, // 30 days
482
- * })
483
- *
484
- * // Return plainTextToken to user - this is the only time it's available
485
- * return ctx.json({ token: plainTextToken })
486
- * ```
487
- */
488
- declare function createApiToken(store: ApiTokenStore, options: CreateApiTokenOptions): Promise<CreateApiTokenResult>;
489
- /**
490
- * Parse a plain text token into its components.
491
- */
492
- declare function parseApiToken(plainTextToken: string): {
493
- id: string;
494
- token: string;
495
- } | null;
496
- /**
497
- * Verify an API token and return the associated user ID.
498
- *
499
- * @example
500
- * ```ts
501
- * const result = await verifyApiToken(plainTextToken, store)
502
- *
503
- * if (!result) {
504
- * return ctx.json({ error: 'Invalid token' }, 401)
505
- * }
506
- *
507
- * console.log(`User ${result.userId} authenticated with abilities:`, result.abilities)
508
- * ```
509
- */
510
- declare function verifyApiToken(plainTextToken: string, store: ApiTokenStore, options?: {
511
- updateLastUsed?: boolean;
512
- }): Promise<{
513
- token: ApiToken;
514
- userId: string | number;
515
- abilities: string[];
516
- } | null>;
517
- /**
518
- * Check if a token has a specific ability.
519
- */
520
- declare function tokenCan(token: ApiToken | {
521
- abilities: string[];
522
- }, ability: string): boolean;
523
- /**
524
- * Check if a token has all specified abilities.
525
- */
526
- declare function tokenCanAll(token: ApiToken | {
527
- abilities: string[];
528
- }, abilities: string[]): boolean;
529
- /**
530
- * Check if a token has any of the specified abilities.
531
- */
532
- declare function tokenCanAny(token: ApiToken | {
533
- abilities: string[];
534
- }, abilities: string[]): boolean;
535
- /**
536
- * Revoke (delete) an API token.
537
- *
538
- * @example
539
- * ```ts
540
- * await revokeApiToken(tokenId, store)
541
- * ```
542
- */
543
- declare function revokeApiToken(id: string, store: ApiTokenStore): Promise<void>;
544
- /**
545
- * Revoke all API tokens for a user.
546
- *
547
- * @example
548
- * ```ts
549
- * // Revoke all tokens when user changes password
550
- * await revokeAllApiTokens(user.id, store)
551
- * ```
552
- */
553
- declare function revokeAllApiTokens(userId: string | number, store: ApiTokenStore): Promise<void>;
554
- /**
555
- * Get all API tokens for a user.
556
- *
557
- * @example
558
- * ```ts
559
- * const tokens = await getUserApiTokens(user.id, store)
560
- * // Returns tokens without the plain text (only metadata)
561
- * ```
562
- */
563
- declare function getUserApiTokens(userId: string | number, store: ApiTokenStore): Promise<ApiToken[]>;
564
- /**
565
- * Context key for storing the authenticated token.
566
- */
567
- declare const API_TOKEN_KEY = "guren:api-token";
568
- /**
569
- * Options for the bearer token middleware.
570
- */
571
- interface BearerTokenMiddlewareOptions {
572
- /**
573
- * Token store implementation.
574
- */
575
- store: ApiTokenStore;
576
- /**
577
- * Function to load the user from the user ID.
578
- */
579
- loadUser?: (userId: string | number) => Promise<unknown>;
580
- /**
581
- * Required abilities for this route.
582
- * If not specified, any valid token is accepted.
583
- */
584
- abilities?: string[];
585
- /**
586
- * Custom handler when authentication fails.
587
- */
588
- onUnauthorized?: (ctx: Context) => Response | Promise<Response>;
589
- /**
590
- * Custom handler when token lacks required abilities.
591
- */
592
- onForbidden?: (ctx: Context, required: string[]) => Response | Promise<Response>;
593
- /**
594
- * Header name to extract the token from.
595
- * @default 'Authorization'
596
- */
597
- headerName?: string;
598
- /**
599
- * Whether to update the token's lastUsedAt timestamp.
600
- * @default true
601
- */
602
- updateLastUsed?: boolean;
603
- }
604
- /**
605
- * Create middleware that authenticates requests using Bearer tokens.
606
- *
607
- * @example
608
- * ```ts
609
- * // Basic usage
610
- * app.use('/api/*', createBearerTokenMiddleware({ store }))
611
- *
612
- * // With ability requirement
613
- * router.delete('/api/posts/:id', [PostController, 'destroy'],
614
- * createBearerTokenMiddleware({
615
- * store,
616
- * abilities: ['posts:delete'],
617
- * })
618
- * )
619
- *
620
- * // With user loading
621
- * app.use('/api/*', createBearerTokenMiddleware({
622
- * store,
623
- * loadUser: async (userId) => User.find(userId),
624
- * }))
625
- * ```
626
- */
627
- declare function createBearerTokenMiddleware(options: BearerTokenMiddlewareOptions): MiddlewareHandler;
628
- /**
629
- * Get the authenticated API token from the request context.
630
- *
631
- * @example
632
- * ```ts
633
- * router.get('/api/me', async (ctx) => {
634
- * const { token, userId, abilities } = getApiToken(ctx)!
635
- * return ctx.json({ userId, tokenName: token.name, abilities })
636
- * })
637
- * ```
638
- */
639
- declare function getApiToken(ctx: Context): {
640
- token: ApiToken;
641
- userId: string | number;
642
- abilities: string[];
643
- } | null;
644
- /**
645
- * Get the authenticated API token from the request context, or throw.
646
- *
647
- * @throws {AuthenticationException} When no token is present in the context.
648
- *
649
- * @example
650
- * ```ts
651
- * router.get('/api/me', async (ctx) => {
652
- * const { token, userId, abilities } = getApiTokenOrFail(ctx)
653
- * return ctx.json({ userId, tokenName: token.name, abilities })
654
- * })
655
- * ```
656
- */
657
- declare function getApiTokenOrFail(ctx: Context): {
658
- token: ApiToken;
659
- userId: string | number;
660
- abilities: string[];
661
- };
662
-
663
- export { getUserApiTokens as $, type Authenticatable as A, type BearerTokenMiddlewareOptions as B, type CreateSessionMiddlewareOptions as C, type DefaultSanitizedKeys as D, type Sanitized as E, type Session as F, type GuardFactory as G, buildOAuthAuthorizeUrl as H, buildOAuthRedirectUrl as I, createApiToken as J, createBearerTokenMiddleware as K, createDiscordOAuthProviderConfig as L, MemoryApiTokenStore as M, createGitHubOAuthProviderConfig as N, type OAuthStateStore as O, type ProviderFactory as P, createGoogleOAuthProviderConfig as Q, createOAuthManager as R, type SessionStore as S, createOAuthState as T, type UserProvider as U, createSessionMiddleware as V, exchangeOAuthCode as W, fetchOAuthUserProfile as X, getApiToken as Y, getApiTokenOrFail as Z, getSessionFromContext as _, type AuthCredentials as a, parseApiToken as a0, parseOAuthRedirectUrl as a1, revokeAllApiTokens as a2, revokeApiToken as a3, sanitizeOAuthRedirect as a4, tokenCan as a5, tokenCanAll as a6, tokenCanAny as a7, verifyApiToken as a8, verifyOAuthState as a9, type AuthManagerContract as b, type AuthManagerOptions as c, type GuardContext as d, type Guard as e, type AttachContextOptions as f, type AuthContext as g, type SessionData as h, type ApiTokenStore as i, type ApiToken as j, type OAuthStatePayload as k, OAuthManager as l, API_TOKEN_KEY as m, type CreateApiTokenOptions as n, type CreateApiTokenResult as o, MemoryOAuthStateStore as p, MemorySessionStore as q, type OAuthAuthorizeOptions as r, type OAuthCallbackPayload as s, type OAuthFallbackEmail as t, type OAuthManagerOptions as u, type OAuthProviderConfig as v, type OAuthProviderFactoryInput as w, type OAuthStateConfig as x, type OAuthTokenResult as y, type OAuthUserProfile as z };