-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.ts
More file actions
1076 lines (957 loc) · 40.6 KB
/
Copy pathworker.ts
File metadata and controls
1076 lines (957 loc) · 40.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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* App Worker — Hono-based Cloudflare Worker for DeepSpace apps.
*
* Each app owns its RecordRoom DOs. Schemas are baked in at deploy time.
*
* Handles:
* - WebSocket → app's own RecordRoom DO (real-time data)
* - Auth proxy → auth-worker (same-origin cookies)
* - Integration proxy → api-worker (LLM, search, etc.)
* - AI chat (Vercel AI SDK + DeepSpace proxy)
* - Server actions (app-defined, bypass user RBAC)
* - Scoped R2 file storage
* - HMAC-authenticated cron
* - Static asset serving with SPA fallback
*/
import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { verifyJwt, apiWorkerFetch, platformWorkerFetch, authWorkerFetch } from 'deepspace/worker'
import type { JwtVerifierConfig, VerifyResult } from 'deepspace/worker'
import { RecordRoom, YjsRoom, CanvasRoom, PresenceRoom, CronRoom, JobRoom } from 'deepspace/worker'
import type { Job, JobContext, ActionTools, ActionResult, DOManifest, DOBindings } from 'deepspace/worker'
import { actions } from './src/actions/index.js'
import { tasks as cronTasks, runTask as runCronTask } from './src/cron.js'
import { runJob } from './src/jobs.js'
import { schemas } from './src/schemas.js'
import { integrations } from './src/integrations.js'
import { registerAiChatRoutes } from './src/ai/chat-routes.js'
import { buildWrappedStats, isValidUsername } from './src/server/wrapped/aggregate.js'
import { isWrappedError, type WrappedStats, type WrappedError } from './src/lib/wrapped/types.js'
// =============================================================================
// DO Manifest — declares all Durable Objects for dynamic deploy bindings
// =============================================================================
export const __DO_MANIFEST__ = [
{ binding: 'RECORD_ROOMS', className: 'AppRecordRoom', sqlite: true },
{ binding: 'YJS_ROOMS', className: 'AppYjsRoom', sqlite: true },
{ binding: 'CANVAS_ROOMS', className: 'AppCanvasRoom', sqlite: true },
{ binding: 'PRESENCE_ROOMS', className: 'AppPresenceRoom', sqlite: true },
{ binding: 'CRON_ROOMS', className: 'AppCronRoom', sqlite: true },
{ binding: 'JOB_ROOMS', className: 'AppJobRoom', sqlite: true },
] as const satisfies DOManifest
// =============================================================================
// Durable Objects — extend to customize behavior
// =============================================================================
export class AppRecordRoom extends RecordRoom<Env> {
constructor(state: DurableObjectState, env: Env) {
super(state, env, schemas, { ownerUserId: env.OWNER_USER_ID })
}
}
export class AppYjsRoom extends YjsRoom<Env> {}
export class AppCanvasRoom extends CanvasRoom<Env> {}
export class AppPresenceRoom extends PresenceRoom<Env> {}
/**
* AppCronRoom — runs scheduled tasks defined in src/cron.ts.
*
* Tasks are configured at construction time. The DO alarm fires at the
* next interval / cron-expression match, calls `onTask(name)`, and
* records the execution in its `cron_history` table. Admin clients can
* watch via the `useCronMonitor('app:<APP_NAME>')` hook.
*/
export class AppCronRoom extends CronRoom<Env> {
constructor(state: DurableObjectState, env: Env) {
super(state, env, { tasks: cronTasks })
}
protected async onTask(taskName: string): Promise<void> {
await runCronTask(taskName, this.env)
}
}
/**
* AppJobRoom — durable background-job queue defined in src/jobs.ts.
*
* Use this for any work that needs to outlive an HTTP response: AI
* generation, exports, renders, scheduled side effects. The DO alarm
* picks up queued jobs and calls `onJob(job, ctx)`; crashes mid-run are
* recovered automatically. Clients enqueue and subscribe via the
* `useJobs('app:<APP_NAME>')` hook; server-side code uses the
* `enqueueJob` helper from 'deepspace/worker'.
*/
export class AppJobRoom extends JobRoom<Env> {
constructor(state: DurableObjectState, env: Env) {
super(state, env)
}
protected async onJob(job: Job, ctx: JobContext): Promise<unknown> {
return await runJob(job, ctx, this.env)
}
}
// =============================================================================
// Types
// =============================================================================
export interface Env extends DOBindings<typeof __DO_MANIFEST__> {
ASSETS: Fetcher
/**
* Upstream platform-worker. In production this is a [[services]] binding;
* in `deepspace dev` the binding is absent and the helper falls back to
* `PLATFORM_WORKER_URL` (written into .dev.vars by the CLI).
*
* R2 lives on the platform side, not the app: the `/api/files/*` route
* below proxies to platform-worker `/internal/files/*` which serves a
* shared `APP_FILES` bucket scoped per-app via the `?scope=` query:
* - `?scope=app` → apps/<APP_NAME>/… (per-app shared)
* - `?scope=self` → apps/<APP_NAME>/users/<userId>/… (per-user, default)
*
* Apps don't need a local R2 binding for the standard flow. If you need
* a wholly separate bucket, add `[[r2_buckets]]` to wrangler.toml AND a
* field here — but prefer the proxied path so the platform retains
* unified moderation / quota / cleanup hooks.
*/
PLATFORM_WORKER?: Fetcher
PLATFORM_WORKER_URL?: string
APP_IDENTITY_TOKEN: string
/**
* Upstream api-worker. Same pattern as PLATFORM_WORKER above —
* binding in prod, URL fallback in dev.
*/
API_WORKER?: Fetcher
API_WORKER_URL?: string
AUTH_JWT_PUBLIC_KEY: string
AUTH_JWT_ISSUER: string
AUTH_WORKER_URL: string
APP_NAME: string
OWNER_USER_ID: string
/**
* Long-lived JWT minted for the app owner at deploy time. Server-side
* code (actions, cron, AI helpers) uses this to authenticate to the
* api-worker for developer-billed calls — the owner is billed because
* they are the JWT subject.
*/
APP_OWNER_JWT: string
/**
* When set to "true", the app worker exposes /api/debug/* (set-role,
* sql, query, records, status) by forwarding to the RecordRoom DO's
* debug handler. Tests need this for role elevation and state cleanup.
*
* The CLI writes this to .dev.vars on `deepspace dev`/`deepspace test`
* but never to production secrets, so deployed apps don't expose
* debug routes by default.
*/
ALLOW_DEBUG_ROUTES?: string
}
export type AppContext = { Bindings: Env }
// =============================================================================
// App
// =============================================================================
const app = new Hono<AppContext>()
app.use('/api/*', cors())
// ---------------------------------------------------------------------------
// Auth
// ---------------------------------------------------------------------------
function jwtConfig(env: Env): JwtVerifierConfig {
return { publicKey: env.AUTH_JWT_PUBLIC_KEY, issuer: env.AUTH_JWT_ISSUER }
}
async function resolveAuth(req: Request, env: Env): Promise<VerifyResult | null> {
const header = req.headers.get('Authorization')
const token = header?.startsWith('Bearer ') ? header.slice(7) : null
if (!token) return null
return (await verifyJwt(jwtConfig(env), token)).result
}
// ---------------------------------------------------------------------------
// Social OAuth redirect + code exchange
// ---------------------------------------------------------------------------
app.get('/api/auth/social-redirect', (c) => {
const provider = c.req.query('provider')
if (!provider) return c.json({ error: 'Missing provider' }, 400)
const appOrigin = new URL(c.req.url).origin
const authOrigin = new URL(c.env.AUTH_WORKER_URL).origin
return c.redirect(
`${authOrigin}/login/social?provider=${encodeURIComponent(provider)}&returnTo=${encodeURIComponent(appOrigin)}`,
)
})
app.get('/api/auth/oauth-complete', async (c) => {
const code = c.req.query('code')
const appOrigin = new URL(c.req.url).origin
if (!code) return c.redirect(appOrigin)
const res = await authWorkerFetch(c.env, '/api/auth/exchange-code', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code }),
})
if (!res.ok) return c.redirect(appOrigin)
const data = (await res.json()) as { sessionToken?: string }
if (!data.sessionToken) return c.redirect(appOrigin)
const sessionToken = data.sessionToken
return new Response(null, {
status: 302,
headers: {
Location: appOrigin,
'Set-Cookie': `__Secure-better-auth.session_token=${encodeURIComponent(sessionToken)}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=2592000`,
},
})
})
app.all('/api/auth/sign-out', async (c) => {
try {
await authWorkerFetch(c.env, '/api/auth/sign-out', {
method: c.req.method,
headers: c.req.raw.headers,
body: c.req.method !== 'GET' && c.req.method !== 'HEAD' ? c.req.raw.body : undefined,
})
} catch {
// Still expire the app-scoped cookie below. A network/auth-worker
// failure must not leave the browser immediately signed back in.
}
return new Response(JSON.stringify({ success: true }), {
status: 200,
headers: {
'Content-Type': 'application/json',
'Set-Cookie': '__Secure-better-auth.session_token=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0',
},
})
})
// ---------------------------------------------------------------------------
// Auth proxy → auth-worker (same-origin cookies)
// ---------------------------------------------------------------------------
app.all('/api/auth/*', async (c) => {
const url = new URL(c.req.url)
const res = await authWorkerFetch(c.env, url.pathname + url.search, {
method: c.req.method,
headers: c.req.raw.headers,
body: c.req.method !== 'GET' && c.req.method !== 'HEAD' ? c.req.raw.body : undefined,
})
const headers = new Headers(res.headers)
const setCookie = headers.get('set-cookie')
if (setCookie) {
headers.set('set-cookie', setCookie.replace(/;\s*Domain=[^;]*/gi, ''))
}
return new Response(res.body, { status: res.status, headers })
})
// ---------------------------------------------------------------------------
// Debug proxy → app's RecordRoom DO
//
// Forwards /api/debug/* (set-role, sql, query, records, user-role, status)
// to the DO's debug handler. The DO ships these endpoints unconditionally,
// so we gate the proxy on env.ALLOW_DEBUG_ROUTES === "true". The CLI
// writes that env var to the SDK-managed section of .dev.vars on
// `deepspace dev`/`deepspace test`, which is stripped on deploy —
// production apps return 404 here by default.
//
// To opt /api/debug/* INTO production (admin scripts, one-off cleanup,
// staging environments), set `ALLOW_DEBUG_ROUTES=true` in the USER
// section of .dev.vars (below the `# --- not managed by the SDK ---`
// divider). The CLI ships user-section values as secret_text bindings,
// so it lands in env.ALLOW_DEBUG_ROUTES on the deployed worker.
// The DO's debug handler has NO auth — anyone who can reach this route
// can read and mutate any record. Turn this on deliberately.
// ---------------------------------------------------------------------------
app.all('/api/debug/*', async (c) => {
if (c.env.ALLOW_DEBUG_ROUTES !== 'true') {
return c.notFound()
}
const stub = c.env.RECORD_ROOMS.get(c.env.RECORD_ROOMS.idFromName(`app:${c.env.APP_NAME}`))
// Forward verbatim, preserving method, headers, body, and the full URL
// (the DO's debug handler dispatches on url.pathname).
return stub.fetch(c.req.raw)
})
// ---------------------------------------------------------------------------
// Integrations proxy → api-worker
// ---------------------------------------------------------------------------
app.get('/api/integrations', async (c) => {
try {
const res = await apiWorkerFetch(c.env, '/api/integrations')
return new Response(res.body, { status: res.status, headers: res.headers })
} catch {
return c.json({ error: 'Failed to fetch integration catalog' }, 502)
}
})
// OAuth: per-user connection status. Always user-billed — must forward caller's JWT.
app.get('/api/integrations/status', async (c) => {
const auth = await resolveAuth(c.req.raw, c.env)
if (!auth) return c.json({ error: 'Sign in required' }, 401)
const token = c.req.header('Authorization')?.slice(7)
try {
const res = await apiWorkerFetch(c.env, '/api/integrations/status', {
headers: token ? { Authorization: `Bearer ${token}` } : {},
})
return new Response(res.body, { status: res.status, headers: res.headers })
} catch {
return c.json({ error: 'Status proxy failed' }, 502)
}
})
// OAuth: disconnect a provider for the calling user. Always user-billed.
app.delete('/api/integrations/oauth/:provider/disconnect', async (c) => {
const auth = await resolveAuth(c.req.raw, c.env)
if (!auth) return c.json({ error: 'Sign in required' }, 401)
const token = c.req.header('Authorization')?.slice(7)
const provider = c.req.param('provider')
try {
const res = await apiWorkerFetch(
c.env,
`/api/integrations/oauth/${encodeURIComponent(provider)}/disconnect`,
{
method: 'DELETE',
headers: token ? { Authorization: `Bearer ${token}` } : {},
},
)
return new Response(res.body, { status: res.status, headers: res.headers })
} catch {
return c.json({ error: 'Disconnect proxy failed' }, 502)
}
})
app.all('/api/integrations/:name/:endpoint', async (c) => {
const integrationName = c.req.param('name')
const billingMode = integrations[integrationName]?.billing ?? 'developer'
const auth = await resolveAuth(c.req.raw, c.env)
if (!auth && billingMode === 'user') {
return c.json({ error: 'Sign in required for this integration' }, 401)
}
const target = `/api/integrations/${integrationName}/${c.req.param('endpoint')}`
const headers: Record<string, string> = {
'Content-Type': c.req.header('Content-Type') ?? 'application/json',
}
// Pick the JWT whose subject is the user we want billed:
// - developer-billed → the app owner (via APP_OWNER_JWT)
// - user-billed → the caller (forward their Bearer token)
// The api-worker bills the JWT subject; it does not accept any
// client-supplied billing override.
if (billingMode === 'developer') {
headers['Authorization'] = `Bearer ${c.env.APP_OWNER_JWT}`
} else {
const token = c.req.header('Authorization')?.slice(7)
if (token) headers['Authorization'] = `Bearer ${token}`
}
const hasBody = c.req.method !== 'GET' && c.req.method !== 'HEAD'
const body = hasBody ? await c.req.text() : undefined
try {
const res = await apiWorkerFetch(c.env, target, {
method: c.req.method,
headers,
body,
})
return new Response(res.body, { status: res.status, headers: res.headers })
} catch {
return c.json({ error: 'Integration proxy failed' }, 502)
}
})
// ---------------------------------------------------------------------------
// WebSocket routes
// ---------------------------------------------------------------------------
// The DO reads identity (userId, userName, userEmail, userImageUrl, role)
// off the URL it receives and trusts it. Anything the client put on the URL
// is stripped on every code path; identity is re-applied only from a
// verified JWT. Three states: no token = anonymous (the SDK's
// allowAnonymous flow), invalid token = 401, valid token = JWT identity.
function wsRoute(
doNamespace: (env: Env) => DurableObjectNamespace,
extraParams?: (auth: VerifyResult) => Record<string, string>,
) {
return async (c: any) => {
const id = c.req.param('roomId') ?? c.req.param('docId') ?? c.req.param('scopeId')
const url = new URL(c.req.url)
const token = url.searchParams.get('token')
let auth: VerifyResult | null = null
if (token) {
auth = (await verifyJwt(jwtConfig(c.env), token)).result
if (!auth) return new Response('Unauthorized', { status: 401 })
}
const doUrl = new URL(c.req.url)
doUrl.searchParams.delete('token')
for (const k of ['userId', 'userName', 'userEmail', 'userImageUrl', 'role']) {
doUrl.searchParams.delete(k)
}
if (auth) {
doUrl.searchParams.set('userId', auth.userId)
if (auth.claims.name) doUrl.searchParams.set('userName', auth.claims.name)
if (auth.claims.email) doUrl.searchParams.set('userEmail', auth.claims.email)
if (auth.claims.image) doUrl.searchParams.set('userImageUrl', auth.claims.image)
if (extraParams) {
for (const [k, v] of Object.entries(extraParams(auth))) {
doUrl.searchParams.set(k, v)
}
}
}
const ns = doNamespace(c.env)
const stub = ns.get(ns.idFromName(id))
return stub.fetch(new Request(doUrl.toString(), c.req.raw))
}
}
app.get(
'/ws/:roomId',
wsRoute((env) => env.RECORD_ROOMS),
)
type DocsYjsRole = 'admin' | 'member' | 'viewer'
interface DocumentRecordForAccess {
ownerId?: string
collaborators?: string
editors?: string
}
type DocumentAccessLookup =
| { kind: 'found'; doc: DocumentRecordForAccess }
| { kind: 'not-docs-room' }
| { kind: 'error' }
function parseAccessList(raw: string | undefined): string[] {
if (!raw) return []
try {
const parsed = JSON.parse(raw)
return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === 'string') : []
} catch {
return []
}
}
async function getDocumentForAccess(
env: Env,
docId: string,
): Promise<DocumentAccessLookup> {
const stub = env.RECORD_ROOMS.get(env.RECORD_ROOMS.idFromName(`app:${env.APP_NAME}`))
try {
const res = await stub.fetch(
new Request('https://internal/api/tools/execute', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-User-Id': env.OWNER_USER_ID,
'X-App-Action': 'true',
},
body: JSON.stringify({
tool: 'records.get',
params: { collection: 'documents', recordId: docId },
}),
}),
)
const json = (await res.json()) as {
success?: boolean
error?: string
data?: { record?: { data?: DocumentRecordForAccess } }
}
if (json.success && json.data?.record?.data) {
return { kind: 'found', doc: json.data.record.data }
}
if (
json.error === 'Record not found' ||
json.error?.startsWith('Schema not registered for collection: documents')
) {
return { kind: 'not-docs-room' }
}
return { kind: 'error' }
} catch {
return { kind: 'error' }
}
}
async function resolveDocsYjsRole(
env: Env,
docId: string,
userId: string,
): Promise<DocsYjsRole | null> {
const lookup = await getDocumentForAccess(env, docId)
if (lookup.kind === 'not-docs-room') return 'member'
if (lookup.kind === 'error') return null
const { doc } = lookup
if (doc.ownerId === userId || userId === env.OWNER_USER_ID) return 'admin'
const editors = parseAccessList(doc.editors)
if (editors.includes(userId)) return 'member'
const collaborators = parseAccessList(doc.collaborators)
if (collaborators.includes(userId)) return 'viewer'
return null
}
app.get('/ws/yjs/:docId', async (c) => {
const docId = c.req.param('docId')
const url = new URL(c.req.url)
const token = url.searchParams.get('token')
const auth = token ? (await verifyJwt(jwtConfig(c.env), token)).result : null
if (!auth) return new Response('Unauthorized', { status: 401 })
const role = await resolveDocsYjsRole(c.env, docId, auth.userId)
if (!role) return new Response('Forbidden', { status: 403 })
const doUrl = new URL(c.req.url)
doUrl.searchParams.set('userId', auth.userId)
doUrl.searchParams.set('role', role)
doUrl.searchParams.delete('token')
const stub = c.env.YJS_ROOMS.get(c.env.YJS_ROOMS.idFromName(docId))
return stub.fetch(new Request(doUrl.toString(), c.req.raw))
})
app.get(
'/ws/canvas/:docId',
wsRoute(
(env) => env.CANVAS_ROOMS,
() => ({ role: 'member' }),
),
)
app.get(
'/ws/presence/:scopeId',
wsRoute(
(env) => env.PRESENCE_ROOMS,
(auth) => ({
...(auth.claims.name ? { userName: auth.claims.name } : {}),
...(auth.claims.email ? { userEmail: auth.claims.email } : {}),
...(auth.claims.image ? { userImageUrl: auth.claims.image } : {}),
}),
),
)
app.get(
'/ws/cron/:roomId',
wsRoute(
(env) => env.CRON_ROOMS,
// Authenticated users get write access (trigger / pause / resume).
// Anonymous connections fall through with no role and become viewers,
// which CronRoom enforces as read-only. Apps that want stricter access
// (e.g. owner-only) should replace this with an inline handler that
// resolves role from app state — see the /ws/yjs route for the pattern.
() => ({ role: 'member' }),
),
)
app.get(
'/ws/jobs/:roomId',
wsRoute((env) => env.JOB_ROOMS),
)
// ---------------------------------------------------------------------------
// Server actions
// ---------------------------------------------------------------------------
app.post('/api/actions/:name', async (c) => {
const auth = await resolveAuth(c.req.raw, c.env)
if (!auth) return c.json({ error: 'Unauthorized' }, 401)
const name = c.req.param('name')
const action = actions[name]
if (!action) return c.json({ error: 'Action not found' }, 404)
const params = await c.req.json<Record<string, unknown>>()
const callerJwt = c.req.header('Authorization')!.slice(7)
const tools = createActionTools(c.env, auth.userId, callerJwt)
const result = await action({ userId: auth.userId, params, tools, env: c.env, callerJwt })
return c.json(result as unknown as Record<string, unknown>)
})
// ---------------------------------------------------------------------------
// AI chat — multi-turn tool-use via Vercel AI SDK + DeepSpace proxy
// ---------------------------------------------------------------------------
// Routes implementation lives in `src/ai/chat-routes.ts` to keep this file
// focused on app-level wiring. `resolveAuth` is passed in to avoid a runtime
// circular import (chat-routes imports `Env`/`AppContext` as types only).
registerAiChatRoutes(app, resolveAuth)
// ---------------------------------------------------------------------------
// Scoped R2 files → platform-worker
//
// The app has no local R2 binding by design; the platform-worker holds a
// shared `APP_FILES` bucket and scopes keys per-app via the `?scope=`
// query string:
//
// POST /api/files/upload?scope=app → uploads under apps/<APP_NAME>/
// POST /api/files/upload → uploads under apps/<APP_NAME>/users/<userId>/
// GET /api/files → list (same scoping)
// GET /api/files/<key> → public read (no auth)
// DELETE /api/files/<key> → delete (auth required, scope-checked)
//
// Use `?scope=app` for content that belongs to the app as a whole (library
// preview images, AI-generated assets, etc.). Use the default user scope
// for per-user uploads (avatars, project assets). All write paths require
// a signed user JWT; reads are public.
// ---------------------------------------------------------------------------
app.all('/api/files/*', async (c) => {
const auth = await resolveAuth(c.req.raw, c.env)
const userId = auth?.userId ?? null
const url = new URL(c.req.url)
const platformUrl = new URL(c.req.url)
platformUrl.pathname = url.pathname.replace('/api/files', '/internal/files')
const headers = new Headers(c.req.raw.headers)
// Strip any caller-supplied identity before re-asserting from the verified
// JWT. platform-worker trusts `x-user-id` (gated by the HMAC'd app-identity
// token) to scope `?scope=self` keys, so leaking a spoofed header here would
// let an unauthenticated browser read another user's files.
headers.delete('x-user-id')
headers.set('x-app-identity-token', c.env.APP_IDENTITY_TOKEN)
headers.set('x-app-name', c.env.APP_NAME)
if (userId) headers.set('x-user-id', userId)
const resp = await platformWorkerFetch(
c.env,
new Request(platformUrl.toString(), {
method: c.req.method,
headers,
body: c.req.raw.body,
}),
)
// Rewrite URLs in JSON responses to use the app's origin
const contentType = resp.headers.get('content-type') ?? ''
if (contentType.includes('application/json')) {
const body = (await resp.json()) as Record<string, unknown>
const rewriteUrl = (u: string) => u.replace(/^https?:\/\/[^/]+/, url.origin)
if (typeof body.url === 'string') body.url = rewriteUrl(body.url)
if (Array.isArray(body.files)) {
for (const f of body.files as Array<Record<string, unknown>>) {
if (typeof f.url === 'string') f.url = rewriteUrl(f.url)
}
}
return c.json(body, resp.status as any)
}
return new Response(resp.body, { status: resp.status, headers: resp.headers })
})
// ---------------------------------------------------------------------------
// /_deepspace/* — same-origin proxy to api-worker for authenticated SDK
// hooks. Attaches APP_IDENTITY_TOKEN + APP_NAME so the browser never sees
// the platform secret. Every request requires a signed user JWT.
//
// SECURITY: exact (method, path) allowlist — not a prefix match. A prefix
// match leaks deploy/CLI surfaces like POST /api/subscriptions/sync into the
// browser context, where an XSS or compromised user session can become a
// confused deputy. Adding a new browser hook in the SDK requires explicitly
// extending the BROWSER_PROXY_ROUTES tuple below.
// ---------------------------------------------------------------------------
interface ProxyRoute {
method: string
path: string
/** Skip the user-JWT gate. Default false. Pricing tables are public. */
publicRead?: boolean
/** Inject `?appName=...` (from env) into the forwarded URL. Default false. */
injectAppName?: boolean
}
const BROWSER_PROXY_ROUTES: ReadonlyArray<ProxyRoute> = [
// useSubscription — read state, subscribe, manage billing.
{ method: 'GET', path: '/_deepspace/subscriptions/me' },
{ method: 'POST', path: '/_deepspace/subscriptions/checkout' },
{ method: 'POST', path: '/_deepspace/subscriptions/portal' },
// useCheckout (one-time charges)
{ method: 'POST', path: '/_deepspace/charges/create' },
{ method: 'GET', path: '/_deepspace/charges/me' },
]
app.all('/_deepspace/*', async (c) => {
const url = new URL(c.req.url)
const method = c.req.method
const route = BROWSER_PROXY_ROUTES.find(
(r) => r.method === method && r.path === url.pathname,
)
if (!route) {
return c.json({ error: 'not_found' }, 404)
}
// Public-read routes (pricing tables) skip the JWT gate. Everything else
// requires a signed-in user.
let auth: Awaited<ReturnType<typeof resolveAuth>> | null = null
if (!route.publicRead) {
auth = await resolveAuth(c.req.raw, c.env)
if (!auth?.userId) return c.json({ error: 'unauthorized' }, 401)
}
// Inject appName into the query string when the route needs it. We can't
// rely on the HMAC header for routes the platform serves without HMAC
// (e.g. /plans is public). Use URLSearchParams.set so we OVERWRITE any
// caller-supplied appName — otherwise a request to
// `/_deepspace/subscriptions/plans?appName=other_app` would forward a
// duplicate-key query string and the platform would pick whichever value
// its parser sees first.
const forwardedParams = new URLSearchParams(url.search)
if (route.injectAppName) {
forwardedParams.set('appName', c.env.APP_NAME)
}
const queryString = forwardedParams.toString()
const apiPath =
url.pathname.replace('/_deepspace/', '/api/') + (queryString ? `?${queryString}` : '')
const headers = new Headers(c.req.raw.headers)
headers.delete('x-user-id')
headers.set('x-app-identity-token', c.env.APP_IDENTITY_TOKEN)
headers.set('x-app-name', c.env.APP_NAME)
if (auth?.userId) headers.set('x-user-id', auth.userId)
return apiWorkerFetch(c.env, apiPath, {
method,
headers,
body: ['GET', 'HEAD'].includes(method) ? undefined : c.req.raw.body,
})
})
// ---------------------------------------------------------------------------
// GitHub Wrapped: data layer + share card (tokenless, idempotent, cached)
//
// Both routes cache on caches.default keyed by username:year with
// Cache-Control: public, max-age=21600, so repeat views never re-hit GitHub.
// Every number in the payload traces to real GitHub data (see
// docs/founder/data-plan.md); there is no random or invented stat.
// ---------------------------------------------------------------------------
function resolveWrappedYear(c: { req: { query: (k: string) => string | undefined } }): {
year: number
param: number | undefined
} {
const now = new Date().getUTCFullYear()
const raw = c.req.query('year')
const parsed = raw && /^\d{4}$/.test(raw) ? parseInt(raw, 10) : undefined
// Clamp to GitHub's lifetime (launched 2008) .. current year. Out-of-range
// years always return an empty graph and would otherwise each be a distinct
// cache key, letting one known username force unlimited cold (billed) rebuilds.
const param = parsed !== undefined && parsed >= 2008 && parsed <= now ? parsed : undefined
return { year: param ?? now, param }
}
/** Just the bits of the Hono context the wrapped helpers touch. */
type WrappedCtx = {
env: Env
req: { header(name: string): string | undefined }
executionCtx: { waitUntil(p: Promise<unknown>): void }
}
/** Minimal KV shape (avoids a hard dep on @cloudflare/workers-types). */
type RateKV = {
get(key: string): Promise<string | null>
put(key: string, value: string, opts?: { expirationTtl?: number }): Promise<void>
}
/**
* Per-IP cap on the anonymous, owner-billed routes (abuse guard for the GitHub
* integration spend). Generous enough that real users never hit it; single-IP
* enumeration bots do. Fails OPEN when RATE_KV is not provisioned (or on any KV
* error), so it can never block a deploy.
*/
const RATE_LIMIT_PER_MIN = 40
async function rateLimited(c: WrappedCtx): Promise<boolean> {
// Fails OPEN on ANY error (missing binding, KV failure, no executionCtx, etc.)
// so the rate limiter can never turn into a 500 on the billed routes.
try {
const kv = (c.env as unknown as Record<string, unknown>).RATE_KV as RateKV | undefined
if (!kv) return false
const ip = c.req.header('CF-Connecting-IP') || c.req.header('x-forwarded-for') || ''
if (!ip) return false
const key = `rl:${ip}:${Math.floor(Date.now() / 60000)}`
const count = parseInt((await kv.get(key)) ?? '0', 10) || 0
if (count >= RATE_LIMIT_PER_MIN) return true
try {
c.executionCtx.waitUntil(kv.put(key, String(count + 1), { expirationTtl: 120 }).catch(() => {}))
} catch {
// no executionCtx available — best-effort fire-and-forget instead
void kv.put(key, String(count + 1), { expirationTtl: 120 }).catch(() => {})
}
return false
} catch {
return false
}
}
/**
* Build + cache WrappedStats, SHARED by /api/wrapped and /api/og so one cold
* share (a crawler fetches the OG image, the human opens the page) bills GitHub
* once instead of twice. Errors are never cached.
*/
async function getCachedStats(
c: WrappedCtx,
username: string,
year: number,
param: number | undefined,
): Promise<WrappedStats | WrappedError> {
// Cache in KV — Workers-for-Platforms does not permit `caches.default`. KV is
// global, so it dedups the billed GitHub calls across colos. Best-effort: any
// KV error just falls through to a rebuild.
const kv = (c.env as unknown as Record<string, unknown>).RATE_KV as RateKV | undefined
const key = `stats:${username.toLowerCase()}:${year}`
if (kv) {
try {
const hit = await kv.get(key)
if (hit) return JSON.parse(hit) as WrappedStats
} catch {
// fall through to rebuild
}
}
const result = await buildWrappedStats(c.env, username, param)
if (!isWrappedError(result) && kv) {
const payload = JSON.stringify(result)
try {
c.executionCtx.waitUntil(kv.put(key, payload, { expirationTtl: 21600 }).catch(() => {}))
} catch {
void kv.put(key, payload, { expirationTtl: 21600 }).catch(() => {})
}
}
return result
}
app.get('/api/wrapped/:username', async (c) => {
if (await rateLimited(c)) {
return c.json({ error: 'Too many requests. Give it a minute.', code: 'RATE_LIMITED' }, 429)
}
const username = c.req.param('username')
const { year, param } = resolveWrappedYear(c)
const result = await getCachedStats(c, username, year, param)
if (isWrappedError(result)) {
const status =
result.code === 'NOT_FOUND' ? 404 : result.code === 'BAD_INPUT' ? 400 : result.code === 'RATE_LIMITED' ? 429 : 502
return c.json(result, status)
}
return new Response(JSON.stringify(result), {
status: 200,
headers: { 'Content-Type': 'application/json', 'Cache-Control': 'public, max-age=21600' },
})
})
app.get('/api/og/:username', async (c) => {
if (await rateLimited(c)) {
return c.json({ error: 'Too many requests. Give it a minute.', code: 'RATE_LIMITED' }, 429)
}
const username = c.req.param('username')
if (!isValidUsername(username)) {
return c.json({ error: 'Invalid GitHub username.', code: 'BAD_INPUT' }, 400)
}
// Open Graph image. v1 ships the user's GitHub avatar as a no-wasm fallback:
// the personalized Satori trophy card is deferred because workers-og's wasm
// does not bundle on the DeepSpace deploy pipeline (see docs/founder/sdk-issues.md).
// The full trophy card still renders in-app (DOM/CSS) on the final story section.
const avatarRes = await fetch(`https://github.com/${encodeURIComponent(username)}.png?size=600`, {
headers: { 'User-Agent': 'GitHubWrapped/1.0' },
})
if (!avatarRes.ok || !avatarRes.body) {
return c.json({ error: 'No image for that user.', code: 'NOT_FOUND' }, 404)
}
const response = new Response(avatarRes.body, {
status: 200,
headers: {
'Content-Type': avatarRes.headers.get('content-type') ?? 'image/png',
'Cache-Control': 'public, max-age=86400',
},
})
return response
})
// ---------------------------------------------------------------------------
// Static assets (SPA fallback) + per-user Open Graph meta
//
// A bare single-segment path that looks like a GitHub username (e.g. /torvalds)
// is an SPA route; we serve index.html but inject per-user og:/twitter: tags via
// HTMLRewriter so shared links unfurl with the user's trophy card. Humans still
// get the SPA; only the <head> meta differs.
// ---------------------------------------------------------------------------
const RESERVED_PATHS = new Set([
'home',
'settings',
'api-status',
'login',
'logout',
'about',
'privacy',
'terms',
'index.html',
'favicon.ico',
'robots.txt',
'assets',
'manifest.webmanifest',
])
function usernameFromPath(pathname: string): string | null {
const seg = decodeURIComponent(pathname.replace(/^\/+/, '').replace(/\/+$/, ''))
if (!seg || seg.includes('/') || seg.includes('.')) return null
if (RESERVED_PATHS.has(seg.toLowerCase())) return null
return isValidUsername(seg) ? seg : null
}
function escapeAttr(s: string): string {
return s
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
}
function injectOgMeta(res: Response, username: string, origin: string): Response {
const year = new Date().getUTCFullYear()
const title = `${username} on GitHub Wrapped ${year}`
const desc = `See ${username}'s year in code: contributions, streaks, top languages, and their developer archetype.`
const image = `${origin}/api/og/${encodeURIComponent(username)}`
const pageUrl = `${origin}/${encodeURIComponent(username)}`
const tags =
`<meta property="og:title" content="${escapeAttr(title)}">` +
`<meta property="og:description" content="${escapeAttr(desc)}">` +
`<meta property="og:image" content="${escapeAttr(image)}">` +
`<meta property="og:type" content="website">` +
`<meta property="og:url" content="${escapeAttr(pageUrl)}">` +
`<meta name="twitter:card" content="summary_large_image">` +
`<meta name="twitter:title" content="${escapeAttr(title)}">` +
`<meta name="twitter:description" content="${escapeAttr(desc)}">` +
`<meta name="twitter:image" content="${escapeAttr(image)}">`
return new HTMLRewriter()
.on('head', {
element(el) {
el.append(tags, { html: true })
},
})
.transform(res)
}
app.get('*', async (c) => {
const url = new URL(c.req.url)
// NOTE: dead in prod. Workers-for-Platforms does not route bare SPA paths
// through the worker (even with run_worker_first), so this branch never runs on
// the deploy; index.html (with its static OG meta) is served from the edge.
// Kept for if/when the platform routes SPA paths through the worker; the live
// unfurl relies on the static meta in index.html instead. See sdk-issues.md #2.
//
// A single-segment username route (e.g. /torvalds) is an SPA route, not an
// asset. Serve index.html with per-user OG meta injected so shared links
// unfurl with the trophy card. Humans still get the full SPA underneath.
// This is checked before the asset fetch so it is robust whether the assets
// binding returns 404 or already SPA-rewrites unmatched paths to index.html.
const username = usernameFromPath(url.pathname)
if (username) {
const indexReq = new Request(new URL('/', url).toString(), c.req.raw)
const indexRes = await c.env.ASSETS.fetch(indexReq)
const ct = indexRes.headers.get('content-type') ?? ''
if (ct.includes('text/html')) {
const out = injectOgMeta(indexRes, username, url.origin)
try {
out.headers.set('x-wrapped-og', 'injected')
} catch {
/* immutable headers in some runtimes; ignore */
}
return out
}
return indexRes
}
const assetRes = await c.env.ASSETS.fetch(c.req.raw)
if (assetRes.status !== 404) return assetRes
// 404 from assets -> SPA fallback to index.html.
const indexReq = new Request(new URL('/', url).toString(), c.req.raw)
return c.env.ASSETS.fetch(indexReq)
})
// =============================================================================
// Action Tools — route to app's own RecordRoom DO
// =============================================================================
function createActionTools(env: Env, userId: string, callerJwt: string): ActionTools {
const stub = env.RECORD_ROOMS.get(env.RECORD_ROOMS.idFromName(`app:${env.APP_NAME}`))