-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
377 lines (331 loc) · 13.6 KB
/
server.ts
File metadata and controls
377 lines (331 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
import { existsSync, readFileSync } from 'node:fs'
import { createServer as createHttpServer } from 'node:http'
import { resolve } from 'node:path'
import { getRequestListener, serve } from '@hono/node-server'
import { serveStatic } from '@hono/node-server/serve-static'
import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { marked } from 'marked'
import type { ViteDevServer } from 'vite'
import * as _accounts from '~/api/accounts'
import * as _admin from '~/api/admin'
import * as _ark from '~/api/ark'
import { arkMiddleware } from '~/api/ark-middleware.server'
import type { AuthEnv } from '~/api/auth.server'
import { authMiddleware, requireAuth } from '~/api/auth.server'
import * as _collections from '~/api/collections'
import * as _files from '~/api/files'
import * as _health from '~/api/health'
import * as _kfSummary from '~/api/kf-summary'
import * as _query from '~/api/query'
import * as _schemas from '~/api/schemas'
import * as _uploads from '~/api/uploads'
import * as _versions from '~/api/versions'
import { auth } from '~/lib/auth'
import { getMirrorConfig } from '~/lib/mirror-config'
const isProd = process.env.NODE_ENV === 'production'
let vite: ViteDevServer | undefined
let devHttpServer: import('node:http').Server | undefined
// In dev, proxy API modules through Vite's SSR loader for hot reload
function hot<T extends Record<string, any>>(staticMod: T, modulePath: string): T {
if (isProd) return staticMod
return new Proxy(staticMod as object, {
get(_, prop) {
if (typeof prop === 'symbol') return undefined
return async (...args: unknown[]) => {
const mod = await vite!.ssrLoadModule(modulePath)
return (mod[prop as string] as Function)(...args)
}
},
}) as T
}
const accounts = hot(_accounts, '/src/api/accounts.ts')
const admin = hot(_admin, '/src/api/admin.ts')
const ark = hot(_ark, '/src/api/ark.ts')
const collections = hot(_collections, '/src/api/collections.ts')
const files = hot(_files, '/src/api/files.ts')
const health = hot(_health, '/src/api/health.ts')
const kfSummary = hot(_kfSummary, '/src/api/kf-summary.ts')
const query = hot(_query, '/src/api/query.ts')
const schemas = hot(_schemas, '/src/api/schemas.ts')
const uploads = hot(_uploads, '/src/api/uploads.ts')
const versions = hot(_versions, '/src/api/versions.ts')
const app = new Hono<AuthEnv>()
// --- CORS ---
app.use('/api/*', cors({ origin: '*', credentials: true }))
// --- Auth middleware for API routes ---
app.use('/api/*', authMiddleware)
// --- Mirror mode guard for admin routes ---
app.use('/api/admin/*', async (c, next) => {
const config = getMirrorConfig()
if (!config.enabled) {
return c.json({ error: 'Not found', statusCode: 404 }, 404)
}
await next()
})
// --- ARK resolution middleware ---
app.use('/ark\\:*', arkMiddleware)
// --- Better-auth handler (OIDC login, sessions, API keys) ---
app.on(['GET', 'POST'], '/api/auth/*', async (c) => {
return auth.handler(c.req.raw)
})
// /login redirect — fall through to React route only when there's an error to display
app.get('/login', async (c, next) => {
const url = new URL(c.req.url)
if (!url.searchParams.has('error')) {
const signInUrl = new URL('/api/auth/sign-in/oauth2', url.origin)
const authRes = await auth.handler(
new Request(signInUrl, {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json',
Cookie: c.req.header('cookie') ?? '',
Origin: url.origin,
}),
body: JSON.stringify({ providerId: 'kf-auth', callbackURL: '/dashboard' }),
}),
)
const body = await authRes.json()
if (body.url) {
const redirect = new Response(null, { status: 302, headers: { Location: body.url } })
for (const [key, value] of authRes.headers.entries()) {
if (key.toLowerCase() === 'set-cookie') redirect.headers.append(key, value)
}
return redirect
}
}
await next()
})
// --- API routes ---
app.get('/api/health', health.check)
// KF internal (service-to-service)
app.get('/api/kf/summary', kfSummary.summary)
// Admin (mirror)
app.get('/api/admin/mirror/status', admin.mirrorStatus)
app.post('/api/admin/mirror/test', admin.mirrorTest)
app.post('/api/admin/mirror/sync', admin.mirrorSync)
app.post('/api/admin/mirror/sync/stop', admin.mirrorSyncStop)
app.get('/api/admin/mirror/sync/progress', admin.mirrorSyncProgress)
app.get('/api/admin/mirror/sync/active', admin.mirrorSyncActive)
app.get('/api/admin/mirror/history', admin.mirrorHistory)
// Query
app.get('/api/query/sqlite/:owner/:slug/:version', query.sqlite)
app.get('/api/query/ddl/:owner/:slug/:version', query.ddl)
app.post('/api/query/generate-sql', query.generateSql)
app.get('/api/query/collections/search', query.searchCollections)
app.get('/api/query/collections/:owner/:slug/versions', query.collectionVersions)
// Schemas
app.get('/api/schemas', schemas.listSchemas)
app.get('/api/schemas/:id', schemas.getSchema)
app.get('/api/collections/:owner/:slug/schemas', schemas.collectionSchemas)
app.post('/api/schemas/:id/labels', requireAuth('write'), schemas.addLabel)
app.delete('/api/schemas/:id/labels/:label', requireAuth('admin'), schemas.removeLabel)
// ARK
app.get('/api/ark/resolve', ark.resolve)
app.get('/api/collections/:owner/:slug/ark', requireAuth('read'), ark.getArk)
app.patch('/api/collections/:owner/:slug/ark', requireAuth('write'), ark.updateArk)
app.get(
'/api/collections/:owner/:slug/ark/record-types',
requireAuth('read'),
ark.getArkRecordTypes,
)
app.patch(
'/api/collections/:owner/:slug/ark/record-types',
requireAuth('write'),
ark.updateArkRecordTypes,
)
app.patch('/api/accounts/:slug/ark', requireAuth('admin'), ark.updateAccountArk)
// Collections
app.get('/api/collections', collections.list)
app.post('/api/accounts/:owner/collections', requireAuth('write'), collections.create)
app.get('/api/collections/:owner/:slug', collections.get)
app.patch('/api/collections/:owner/:slug', requireAuth('write'), collections.update)
app.delete('/api/collections/:owner/:slug', requireAuth('admin'), collections.remove)
app.post('/api/collections/:owner/:slug/transfer', requireAuth(), collections.transfer)
app.get('/api/accounts/:owner/collections', collections.listByOwner)
app.get('/api/collections/:owner/:slug/export', collections.exportArchive)
// Files
app.on('HEAD', '/api/collections/:owner/:slug/files/:hash', files.headFile)
app.get('/api/collections/:owner/:slug/files/:hash', files.getFile)
app.put('/api/collections/:owner/:slug/files/:hash', requireAuth('write'), files.putFile)
// Uploads
app.post(
'/api/collections/:owner/:slug/versions/upload',
requireAuth('write'),
uploads.startSession,
)
app.put(
'/api/collections/:owner/:slug/versions/upload/:sessionId',
requireAuth('write'),
uploads.appendBatch,
)
app.get(
'/api/collections/:owner/:slug/versions/upload/:sessionId',
requireAuth('read'),
uploads.getSession,
)
app.post(
'/api/collections/:owner/:slug/versions/upload/:sessionId/finalize',
requireAuth('write'),
uploads.finalize,
)
app.delete(
'/api/collections/:owner/:slug/versions/upload/:sessionId',
requireAuth('write'),
uploads.cancelSession,
)
// Versions
app.get('/api/collections/:owner/:slug/versions', versions.list)
app.get('/api/collections/:owner/:slug/versions/latest', versions.latest)
app.get('/api/collections/:owner/:slug/versions/:n', versions.getByNumber)
app.get('/api/collections/:owner/:slug/versions/:n/records', versions.records)
app.get('/api/collections/:owner/:slug/versions/:n/files', versions.files)
app.get('/api/collections/:owner/:slug/versions/:n/manifest', versions.manifest)
app.post('/api/collections/:owner/:slug/versions', requireAuth('write'), versions.push)
app.get('/api/collections/:owner/:slug/versions/:n/diff', versions.diff)
// Accounts (custom routes — org CRUD, members, invitations, API keys handled by /api/auth/*)
app.get('/api/accounts/me', requireAuth(), accounts.getMe)
app.get('/api/accounts/available-kf-orgs', requireAuth(), accounts.availableKfOrgs)
app.get('/api/accounts/:slug', accounts.getBySlug)
app.get('/api/accounts/:slug/members', accounts.listMembers)
app.patch('/api/accounts/me', requireAuth(), accounts.updateMe)
app.post('/api/accounts/:slug/avatar', requireAuth(), accounts.uploadOrgAvatar)
app.delete('/api/accounts/me', requireAuth(), accounts.deleteMe)
// --- Blog content API (serves rendered markdown) ---
app.get('/api/blog/:slug', (c) => {
const slug = c.req.param('slug')
const mdPath = resolve('content/blog', `${slug}.md`)
if (!existsSync(mdPath)) {
return c.json({ error: 'Not found' }, 404)
}
const raw = readFileSync(mdPath, 'utf-8')
// Strip frontmatter
const fmEnd = raw.indexOf('---', 4)
const body = fmEnd > 0 ? raw.slice(fmEnd + 3).trim() : raw
const html = marked(body)
return c.html(typeof html === 'string' ? html : '')
})
// API 404 catch-all
app.all('/api/*', (c) => {
return c.json({ error: 'API route not found', statusCode: 404 }, 404)
})
// --- SSR ---
if (isProd) {
// Verify SSR build artifacts exist at startup (fail fast, don't wait for first request)
const clientHtml = resolve('dist/client/index.html')
const ssrBundle = resolve('dist/server/entry-server.js')
if (!existsSync(clientHtml)) throw new Error(`Missing ${clientHtml} — did 'pnpm build' run?`)
if (!existsSync(ssrBundle)) throw new Error(`Missing ${ssrBundle} — did 'pnpm build' run?`)
// Serve Vite build assets (hashed JS/CSS bundles)
app.use('/assets/*', serveStatic({ root: './dist/client' }))
// Serve public/ folder files (favicon, wasm, .well-known, etc.)
app.use('/*', serveStatic({ root: './public' }))
// Run migrations on startup
const { runMigrations } = await import('~/db/migrate')
await runMigrations()
const template = readFileSync(clientHtml, 'utf-8')
const { render, loadData } = await import(ssrBundle as string)
app.get('/__data', async (c) => {
const path = new URL(c.req.url).searchParams.get('path')
if (!path) return c.json({ error: 'Missing path param' }, 400)
const fakeUrl = new URL(path, c.req.url)
const req = new Request(fakeUrl, { headers: c.req.raw.headers })
const result = await loadData(req)
if (result.redirect) return c.json({ redirect: result.redirect }, 200)
return c.json(result)
})
app.get('*', async (c) => {
const { html, ssrData, redirect, statusCode, title, description } = await render(c.req.raw)
if (redirect) {
return c.redirect(redirect, 302)
}
let page = template
.replace('<!--ssr-outlet-->', html)
.replace(
'<!--ssr-data-->',
`<script>window.__SSR_DATA__=${JSON.stringify(ssrData).replace(/</g, '\\u003c')}</script>`,
)
if (title) {
page = page.replace('<title>Underlay</title>', `<title>${title}</title>`)
}
if (description) {
page = page.replace(
'</head>',
`<meta name="description" content="${description.replace(/"/g, '"')}" />\n</head>`,
)
}
return c.html(page, statusCode ?? 200)
})
} else {
devHttpServer = createHttpServer()
const { createServer: createViteServer } = await import('vite')
vite = await createViteServer({
server: { middlewareMode: true, hmr: { server: devHttpServer } },
appType: 'custom',
})
// Vite's Connect middleware for HMR and asset transforms
app.use('*', async (c, next) => {
const nodeReq = (c.env as any).incoming
const nodeRes = (c.env as any).outgoing
if (!nodeReq || !nodeRes) return next()
return new Promise<Response | void>((resolve) => {
vite!.middlewares(nodeReq, nodeRes, () => resolve(next()))
})
})
app.get('/__data', async (c) => {
const path = new URL(c.req.url).searchParams.get('path')
if (!path) return c.json({ error: 'Missing path param' }, 400)
const { loadData } = await vite!.ssrLoadModule('/src/entry-server.tsx')
const fakeUrl = new URL(path, c.req.url)
const req = new Request(fakeUrl, { headers: c.req.raw.headers })
const result = await loadData(req)
if (result.redirect) return c.json({ redirect: result.redirect }, 200)
return c.json(result)
})
app.get('*', async (c) => {
const url = c.req.url
let template = readFileSync(resolve('index.html'), 'utf-8')
template = await vite!.transformIndexHtml(url, template)
const { render } = await vite!.ssrLoadModule('/src/entry-server.tsx')
const { html, ssrData, redirect, statusCode, title, description } = await render(c.req.raw)
if (redirect) {
return c.redirect(redirect, 302)
}
let page = template
.replace('<!--ssr-outlet-->', html)
.replace(
'<!--ssr-data-->',
`<script>window.__SSR_DATA__=${JSON.stringify(ssrData).replace(/</g, '\\u003c')}</script>`,
)
if (title) {
page = page.replace('<title>Underlay</title>', `<title>${title}</title>`)
}
if (description) {
page = page.replace(
'</head>',
`<meta name="description" content="${description.replace(/"/g, '"')}" />\n</head>`,
)
}
return c.html(page, statusCode ?? 200)
})
}
const port = Number(process.env.PORT) || 3000
const KF_AUTH_INTERNAL_URL =
process.env.OIDC_ISSUER_INTERNAL_URL ?? process.env.OIDC_ISSUER_URL ?? 'http://localhost:3000'
try {
const res = await fetch(`${KF_AUTH_INTERNAL_URL}/api/health`, {
signal: AbortSignal.timeout(5000),
})
if (!res.ok) throw new Error(`status ${res.status}`)
} catch (err: any) {
console.error(`FATAL: KF Auth not reachable at ${KF_AUTH_INTERNAL_URL}/api/health`)
console.error(err.message)
process.exit(1)
}
console.log(`Server running at http://localhost:${port}`)
if (devHttpServer) {
devHttpServer.on('request', getRequestListener(app.fetch))
devHttpServer.listen(port)
} else {
serve({ fetch: app.fetch, port })
}