@kerf-js/start 0.0.0-stage → 0.1.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 (236) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +1468 -2
  3. package/crate/Cargo.lock +1347 -0
  4. package/crate/Cargo.toml +72 -0
  5. package/crate/README.md +322 -0
  6. package/crate/rust-toolchain.toml +3 -0
  7. package/crate/src/build/emit.rs +103 -0
  8. package/crate/src/build.rs +367 -0
  9. package/crate/src/ctx.rs +186 -0
  10. package/crate/src/envelope.rs +163 -0
  11. package/crate/src/functions.rs +173 -0
  12. package/crate/src/lib.rs +118 -0
  13. package/crate/src/native.rs +212 -0
  14. package/crate/src/otel.rs +62 -0
  15. package/crate/src/server.rs +203 -0
  16. package/package.json +123 -3
  17. package/src/app.mjs +136 -0
  18. package/src/asset-receipt.d.mts +13 -0
  19. package/src/asset-receipt.mjs +61 -0
  20. package/src/auth/better-auth.ts +280 -0
  21. package/src/auth/drizzle.ts +17 -0
  22. package/src/auth/emails.ts +44 -0
  23. package/src/auth.ts +62 -0
  24. package/src/boot.ts +57 -0
  25. package/src/builtin.tsx +19 -0
  26. package/src/bus/postgres.ts +104 -0
  27. package/src/bus.ts +51 -0
  28. package/src/cache.ts +4 -0
  29. package/src/capture.ts +50 -0
  30. package/src/changes-sql.d.mts +20 -0
  31. package/src/changes-sql.mjs +115 -0
  32. package/src/changes.ts +352 -0
  33. package/src/channel/connections.ts +216 -0
  34. package/src/channel/socket.ts +396 -0
  35. package/src/channel-fake.ts +70 -0
  36. package/src/channel.ts +250 -0
  37. package/src/client.tsx +27 -0
  38. package/src/contract/describe.mjs +237 -0
  39. package/src/contract.mjs +299 -0
  40. package/src/cron.ts +74 -0
  41. package/src/data/after.ts +57 -0
  42. package/src/data/cache.ts +354 -0
  43. package/src/data/definitions.ts +94 -0
  44. package/src/data/draft.ts +104 -0
  45. package/src/data/foundation.ts +95 -0
  46. package/src/data/live-api.ts +22 -0
  47. package/src/data/mutation.ts +138 -0
  48. package/src/data/primitives.ts +135 -0
  49. package/src/data/query.ts +106 -0
  50. package/src/data/transport.ts +123 -0
  51. package/src/data/types.ts +333 -0
  52. package/src/data.ts +125 -0
  53. package/src/db/bun-sqlite.d.ts +13 -0
  54. package/src/db/changes-mysql.ts +126 -0
  55. package/src/db/changes-postgres.ts +238 -0
  56. package/src/db/changes-sqlite.ts +183 -0
  57. package/src/db/core.ts +95 -0
  58. package/src/db/index.ts +43 -0
  59. package/src/db/mysql.ts +84 -0
  60. package/src/db/postgres.ts +102 -0
  61. package/src/db/sqlite.ts +166 -0
  62. package/src/derive.d.mts +19 -0
  63. package/src/derive.mjs +237 -0
  64. package/src/dev-runtime.mjs +46 -0
  65. package/src/email.ts +146 -0
  66. package/src/exec/errors.ts +87 -0
  67. package/src/exec/impl.ts +21 -0
  68. package/src/exec/landing.ts +66 -0
  69. package/src/exec/limit.ts +25 -0
  70. package/src/exec/once.ts +24 -0
  71. package/src/exec/scope.ts +328 -0
  72. package/src/exec/touch.ts +80 -0
  73. package/src/exec/validation.ts +176 -0
  74. package/src/exec/warm.ts +50 -0
  75. package/src/exec.ts +400 -0
  76. package/src/extension.ts +48 -0
  77. package/src/first-paint.ts +74 -0
  78. package/src/form/value.ts +15 -0
  79. package/src/form.tsx +223 -0
  80. package/src/gate.css +6 -0
  81. package/src/hub/channels.ts +102 -0
  82. package/src/hub/connections.ts +147 -0
  83. package/src/hub/delivery.ts +62 -0
  84. package/src/hub/feed.ts +168 -0
  85. package/src/hub/presence.ts +64 -0
  86. package/src/hub/route.ts +159 -0
  87. package/src/hub/subscriptions.ts +213 -0
  88. package/src/hub/topic.ts +98 -0
  89. package/src/hub/tracked.ts +12 -0
  90. package/src/hub/types.ts +190 -0
  91. package/src/hub/view.ts +147 -0
  92. package/src/hub.ts +196 -0
  93. package/src/index.ts +184 -0
  94. package/src/inline.mjs +359 -0
  95. package/src/inspect/compare.mjs +162 -0
  96. package/src/inspect/routes.mjs +154 -0
  97. package/src/inspect/samples.mjs +59 -0
  98. package/src/inspect/url.mjs +2 -0
  99. package/src/inspect.mjs +239 -0
  100. package/src/jobs.ts +223 -0
  101. package/src/link/election.ts +178 -0
  102. package/src/link/lines.ts +27 -0
  103. package/src/link.ts +385 -0
  104. package/src/list-drizzle.ts +136 -0
  105. package/src/list.ts +315 -0
  106. package/src/listen.ts +54 -0
  107. package/src/live/api.ts +18 -0
  108. package/src/live/backoff.ts +6 -0
  109. package/src/live/frames.ts +42 -0
  110. package/src/live/read.ts +77 -0
  111. package/src/live/sub-types.ts +24 -0
  112. package/src/live/transport.ts +86 -0
  113. package/src/live/types.ts +52 -0
  114. package/src/live-fake.ts +57 -0
  115. package/src/live-target.mjs +231 -0
  116. package/src/live.ts +390 -0
  117. package/src/media.ts +50 -0
  118. package/src/migrations.mjs +27 -0
  119. package/src/mux-session.ts +6 -0
  120. package/src/mux.ts +232 -0
  121. package/src/og/DefaultCard.tsx +91 -0
  122. package/src/og/fonts.mjs +72 -0
  123. package/src/og/images.mjs +124 -0
  124. package/src/og/index.mjs +222 -0
  125. package/src/og/native.mjs +36 -0
  126. package/src/range.mjs +31 -0
  127. package/src/router.ts +199 -0
  128. package/src/routes.mjs +193 -0
  129. package/src/run/admission.ts +67 -0
  130. package/src/run/boot.tsx +115 -0
  131. package/src/run/cache-presentation.ts +67 -0
  132. package/src/run/cache.ts +254 -0
  133. package/src/run/helpers.ts +197 -0
  134. package/src/run/listeners.ts +166 -0
  135. package/src/run/navigation.ts +385 -0
  136. package/src/run/page-skeleton.tsx +35 -0
  137. package/src/run/prefetch.ts +129 -0
  138. package/src/run/retain-view.ts +18 -0
  139. package/src/run/shape-preparation.ts +97 -0
  140. package/src/run/shape-styles.ts +72 -0
  141. package/src/run/source-context/pin.ts +124 -0
  142. package/src/run/source-context.ts +311 -0
  143. package/src/run.tsx +74 -0
  144. package/src/rust/common.ts +163 -0
  145. package/src/rust/native.ts +282 -0
  146. package/src/rust.ts +207 -0
  147. package/src/server/background.ts +34 -0
  148. package/src/server/card.tsx +65 -0
  149. package/src/server/compression.ts +115 -0
  150. package/src/server/core.ts +70 -0
  151. package/src/server/cron.ts +49 -0
  152. package/src/server/dispatch.ts +73 -0
  153. package/src/server/form.ts +92 -0
  154. package/src/server/functions.ts +133 -0
  155. package/src/server/handler.ts +57 -0
  156. package/src/server/head.ts +96 -0
  157. package/src/server/health.ts +36 -0
  158. package/src/server/jobs.ts +112 -0
  159. package/src/server/lifecycle.ts +48 -0
  160. package/src/server/log.ts +42 -0
  161. package/src/server/media.ts +61 -0
  162. package/src/server/navigation-cache.ts +75 -0
  163. package/src/server/navigation.tsx +86 -0
  164. package/src/server/page-cold.ts +96 -0
  165. package/src/server/page-stream.tsx +181 -0
  166. package/src/server/page-types.ts +51 -0
  167. package/src/server/page-warm.ts +131 -0
  168. package/src/server/page.ts +69 -0
  169. package/src/server/payload.ts +89 -0
  170. package/src/server/prerender.ts +64 -0
  171. package/src/server/preview.tsx +67 -0
  172. package/src/server/render.ts +197 -0
  173. package/src/server/request.ts +192 -0
  174. package/src/server/resolver.ts +228 -0
  175. package/src/server/routes.ts +150 -0
  176. package/src/server/security.ts +50 -0
  177. package/src/server/services.ts +69 -0
  178. package/src/server/shutdown.ts +23 -0
  179. package/src/server/text.ts +29 -0
  180. package/src/server/types.ts +170 -0
  181. package/src/server.tsx +138 -0
  182. package/src/shape.d.mts +3 -0
  183. package/src/shape.mjs +97 -0
  184. package/src/share/display.ts +50 -0
  185. package/src/share/network.ts +119 -0
  186. package/src/share/receive.ts +70 -0
  187. package/src/share/state.ts +30 -0
  188. package/src/share/tab-queue.ts +28 -0
  189. package/src/share-server.ts +293 -0
  190. package/src/share.ts +397 -0
  191. package/src/sheets.mjs +87 -0
  192. package/src/sidecar/build.mjs +170 -0
  193. package/src/sidecar/cargo.mjs +164 -0
  194. package/src/sidecar/common.mjs +17 -0
  195. package/src/sidecar/dev-build.mjs +91 -0
  196. package/src/sidecar/dev-watch.mjs +88 -0
  197. package/src/sidecar/manifest.mjs +19 -0
  198. package/src/sidecar/process.mjs +58 -0
  199. package/src/sidecar/refresh.mjs +19 -0
  200. package/src/sidecar.mjs +162 -0
  201. package/src/socket/check.ts +50 -0
  202. package/src/socket/deliver.ts +16 -0
  203. package/src/socket/publish.ts +56 -0
  204. package/src/socket/rooms.ts +41 -0
  205. package/src/socket/route.ts +79 -0
  206. package/src/socket/shared.ts +26 -0
  207. package/src/socket/types.ts +48 -0
  208. package/src/socket.ts +400 -0
  209. package/src/stream.ts +22 -0
  210. package/src/verify/app.ts +39 -0
  211. package/src/verify/cleanup.ts +27 -0
  212. package/src/verify/database.ts +11 -0
  213. package/src/verify/live.ts +63 -0
  214. package/src/verify/notify.ts +35 -0
  215. package/src/verify/skip.ts +19 -0
  216. package/src/verify/support.ts +149 -0
  217. package/src/verify/timing.ts +15 -0
  218. package/src/verify/trigger.ts +14 -0
  219. package/src/verify.ts +152 -0
  220. package/src/view.tsx +132 -0
  221. package/src/vite/asset-bytes.mjs +95 -0
  222. package/src/vite/assets.mjs +117 -0
  223. package/src/vite/config-hooks.mjs +166 -0
  224. package/src/vite/dev-hooks.mjs +103 -0
  225. package/src/vite/dev.mjs +102 -0
  226. package/src/vite/entries.mjs +149 -0
  227. package/src/vite/module-hooks.mjs +290 -0
  228. package/src/vite/route-modules.mjs +289 -0
  229. package/src/vite/server-functions.mjs +222 -0
  230. package/src/vite/shape-entry-css.mjs +187 -0
  231. package/src/vite/shape-override.mjs +226 -0
  232. package/src/vite/shared.mjs +55 -0
  233. package/src/vite/sheets.mjs +92 -0
  234. package/src/vite/state.mjs +89 -0
  235. package/src/vite/syntax.mjs +139 -0
  236. package/src/vite.mjs +202 -0
@@ -0,0 +1,280 @@
1
+ // Better Auth as kerf's default auth provider (research 28 §3, 34 §5). `src/auth.server.ts` default-exports `createAuth(…)`.
2
+ // No client code: sign-in is a mutation, so nothing of Better Auth ships to the browser.
3
+
4
+ import { betterAuth, type BetterAuthOptions, type BetterAuthPlugin } from 'better-auth'
5
+ import { mailed } from './emails'
6
+ import { createAuthMiddleware } from 'better-auth/api'
7
+ import { expireCookie } from 'better-auth/cookies'
8
+ import { jwt, type JwtOptions } from 'better-auth/plugins/jwt'
9
+ import { CLIENT_IP, currentScope, fnOf, StartError } from '../data'
10
+ import type { DbHandle } from '../db/core'
11
+
12
+ const SESSION = /(?:^|;\s*)(?:__Secure-)?[\w.-]*session_token=/
13
+ const BEARER = /^Bearer\s+(\S+)$/i
14
+ const CHUNK = /^(?:__Secure-)?[\w.-]*session_data\.\d+=/
15
+ /** A socket or stream keeps its `ctx` past this request, and an extension's route is its own, so they never read the cache. */
16
+ const HELD = /^\/_kerf\/(rt|ws|x\/)/
17
+ const FN = '/_kerf/fn/'
18
+ const ANONYMOUS = { user: null, session: null }
19
+ const TABLES = ['user', 'session', 'account', 'verification', 'jwks']
20
+ const ROTATE = 60 * 60 * 24 * 30
21
+
22
+ /** A cache too big for one cookie is no cache: that session just reads the database. An expired chunk still goes out. */
23
+ const oversized = (line: string) =>
24
+ CHUNK.test(line) && !/max-age=0/i.test(line) && !/^[^=]+=;/.test(line)
25
+
26
+ /** Better Auth's own routes follow the rule `session()` does: only reading who you are can answer from the cache. */
27
+ const cacheRules: BetterAuthPlugin = {
28
+ id: 'kerf-session-cache',
29
+ hooks: {
30
+ // `/token` above all: a revoked session mustn't mint a 15-minute token from a cookie it still holds.
31
+ before: [
32
+ {
33
+ matcher: (c) => c.path !== '/get-session',
34
+ handler: createAuthMiddleware((c) =>
35
+ Promise.resolve({ context: { query: { ...c.query, disableCookieCache: true } } }),
36
+ ),
37
+ },
38
+ ],
39
+ // With `revokeOtherSessions` this response already carries the new session's cookies.
40
+ after: [
41
+ {
42
+ matcher: (c) => c.path === '/change-password',
43
+ handler: createAuthMiddleware((c) =>
44
+ Promise.resolve(
45
+ void (c.context.newSession || expireCookie(c, c.context.authCookies.sessionData)),
46
+ ),
47
+ ),
48
+ },
49
+ // Chunks go on every request after this one: a big enough user would pass the server's header limit and be locked out with 431s.
50
+ {
51
+ matcher: () => true,
52
+ handler: createAuthMiddleware((c) => {
53
+ const out = (c.context as { responseHeaders?: Headers }).responseHeaders
54
+ const all = out?.getSetCookie() ?? []
55
+ if (out && all.some(oversized)) {
56
+ out.delete('set-cookie')
57
+ for (const line of all) if (!oversized(line)) out.append('set-cookie', line)
58
+ }
59
+ return Promise.resolve()
60
+ }),
61
+ },
62
+ ],
63
+ },
64
+ }
65
+
66
+ /** `createAuth({ api })`: Better Auth's `jwt` options, and which server functions take a bearer token. */
67
+ export interface ApiAccess extends JwtOptions {
68
+ /** The server functions a bearer token may call, as a function so this module needn't load them first. No others read it. */
69
+ functions?: () => unknown[]
70
+ }
71
+ type Found = NonNullable<
72
+ Awaited<ReturnType<ReturnType<typeof betterAuth<BetterAuthOptions>>['api']['getSession']>>
73
+ >
74
+ type Session = { user: Found['user'] | null; session: Found['session'] | null }
75
+ /** What a token of ours carries: Better Auth's claims, the session it came from, and the user's fields. */
76
+ type Claims = {
77
+ sub: string
78
+ sid: string
79
+ iss?: string
80
+ aud?: string | string[]
81
+ exp?: number
82
+ iat?: number
83
+ } & Record<string, unknown>
84
+ /** The calls made here. The `jwt` plugin is optional, so `verifyJWT` isn't in the instance's own type. */
85
+ interface Methods {
86
+ verifyJWT(input: { body: { token: string } }): Promise<{ payload: Claims | null }>
87
+ getSession(input: {
88
+ headers: Headers
89
+ returnHeaders: true
90
+ query?: { disableCookieCache: boolean }
91
+ }): Promise<{ headers: Headers; response: Found | null }>
92
+ }
93
+ type Signed = Parameters<NonNullable<NonNullable<JwtOptions['jwt']>['definePayload']>>[0]
94
+
95
+ const buildSecret = () =>
96
+ Array.from(crypto.getRandomValues(new Uint8Array(32)), (x) =>
97
+ x.toString(16).padStart(2, '0'),
98
+ ).join('')
99
+
100
+ /** `createAuth`: the database, the secret, and any Better Auth option on top. */
101
+ export interface AuthOptions<S extends Record<string, unknown>, O extends BetterAuthOptions> {
102
+ db: { $kerf: DbHandle }
103
+ /** The tables, Better Auth's included, for a data layer that needs them. */
104
+ schema?: S
105
+ /** 32+ characters (A001 in production). */
106
+ secret?: string | undefined
107
+ /** The rest of Better Auth's options; they win over the defaults here. */
108
+ options?: O
109
+ /** Short-lived JWTs for other services and API clients, with a public JWKS: Better Auth's `jwt` options. `false` turns it off. */
110
+ api?: ApiAccess | false
111
+ }
112
+
113
+ function sessionReader(
114
+ auth: {
115
+ $context: Promise<{
116
+ internalAdapter: {
117
+ listSessions(
118
+ user: string,
119
+ options: { onlyActiveSessions: boolean },
120
+ ): Promise<{ id: string }[]>
121
+ }
122
+ }>
123
+ },
124
+ methods: Methods,
125
+ claims: { issuer?: string | undefined; audience?: string | string[] | undefined },
126
+ functions: (() => unknown[]) | undefined,
127
+ api: ApiAccess | false | undefined,
128
+ ) {
129
+ /** Who a token says, for a function that takes one. A write also needs the session behind it to still be there. */
130
+ async function bearer(token: string, read: boolean): Promise<Session> {
131
+ // Unchecked, Better Auth would skip `iss` and `aud`: with no URL configured, no token is good.
132
+ if (!claims.issuer || !claims.audience) return ANONYMOUS
133
+ const { payload } = await methods.verifyJWT({ body: { token } })
134
+ if (!payload) return ANONYMOUS
135
+ if (!read) {
136
+ const live = await (
137
+ await auth.$context
138
+ ).internalAdapter.listSessions(payload.sub, { onlyActiveSessions: true })
139
+ if (!live.some((s) => s.id === payload.sid)) return ANONYMOUS
140
+ }
141
+ const { iss: _iss, aud: _aud, exp: _exp, iat: _iat, sub, sid: _sid, ...user } = payload
142
+ return { user: { ...user, id: sub } as unknown as Found['user'], session: null }
143
+ }
144
+
145
+ const marked = (pathname: string) => {
146
+ if (!functions || !pathname.startsWith(FN)) return false
147
+ const id = pathname.slice(FN.length)
148
+ return functions().some((f) => encodeURIComponent((fnOf(f) as { $id: string }).$id) === id)
149
+ }
150
+
151
+ return async function session(request: Request): Promise<Session> {
152
+ const read = request.method === 'GET' || request.method === 'HEAD'
153
+ const { pathname } = new URL(request.url)
154
+ const token = request.headers.get('authorization')?.match(BEARER)?.[1]
155
+ if (token && api !== false && marked(pathname)) return bearer(token, read)
156
+ if (!SESSION.test(request.headers.get('cookie') ?? '')) return ANONYMOUS
157
+ const { headers, response: s } = await methods.getSession({
158
+ headers: request.headers,
159
+ returnHeaders: true,
160
+ ...(!(read && !HELD.test(pathname)) && { query: { disableCookieCache: true } }),
161
+ })
162
+ // A fresh cache cookie, a slid expiry or a dead session's removal. Not `forward`: who's signed in hasn't changed.
163
+ // A socket's re-check runs inside whichever request poked it, and its cookies are that socket's, not this response's.
164
+ const scope = currentScope() as { request?: Request; headers?: Headers } | undefined
165
+ if (scope?.headers && scope.request === request)
166
+ for (const c of headers.getSetCookie()) scope.headers.append('set-cookie', c)
167
+ return { user: s?.user ?? null, session: s?.session ?? null }
168
+ }
169
+ }
170
+
171
+ function requireStore(db: { $kerf: DbHandle }, options: BetterAuthOptions | undefined) {
172
+ const handle = db.$kerf
173
+ if (options?.database) for (const name of TABLES) handle.exempt.add(name)
174
+ else
175
+ throw new StartError(
176
+ 'A005',
177
+ 'Better Auth has no store',
178
+ "pass `options.database`: `drizzleAuth(db, schema)` from @kerf-js/start/auth/drizzle, or your data layer's adapter",
179
+ )
180
+ }
181
+
182
+ /** The `jwt` plugin: a new signing key every 30 days; old ones keep verifying for Better Auth's grace period (30 days). */
183
+ function apiTokens(access: Omit<ApiAccess, 'functions'>, claims: JwtOptions['jwt']) {
184
+ return jwt({
185
+ ...access,
186
+ jwks: { rotationInterval: ROTATE, ...access.jwks },
187
+ jwt: claims,
188
+ disableSettingJwtHeader: true,
189
+ })
190
+ }
191
+
192
+ /** A production server's secret (A001) and its own URL (A007). */
193
+ function checkServer(secret: string | undefined, origin: unknown) {
194
+ if (process.env.NODE_ENV !== 'production') return
195
+ if ((secret?.length ?? 0) < 32)
196
+ throw new StartError(
197
+ 'A001',
198
+ 'the auth secret is missing or under 32 characters',
199
+ "set `BETTER_AUTH_SECRET` (`openssl rand -base64 32`) in the server's environment",
200
+ )
201
+ // Without it Better Auth takes its origin from each request's Host header: a forged Host would steer the links in
202
+ // reset and verification emails, and the origin check, to another site.
203
+ if (!origin)
204
+ throw new StartError(
205
+ 'A007',
206
+ "the auth server's own URL is missing",
207
+ "set `BETTER_AUTH_URL` (`https://your.site`) in the server's environment, or pass `options.baseURL`",
208
+ )
209
+ }
210
+
211
+ /** A Better Auth instance with Kerf's defaults, on the store `options.database` names. */
212
+ export function createAuth<
213
+ S extends Record<string, unknown>,
214
+ const O extends BetterAuthOptions = {},
215
+ >({ db, secret, options, api }: AuthOptions<S, O>) {
216
+ requireStore(db, options)
217
+ const { functions, ...access } = api || {}
218
+ const origin =
219
+ typeof options?.baseURL === 'string' ? options.baseURL : process.env.BETTER_AUTH_URL
220
+ const claims = {
221
+ expirationTime: '15m',
222
+ issuer: origin,
223
+ audience: origin,
224
+ ...access.jwt,
225
+ // Which session a token came from, so a write can ask whether it still exists.
226
+ definePayload: async (s: Signed) => ({
227
+ ...((await access.jwt?.definePayload?.(s)) ?? s.user),
228
+ sid: s.session.id,
229
+ }),
230
+ }
231
+ const auth = betterAuth({
232
+ // A build loads this module with no environment, and in production Better Auth refuses to start without a secret: the
233
+ // build gets one of its own, since nothing it makes is signed. A server still needs the real one (A001).
234
+ secret: secret ?? (process.env.KERF_BUILD ? buildSecret() : undefined),
235
+ // A build's prerender holds no environment; a server takes `BETTER_AUTH_URL`, or the request's origin.
236
+ ...(process.env.KERF_BUILD && { baseURL: 'http://localhost' }),
237
+ telemetry: { enabled: false },
238
+ ...options,
239
+ ...mailed(options),
240
+ // Login stays an opaque token in the database. This only spares reads of it, for a window: see `session()`.
241
+ session: {
242
+ ...options?.session,
243
+ cookieCache: {
244
+ enabled: true,
245
+ maxAge: 300,
246
+ strategy: 'compact',
247
+ ...options?.session?.cookieCache,
248
+ },
249
+ },
250
+ // Signing a JWT on every session read would put a query back on each page, and login has no use for one.
251
+ plugins: [
252
+ ...(options?.plugins ?? []),
253
+ cacheRules,
254
+ ...(api === false ? [] : [apiTokens(access, claims)]),
255
+ ],
256
+ // The server stamps this header from the socket (server.tsx), so rate limits aren't one bucket for everyone.
257
+ // Its schema check runs when this module loads. On Kysely that connects, in a build, and before a fresh database has
258
+ // had kerf's migrations. Q014 covers a schema that doesn't match, so it's off unless you turn it on.
259
+ advanced: {
260
+ ...options?.advanced,
261
+ database: { validateSchema: false, ...options?.advanced?.database },
262
+ ipAddress: { ipAddressHeaders: [CLIENT_IP], ...options?.advanced?.ipAddress },
263
+ },
264
+ })
265
+ const methods = auth.api as unknown as Methods
266
+
267
+ return Object.assign(auth, {
268
+ basePath: options?.basePath,
269
+ /**
270
+ * With no session cookie it's `null` without a query, so anonymous pages don't touch the database. A page or query
271
+ * reads the signed cookie cache; a mutation (not GET) and anything that outlives the request read the database, so a
272
+ * revoked session may be shown a page for the cache's window but can't write.
273
+ */
274
+ session: sessionReader(auth, methods, claims, functions, api),
275
+ $kerf: {
276
+ /** On the first request (never in a build, which holds no secrets). */
277
+ check: () => checkServer(secret, origin ?? options?.baseURL),
278
+ },
279
+ })
280
+ }
@@ -0,0 +1,17 @@
1
+ // Better Auth on a Drizzle client, as `options.database`. It's an entry of its own so that a Drizzle app without auth
2
+ // needs no better-auth, and an app on another data layer needs no drizzle-orm.
3
+
4
+ import { drizzleAdapter } from 'better-auth/adapters/drizzle'
5
+ import { getTableName, isTable } from 'drizzle-orm'
6
+ import type { DbHandle } from '../db/core'
7
+
8
+ const PROVIDER = { sqlite: 'sqlite', postgresql: 'pg', mysql: 'mysql' } as const
9
+
10
+ /** Better Auth's store on a Kerf database, for `createAuth`'s `options.database`. */
11
+ export function drizzleAuth(db: { $kerf: DbHandle }, schema?: Record<string, unknown>) {
12
+ for (const name of ['user', 'session', 'account', 'verification', 'jwks']) {
13
+ const t = schema?.[name]
14
+ if (isTable(t)) db.$kerf.exempt.add(getTableName(t))
15
+ }
16
+ return drizzleAdapter(db, { provider: PROVIDER[db.$kerf.dialect], schema })
17
+ }
@@ -0,0 +1,44 @@
1
+ import type { BetterAuthOptions } from 'better-auth'
2
+ import { sendEmail } from '../email'
3
+
4
+ type Mailed = Pick<BetterAuthOptions, 'emailAndPassword' | 'emailVerification'>
5
+ interface Link {
6
+ user: { email: string; name?: string | null }
7
+ url: string
8
+ }
9
+
10
+ const greet = (user: Link['user']) => (user.name ? `Hi ${user.name},` : 'Hi,')
11
+
12
+ /**
13
+ * Better Auth's reset and verification emails, sent through `sendEmail` (the app's mailer, `RESEND_API_KEY`,
14
+ * `SMTP_URL`, or the console in dev) unless the app passed its own. The mailer is found when one is sent, not here.
15
+ */
16
+ export function mailed(options: BetterAuthOptions | undefined): Mailed {
17
+ const password = { enabled: true, ...options?.emailAndPassword }
18
+ return {
19
+ emailAndPassword: {
20
+ ...password,
21
+ sendResetPassword:
22
+ password.sendResetPassword ??
23
+ (async ({ user, url }: Link) => {
24
+ await sendEmail({
25
+ to: user.email,
26
+ subject: 'Reset your password',
27
+ text: `${greet(user)}\n\nOpen this link to choose a new password:\n${url}\n\nIf you didn't ask for this, ignore this email.`,
28
+ })
29
+ }),
30
+ },
31
+ emailVerification: {
32
+ ...options?.emailVerification,
33
+ sendVerificationEmail:
34
+ options?.emailVerification?.sendVerificationEmail ??
35
+ (async ({ user, url }: Link) => {
36
+ await sendEmail({
37
+ to: user.email,
38
+ subject: 'Confirm your email',
39
+ text: `${greet(user)}\n\nOpen this link to confirm your email address:\n${url}`,
40
+ })
41
+ }),
42
+ },
43
+ }
44
+ }
package/src/auth.ts ADDED
@@ -0,0 +1,62 @@
1
+ // `@kerf-js/start/auth`: what kerf needs from any auth provider (research 34 §5). A provider is `src/auth.server.ts`'s default
2
+ // export: `handler` serves its routes under `basePath`, and `session` says who a request is. Nothing here knows Better
3
+ // Auth (`@kerf-js/start/auth/better-auth`, the default), so a hand-written provider has no private path to work around.
4
+
5
+ import { FnError, type Context } from './data'
6
+
7
+ /** Where a session comes from: Better Auth by default, or anything with a `handler` and a `session`. */
8
+ export interface AuthProvider<U = unknown, S = unknown> {
9
+ /** Serves everything under `basePath`. */
10
+ handler(request: Request): Promise<Response> | Response
11
+ /**
12
+ * Who this request is. Anonymous is `{ user: null, session: null }`, and should cost no query. A provider that caches
13
+ * sessions may answer a GET from the cache, and must ask its store for any other method: that's what a mutation runs on.
14
+ */
15
+ session(request: Request): Promise<{ user: U | null; session: S | null }>
16
+ /** Where `handler` is mounted (default `/api/auth`). */
17
+ basePath?: string | undefined
18
+ $kerf?: {
19
+ /** On the first request, never in a build: throw for a server that can't run safely. */
20
+ check(): void
21
+ }
22
+ }
23
+
24
+ /** A provider you wrote: checks its shape, and types `ctx.user` from your `session`. */
25
+ export function defineAuth<U, S>(provider: AuthProvider<U, S>): AuthProvider<U, S> {
26
+ return provider
27
+ }
28
+
29
+ /** `{ user, session }` for `ctx` (`src/context.server.ts`), from any provider. */
30
+ export const session = <A extends { session(request: Request): unknown }>(
31
+ auth: A,
32
+ request: Request,
33
+ ): ReturnType<A['session']> => auth.session(request) as ReturnType<A['session']>
34
+
35
+ const changed = new WeakSet<Headers>()
36
+
37
+ /** `forward` put a provider's cookie on this response, so who's signed in may have changed. */
38
+ export const sessionChanged = (headers: Headers) => changed.has(headers)
39
+
40
+ /**
41
+ * Finish a provider's Response (Better Auth's with `asResponse: true`): its cookies go on this response, so a redirect
42
+ * after it is a full load, and a failure rejects with the provider's message (`e.message` on the client).
43
+ */
44
+ export async function forward<T = unknown>(
45
+ ctx: Context,
46
+ call: Response | Promise<Response>,
47
+ ): Promise<T> {
48
+ const res = await call
49
+ for (const c of res.headers.getSetCookie()) {
50
+ ctx.response.headers.append('set-cookie', c)
51
+ changed.add(ctx.response.headers)
52
+ }
53
+ const body = (await res.json().catch(() => null)) as
54
+ | (T & { code?: string; message?: string })
55
+ | null
56
+ if (!res.ok)
57
+ throw new FnError(
58
+ { ...(body?.code && { code: body.code }), message: body?.message ?? 'Authentication failed' },
59
+ res.status,
60
+ )
61
+ return body as T
62
+ }
package/src/boot.ts ADDED
@@ -0,0 +1,57 @@
1
+ // All a page that's only being read runs (PLAN §11). It starts `full` (the router, the runtime) when the page needs code at once, when something happens on an island, or when an island that
2
+ // wants to be running, or that isn't in the first view and so wasn't preloaded, comes into view. A visitor who asked for
3
+ // less data gets it on interaction only. `#kerf-route` and the islands' comments are read by `start()` once it's here.
4
+
5
+ /** What the inline script left on `window`: the queue, and how to play or wake it. */
6
+ export interface Held {
7
+ q: unknown[]
8
+ p: (held: unknown) => void
9
+ w?: (k: Element, lead?: 1) => void
10
+ r?: 1
11
+ /** The page is running: a page that hydrates whole stops holding events off its islands. */
12
+ s?: 1
13
+ n?: unknown
14
+ l?: Element
15
+ d?: unknown
16
+ }
17
+
18
+ export function boot(full: () => Promise<unknown>) {
19
+ const q = (window as Window & { __wq?: Held }).__wq
20
+ let io: IntersectionObserver | undefined // oxlint-disable-line prefer-const -- `go` reads it, and can run before it's set
21
+ const go = () => {
22
+ if (q) q.w = () => {}
23
+ io?.disconnect()
24
+ full().catch(() => {
25
+ // No code is coming: what's held takes its default.
26
+ if (!q) return
27
+ q.r = 1
28
+ q.q.splice(0).forEach(q.p)
29
+ })
30
+ }
31
+ if (!q || q.n || q.q.length) return go()
32
+ q.w = (k: Element, lead?: 1) => {
33
+ if (lead) q.l = k
34
+ go()
35
+ }
36
+ if (q.d) return
37
+ const first = new WeakSet<Element>()
38
+ const needs = new WeakSet<Element>()
39
+ io = new IntersectionObserver(
40
+ (list) => {
41
+ for (const e of list) {
42
+ const was = first.has(e.target)
43
+ first.add(e.target)
44
+ if (e.isIntersecting && (was || needs.has(e.target))) return go()
45
+ }
46
+ },
47
+ { rootMargin: '600px' },
48
+ )
49
+ const w = document.createTreeWalker(document.body, 128)
50
+ while (w.nextNode()) {
51
+ const c = w.currentNode as Comment
52
+ const el = c.data.startsWith('wi:') && c.nextElementSibling
53
+ if (!el) continue
54
+ if (JSON.parse(c.data.slice(3))[3] === 'v') needs.add(el)
55
+ io.observe(el)
56
+ }
57
+ }
@@ -0,0 +1,19 @@
1
+ // The 404 and error pages an app gets until it adds `src/routes/404.tsx` or `src/routes/_error.tsx`.
2
+
3
+ export function NotFoundPage(props: { data: { path?: string } }) {
4
+ return (
5
+ <main>
6
+ <h1>Not found</h1>
7
+ <p>Nothing lives at {props.data?.path}.</p>
8
+ </main>
9
+ )
10
+ }
11
+
12
+ export function ErrorPage(props: { data: { status: number; message: string } }) {
13
+ return (
14
+ <main>
15
+ <h1>Something went wrong</h1>
16
+ <p>{props.data?.message}</p>
17
+ </main>
18
+ )
19
+ }
@@ -0,0 +1,104 @@
1
+ // LISTEN/NOTIFY (research 30 §3): one dedicated connection and one Postgres channel, with the logical channel in the
2
+ // payload, because Postgres identifiers stop at 63 bytes and tags don't. NOTIFY stops at 8,000 bytes, so a longer
3
+ // message goes base64 in numbered chunks inside one transaction, which Postgres delivers together and in order.
4
+
5
+ import postgres from 'postgres'
6
+ import type { Bus } from '../bus'
7
+ import { StartError } from '../data'
8
+
9
+ /** `postgresBus`: the database to send NOTIFY through. */
10
+ export interface PostgresBusOptions {
11
+ /** `postgres://…`, direct: pgBouncer in transaction mode breaks LISTEN. */
12
+ url: string
13
+ }
14
+
15
+ const CHANNEL = 'kerf_bus'
16
+ const WHOLE = 7_900
17
+ const CHUNK = 7_800
18
+
19
+ function delivery(listeners: Map<string, Set<(message: string) => void>>) {
20
+ return (text: string) => {
21
+ const at = text.indexOf('\n')
22
+ const list = listeners.get(text.slice(0, at))
23
+ if (list) for (const on of list) on(text.slice(at + 1))
24
+ }
25
+ }
26
+
27
+ /** A bus on Postgres NOTIFY, for several instances with no broker beside the database. */
28
+ export function postgresBus({ url }: PostgresBusOptions): Bus {
29
+ if (!url && process.env.KERF_BUILD) url = 'postgres://localhost/build' // a build loads this module and never connects
30
+ if (!/^postgres(ql)?:\/\//.test(url ?? ''))
31
+ throw new StartError(
32
+ 'Q013',
33
+ `\`postgresBus\` needs a \`postgres://\` URL, not \`${(url ?? '').replace(/\/\/.*@/, '//…@')}\``,
34
+ 'set `DATABASE_URL`, or leave `bus` out for the memory bus on one instance',
35
+ )
36
+ let sql: ReturnType<typeof postgres> | undefined
37
+ const client = () => (sql ??= postgres(url, { max: 2, idle_timeout: 20, onnotice: () => {} }))
38
+ const listeners = new Map<string, Set<(message: string) => void>>()
39
+ const gaps = new Set<() => void>()
40
+ const parts = new Map<string, string[]>()
41
+ let listening: Promise<unknown> | undefined
42
+ let connected = false
43
+
44
+ const deliver = delivery(listeners)
45
+ const received = (payload: string) => {
46
+ if (payload[0] === '=') return deliver(payload.slice(1))
47
+ const [id, i, n, body] = payload.slice(1).split(':')
48
+ if (id === undefined || i === undefined || n === undefined || body === undefined)
49
+ return undefined
50
+ const got = parts.get(id) ?? []
51
+ got[+i] = body
52
+ parts.set(id, got)
53
+ if (Object.keys(got).length < +n) return undefined
54
+ parts.delete(id)
55
+ deliver(Buffer.from(got.join(''), 'base64').toString())
56
+ }
57
+ /** `onlisten` runs on every (re)connect: after the first, whatever was published meanwhile is gone. */
58
+ const listen = () =>
59
+ (listening ??= client()
60
+ .listen(CHANNEL, received, () => {
61
+ if (connected) {
62
+ parts.clear()
63
+ for (const gap of gaps) gap()
64
+ }
65
+ connected = true
66
+ })
67
+ .catch((e) => {
68
+ listening = undefined // the next subscribe tries again
69
+ throw e
70
+ }))
71
+
72
+ return {
73
+ name: 'postgres',
74
+ async publish(channel, message) {
75
+ const text = `${channel}\n${message}`
76
+ if (Buffer.byteLength(text) <= WHOLE) return void (await client().notify(CHANNEL, '=' + text))
77
+ const b64 = Buffer.from(text).toString('base64')
78
+ const id = crypto.randomUUID()
79
+ const n = Math.ceil(b64.length / CHUNK)
80
+ await client().begin(async (tx) => {
81
+ for (let i = 0; i < n; i++)
82
+ await tx`select pg_notify(${CHANNEL}, ${`+${id}:${i}:${n}:${b64.slice(i * CHUNK, (i + 1) * CHUNK)}`})`
83
+ })
84
+ },
85
+ async subscribe(channel, on, gap) {
86
+ let list = listeners.get(channel)
87
+ if (!list) listeners.set(channel, (list = new Set()))
88
+ list.add(on)
89
+ if (gap) gaps.add(gap)
90
+ await listen()
91
+ return () => {
92
+ list.delete(on)
93
+ if (!list.size) listeners.delete(channel)
94
+ if (gap) gaps.delete(gap)
95
+ }
96
+ },
97
+ async close() {
98
+ await sql?.end({ timeout: 1 })
99
+ sql = undefined
100
+ listening = undefined
101
+ connected = false
102
+ },
103
+ }
104
+ }
package/src/bus.ts ADDED
@@ -0,0 +1,51 @@
1
+ // The fan-out bus (research 30 §3): strings, at-most-once, ordered per publisher. Tags, topics, rings and cursors stay
2
+ // in the hub, so a bus is three methods. `@kerf-js/realtime-redis`, `-nats` and `-durable-object` implement this interface.
3
+
4
+ /** How one instance reaches the others: the in-memory bus for one process, a plugin's for many. */
5
+ export interface Bus {
6
+ readonly name: string
7
+ publish(channel: string, message: string): Promise<void>
8
+ /**
9
+ * Resolves once listening, with the way to stop. `gap` means messages may have been lost (a dropped connection):
10
+ * the hub treats everything before it as out of the resume window.
11
+ */
12
+ subscribe(channel: string, on: (message: string) => void, gap?: () => void): Promise<() => void>
13
+ close?(): Promise<void>
14
+ }
15
+
16
+ /** The bus a `realtime.bus` plugin provides, loaded on the first publish or subscribe: `kerf build` reaches for neither. */
17
+ export function slotBus(plugin: string, load: () => Promise<Bus>): Bus {
18
+ let bus: Promise<Bus> | undefined
19
+ const get = () => (bus ??= load())
20
+ return {
21
+ name: plugin.replace(/^.*realtime-/, ''),
22
+ publish: (channel, message) => get().then((b) => b.publish(channel, message)),
23
+ subscribe: (channel, on, gap) => get().then((b) => b.subscribe(channel, on, gap)),
24
+ close: () => (bus ? bus.then((b) => b.close?.()) : Promise.resolve()),
25
+ }
26
+ }
27
+
28
+ /** One process (PLAN §4.2). Delivered in a microtask: no code may rely on a fan-out no other bus has. */
29
+ export function memoryBus(): Bus {
30
+ const channels = new Map<string, Set<(message: string) => void>>()
31
+ return {
32
+ name: 'memory',
33
+ publish(channel, message) {
34
+ const list = channels.get(channel)
35
+ if (list)
36
+ queueMicrotask(() => {
37
+ for (const on of list) on(message)
38
+ })
39
+ return Promise.resolve()
40
+ },
41
+ subscribe(channel, on) {
42
+ let list = channels.get(channel)
43
+ if (!list) channels.set(channel, (list = new Set()))
44
+ list.add(on)
45
+ return Promise.resolve(() => {
46
+ list.delete(on)
47
+ if (!list.size) channels.delete(channel)
48
+ })
49
+ },
50
+ }
51
+ }
package/src/cache.ts ADDED
@@ -0,0 +1,4 @@
1
+ // `@kerf-js/start/cache`: what `src/cache.server.ts` default-exports, the store behind `query({ cache })`.
2
+ // Memory (one process, bounded) unless the app picks another; `redisStore()` in @kerf-js/realtime-redis shares it.
3
+ export { memoryStore } from './exec/scope'
4
+ export type { MemoryLimits, Store, Stored } from './exec/scope'