@lupinum/ginko-server 0.0.0-stage → 0.18.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 (95) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE +21 -0
  3. package/README.md +176 -2
  4. package/convex/_generated/api.d.ts +185 -0
  5. package/convex/_generated/api.js +23 -0
  6. package/convex/_generated/dataModel.d.ts +60 -0
  7. package/convex/_generated/server.d.ts +162 -0
  8. package/convex/_generated/server.js +101 -0
  9. package/convex/account.ts +110 -0
  10. package/convex/agent.ts +814 -0
  11. package/convex/auth.config.ts +4 -0
  12. package/convex/auth.ts +62 -0
  13. package/convex/backup.ts +94 -0
  14. package/convex/betterAuth/_generated/api.ts +56 -0
  15. package/convex/betterAuth/_generated/component.ts +431 -0
  16. package/convex/betterAuth/_generated/dataModel.ts +60 -0
  17. package/convex/betterAuth/_generated/server.ts +169 -0
  18. package/convex/betterAuth/adapter.ts +7 -0
  19. package/convex/betterAuth/convex.config.ts +3 -0
  20. package/convex/betterAuth/schema.ts +102 -0
  21. package/convex/betterAuth/schemaMetadata.ts +697 -0
  22. package/convex/betterAuth/schemaOptions.ts +13 -0
  23. package/convex/betterAuth/schemaPlugins.ts +13 -0
  24. package/convex/bundle.ts +183 -0
  25. package/convex/changes.ts +136 -0
  26. package/convex/cleanup.ts +44 -0
  27. package/convex/connect.ts +143 -0
  28. package/convex/convex.config.ts +7 -0
  29. package/convex/crons.ts +14 -0
  30. package/convex/demo.ts +72 -0
  31. package/convex/entries.ts +1770 -0
  32. package/convex/facts.ts +129 -0
  33. package/convex/files.ts +631 -0
  34. package/convex/http.ts +21 -0
  35. package/convex/image.ts +45 -0
  36. package/convex/images.ts +54 -0
  37. package/convex/invites.ts +227 -0
  38. package/convex/lib/access.ts +180 -0
  39. package/convex/lib/agentTools.ts +331 -0
  40. package/convex/lib/content.ts +317 -0
  41. package/convex/lib/corpus.ts +83 -0
  42. package/convex/lib/diff.ts +50 -0
  43. package/convex/lib/fail.ts +27 -0
  44. package/convex/lib/files.ts +70 -0
  45. package/convex/lib/history.ts +103 -0
  46. package/convex/lib/i18n.ts +52 -0
  47. package/convex/lib/input.ts +57 -0
  48. package/convex/lib/library.ts +28 -0
  49. package/convex/lib/lifecycle.ts +100 -0
  50. package/convex/lib/list.ts +112 -0
  51. package/convex/lib/migrations.ts +126 -0
  52. package/convex/lib/names.ts +56 -0
  53. package/convex/lib/pending.ts +84 -0
  54. package/convex/lib/policy.ts +155 -0
  55. package/convex/lib/publicness.ts +87 -0
  56. package/convex/lib/reminders.ts +27 -0
  57. package/convex/lib/search.ts +132 -0
  58. package/convex/lib/siteUrl.ts +95 -0
  59. package/convex/lib/status.ts +109 -0
  60. package/convex/lib/translation.ts +56 -0
  61. package/convex/lib/trees.ts +43 -0
  62. package/convex/lib/write.ts +296 -0
  63. package/convex/mail.ts +136 -0
  64. package/convex/members.ts +129 -0
  65. package/convex/migrations.ts +105 -0
  66. package/convex/navigation.ts +276 -0
  67. package/convex/ops.ts +50 -0
  68. package/convex/proposals.ts +753 -0
  69. package/convex/refresh.ts +163 -0
  70. package/convex/release.ts +435 -0
  71. package/convex/reminders.ts +116 -0
  72. package/convex/retention.ts +121 -0
  73. package/convex/routes/bundle.ts +62 -0
  74. package/convex/routes/connect.ts +80 -0
  75. package/convex/routes/export.ts +23 -0
  76. package/convex/routes/file.ts +34 -0
  77. package/convex/routes/key.ts +53 -0
  78. package/convex/routes/mcp.ts +300 -0
  79. package/convex/routes/release.ts +66 -0
  80. package/convex/routes/upload.ts +94 -0
  81. package/convex/schema.ts +443 -0
  82. package/convex/search.ts +58 -0
  83. package/convex/seed.ts +624 -0
  84. package/convex/siteDeletion.ts +78 -0
  85. package/convex/sites.ts +393 -0
  86. package/convex/tasks.ts +51 -0
  87. package/convex/tsconfig.json +27 -0
  88. package/convex/uploads.ts +429 -0
  89. package/convex/uploadsNode.ts +86 -0
  90. package/convex/views.ts +111 -0
  91. package/i18n/de.json +364 -0
  92. package/i18n/en.json +364 -0
  93. package/i18n/es.json +364 -0
  94. package/i18n/fr.json +364 -0
  95. package/package.json +45 -3
@@ -0,0 +1,116 @@
1
+ // The weekly reminder (SPEC 10): content that is out of date for the coming week (`staleOf`, the rule
2
+ // the Studio shows too), and the due status lines of the Today page (lib/status.ts) in the Studio's words, go out in
3
+ // one mail per person and site, each brick once per person and week, on the day before the site's week starts (Sunday
4
+ // for Monday-first weeks), between 17:00 and 18:00 in the site's time zone.
5
+ import { startOfWeek, type Json } from '@lupinum/ginko'
6
+ import { addDays, labelOf, plannedWeeks, staleOf, todayIn, workWeekOf, type Schema } from '@lupinum/ginko/internal'
7
+ import { v } from 'convex/values'
8
+ import { components } from './_generated/api'
9
+ import type { Doc } from './_generated/dataModel'
10
+ import { internalMutation, type MutationCtx } from './_generated/server'
11
+ import { localeOfUser, t } from './lib/i18n'
12
+ import { isReminded, reminderBricks } from './lib/reminders'
13
+ import { statesOf, statusText } from './lib/status'
14
+ import { mailAvailable, queueMail, siteOrigin } from './mail'
15
+
16
+ const REMIND_HOUR = 17
17
+
18
+ /** Hour of day (0 to 23) at `now` in `timeZone`. */
19
+ function hourIn(timeZone: string, now: Date): number {
20
+ const hour = new Intl.DateTimeFormat('en-GB', { timeZone, hour: '2-digit', hourCycle: 'h23' }).formatToParts(now).find((p) => p.type === 'hour')?.value
21
+ return Number(hour)
22
+ }
23
+
24
+ /** Whether tomorrow is the first day of the site's week. */
25
+ const isDayBeforeWeekStart = (date: string, schema: Schema) => startOfWeek(addDays(date, 1), schema.week) === addDays(date, 1)
26
+
27
+ /**
28
+ * Hourly. Sends the reminders of every site whose 17:00 hour on the day before the week starts it is. `now` is for tests and the
29
+ * live check; the cron passes nothing. `sent` counts mails. Sending twice is harmless: a `reminders` row per site,
30
+ * brick, week and person stops it.
31
+ */
32
+ export const sweep = internalMutation({
33
+ args: { now: v.optional(v.number()) },
34
+ handler: async (ctx, args): Promise<{ sent: number }> => {
35
+ if (!mailAvailable()) return { sent: 0 }
36
+ const now = new Date(args.now ?? Date.now())
37
+ let sent = 0
38
+ for (const site of await ctx.db.query('sites').collect()) {
39
+ if (site.deleting) continue
40
+ const schema = site.schema as Schema
41
+ const today = todayIn(schema.timeZone, now)
42
+ if (!isDayBeforeWeekStart(today, schema) || hourIn(schema.timeZone, now) !== REMIND_HOUR) continue
43
+ sent += await remindSite(ctx, site, schema, today, now.getTime())
44
+ }
45
+ return { sent }
46
+ },
47
+ })
48
+
49
+ async function remindSite(ctx: MutationCtx, site: Doc<'sites'>, schema: Schema, today: string, at: number): Promise<number> {
50
+ // Tomorrow starts the coming week; asking from there keeps the rule right for any first day.
51
+ const coming = addDays(today, 1)
52
+ const info = schema.week
53
+ const week = workWeekOf(coming, info)
54
+ const members = await ctx.db.query('memberships').withIndex('by_site', (q) => q.eq('site', site._id)).collect()
55
+ // Live entries of the collections that plan weeks ahead (no drafts, nothing deleted), read once per site.
56
+ const live = new Map<string, { data: Record<string, Json> }[]>()
57
+ for (const [key, brick] of Object.entries(schema.bricks)) {
58
+ if (brick.kind !== 'collection' || !brick.plans) continue
59
+ const rows = await ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', site._id).eq('brick', key)).collect()
60
+ live.set(key, rows.filter((r) => !r.deletedAt && r.state !== 'draft').map((r) => ({ data: r.data as Record<string, Json> })))
61
+ }
62
+ const bricks = reminderBricks(schema)
63
+ // Status lines are asked for the coming week's first day, like the weekly rule.
64
+ const states = new Map((await statesOf(ctx, site, bricks.filter((b) => !b.weekly).map((b) => b.key), coming)).map((s) => [s.brick, s]))
65
+ // What is due this Sunday, per brick: the words of its mail line in a reader's language.
66
+ const due: { key: string; refs: string[]; line: (locale: string) => string }[] = []
67
+ for (const { key, brick, weekly, refs } of bricks) {
68
+ const label = (locale: string) => labelOf(brick.label, locale, schema.locales[0]!)
69
+ if (weekly) {
70
+ const entry = await ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', site._id).eq('brick', key)).first()
71
+ if (!entry || entry.deletedAt) continue
72
+ const state = staleOf(brick, entry.data, coming, info, plannedWeeks(schema, key, (k) => live.get(k) ?? []))
73
+ if (!state || state.current) continue
74
+ due.push({ key, refs, line: (locale) => t(locale, 'mail.weekly.item', { brick: label(locale), line: t(locale, 'mail.weekly.week') }) })
75
+ } else {
76
+ const state = states.get(key)
77
+ const line = state?.due && state.line ? state.line : undefined
78
+ if (!line) continue
79
+ // The line is about the coming day, which the Today page's words call "today"; the mail names it tomorrow.
80
+ const words = (locale: string) => line.kind === 'hours' && 'unknown' in line.today ? t(locale, 'mail.weekly.hoursUnknown') : statusText(locale, schema, brick, line)
81
+ due.push({ key, refs, line: (locale) => t(locale, 'mail.weekly.item', { brick: label(locale), line: words(locale) }) })
82
+ }
83
+ }
84
+ if (!due.length) return 0
85
+ let sent = 0
86
+ // One mail per person and site (decision C): every due item they may fix (owners all, staff with a task that fixes
87
+ // it, SPEC 2.7) that this week's mail has not named yet. A `reminders` row per brick keeps a rerun from repeating it.
88
+ for (const member of members) {
89
+ const items: typeof due = []
90
+ for (const item of due) {
91
+ if (!isReminded(member, item.refs)) continue
92
+ const done = await ctx.db.query('reminders').withIndex('by_site_brick_week_user', (q) => q.eq('site', site._id).eq('brick', item.key).eq('week', week).eq('user', member.user)).first()
93
+ if (!done) items.push(item)
94
+ }
95
+ if (!items.length) continue
96
+ const to = await addressOf(ctx, member.user)
97
+ if (!to) continue
98
+ const locale = await localeOfUser(ctx, member.user)
99
+ for (const item of items) await ctx.db.insert('reminders', { site: site._id, brick: item.key, week, user: member.user, at })
100
+ await queueMail(ctx, {
101
+ to,
102
+ subject: t(locale, 'mail.weekly.subject', { site: site.name, count: items.length }),
103
+ text: t(locale, 'mail.weekly.text', { site: site.name, items: items.map((item) => item.line(locale)).join('\n'), link: `${siteOrigin()}/s/${site.slug}`, settings: `${siteOrigin()}/?all` }),
104
+ })
105
+ sent++
106
+ }
107
+ return sent
108
+ }
109
+
110
+ /** The verified address of a person who has not switched reminders off, else nothing. */
111
+ async function addressOf(ctx: MutationCtx, userId: string): Promise<string | undefined> {
112
+ const settings = await ctx.db.query('userSettings').withIndex('by_user', (q) => q.eq('user', userId)).unique()
113
+ if (settings?.remindByMail === false) return undefined
114
+ const user = await ctx.runQuery(components.betterAuth.adapter.findOne, { model: 'user', where: [{ field: 'id', value: userId }] })
115
+ return user?.emailVerified === true && typeof user.email === 'string' ? user.email : undefined
116
+ }
@@ -0,0 +1,121 @@
1
+ // Retention (SPEC 12). Daily; one run handles at most 200 documents in all. A run that uses up
2
+ // its budget schedules the next run at once, so the rest follows in batches.
3
+ import { addDays, deletesExpired, todayIn, visibleUntil, type Schema } from '@lupinum/ginko/internal'
4
+ import { internal } from './_generated/api'
5
+ import { internalMutation } from './_generated/server'
6
+ import { windowOf } from './bundle'
7
+ import { SYSTEM } from './lib/access'
8
+ import { deletePrevious, purgeUpload } from './lib/library'
9
+ import { msg, recorded } from './lib/history'
10
+ import { countersOf, DELETED_KEPT, purgeEntry, softRemove, writeCounters } from './lib/lifecycle'
11
+
12
+ export const BATCH = 200
13
+ const DAY = 24 * 60 * 60 * 1000
14
+ const OPS_KEPT = 30 * DAY
15
+ const CHANGES_KEPT = 365 * DAY
16
+ /** Trash and files before a replace (SPEC 12). */
17
+ const TRASH_KEPT = 30 * DAY
18
+ const PREVIOUS_KEPT = 30 * DAY
19
+ /** The outbox holds sign-in codes in plain text (local and `.test` addresses): a day is enough to read them. */
20
+ const OUTBOX_KEPT = DAY
21
+ /** Rate windows are only needed for the current minute; a day is kept for inspection. */
22
+ const WINDOWS_KEPT_MINUTES = 24 * 60
23
+
24
+ export const daily = internalMutation({
25
+ args: {},
26
+ handler: async (ctx): Promise<null> => {
27
+ const now = Date.now()
28
+ let left = BATCH
29
+
30
+ const ops = await ctx.db.query('ops').withIndex('by_at', (q) => q.lt('at', now - OPS_KEPT)).take(left)
31
+ for (const op of ops) await ctx.db.delete(op._id)
32
+ left -= ops.length
33
+
34
+ const changes = await ctx.db.query('changes').withIndex('by_at', (q) => q.lt('at', now - CHANGES_KEPT)).take(left)
35
+ for (const change of changes) {
36
+ const refs = await ctx.db.query('fileRefs').withIndex('by_holder', (q) => q.eq('holder', 'change').eq('holderId', change._id)).collect()
37
+ for (const ref of refs) await ctx.db.delete(ref._id)
38
+ await ctx.db.delete(change._id)
39
+ }
40
+ left -= changes.length
41
+
42
+ // Decided proposals and releases go with the changes they led to (SPEC 17). An undecided or scheduled one stays.
43
+ const decided = await ctx.db.query('proposals').withIndex('by_decided', (q) => q.gt('decidedAt', 0).lt('decidedAt', now - CHANGES_KEPT)).take(left)
44
+ for (const row of decided) if (row.status !== 'scheduled') await ctx.db.delete(row._id)
45
+ left -= decided.length
46
+ const releases = await ctx.db.query('releases').withIndex('by_decided', (q) => q.gt('decidedAt', 0).lt('decidedAt', now - CHANGES_KEPT)).take(left)
47
+ for (const row of releases) if (row.status !== 'scheduled') await ctx.db.delete(row._id)
48
+ left -= releases.length
49
+
50
+ // Replaced files: the storage of an earlier version goes 30 days after the replace. The few rows with `previous` are all looked at.
51
+ for (const row of await ctx.db.query('uploads').withIndex('by_previous', (q) => q.eq('hasPrevious', true)).take(BATCH * 3)) {
52
+ if (left === 0) break
53
+ const old = (row.previous ?? []).filter((p) => p.replacedAt < now - PREVIOUS_KEPT)
54
+ if (!old.length) continue
55
+ for (const p of old) await deletePrevious(ctx, p)
56
+ const rest = (row.previous ?? []).filter((p) => p.replacedAt >= now - PREVIOUS_KEPT)
57
+ await ctx.db.patch(row._id, { previous: rest.length ? rest : undefined, hasPrevious: rest.length ? true : undefined })
58
+ left--
59
+ }
60
+
61
+ const windows = await ctx.db.query('rateWindows').withIndex('by_window', (q) => q.lt('window', windowOf(now) - WINDOWS_KEPT_MINUTES)).take(left)
62
+ for (const window of windows) await ctx.db.delete(window._id)
63
+ left -= windows.length
64
+
65
+ const mails = await ctx.db.query('outbox').withIndex('by_at', (q) => q.lt('at', now - OUTBOX_KEPT)).take(left)
66
+ for (const mail of mails) await ctx.db.delete(mail._id)
67
+ left -= mails.length
68
+
69
+ for (const site of await ctx.db.query('sites').collect()) {
70
+ if (left === 0) break
71
+ const schema = site.schema as Schema
72
+ const today = todayIn(schema.timeZone, new Date(now))
73
+ // An entry is expired when it has been invisible for 30 days: its last visible day is before this date.
74
+ const expiredSince = addDays(today, -30)
75
+ // The site's counters change in this loop; one patch at the end writes them.
76
+ const state = countersOf(site)
77
+ let touched = false
78
+
79
+ for (const [key, brick] of Object.entries(schema.bricks)) {
80
+ if (left === 0) break
81
+ if (deletesExpired(brick)) {
82
+ const rows = await ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', site._id).eq('brick', key)).collect()
83
+ // Drafts are left alone: nobody has published them yet (SPEC 15).
84
+ const expired = rows.filter((row) => {
85
+ const until = visibleUntil(brick, row.data)
86
+ return !row.deletedAt && row.state !== 'draft' && until !== undefined && until < expiredSince
87
+ })
88
+ for (const row of expired.slice(0, left)) {
89
+ await softRemove(ctx, state, row, `retention:${row._id}:${row.lifeRev + 1}`, SYSTEM, recorded(msg('history.expiredAutoRemoved')), now)
90
+ left--
91
+ touched = true
92
+ }
93
+ }
94
+
95
+ // Live entries have no deletedAt, and in the index `undefined` sorts before every number:
96
+ // without the lower bound this range would hard-delete every live entry.
97
+ const deleted = await ctx.db.query('entries').withIndex('by_site_brick_deleted', (q) => q.eq('site', site._id).eq('brick', key).gt('deletedAt', 0).lt('deletedAt', now - DELETED_KEPT)).take(left)
98
+ for (const row of deleted) await purgeEntry(ctx, state, row)
99
+ if (deleted.length) touched = true
100
+ left -= deleted.length
101
+ }
102
+
103
+ // Trash: 30 days, then the file goes for good, but only when nothing refers to it any more
104
+ // (an entry or a change within its year). Files that are still referred to stay and are looked at again tomorrow.
105
+ if (left > 0) {
106
+ const trashed = await ctx.db.query('uploads').withIndex('by_site_trashed', (q) => q.eq('site', site._id).gt('trashedAt', 0).lt('trashedAt', now - TRASH_KEPT)).take(BATCH * 3)
107
+ for (const row of trashed) {
108
+ if (left === 0) break
109
+ if (await ctx.db.query('fileRefs').withIndex('by_file', (q) => q.eq('file', row._id)).first()) continue
110
+ await purgeUpload(ctx, row)
111
+ left--
112
+ }
113
+ }
114
+
115
+ if (touched) await writeCounters(ctx, site._id, state)
116
+ }
117
+
118
+ if (left === 0) await ctx.scheduler.runAfter(0, internal.retention.daily, {})
119
+ return null
120
+ },
121
+ })
@@ -0,0 +1,62 @@
1
+ // GET /bundle/<site>?format=3&locale=<l>[&minRev=<schemaRev>.<contentRev>][&files=stable] (SPEC 6).
2
+ // Order: format, rate limit (also finds the site), build. Every answer is JSON with code and
3
+ // an English message on errors (a site's server reads them); the HTTP status carries the SPEC 6 mapping.
4
+ import { BUNDLE_FORMAT } from '@lupinum/ginko/internal'
5
+ import type { HttpRouter } from 'convex/server'
6
+ import { internal } from '../_generated/api'
7
+ import { SITE_TOKEN_HEADER } from '../bundle'
8
+ import { httpAction } from '../_generated/server'
9
+
10
+ const headers = {
11
+ 'content-type': 'application/json; charset=utf-8',
12
+ 'cache-control': 'no-store',
13
+ 'access-control-allow-origin': '*',
14
+ }
15
+
16
+ function reply(status: number, body: unknown): Response {
17
+ return new Response(JSON.stringify(body), { status, headers })
18
+ }
19
+
20
+ function failure(status: number, code: string, message: string): Response {
21
+ return reply(status, { code, message })
22
+ }
23
+
24
+ /** `<schemaRev>.<contentRev>`; a malformed value is ignored. */
25
+ function parseMinRev(value: string | null): { schemaRev: number; contentRev: number } | undefined {
26
+ const match = value?.match(/^(\d+)\.(\d+)$/)
27
+ if (!match) return undefined
28
+ return { schemaRev: Number(match[1]), contentRev: Number(match[2]) }
29
+ }
30
+
31
+ const bundle = httpAction(async (ctx, request) => {
32
+ try {
33
+ const url = new URL(request.url)
34
+ const slug = url.pathname.slice('/bundle/'.length)
35
+ if (url.searchParams.get('format') !== String(BUNDLE_FORMAT)) {
36
+ return failure(400, 'FORMAT_UNSUPPORTED', `This format does not exist. Expected: format=${BUNDLE_FORMAT}.`)
37
+ }
38
+
39
+ const token = request.headers.get(SITE_TOKEN_HEADER) ?? undefined
40
+ const admitted = await ctx.runMutation(internal.bundle.admit, { slug, token })
41
+ if (admitted === 'SITE_NOT_FOUND') return failure(404, 'SITE_NOT_FOUND', 'This site does not exist.')
42
+ if (admitted === 'RATE_LIMITED') return failure(429, 'RATE_LIMITED', 'Too many requests. Please wait a minute.')
43
+
44
+ const result = await ctx.runQuery(internal.bundle.build, {
45
+ slug,
46
+ locale: url.searchParams.get('locale') ?? '',
47
+ minRev: parseMinRev(url.searchParams.get('minRev')),
48
+ // Opt-in: a site version that does not know the /__ginko/file route keeps live storage URLs.
49
+ ...(url.searchParams.get('files') === 'stable' ? { stableFiles: true } : {}),
50
+ })
51
+ if (result === 'SITE_NOT_FOUND') return failure(404, 'SITE_NOT_FOUND', 'This site does not exist.')
52
+ if (result === 'STALE') return failure(409, 'STALE', 'The content is older than requested. Please load it again later.')
53
+ return reply(200, result)
54
+ } catch {
55
+ return failure(503, 'INTERNAL', 'The platform cannot be reached right now.')
56
+ }
57
+ })
58
+
59
+ /** HTTP routes of this area. http.ts only composes. */
60
+ export function register(http: HttpRouter) {
61
+ http.route({ pathPrefix: '/bundle/', method: 'GET', handler: bundle })
62
+ }
@@ -0,0 +1,80 @@
1
+ // HTTP routes of `ginko connect` (connect.ts): `POST /connect/start` opens a request, `POST /connect/poll` asks for its
2
+ // key. Both are public and take no key. Secrets (the device code, the key) travel only in bodies, never in a URL, a
3
+ // log line or an error message.
4
+ import { sha256 } from '@lupinum/ginko/internal'
5
+ import type { HttpRouter } from 'convex/server'
6
+ import { internal } from '../_generated/api'
7
+ import { httpAction } from '../_generated/server'
8
+ import { CONNECT, USER_CODE_ALPHABET } from '../connect'
9
+ import { failure, json } from './key'
10
+
11
+ /** Bodies are tiny; anything larger is not a connect call. */
12
+ const MAX_BODY = 1024
13
+ const DEVICE_CODE = /^[A-Za-z0-9_-]{43}$/
14
+ const NOT_VALID = 'This connect request is not valid. Start again with ginko connect.'
15
+
16
+ async function bodyOf(request: Request): Promise<Record<string, unknown> | undefined> {
17
+ const raw = await request.text()
18
+ if (raw.length > MAX_BODY) return undefined
19
+ try {
20
+ const body: unknown = JSON.parse(raw)
21
+ return typeof body === 'object' && body !== null && !Array.isArray(body) ? body as Record<string, unknown> : undefined
22
+ } catch {
23
+ return undefined
24
+ }
25
+ }
26
+
27
+ const base64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
28
+
29
+ /** 8 symbols of the alphabet, each equally likely (bytes at or above the largest multiple of 31 are drawn again). */
30
+ function userCode(): string {
31
+ const limit = 256 - (256 % USER_CODE_ALPHABET.length)
32
+ let code = ''
33
+ while (code.length < 8) {
34
+ for (const byte of crypto.getRandomValues(new Uint8Array(16))) {
35
+ if (byte < limit && code.length < 8) code += USER_CODE_ALPHABET[byte % USER_CODE_ALPHABET.length]
36
+ }
37
+ }
38
+ return code
39
+ }
40
+
41
+ const start = httpAction(async (ctx, request) => {
42
+ const body = await bodyOf(request)
43
+ // Control characters would reach the Studio page and the Team page's key list.
44
+ const label = typeof body?.label === 'string' ? body.label.replace(/[\p{Cc}\p{Cf}]/gu, ' ').trim() : ''
45
+ if (label.length < 1 || label.length > CONNECT.labelMax) return failure('INVALID', `The label must have 1 to ${CONNECT.labelMax} characters.`)
46
+ const siteUrl = process.env.SITE_URL?.replace(/\/+$/, '')
47
+ if (!siteUrl) return failure('INTERNAL', 'The platform has no SITE_URL, so it cannot name the page that confirms the code.')
48
+ const deviceCode = base64url(crypto.getRandomValues(new Uint8Array(32)))
49
+ // A clash with a live code is rare (31⁸ codes, at most 200 live); a new code is drawn.
50
+ for (let attempt = 0; attempt < 3; attempt++) {
51
+ const code = userCode()
52
+ const opened = await ctx.runMutation(internal.connect.open, { deviceHash: sha256(deviceCode), userCode: code, label })
53
+ if (opened.ok) {
54
+ return json(200, {
55
+ deviceCode,
56
+ userCode: `${code.slice(0, 4)}-${code.slice(4)}`,
57
+ verifyUrl: `${siteUrl}/connect`,
58
+ interval: CONNECT.intervalSeconds,
59
+ expiresIn: Math.round(CONNECT.lifetimeMs / 1000),
60
+ })
61
+ }
62
+ if (opened.reason === 'full') return json(429, { code: 'RATE_LIMITED', message: 'Too many connect requests are open. Try again in 10 minutes.' })
63
+ }
64
+ return failure('INTERNAL', 'Could not open a connect request. Try again.')
65
+ })
66
+
67
+ const poll = httpAction(async (ctx, request) => {
68
+ const body = await bodyOf(request)
69
+ const deviceCode = body?.deviceCode
70
+ if (typeof deviceCode !== 'string' || !DEVICE_CODE.test(deviceCode)) return failure('INVALID', NOT_VALID)
71
+ const answer = await ctx.runMutation(internal.connect.redeem, { deviceHash: sha256(deviceCode) })
72
+ if (answer.state === 'pending') return json(200, { status: 'pending' })
73
+ if (answer.state === 'invalid') return failure('INVALID', NOT_VALID)
74
+ return json(200, { site: answer.site, key: answer.key })
75
+ })
76
+
77
+ export function register(http: HttpRouter) {
78
+ http.route({ path: '/connect/start', method: 'POST', handler: start })
79
+ http.route({ path: '/connect/poll', method: 'POST', handler: poll })
80
+ }
@@ -0,0 +1,23 @@
1
+ // HTTP route for `ginko export` and `pnpm local:pull` (SPEC 9, 12): `GET /export?site=<slug>`.
2
+ // Same push key, site check and error answers as GET /release/state; the key needs scope export or pull.
3
+ import type { HttpRouter } from 'convex/server'
4
+ import { internal } from '../_generated/api'
5
+ import { httpAction } from '../_generated/server'
6
+ import { authenticate, errorResponse, failure, json } from './key'
7
+
8
+ const exportSite = httpAction(async (ctx, request) => {
9
+ const key = await authenticate(ctx, request, ['export', 'pull'])
10
+ if (key instanceof Response) return key
11
+ const slug = new URL(request.url).searchParams.get('site')
12
+ if (!slug) return failure('INVALID', 'The parameter site is missing.')
13
+ if (slug !== key.siteSlug) return failure('FORBIDDEN', 'This key belongs to another site.')
14
+ try {
15
+ return json(200, await ctx.runQuery(internal.backup.snapshot, { site: key.site }))
16
+ } catch (error) {
17
+ return errorResponse(error, 'The export failed. Please try again later.')
18
+ }
19
+ })
20
+
21
+ export function register(http: HttpRouter) {
22
+ http.route({ path: '/export', method: 'GET', handler: exportSite })
23
+ }
@@ -0,0 +1,34 @@
1
+ // GET /file/<site-slug>/<uploadId>/<storageId>: the stable address of a site's file. The site's own server
2
+ // (`/__ginko/file/…`) asks here and gets a redirect to the current storage URL, so pages never hold storage hosts.
3
+ // The bytes of a storage id never change, but its storage address may (a new backend or host), so the redirect is
4
+ // cached for an hour only; the site caches the bytes. The check makes sure the route only serves files that a ready
5
+ // upload of that site owns.
6
+ import type { HttpRouter } from 'convex/server'
7
+ import { internal } from '../_generated/api'
8
+ import { httpAction } from '../_generated/server'
9
+
10
+ function notFound(): Response {
11
+ return new Response(JSON.stringify({ code: 'FILE_NOT_FOUND', message: 'This file does not exist.' }), {
12
+ status: 404,
13
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'access-control-allow-origin': '*' },
14
+ })
15
+ }
16
+
17
+ const file = httpAction(async (ctx, request) => {
18
+ try {
19
+ const [slug = '', upload = '', storage = ''] = new URL(request.url).pathname.slice('/file/'.length).split('/')
20
+ const target = await ctx.runQuery(internal.bundle.fileUrl, { slug: decodeURIComponent(slug), upload, storage })
21
+ if (!target) return notFound()
22
+ return new Response(null, { status: 302, headers: { location: target, 'cache-control': 'public, max-age=3600', 'access-control-allow-origin': '*' } })
23
+ } catch {
24
+ return new Response(JSON.stringify({ code: 'INTERNAL', message: 'The platform cannot be reached right now.' }), {
25
+ status: 503,
26
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
27
+ })
28
+ }
29
+ })
30
+
31
+ /** HTTP routes of this area. http.ts only composes. */
32
+ export function register(http: HttpRouter) {
33
+ http.route({ pathPrefix: '/file/', method: 'GET', handler: file })
34
+ }
@@ -0,0 +1,53 @@
1
+ // Shared by the CLI routes (release, export): the push key `Authorization: Bearer ginko_<site>_<32>`
2
+ // names the site, only its SHA-256 is stored. Answers are JSON; errors carry `code` and an English message
3
+ // (the CLI prints it to a developer), plus `key`/`params` when the error came from the catalog.
4
+ import { sha256 } from '@lupinum/ginko/internal'
5
+ import { internal } from '../_generated/api'
6
+ import type { ActionCtx } from '../_generated/server'
7
+ import { t, type MessageKey } from '../lib/i18n'
8
+ import { SLUG_PATTERN } from '../lib/input'
9
+
10
+ export type Scope = 'release' | 'pull' | 'check' | 'export'
11
+
12
+ const TOKEN = new RegExp(`^ginko_${SLUG_PATTERN}_[a-z0-9]{32}$`)
13
+
14
+ /** HTTP status per error code. Codes outside SPEC 11 (UNAUTHORIZED, INTERNAL) are used here only. */
15
+ const STATUS: Record<string, number> = {
16
+ INVALID: 400, SCHEMA_REJECTED: 400, MIGRATION_CHANGED: 400, MIGRATION_INCOMPLETE: 400,
17
+ UNAUTHORIZED: 401, FORBIDDEN: 403, NOT_FOUND: 404, SITE_NOT_FOUND: 404, CHANGED_SINCE: 409,
18
+ TOO_LARGE: 413, RELEASE_TOO_LARGE: 413,
19
+ }
20
+
21
+ export function json(status: number, body: unknown): Response {
22
+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store' } })
23
+ }
24
+
25
+ export function failure(code: string, message: string, details?: unknown): Response {
26
+ return json(STATUS[code] ?? 500, { code: STATUS[code] ? code : 'INTERNAL', message, ...(details === undefined ? {} : { details }) })
27
+ }
28
+
29
+ /** Turns a thrown `fail(...)` (ConvexError with `{ code, message, details? }`) into the HTTP answer. */
30
+ export function errorResponse(error: unknown, fallback = 'The release failed. Please try again later.'): Response {
31
+ const data = (error as { data?: unknown }).data
32
+ if (data && typeof data === 'object' && 'code' in data && 'message' in data) {
33
+ const { code, message, key, params, details } = data as { code: string; message: string; key?: string; params?: Record<string, string | number>; details?: unknown }
34
+ // `message` is the catalog's German default; the developer reads English.
35
+ return failure(code, key ? t('en', key as MessageKey, params) : message, details)
36
+ }
37
+ return failure('INTERNAL', fallback)
38
+ }
39
+
40
+ /** "Last used" on the Team page is a date, so one stamp an hour is enough and a busy CI adds few writes. */
41
+ const TOUCH_EVERY_MS = 60 * 60_000
42
+
43
+ /** Resolves the bearer key to its site and checks revocation and scope. Returns a response on failure. */
44
+ export async function authenticate(ctx: ActionCtx, request: Request, scopes: Scope[]) {
45
+ const header = request.headers.get('authorization') ?? ''
46
+ const token = header.startsWith('Bearer ') ? header.slice('Bearer '.length).trim() : ''
47
+ if (!TOKEN.test(token)) return failure('UNAUTHORIZED', 'The key is missing or invalid.')
48
+ const key = await ctx.runQuery(internal.release.pushKey, { hash: sha256(token) })
49
+ if (!key || key.revokedAt !== null) return failure('UNAUTHORIZED', 'The key is missing or invalid.')
50
+ if (!scopes.some((s) => key.scopes.includes(s))) return failure('FORBIDDEN', 'This key may not do that.')
51
+ if (key.lastUsedAt === null || Date.now() - key.lastUsedAt > TOUCH_EVERY_MS) await ctx.runMutation(internal.release.touchPushKey, { key: key.keyId })
52
+ return key
53
+ }