@kerf-js/start 0.1.2-nightly.20261118.85 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/app.mjs +42 -36
- package/src/contract.mjs +3 -11
- package/src/dev-runtime.mjs +103 -34
- package/src/inspect/server.mjs +16 -0
- package/src/inspect.mjs +4 -11
- package/src/server/form.ts +4 -3
- package/src/server/functions.ts +6 -3
- package/src/server/node-preset.mjs +4 -2
- package/src/server/origin.ts +33 -0
- package/src/sidecar/dev-watch.mjs +32 -12
- package/src/vite/build-paths.d.mts +2 -0
- package/src/vite/build-paths.mjs +45 -0
- package/src/vite/config-hooks.mjs +4 -1
- package/src/vite/dev-hooks.mjs +16 -8
- package/src/vite/entries.mjs +7 -2
- package/src/vite/module-hooks.mjs +15 -3
- package/src/vite/nitro-output.d.mts +8 -0
- package/src/vite/nitro-output.mjs +291 -0
- package/src/vite/output-manifests.d.mts +7 -0
- package/src/vite/output-manifests.mjs +75 -0
- package/src/vite/route-modules.mjs +3 -3
- package/src/vite/shared.mjs +18 -1
- package/src/vite/sheets.mjs +13 -8
- package/src/vite/state.mjs +16 -1
- package/src/vite/trace-deps.mjs +77 -0
- package/src/vite.mjs +22 -35
- package/src/watch-tree.mjs +26 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kerf-js/start",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "kerf Start: file routes, server functions, streaming SSR, a database and auth",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"kerf"
|
|
@@ -86,7 +86,7 @@
|
|
|
86
86
|
"vite": "8.3.5"
|
|
87
87
|
},
|
|
88
88
|
"peerDependencies": {
|
|
89
|
-
"@kerf-js/core": "^0.1.
|
|
89
|
+
"@kerf-js/core": "^0.1.3",
|
|
90
90
|
"better-auth": "^1.7.0",
|
|
91
91
|
"drizzle-orm": "^0.45.0",
|
|
92
92
|
"drizzle-zod": "^0.8.0",
|
package/src/app.mjs
CHANGED
|
@@ -1,18 +1,21 @@
|
|
|
1
|
-
// `kerf dev` and `kerf build` for an app with src/routes
|
|
1
|
+
// `kerf dev` and `kerf build` for an app with src/routes: Vite 8 with kerf() (hydratable output),
|
|
2
2
|
// kerfStart() and Nitro's Vite plugin. A vite.config in the app is merged in. The CLI passes the config's `site`.
|
|
3
3
|
|
|
4
|
-
import { existsSync, readFileSync, readdirSync } from 'node:fs'
|
|
4
|
+
import { existsSync, readFileSync, readdirSync, realpathSync } from 'node:fs'
|
|
5
5
|
import { join, resolve } from 'node:path'
|
|
6
6
|
import { fileURLToPath } from 'node:url'
|
|
7
7
|
import { createBuilder, createServer } from 'vite'
|
|
8
8
|
import { nitro } from 'nitro/vite'
|
|
9
9
|
import kerf from '@kerf-js/core/vite'
|
|
10
|
-
import { devRunner,
|
|
10
|
+
import { devRunner, devRuntime } from './dev-runtime.mjs'
|
|
11
11
|
import { pageSockets } from './live-target.mjs'
|
|
12
12
|
import kerfStart, { startDir } from './vite.mjs'
|
|
13
13
|
import { ownNodePreset } from './server/node-preset.mjs'
|
|
14
|
+
import { buildDate, finalizeBuild, nitroOutput } from './vite/nitro-output.mjs'
|
|
15
|
+
import { labelChunkGroups } from './vite/shared.mjs'
|
|
16
|
+
import { externalAddons, traceDeps } from './vite/trace-deps.mjs'
|
|
14
17
|
|
|
15
|
-
/**
|
|
18
|
+
/** Enable crossws only for apps that declare a channel or shared state. */
|
|
16
19
|
function usesSockets(root) {
|
|
17
20
|
const src = join(root, 'src')
|
|
18
21
|
if (!existsSync(src)) return false
|
|
@@ -33,8 +36,10 @@ function config({
|
|
|
33
36
|
logLevel,
|
|
34
37
|
command,
|
|
35
38
|
nitro: nitroOptions = {},
|
|
39
|
+
production,
|
|
40
|
+
refreshPlugins,
|
|
36
41
|
}) {
|
|
37
|
-
root = resolve(root)
|
|
42
|
+
root = command === 'build' ? realpathSync(root) : resolve(root)
|
|
38
43
|
const sockets = usesSockets(root)
|
|
39
44
|
const runner = devRunner(sockets)
|
|
40
45
|
const user = ['vite.config.ts', 'vite.config.mts', 'vite.config.js', 'vite.config.mjs']
|
|
@@ -54,7 +59,7 @@ function config({
|
|
|
54
59
|
plugins: [
|
|
55
60
|
kerf({ hydratable: site?.render !== 'shell', csp: site?.csp }),
|
|
56
61
|
kerfStart({ root, site, hydration }),
|
|
57
|
-
|
|
62
|
+
refreshPlugins && devRuntime(refreshPlugins),
|
|
58
63
|
nitro({
|
|
59
64
|
preset,
|
|
60
65
|
// Every app gets this: built assets ship as .br and .gz next to the file, and Nitro picks by Accept-Encoding.
|
|
@@ -66,23 +71,31 @@ function config({
|
|
|
66
71
|
}),
|
|
67
72
|
...(sockets && { features: { websocket: true } }),
|
|
68
73
|
...(runner && { devServer: { runner } }),
|
|
69
|
-
//
|
|
74
|
+
// The server lists share cards so Nitro can prerender the PNGs.
|
|
70
75
|
...(site?.render !== 'shell' && {
|
|
71
76
|
prerender: { routes: ['/_kerf/og-routes'], failOnError: true },
|
|
72
77
|
}),
|
|
73
78
|
// Prerendered cards are static files at content-addressed URLs: immutable. The rule names each file (a
|
|
74
79
|
// `/_kerf/og/**` rule would also override the handler's no-cache for a stale `?v=` on demand). Prerender runs
|
|
75
80
|
// before Nitro bundles the server, so rules added when it is done are in the build. (Dev sends no-store.)
|
|
76
|
-
...
|
|
81
|
+
...traceDeps(root),
|
|
77
82
|
...nitroOptions,
|
|
78
83
|
...(command === 'build' && {
|
|
79
84
|
hooks: {
|
|
80
|
-
...(site?.render
|
|
85
|
+
...(site?.render !== 'shell' && immutableCards()),
|
|
81
86
|
...nitroOptions.hooks,
|
|
87
|
+
async compiled(instance) {
|
|
88
|
+
production.output = instance.options.output
|
|
89
|
+
await nitroOptions.hooks?.compiled?.(instance)
|
|
90
|
+
},
|
|
82
91
|
async 'build:before'(instance) {
|
|
83
92
|
await nitroOptions.hooks?.['build:before']?.(instance)
|
|
84
93
|
ownNodePreset(instance, site)
|
|
85
94
|
},
|
|
95
|
+
async 'rollup:before'(instance, bundle) {
|
|
96
|
+
await nitroOptions.hooks?.['rollup:before']?.(instance, bundle)
|
|
97
|
+
shapeBundle(instance, bundle, production.date)
|
|
98
|
+
},
|
|
86
99
|
},
|
|
87
100
|
plugins: [
|
|
88
101
|
fileURLToPath(new URL('./range.mjs', import.meta.url)),
|
|
@@ -94,26 +107,12 @@ function config({
|
|
|
94
107
|
}
|
|
95
108
|
}
|
|
96
109
|
|
|
97
|
-
/**
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
...(existsSync(join(root, '.kerf/slots/media.server.ts'))
|
|
104
|
-
? ['css-tree*', 'csso*', 'sharp*']
|
|
105
|
-
: []),
|
|
106
|
-
...(existsSync(join(root, 'node_modules/nodemailer')) ? ['nodemailer*'] : []),
|
|
107
|
-
]
|
|
108
|
-
return deps.length ? { traceDeps: deps } : {}
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/** Where the last build's Nitro wrote. A preset may move it (Netlify serves `dist`). */
|
|
112
|
-
let wrote
|
|
113
|
-
|
|
114
|
-
function recordOutput(instance) {
|
|
115
|
-
const { dir, publicDir } = instance.options.output
|
|
116
|
-
wrote = publicDir.startsWith(dir) ? dir : publicDir
|
|
110
|
+
/** What Start adds to each bundle Nitro builds: the prerender's and the server's. */
|
|
111
|
+
function shapeBundle(instance, bundle, date) {
|
|
112
|
+
bundle.plugins.push(nitroOutput(instance, date))
|
|
113
|
+
// the prerender bundle resolves without tracing; the server's bundle traces the addon into `.output`
|
|
114
|
+
if (instance.options.preset === 'nitro-prerender') bundle.plugins.push(externalAddons())
|
|
115
|
+
labelChunkGroups(bundle, 'nitro')
|
|
117
116
|
}
|
|
118
117
|
|
|
119
118
|
function immutableCards() {
|
|
@@ -121,7 +120,6 @@ function immutableCards() {
|
|
|
121
120
|
return {
|
|
122
121
|
'prerender:generate'(_route, instance) {
|
|
123
122
|
built = instance
|
|
124
|
-
recordOutput(instance)
|
|
125
123
|
},
|
|
126
124
|
'prerender:done'({ prerenderedRoutes }) {
|
|
127
125
|
if (!built) return
|
|
@@ -138,21 +136,29 @@ function immutableCards() {
|
|
|
138
136
|
|
|
139
137
|
/** Start the dev server; resolves with it once it listens. */
|
|
140
138
|
export async function dev(options) {
|
|
141
|
-
const
|
|
142
|
-
await
|
|
143
|
-
|
|
139
|
+
const refreshPlugins = () => config({ ...options, refreshPlugins }).plugins
|
|
140
|
+
const server = await createServer(config({ ...options, refreshPlugins }))
|
|
141
|
+
try {
|
|
142
|
+
await server.listen()
|
|
143
|
+
return server
|
|
144
|
+
} catch (error) {
|
|
145
|
+
await server.close()
|
|
146
|
+
throw error
|
|
147
|
+
}
|
|
144
148
|
}
|
|
145
149
|
|
|
146
150
|
/** Build client and server for `preset` (node by default; bun, deno_server…), into `.output/` unless the preset moves it. */
|
|
147
151
|
export async function build(options) {
|
|
152
|
+
const production = { date: buildDate(process.env.SOURCE_DATE_EPOCH) }
|
|
148
153
|
process.env.KERF_START_DIR ??= startDir // for the share cards a build draws (og/native.mjs)
|
|
149
154
|
const building = process.env.KERF_BUILD
|
|
150
155
|
process.env.KERF_BUILD ??= '1'
|
|
151
156
|
try {
|
|
152
|
-
const builder = await createBuilder(config({ ...options, command: 'build' }))
|
|
153
|
-
wrote = undefined
|
|
157
|
+
const builder = await createBuilder(config({ ...options, command: 'build', production }))
|
|
154
158
|
await builder.buildApp()
|
|
155
|
-
|
|
159
|
+
const { dir, publicDir } = production.output
|
|
160
|
+
await finalizeBuild(production.output, production.date)
|
|
161
|
+
return { output: publicDir.startsWith(dir) ? dir : publicDir }
|
|
156
162
|
} finally {
|
|
157
163
|
if (building === undefined) delete process.env.KERF_BUILD
|
|
158
164
|
}
|
package/src/contract.mjs
CHANGED
|
@@ -6,8 +6,6 @@ import { scanRoutes } from './routes.mjs'
|
|
|
6
6
|
import { createHash } from 'node:crypto'
|
|
7
7
|
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
8
8
|
import { join, resolve } from 'node:path'
|
|
9
|
-
import { createServer } from 'vite'
|
|
10
|
-
import kerf from '@kerf-js/core/vite'
|
|
11
9
|
import {
|
|
12
10
|
holdsSockets,
|
|
13
11
|
literalSecrets,
|
|
@@ -20,7 +18,8 @@ import {
|
|
|
20
18
|
import { readMigrations } from './migrations.mjs'
|
|
21
19
|
import { shapeTree } from './shape.mjs'
|
|
22
20
|
import { describe } from './contract/describe.mjs'
|
|
23
|
-
import
|
|
21
|
+
import { startDir } from './vite.mjs'
|
|
22
|
+
import { inspectionServer } from './inspect/server.mjs'
|
|
24
23
|
|
|
25
24
|
export { describe }
|
|
26
25
|
|
|
@@ -228,14 +227,7 @@ async function withFns({ root, site = {} }, fn) {
|
|
|
228
227
|
const env = process.env.NODE_ENV
|
|
229
228
|
let server
|
|
230
229
|
try {
|
|
231
|
-
server = await
|
|
232
|
-
root,
|
|
233
|
-
configFile: false,
|
|
234
|
-
logLevel: 'silent',
|
|
235
|
-
appType: 'custom',
|
|
236
|
-
server: { middlewareMode: true, hmr: false, ws: false },
|
|
237
|
-
plugins: [kerf({ hydratable: true, csp: site?.csp }), kerfStart({ root, site })],
|
|
238
|
-
})
|
|
230
|
+
server = await inspectionServer(root, site)
|
|
239
231
|
await server.ssrLoadModule('virtual:kerf/fns')
|
|
240
232
|
const { fns } = await server.ssrLoadModule(join(startDir, 'data.ts'))
|
|
241
233
|
return await fn(fns, server)
|
package/src/dev-runtime.mjs
CHANGED
|
@@ -1,46 +1,115 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
1
|
+
// Nitro starts evaluating each entry as soon as it receives the environment registration.
|
|
2
|
+
// Vite creates environments before running configureServer, buildStart and the optimizer's init.
|
|
3
|
+
// If the SSR stylesheet crawl reaches the client graph then, Vite can replace the dependency
|
|
4
|
+
// metadata for an optimized import while the crawl is still waiting for that import to load.
|
|
5
5
|
|
|
6
6
|
const alternate = Boolean(process.versions.bun || process.versions.deno)
|
|
7
7
|
|
|
8
|
+
/** Use Vite's own HTTP server for WebSocket upgrades on Bun and Deno. */
|
|
8
9
|
export const devRunner = (sockets) => (alternate && sockets ? 'self' : undefined)
|
|
9
10
|
|
|
10
11
|
const GUARD = /if \("Deno" in globalThis \|\| "Bun" in globalThis\) throw new Error\([^)]*\);?/
|
|
12
|
+
const WORKER_TIMEOUT = 30_000
|
|
11
13
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
14
|
+
/** Register Nitro entries after the environments they import through are ready. */
|
|
15
|
+
export function devRuntime(refreshPlugins) {
|
|
16
|
+
let nitro
|
|
17
|
+
let register
|
|
18
|
+
let useSelf
|
|
19
|
+
return {
|
|
20
|
+
name: 'kerf:dev-runtime',
|
|
21
|
+
apply: 'serve',
|
|
22
|
+
enforce: 'post',
|
|
23
|
+
nitro: {
|
|
24
|
+
setup(instance) {
|
|
25
|
+
nitro = instance
|
|
26
|
+
},
|
|
27
|
+
},
|
|
28
|
+
configResolved(config) {
|
|
29
|
+
useSelf = (nitro.options.devServer.runner || process.env.NITRO_DEV_RUNNER) === 'self'
|
|
30
|
+
const dev = config.environments.nitro.dev
|
|
31
|
+
const createNitro = dev.createEnvironment
|
|
32
|
+
const held = Promise.withResolvers()
|
|
33
|
+
dev.createEnvironment = async (...args) => {
|
|
34
|
+
try {
|
|
35
|
+
const env = await createNitro(...args)
|
|
36
|
+
register = holdRegistrations(env.devServer, useSelf)
|
|
37
|
+
return env
|
|
38
|
+
} finally {
|
|
39
|
+
held.resolve()
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
// Nitro can resend registrations as soon as the worker reports ready, including services
|
|
43
|
+
// still under construction. Install the gate before Nitro starts creating those services.
|
|
44
|
+
for (const [name, environment] of Object.entries(config.environments)) {
|
|
45
|
+
if (name === 'nitro' || environment.consumer !== 'server') continue
|
|
46
|
+
const create = environment.dev.createEnvironment
|
|
47
|
+
environment.dev.createEnvironment = async (...args) => {
|
|
48
|
+
await held.promise
|
|
49
|
+
return create(...args)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
configureServer(server) {
|
|
54
|
+
// Vite creates the replacement server before closing the current one. Nitro's plugin
|
|
55
|
+
// retains its RunnerManager across configs; each server needs to own the runner it closes.
|
|
56
|
+
server.config.inlineConfig.plugins = refreshPlugins()
|
|
57
|
+
const environments = Object.values(server.environments)
|
|
58
|
+
let remaining = environments.length
|
|
59
|
+
for (const environment of environments) {
|
|
60
|
+
const listen = environment.listen.bind(environment)
|
|
61
|
+
environment.listen = async (...args) => {
|
|
62
|
+
await listen(...args)
|
|
63
|
+
if (--remaining === 0) await register()
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
closeServer: () => nitro.close(),
|
|
68
|
+
transform: {
|
|
69
|
+
filter: { id: /crossws/, code: 'incompatible environment' },
|
|
70
|
+
handler: (code) => (alternate && useSelf ? code.replace(GUARD, '') : undefined),
|
|
71
|
+
},
|
|
72
|
+
}
|
|
73
|
+
}
|
|
29
74
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
75
|
+
function holdRegistrations(worker, useSelf) {
|
|
76
|
+
const send = worker.sendMessage
|
|
77
|
+
const entries = new Map()
|
|
78
|
+
worker.sendMessage = (message) => {
|
|
79
|
+
if (message?.type === 'custom' && message.event === 'nitro:vite-env')
|
|
80
|
+
entries.set(message.data.name, message)
|
|
81
|
+
else send.call(worker, message)
|
|
82
|
+
}
|
|
83
|
+
return async () => {
|
|
84
|
+
await worker.waitForReady(WORKER_TIMEOUT)
|
|
85
|
+
worker.sendMessage = send
|
|
86
|
+
for (const [name, message] of entries) {
|
|
87
|
+
// A self runner reuses Nitro's module and its global table across Vite restarts.
|
|
88
|
+
if (useSelf && globalThis.__nitro_vite_envs__)
|
|
89
|
+
globalThis.__nitro_vite_envs__[name] = undefined
|
|
90
|
+
worker.sendMessage(message)
|
|
91
|
+
}
|
|
92
|
+
await registrationsReceived(worker)
|
|
93
|
+
}
|
|
37
94
|
}
|
|
38
95
|
|
|
39
|
-
function
|
|
40
|
-
const
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
96
|
+
async function registrationsReceived(worker) {
|
|
97
|
+
const token = 'kerf:dev-registered'
|
|
98
|
+
const settled = Promise.withResolvers()
|
|
99
|
+
const timer = setTimeout(
|
|
100
|
+
() =>
|
|
101
|
+
settled.reject(new Error('Nitro did not register the Vite environments within 30 seconds')),
|
|
102
|
+
WORKER_TIMEOUT,
|
|
103
|
+
)
|
|
104
|
+
const onMessage = (message) => {
|
|
105
|
+
if (message?.type === 'pong' && message.data === token) settled.resolve()
|
|
106
|
+
}
|
|
107
|
+
worker.onMessage(onMessage)
|
|
108
|
+
try {
|
|
109
|
+
worker.sendMessage({ type: 'ping', data: token })
|
|
110
|
+
await settled.promise
|
|
111
|
+
} finally {
|
|
112
|
+
clearTimeout(timer)
|
|
113
|
+
worker.offMessage(onMessage)
|
|
45
114
|
}
|
|
46
115
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { createServer } from 'vite'
|
|
2
|
+
import kerf from '@kerf-js/core/vite'
|
|
3
|
+
import kerfStart from '../vite.mjs'
|
|
4
|
+
|
|
5
|
+
/** Load SSR modules for a one-shot check without touching the live dev server's dependency cache. */
|
|
6
|
+
export function inspectionServer(root, site) {
|
|
7
|
+
return createServer({
|
|
8
|
+
root,
|
|
9
|
+
configFile: false,
|
|
10
|
+
logLevel: 'silent',
|
|
11
|
+
appType: 'custom',
|
|
12
|
+
optimizeDeps: { noDiscovery: true },
|
|
13
|
+
server: { middlewareMode: true, hmr: false, ws: false, watch: null },
|
|
14
|
+
plugins: [kerf({ hydratable: true, csp: site?.csp }), kerfStart({ root, site })],
|
|
15
|
+
})
|
|
16
|
+
}
|
package/src/inspect.mjs
CHANGED
|
@@ -6,13 +6,13 @@
|
|
|
6
6
|
|
|
7
7
|
import { readFileSync } from 'node:fs'
|
|
8
8
|
import { join, resolve } from 'node:path'
|
|
9
|
-
import {
|
|
10
|
-
import
|
|
11
|
-
import kerfStart, { startDir } from './vite.mjs'
|
|
9
|
+
import { parseSync } from 'vite'
|
|
10
|
+
import { startDir } from './vite.mjs'
|
|
12
11
|
import { deployUrl } from './derive.mjs'
|
|
13
12
|
import { compare } from './inspect/compare.mjs'
|
|
14
13
|
import { inspectRoutes } from './inspect/routes.mjs'
|
|
15
14
|
import { inspectSamples, inspectCards } from './inspect/samples.mjs'
|
|
15
|
+
import { inspectionServer } from './inspect/server.mjs'
|
|
16
16
|
import { filePath, scanRoutes } from './routes.mjs'
|
|
17
17
|
|
|
18
18
|
const quote = (s) => JSON.stringify(s)
|
|
@@ -133,14 +133,7 @@ function makeTaker(found, run, seen, manifest, pages) {
|
|
|
133
133
|
*/
|
|
134
134
|
export async function routesMeta({ root, site = {}, preset }) {
|
|
135
135
|
root = resolve(root)
|
|
136
|
-
const server = await
|
|
137
|
-
root,
|
|
138
|
-
configFile: false,
|
|
139
|
-
logLevel: 'silent',
|
|
140
|
-
appType: 'custom',
|
|
141
|
-
server: { middlewareMode: true, hmr: false, ws: false },
|
|
142
|
-
plugins: [kerf({ hydratable: true, csp: site?.csp }), kerfStart({ root, site })],
|
|
143
|
-
})
|
|
136
|
+
const server = await inspectionServer(root, site)
|
|
144
137
|
try {
|
|
145
138
|
const { manifest, modules } = await server.ssrLoadModule('virtual:kerf/routes')
|
|
146
139
|
const { createHandler, cardPath } = await server.ssrLoadModule(join(startDir, 'server.tsx'))
|
package/src/server/form.ts
CHANGED
|
@@ -4,6 +4,7 @@ import type { Scope } from '../exec'
|
|
|
4
4
|
import { bodyLimit, echoed, limited, withHeaders } from './request'
|
|
5
5
|
import type { HandlerOptions } from './types'
|
|
6
6
|
import { functionFault } from './function-fault'
|
|
7
|
+
import { externalOrigin } from './origin'
|
|
7
8
|
export function makeForm(
|
|
8
9
|
options: HandlerOptions,
|
|
9
10
|
page: (url: URL, request: Request, scope: Scope) => Promise<Response>,
|
|
@@ -13,12 +14,12 @@ export function makeForm(
|
|
|
13
14
|
* errors and what was typed. A form can't send `x-kerf`, so the CSRF proof is the browser's own origin headers.
|
|
14
15
|
*/
|
|
15
16
|
return async function form(url: URL, request: Request, scope: Scope): Promise<Response> {
|
|
17
|
+
const expected = externalOrigin(request, options.site?.trustProxy)
|
|
16
18
|
const origin = request.headers.get('origin')
|
|
17
19
|
const from = request.headers.get('sec-fetch-site')
|
|
18
20
|
if (
|
|
19
|
-
!
|
|
20
|
-
|
|
21
|
-
: from === 'same-origin')
|
|
21
|
+
!expected ||
|
|
22
|
+
!(origin ? origin === expected && (!from || from === 'same-origin') : from === 'same-origin')
|
|
22
23
|
) {
|
|
23
24
|
options.onDiagnostic?.({
|
|
24
25
|
code: 'F002',
|
package/src/server/functions.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { ERROR_HEADER } from '../failure'
|
|
|
10
10
|
import { admitValue, errorFrameStatus, peerStatus, shellResponse, tags } from '../shell/operation'
|
|
11
11
|
import { isSchema, validOperationId } from '../shell/wire'
|
|
12
12
|
import type { Answer, Fn } from '../data/types'
|
|
13
|
+
import { externalOrigin } from './origin'
|
|
13
14
|
|
|
14
15
|
/** `/_kerf/fn/<id>`: GET runs a query, POST a mutation (CSRF-checked), both answering JSON (research 27 §3). */
|
|
15
16
|
export async function serverFunction(
|
|
@@ -61,7 +62,7 @@ export async function serverFunction(
|
|
|
61
62
|
const type = request.headers.get('content-type') ?? ''
|
|
62
63
|
const multipart = type.startsWith('multipart/form-data') // `<Form>` with a file; `x-kerf` still forces a preflight
|
|
63
64
|
if (
|
|
64
|
-
crossOrigin(options, request
|
|
65
|
+
crossOrigin(options, request) ||
|
|
65
66
|
request.headers.get('x-kerf') !== '1' ||
|
|
66
67
|
!(multipart || type.startsWith('application/json'))
|
|
67
68
|
)
|
|
@@ -156,7 +157,9 @@ function functionResponses(scope: Scope, options: HandlerOptions, id: string) {
|
|
|
156
157
|
return { out, fail }
|
|
157
158
|
}
|
|
158
159
|
|
|
159
|
-
function crossOrigin(options: HandlerOptions, request: Request
|
|
160
|
+
function crossOrigin(options: HandlerOptions, request: Request) {
|
|
161
|
+
const expected = externalOrigin(request, options.site?.trustProxy)
|
|
162
|
+
if (!expected) return true
|
|
160
163
|
const origin = request.headers.get('origin')
|
|
161
164
|
const from = request.headers.get('sec-fetch-site')
|
|
162
165
|
// Naming an origin permits its mutation; CORS separately decides whether the browser can read it.
|
|
@@ -164,6 +167,6 @@ function crossOrigin(options: HandlerOptions, request: Request, url: URL) {
|
|
|
164
167
|
const trusted = !!origin && !!named && (named === '*' || named.includes(origin))
|
|
165
168
|
return (
|
|
166
169
|
!trusted &&
|
|
167
|
-
((origin && origin !==
|
|
170
|
+
((origin && origin !== expected) || (from && from !== 'same-origin' && from !== 'none'))
|
|
168
171
|
)
|
|
169
172
|
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// The stock Nitro 3 Node entry starts listening while promises returned by plugins are still pending.
|
|
2
2
|
import { createRequire } from 'node:module'
|
|
3
|
-
import { dirname, join
|
|
3
|
+
import { dirname, join } from 'node:path'
|
|
4
4
|
import { fileURLToPath } from 'node:url'
|
|
5
|
+
import { buildPaths } from '../vite/build-paths.mjs'
|
|
5
6
|
|
|
6
7
|
const collector = '#nitro/virtual/kerf-plugins'
|
|
7
8
|
const config = '#nitro/virtual/kerf-node-config'
|
|
@@ -20,6 +21,7 @@ export function ownNodePreset(nitro, site) {
|
|
|
20
21
|
const require = createRequire(options.entry)
|
|
21
22
|
const internal = join(dirname(options.entry), '../../../runtime/internal')
|
|
22
23
|
const plugins = [...new Set(options.plugins)]
|
|
24
|
+
const pathFor = buildPaths(options.rootDir)
|
|
23
25
|
options.entry = '#nitro/virtual/kerf-node-entry'
|
|
24
26
|
options.plugins = [collector]
|
|
25
27
|
// Nitro still creates its hook-aware h3 app and uses its ordinary useNitroApp singleton.
|
|
@@ -30,7 +32,7 @@ export function ownNodePreset(nitro, site) {
|
|
|
30
32
|
export { startScheduleRunner } from ${JSON.stringify(join(internal, 'task.mjs'))}
|
|
31
33
|
export { resolveWebsocketHooks } from ${JSON.stringify(join(internal, 'app.mjs'))}
|
|
32
34
|
export const plugins = [
|
|
33
|
-
${plugins.map((plugin) => `[${JSON.stringify(
|
|
35
|
+
${plugins.map((plugin) => `[${JSON.stringify(pathFor(plugin))}, () => import(${JSON.stringify(plugin)})]`).join(',\n')}
|
|
34
36
|
]
|
|
35
37
|
`
|
|
36
38
|
options.virtual[options.entry] = `
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// CSRF uses the public origin behind an explicitly trusted proxy, without changing routing or cache URLs.
|
|
2
|
+
|
|
3
|
+
/** The browser's origin from an explicitly trusted hop, or null for malformed/short forwarding or TLS downgrades. */
|
|
4
|
+
export function externalOrigin(request: Request, trustProxy?: boolean | number): string | null {
|
|
5
|
+
const url = new URL(request.url)
|
|
6
|
+
if (trustProxy === undefined || trustProxy === false || trustProxy === 0) return url.origin
|
|
7
|
+
const hops = trustProxy === true ? 1 : trustProxy
|
|
8
|
+
if (!Number.isSafeInteger(hops) || hops < 1) return null
|
|
9
|
+
const proto = request.headers.get('x-forwarded-proto')
|
|
10
|
+
const host = request.headers.get('x-forwarded-host')
|
|
11
|
+
if (proto === null && host === null) return url.origin
|
|
12
|
+
if (proto === null) return null
|
|
13
|
+
const protocols = proto.split(',').map((part) => part.trim())
|
|
14
|
+
const hosts = host === null ? null : host.split(',').map((part) => part.trim())
|
|
15
|
+
if (
|
|
16
|
+
protocols.length < hops ||
|
|
17
|
+
protocols.some((part) => !part) ||
|
|
18
|
+
(hosts && (hosts.length !== protocols.length || hosts.some((part) => !part)))
|
|
19
|
+
)
|
|
20
|
+
return null
|
|
21
|
+
const protocol = protocols[protocols.length - hops]
|
|
22
|
+
if (protocol !== 'http' && protocol !== 'https') return null
|
|
23
|
+
if (url.protocol === 'https:' && protocol !== 'https') return null
|
|
24
|
+
// Proxies that preserve Host may set only X-Forwarded-Proto; do not use an unrelated entry from another hop.
|
|
25
|
+
const authority = hosts ? hosts[hosts.length - hops]! : url.host
|
|
26
|
+
if (!/^(?:[a-z\d_-]+(?:\.[a-z\d_-]+)*\.?|\[[\da-f:.]+\])(?::\d{1,5})?$/i.test(authority))
|
|
27
|
+
return null
|
|
28
|
+
try {
|
|
29
|
+
return new URL(`${protocol}://${authority}`).origin
|
|
30
|
+
} catch {
|
|
31
|
+
return null
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { existsSync
|
|
1
|
+
import { existsSync } from 'node:fs'
|
|
2
2
|
import { join } from 'node:path'
|
|
3
3
|
import { isServerModule } from '../vite.mjs'
|
|
4
4
|
import { buildable, crateDir, isNative, urlVariable } from './common.mjs'
|
|
5
|
+
import { watchFailure, watchTree } from '../watch-tree.mjs'
|
|
5
6
|
|
|
6
7
|
export async function watchServices(deps) {
|
|
7
8
|
const {
|
|
@@ -42,11 +43,8 @@ export async function watchServices(deps) {
|
|
|
42
43
|
}
|
|
43
44
|
if (!first.blocked) await rebuild(service)
|
|
44
45
|
const changed = debounce(() => rebuild(service))
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
if (file && !/^target([\\/]|$)/.test(file) && !file.endsWith('.lock')) changed()
|
|
48
|
-
}),
|
|
49
|
-
)
|
|
46
|
+
const crate = watchCrate(dir, service, changed, log)
|
|
47
|
+
if (crate) watchers.push(crate)
|
|
50
48
|
}
|
|
51
49
|
|
|
52
50
|
// A server module's edit may change a schema: the contract is regenerated, and only a change to a service's hash
|
|
@@ -69,12 +67,8 @@ export async function watchServices(deps) {
|
|
|
69
67
|
log(`[kerf] the contract couldn't be regenerated: ${e.message.split('\n')[0]}`)
|
|
70
68
|
}
|
|
71
69
|
})
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
watch(src, { recursive: true }, (_, file) => {
|
|
75
|
-
if (file && isServerModule(`src/${file.replaceAll('\\', '/')}`)) contractChanged()
|
|
76
|
-
}),
|
|
77
|
-
)
|
|
70
|
+
const server = existsSync(src) ? watchServerModules(src, contractChanged, log) : null
|
|
71
|
+
if (server) watchers.push(server)
|
|
78
72
|
|
|
79
73
|
return watchers
|
|
80
74
|
}
|
|
@@ -86,3 +80,29 @@ const debounce = (fn, ms = 200) => {
|
|
|
86
80
|
t = setTimeout(() => fn(), ms)
|
|
87
81
|
}
|
|
88
82
|
}
|
|
83
|
+
|
|
84
|
+
/** A crate's sources, for a rebuild on an edit; its `target` and lockfile are cargo's own writes. */
|
|
85
|
+
const watchCrate = (dir, service, changed, log) =>
|
|
86
|
+
watchTree(
|
|
87
|
+
dir,
|
|
88
|
+
(_, file) => {
|
|
89
|
+
if (file && !/^target([\\/]|$)/.test(file) && !file.endsWith('.lock')) changed()
|
|
90
|
+
},
|
|
91
|
+
(error) =>
|
|
92
|
+
log(
|
|
93
|
+
`[kerf] can't watch crates/${service} (${watchFailure(error)}): restart dev after an edit`,
|
|
94
|
+
),
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
/** The app's server modules, whose edits may change the contract a service is built from. */
|
|
98
|
+
const watchServerModules = (src, changed, log) =>
|
|
99
|
+
watchTree(
|
|
100
|
+
src,
|
|
101
|
+
(_, file) => {
|
|
102
|
+
if (file && isServerModule(`src/${file.replaceAll('\\', '/')}`)) changed()
|
|
103
|
+
},
|
|
104
|
+
(error) =>
|
|
105
|
+
log(
|
|
106
|
+
`[kerf] can't watch src/ (${watchFailure(error)}): restart dev after a server module's schema changes`,
|
|
107
|
+
),
|
|
108
|
+
)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Physical module paths are for resolution. Build identifiers also name linked packages,
|
|
2
|
+
// whose physical locations need not have any fixed relationship with the app.
|
|
3
|
+
import { readFileSync } from 'node:fs'
|
|
4
|
+
import { dirname, isAbsolute, relative, resolve } from 'node:path'
|
|
5
|
+
import { fileURLToPath } from 'node:url'
|
|
6
|
+
|
|
7
|
+
export const slash = (path) => path.replaceAll('\\', '/')
|
|
8
|
+
|
|
9
|
+
/** Use an app-relative path or the nearest linked package's name and package-relative path. */
|
|
10
|
+
export function buildPaths(root) {
|
|
11
|
+
const directories = new Map()
|
|
12
|
+
const packageAt = (dir) => {
|
|
13
|
+
if (directories.has(dir)) return directories.get(dir)
|
|
14
|
+
let pkg
|
|
15
|
+
try {
|
|
16
|
+
const { name } = JSON.parse(readFileSync(resolve(dir, 'package.json'), 'utf8'))
|
|
17
|
+
if (name) pkg = { dir, name }
|
|
18
|
+
} catch (error) {
|
|
19
|
+
if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') throw error
|
|
20
|
+
}
|
|
21
|
+
const parent = dirname(dir)
|
|
22
|
+
if (!pkg && parent !== dir) pkg = packageAt(parent)
|
|
23
|
+
directories.set(dir, pkg)
|
|
24
|
+
return pkg
|
|
25
|
+
}
|
|
26
|
+
return function pathFor(id) {
|
|
27
|
+
const virtualStart = id.indexOf('\0')
|
|
28
|
+
if (virtualStart !== -1) {
|
|
29
|
+
const virtual = id.slice(virtualStart + 1)
|
|
30
|
+
return isAbsolute(virtual) ? pathFor(virtual) : slash(virtual)
|
|
31
|
+
}
|
|
32
|
+
if (id.startsWith('virtual:') || id.startsWith('#nitro/virtual/')) return id
|
|
33
|
+
const path = id.startsWith('file:') ? fileURLToPath(id) : resolve(root, id)
|
|
34
|
+
const local = slash(relative(root, path))
|
|
35
|
+
if (local !== '..' && !local.startsWith('../') && !isAbsolute(local)) return local
|
|
36
|
+
const portable = slash(path)
|
|
37
|
+
const store = portable.lastIndexOf('/node_modules/.pnpm/')
|
|
38
|
+
const installed = store === -1 ? portable.indexOf('/node_modules/') : store
|
|
39
|
+
if (installed !== -1) return portable.slice(installed + 1)
|
|
40
|
+
const pkg = packageAt(dirname(path))
|
|
41
|
+
return pkg
|
|
42
|
+
? `node_modules/${pkg.name}/${slash(relative(pkg.dir, path))}`
|
|
43
|
+
: portable.split('/').at(-1)
|
|
44
|
+
}
|
|
45
|
+
}
|