@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,296 @@
1
+ // Steps 6 and 7 of the shared write flow (SPEC 4.1): check files and budget, then write
2
+ // the entry with its revisions, the change row and the file references in one place.
3
+ import type { Field, Fields, Json } from '@lupinum/ginko'
4
+ import type { FileField } from '@lupinum/ginko/internal'
5
+ import { checkLinks, entryBytes, fileProblem, fitsBudget, linkTargets, stableJson, type LinkIssue, type Schema, type ValidateOptions } from '@lupinum/ginko/internal'
6
+ import type { Doc, Id } from '../_generated/dataModel'
7
+ import type { MutationCtx, QueryCtx } from '../_generated/server'
8
+ import { bundleOf, type NewItem } from '../bundle'
9
+ import { byOf, fail, type Actor } from './access'
10
+ import { fileIdsOf, refIdsIn, treesOf, usesOf, type Data, type IsUploadId, type Prints, type Use } from './content'
11
+ import type { Recorded } from './history'
12
+ import { putTrees } from './trees'
13
+
14
+ export { SITE_BUDGET as BUDGET } from '@lupinum/ginko/internal'
15
+ import { SITE_BUDGET as BUDGET } from '@lupinum/ginko/internal'
16
+
17
+ /**
18
+ * "340 KB", "4.2 MB": sizes in error texts, on the same 1024 base as the Studio's `sizeText` (utils/size.ts). `up` rounds
19
+ * up, for a size over a limit and the amount to cut.
20
+ */
21
+ export function sizeText(bytes: number, up = false): string {
22
+ const round = up ? Math.ceil : Math.round
23
+ const kb = Math.max(1, round(bytes / 1024))
24
+ if (kb < 1024) return `${kb} KB`
25
+ return `${(round(bytes / (1024 * 1024) * 10) / 10).toFixed(1).replace(/\.0$/, '')} MB`
26
+ }
27
+
28
+ /**
29
+ * The params of a budget error: how much is used, the limit, and how much is over it. Used and over round up, so
30
+ * 1 byte over 480 KB reads "481 KB von höchstens 480 KB … etwa 1 KB", never "480 KB von höchstens 480 KB".
31
+ */
32
+ export const overBudget = (used: number, limit: number) => ({ used: sizeText(used, true), limit: sizeText(limit), over: sizeText(used - limit, true) })
33
+
34
+ /** The `$file.<id>` words of Markdown texts that can name an upload: those with the form of an uploads ID. */
35
+ export const uploadIdsOf = (ctx: QueryCtx): IsUploadId => (id) => ctx.db.normalizeId('uploads', id) !== null
36
+
37
+ /**
38
+ * Fields may only point at ready uploads of the same site (SPEC 4.3 point 3). The ids in `images`
39
+ * are the ones written to an `image` field: they must be image uploads, not a PDF.
40
+ */
41
+ export async function checkFiles(ctx: QueryCtx, site: Id<'sites'>, ids: Iterable<string>, images: ReadonlySet<string> = new Set()) {
42
+ for (const id of ids) {
43
+ const upload = ctx.db.normalizeId('uploads', id) ? await ctx.db.get(id as Id<'uploads'>) : null
44
+ if (!upload || upload.site !== site || upload.status !== 'ready' || upload.trashedAt) {
45
+ fail('INVALID', 'errors.fileNoLongerAvailable', undefined, { file: id })
46
+ }
47
+ if (images.has(id) && !upload.mime.startsWith('image/')) fail('INVALID', 'errors.fileNotImage', undefined, { file: id })
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Going back to an older version (undo, revert) brings back the pictures and files it shows: those of `after` that
53
+ * `before` lacks and that lie in the Files trash come out of it, in the same mutation, so the save's file checks pass.
54
+ * A file deleted for good refuses the step. Returns the files taken out of the trash, with the time they went in.
55
+ */
56
+ export async function untrashFilesOf(ctx: MutationCtx, site: Id<'sites'>, fields: Fields, before: Data, after: Data): Promise<UntrashedFile[]> {
57
+ const isUploadId = uploadIdsOf(ctx)
58
+ const known = fileIdsOf(fields, before, { isUploadId })
59
+ const untrashed: UntrashedFile[] = []
60
+ for (const id of fileIdsOf(fields, after, { isUploadId })) {
61
+ const key = ctx.db.normalizeId('uploads', id)
62
+ if (!key || known.has(id)) continue
63
+ const row = await ctx.db.get(key)
64
+ if (!row) fail('NOT_UNDOABLE', 'errors.versionFileDeleted', undefined, { file: id })
65
+ if (row.site !== site || !row.trashedAt) continue
66
+ await ctx.db.patch(key, { trashedAt: undefined })
67
+ untrashed.push({ id: key, name: row.name, trashedAt: row.trashedAt })
68
+ }
69
+ return untrashed
70
+ }
71
+
72
+ export interface UntrashedFile { id: Id<'uploads'>; name: string; trashedAt: number }
73
+
74
+ /** Checks the files an edit adds: those new to the entry, those new to an image field (a PDF may already sit in a file field), and every file newly placed in a file field. */
75
+ export async function checkNewFiles(ctx: QueryCtx, site: Id<'sites'>, fields: Fields, before: Data, after: Data) {
76
+ const isUploadId = uploadIdsOf(ctx)
77
+ const known = fileIdsOf(fields, before, { isUploadId })
78
+ const knownImages = fileIdsOf(fields, before, { only: 'image' })
79
+ const images = new Set([...fileIdsOf(fields, after, { only: 'image' })].filter((id) => !knownImages.has(id)))
80
+ const added = [...fileIdsOf(fields, after, { isUploadId })].filter((id) => !known.has(id))
81
+ await checkFiles(ctx, site, new Set([...added, ...images]), images)
82
+ // A file's rules belong to the field it sits in. An upload already in a lenient field must still pass the stricter field it is newly placed in.
83
+ const placed = new Set(placementsOf(fields, before).map((p) => `${p.path}\n${p.id}`))
84
+ for (const p of placementsOf(fields, after)) {
85
+ if (placed.has(`${p.path}\n${p.id}`)) continue
86
+ const upload = await ctx.db.get(p.id as Id<'uploads'>)
87
+ const problem = upload ? fileProblem(p.field, { size: upload.size, contentType: upload.mime, name: upload.name }) : undefined
88
+ if (problem?.key === 'file.tooBig') fail('INVALID', 'errors.fileTooBig', problem.params as { max: number }, { file: p.id })
89
+ if (problem) fail('INVALID', 'errors.fileTypeNotAllowed', problem.params as { allowed: string }, { file: p.id })
90
+ }
91
+ }
92
+
93
+ /** One entry's content as it becomes live: `before` is what was live (nothing for a draft going online), `after` what goes live. */
94
+ export interface LiveEdit {
95
+ /** `isNew`: not stored yet (a create that is only proposed); its `_id` is a temporary one and the bundle gets it as an extra item. */
96
+ entry: Pick<Doc<'entries'>, '_id' | 'brick'>; fields: Fields; before: Data; after: Data; isNew?: true
97
+ }
98
+
99
+ /**
100
+ * Refuses a write that puts a new broken link live (V1 link check, "blocks publish on error"). Only links
101
+ * the edit adds count: an old broken link in untouched text never blocks, and warnings never do.
102
+ * Cheap first: without a new link target in the Markdown text no bundle is built. Otherwise the bundles of
103
+ * all languages are built with the new data of every edit in place of the stored one and checked by the core
104
+ * `checkLinks` without a `files` option (the platform does not know the site's public files, so an unknown
105
+ * plain path is not an error). Edits of drafts are not live and must not be passed.
106
+ */
107
+ export async function checkNewLinks(ctx: QueryCtx, site: Doc<'sites'>, edits: LiveEdit[]) {
108
+ const issue = await brokenNewLinks(ctx, site, edits)
109
+ if (issue) fail('INVALID', 'errors.linkBroken', { link: issue.href }, { field: issue.field, link: issue.href })
110
+ }
111
+
112
+ /** The first new broken link of the edits, if any; `checkNewLinks` throws on it, the scheduled publish records it. */
113
+ export async function brokenNewLinks(ctx: QueryCtx, site: Doc<'sites'>, edits: LiveEdit[]): Promise<LinkIssue | undefined> {
114
+ const added = new Map<string, Set<string>>()
115
+ for (const e of edits) {
116
+ const known = linkTargets(e.fields, e.before)
117
+ const fresh = new Set([...linkTargets(e.fields, e.after)].filter((href) => !known.has(href)))
118
+ if (fresh.size) added.set(e.entry._id, fresh)
119
+ }
120
+ if (!added.size) return undefined
121
+ const schema = site.schema as Schema
122
+ const overrides = new Map(edits.map((e) => [e.entry._id as string, e.after]))
123
+ const items: NewItem[] = edits.filter((e) => e.isNew).map((e) => ({ brick: e.entry.brick, id: e.entry._id, data: e.after }))
124
+ const bundles = await Promise.all(schema.locales.map((locale) => bundleOf(ctx, site, locale, overrides, items)))
125
+ for (const issue of checkLinks(bundles, schema)) {
126
+ if (issue.severity !== 'error') continue
127
+ const edit = edits.find((e) => issue.brick === e.entry.brick && (issue.id === e.entry._id || issue.id === e.entry.brick))
128
+ if (edit && added.get(edit.entry._id)?.has(issue.href)) return issue
129
+ }
130
+ return undefined
131
+ }
132
+
133
+ /** The `refs` callback for validate(): looks up every entry the data points to (live entries of the target brick on this site). */
134
+ export async function refsFor(ctx: QueryCtx, site: Id<'sites'>, fields: Fields, data: Data): Promise<NonNullable<ValidateOptions['refs']>> {
135
+ const found = new Set<string>()
136
+ for (const { to, id } of refIdsIn(fields, data)) {
137
+ const key = ctx.db.normalizeId('entries', id)
138
+ const row = key ? await ctx.db.get(key) : null
139
+ if (row && row.site === site && row.brick === to && !row.deletedAt) found.add(`${to}\n${id}`)
140
+ }
141
+ return (brick, id) => found.has(`${brick}\n${id}`)
142
+ }
143
+
144
+ /**
145
+ * The Files library descriptions of the images in `data` (image fields and Markdown references), for `usesOf` and
146
+ * validate(): one read per file. Ids that are no upload give no text.
147
+ */
148
+ async function altsFor(ctx: QueryCtx, fields: Fields, data: Data): Promise<(file: string) => Record<string, string> | undefined> {
149
+ const found = new Map<string, Record<string, string>>()
150
+ for (const id of fileIdsOf(fields, data, { isUploadId: uploadIdsOf(ctx) })) {
151
+ const key = ctx.db.normalizeId('uploads', id)
152
+ const alt = key ? (await ctx.db.get(key))?.alt : undefined
153
+ if (alt) found.set(id, alt)
154
+ }
155
+ return (file) => found.get(file)
156
+ }
157
+
158
+ /** Every use of a file in `data` with its "missing alt text" mark, library descriptions included (`usesOf`). */
159
+ export async function entryUses(ctx: QueryCtx, fields: Fields, data: Data, locales: readonly string[]): Promise<Map<string, Use[]>> {
160
+ return usesOf(fields, data, locales, uploadIdsOf(ctx), await altsFor(ctx, fields, data))
161
+ }
162
+
163
+ /** The files of `data` that are ready uploads of this site outside the trash, with their kind: what a `$file.<id>` in a text may name. */
164
+ async function liveUploadsFor(ctx: QueryCtx, site: Id<'sites'>, fields: Fields, data: Data): Promise<NonNullable<ValidateOptions['uploads']>> {
165
+ const live = new Map<string, 'image' | 'file'>()
166
+ for (const id of fileIdsOf(fields, data, { isUploadId: uploadIdsOf(ctx) })) {
167
+ const key = ctx.db.normalizeId('uploads', id)
168
+ const upload = key ? await ctx.db.get(key) : null
169
+ if (upload && upload.site === site && upload.status === 'ready' && !upload.trashedAt) live.set(id, upload.mime.startsWith('image/') ? 'image' : 'file')
170
+ }
171
+ return (file) => live.get(file)
172
+ }
173
+
174
+ /**
175
+ * The options validate() takes from the database: the entries a ref field points to, the library descriptions of the
176
+ * images, and the live uploads the Markdown texts may reference.
177
+ */
178
+ export async function lookupsFor(ctx: QueryCtx, site: Id<'sites'>, fields: Fields, data: Data): Promise<Pick<ValidateOptions, 'refs' | 'fileAlt' | 'uploads'>> {
179
+ return { refs: await refsFor(ctx, site, fields, data), fileAlt: await altsFor(ctx, fields, data), uploads: await liveUploadsFor(ctx, site, fields, data) }
180
+ }
181
+
182
+ /** A file upload in a file field: the field's path in the entry (`doc`, `files.0.doc`), the upload ID and the field's rules. */
183
+ interface Placement {
184
+ path: string
185
+ id: string
186
+ field: FileField
187
+ }
188
+
189
+ /** Every file placed in a file field of the entry, list rows included. */
190
+ function placementsOf(fields: Fields, data: Data): Placement[] {
191
+ const out: Placement[] = []
192
+ const walk = (path: string, field: Field, value: Json | undefined) => {
193
+ if (typeof value !== 'object' || value === null) return
194
+ if (field.type === 'file' && !Array.isArray(value) && typeof value.file === 'string') out.push({ path, id: value.file, field })
195
+ if (field.type === 'list' && Array.isArray(value)) {
196
+ value.forEach((row, i) => {
197
+ if (typeof row === 'object' && row !== null && !Array.isArray(row)) for (const [k, inner] of Object.entries(field.of)) walk(`${path}.${i}.${k}`, inner, row[k])
198
+ })
199
+ }
200
+ }
201
+ for (const [name, field] of Object.entries(fields)) walk(name, field, data[name])
202
+ return out
203
+ }
204
+
205
+ /** Replaces the file references of one holder with exactly `ids`. */
206
+ export async function syncFileRefs(ctx: MutationCtx, site: Id<'sites'>, holder: 'entry' | 'change' | 'pending', holderId: string, ids: Set<string>) {
207
+ const rows = await ctx.db.query('fileRefs').withIndex('by_holder', (q) => q.eq('holder', holder).eq('holderId', holderId)).collect()
208
+ const have = new Set(rows.map((r) => r.file as string))
209
+ for (const row of rows) if (!ids.has(row.file)) await ctx.db.delete(row._id)
210
+ for (const id of ids) if (!have.has(id)) await ctx.db.insert('fileRefs', { site, file: id as Id<'uploads'>, holder, holderId })
211
+ }
212
+
213
+ /**
214
+ * Replaces the file references of one entry with exactly the files in `uses` (from `usesOf`, the
215
+ * same walk that finds the ids), and keeps each row's `uses` and `missingAlt` current.
216
+ */
217
+ export async function syncEntryRefs(ctx: MutationCtx, site: Id<'sites'>, entry: Id<'entries'>, uses: Map<string, Use[]>) {
218
+ const rows = await ctx.db.query('fileRefs').withIndex('by_holder', (q) => q.eq('holder', 'entry').eq('holderId', entry)).collect()
219
+ const have = new Set<string>()
220
+ for (const row of rows) {
221
+ const wanted = uses.get(row.file)
222
+ // A second row for the same file is a leftover; one row per file is the rule.
223
+ if (!wanted || have.has(row.file)) {
224
+ await ctx.db.delete(row._id)
225
+ continue
226
+ }
227
+ have.add(row.file)
228
+ const missingAlt = wanted.some((u) => u.missingAlt)
229
+ if (!same(row.uses, wanted) || row.missingAlt !== missingAlt) await ctx.db.patch(row._id, { uses: wanted, missingAlt })
230
+ }
231
+ for (const [file, list] of uses) {
232
+ if (!have.has(file)) await ctx.db.insert('fileRefs', { site, file: file as Id<'uploads'>, holder: 'entry', holderId: entry, uses: list, missingAlt: list.some((u) => u.missingAlt) })
233
+ }
234
+ }
235
+
236
+ export interface EntryWrite {
237
+ actor: Actor
238
+ entry: Doc<'entries'>
239
+ fields: Fields
240
+ /** Root fields this write changed (value or prints). */
241
+ roots: string[]
242
+ data: Data
243
+ prints: Prints
244
+ kind: 'save' | 'confirm' | 'undo' | 'place'
245
+ history: Recorded
246
+ opId: string
247
+ }
248
+
249
+ /**
250
+ * Writes a changed entry: rev+1, fieldRevs of the roots, contentRev+1 (not for a draft: the
251
+ * public bundle does not change, SPEC 15), budget, one change
252
+ * row with before/after values and prints of the roots, file references. Callers decide
253
+ * before calling whether anything changed; an unchanged write must not reach this.
254
+ */
255
+ export async function commitEntry(ctx: MutationCtx, w: EntryWrite) {
256
+ const { actor, entry } = w
257
+ const site = actor.site
258
+ // A write that does not grow the entry, the site or the trees always passes, so an entry or site over a limit can be shortened.
259
+ const bytes = entryBytes(w.data, w.prints)
260
+ if (!fitsBudget(bytes, entry.bytes, BUDGET.entryBytes)) fail('TOO_LARGE', 'errors.entryTooLarge', overBudget(bytes, BUDGET.entryBytes))
261
+ const siteBytes = site.bytes - entry.bytes + bytes
262
+ if (!fitsBudget(siteBytes, site.bytes, BUDGET.siteBytes)) fail('TOO_LARGE', 'errors.siteStorageLimitReached', overBudget(siteBytes, BUDGET.siteBytes))
263
+ const trees = await treesOf(w.fields, w.data)
264
+ const treeBytes = (site.treeBytes ?? 0) - (entry.treeBytes ?? 0) + trees.bytes
265
+ if (!fitsBudget(treeBytes, site.treeBytes ?? 0, BUDGET.treeBytes)) fail('TOO_LARGE', 'errors.entryTooComplex')
266
+
267
+ const rev = entry.rev + 1
268
+ const fieldRevs = { ...entry.fieldRevs }
269
+ for (const root of w.roots) fieldRevs[root] = rev
270
+ const draft = entry.state === 'draft'
271
+ const contentRev = draft ? site.contentRev : site.contentRev + 1
272
+ const now = Date.now()
273
+ // A draft's edits reach the public when it goes live, so only a live entry's save is its new `contentAt`.
274
+ await ctx.db.patch(entry._id, { data: w.data, prints: w.prints, trees: undefined, rev, fieldRevs, bytes, treeBytes: trees.bytes, ...(draft ? {} : { contentAt: now }) })
275
+ await putTrees(ctx, site._id, entry._id, trees.json)
276
+ await ctx.db.patch(site._id, { contentRev, bytes: siteBytes, treeBytes })
277
+
278
+ const pick = (data: Data) => Object.fromEntries(w.roots.filter((r) => data[r] !== undefined).map((r) => [r, data[r]!]))
279
+ const pickPrints = (prints: Prints) => Object.fromEntries(Object.entries(prints).filter(([leaf]) => w.roots.some((r) => leaf === r || leaf.startsWith(`${r}.`))))
280
+ const before = pick(entry.data as Data)
281
+ const after = pick(w.data)
282
+ const change = await ctx.db.insert('changes', {
283
+ site: site._id, entry: entry._id, brick: entry.brick, ...byOf(actor), opId: w.opId, kind: w.kind, ...w.history,
284
+ fields: w.roots, before, after, printsBefore: pickPrints(entry.prints), printsAfter: pickPrints(w.prints),
285
+ entryRev: rev, contentRev, at: now,
286
+ })
287
+ await syncEntryRefs(ctx, site._id, entry._id, await entryUses(ctx, w.fields, w.data, (site.schema as Schema).locales))
288
+ const isUploadId = uploadIdsOf(ctx)
289
+ const changeFiles = new Set([...fileIdsOf(w.fields, before, { isUploadId }), ...fileIdsOf(w.fields, after, { isUploadId })])
290
+ if (changeFiles.size) await syncFileRefs(ctx, site._id, 'change', change, changeFiles)
291
+ return { change, rev, contentRev }
292
+ }
293
+
294
+ export function same(a: unknown, b: unknown): boolean {
295
+ return stableJson((a ?? null) as Json) === stableJson((b ?? null) as Json)
296
+ }
package/convex/mail.ts ADDED
@@ -0,0 +1,136 @@
1
+ // The one place that sends mail (SPEC 10). GINKO_MAIL picks the way:
2
+ // - `outbox`: mail goes to the `outbox` table, which local development and tests read;
3
+ // - `resend`: mail goes out through Resend (RESEND_API_KEY, GINKO_MAIL_FROM), hosted only. Mail to a
4
+ // `.test` address (a reserved domain that never receives mail) still goes to the outbox, so test
5
+ // accounts can sign in on a hosted deployment: `pnpm outbox <email>` prints their newest mail.
6
+ // Anything else, or a missing key, disables sending: sign-in then shows "Anmeldung noch nicht eingerichtet".
7
+ import { v } from 'convex/values'
8
+ import { components, internal } from './_generated/api'
9
+ import { internalAction, internalMutation, query, type MutationCtx } from './_generated/server'
10
+ import { fail } from './lib/fail'
11
+ import { localeOfUser, t } from './lib/i18n'
12
+ import { normalizeEmail } from './members'
13
+
14
+ export interface Mail {
15
+ to: string
16
+ subject: string
17
+ text: string
18
+ }
19
+
20
+ function mailWay(): 'outbox' | 'resend' | undefined {
21
+ const way = process.env.GINKO_MAIL
22
+ if (way === 'outbox') return 'outbox'
23
+ if (way === 'resend' && process.env.RESEND_API_KEY && process.env.GINKO_MAIL_FROM) return 'resend'
24
+ return undefined
25
+ }
26
+
27
+ /** RFC 2606 reserves `.test`: such an address can never receive mail, so it is safe to keep its mail. */
28
+ function isTestAddress(email: string): boolean {
29
+ return /\.test$/i.test(email.trim())
30
+ }
31
+
32
+ /** Where the Studio lives, for links in mail. */
33
+ export function siteOrigin(): string {
34
+ const origin = process.env.SITE_URL
35
+ if (!origin) throw new Error('SITE_URL is not set in the Convex environment')
36
+ return origin.replace(/\/$/, '')
37
+ }
38
+
39
+ /** Whether mail can be sent at all. */
40
+ export function mailAvailable(): boolean {
41
+ return mailWay() !== undefined
42
+ }
43
+
44
+ /** For the sign-in page: show "Anmeldung noch nicht eingerichtet" instead of a code form that cannot work. */
45
+ export const signInAvailable = query({
46
+ args: {},
47
+ handler: async () => mailAvailable(),
48
+ })
49
+
50
+ /** How long a sign-in code works: auth.ts `emailOTP.expiresIn` (breakit-access pins both). Its mail is not sent again after that. */
51
+ export const CODE_LIFETIME_MS = 5 * 60 * 1000
52
+ /** The waits before the 1st, 2nd and 3rd retry of a mail Resend could not take: short for a code, longer for the rest. */
53
+ const CODE_RETRY_MS = [5_000, 30_000, 2 * 60_000]
54
+ const MAIL_RETRY_MS = [60_000, 10 * 60_000, 60 * 60_000]
55
+
56
+ /** `until`: a sign-in code's end of life; its mail is retried only before that. */
57
+ export async function queueMail(ctx: MutationCtx, mail: Mail, until?: number) {
58
+ const way = mailWay()
59
+ if (!way) fail('INVALID', 'errors.signInNotSetUp')
60
+ if (way === 'outbox' || isTestAddress(mail.to)) {
61
+ await ctx.db.insert('outbox', { ...mail, at: Date.now() })
62
+ return
63
+ }
64
+ // Sent once this mutation commits, so a refused mutation sends nothing. The mail is not stored in a table.
65
+ // `key` stays the same through every retry, so Resend sends a mail it already took after a 5xx only once.
66
+ await ctx.scheduler.runAfter(0, internal.mail.send, { ...mail, key: crypto.randomUUID(), ...(until === undefined ? {} : { until }) })
67
+ }
68
+
69
+ /**
70
+ * One try at Resend. A network error, 429 or 5xx may pass on a retry; any other refusal is the request's own fault.
71
+ * Resend may have taken the mail before such a failure: with the same `key` (Idempotency-Key, kept 24 h, longer than all
72
+ * retries) it does not send it again.
73
+ */
74
+ async function deliver(mail: Mail, key: string | undefined): Promise<{ sent: true } | { sent: false; retry: boolean; reason: string }> {
75
+ let response: Response
76
+ try {
77
+ response = await fetch('https://api.resend.com/emails', {
78
+ method: 'POST',
79
+ headers: { authorization: `Bearer ${process.env.RESEND_API_KEY}`, 'content-type': 'application/json', ...(key === undefined ? {} : { 'idempotency-key': key }) },
80
+ body: JSON.stringify({ from: process.env.GINKO_MAIL_FROM, to: [mail.to], subject: mail.subject, text: mail.text }),
81
+ })
82
+ } catch (error) {
83
+ return { sent: false, retry: true, reason: `network error: ${String(error).slice(0, 200)}` }
84
+ }
85
+ if (response.ok) return { sent: true }
86
+ return { sent: false, retry: response.status === 429 || response.status >= 500, reason: `${response.status} ${(await response.text()).slice(0, 300)}` }
87
+ }
88
+
89
+ /**
90
+ * Delivery through Resend, retried up to 3 times on a passing failure (Convex does not retry actions). A sign-in
91
+ * code is retried only while it still works. A failure is logged without the mail text, which may hold a code.
92
+ */
93
+ export const send = internalAction({
94
+ // `key` is optional only for a mail queued before keys existed.
95
+ args: { to: v.string(), subject: v.string(), text: v.string(), key: v.optional(v.string()), until: v.optional(v.number()), attempt: v.optional(v.number()) },
96
+ handler: async (ctx, { key, until, attempt = 0, ...mail }) => {
97
+ const outcome = await deliver(mail, key)
98
+ if (outcome.sent) return
99
+ const wait = (until === undefined ? MAIL_RETRY_MS : CODE_RETRY_MS)[attempt]
100
+ if (outcome.retry && wait !== undefined && (until === undefined || Date.now() + wait < until)) {
101
+ console.warn(`Mail "${mail.subject}" not sent (${outcome.reason}); retry ${attempt + 1} in ${wait / 1000} s.`)
102
+ await ctx.scheduler.runAfter(wait, internal.mail.send, { ...mail, key, attempt: attempt + 1, ...(until === undefined ? {} : { until }) })
103
+ return
104
+ }
105
+ throw new Error(`Resend refused the mail "${mail.subject}": ${outcome.reason}`)
106
+ },
107
+ })
108
+
109
+ /** Called from the Better Auth `email` hook, which can only reach mutations through runMutation. */
110
+ export const queue = internalMutation({
111
+ args: { to: v.string(), subject: v.string(), text: v.string() },
112
+ handler: async (ctx, mail) => {
113
+ await queueMail(ctx, mail)
114
+ },
115
+ })
116
+
117
+ /**
118
+ * A sign-in code, from the Better Auth `email` hook. It goes only to people who have an account or
119
+ * may create one (SPEC 10). Anyone else gets the same answer but no mail, so the sign-in endpoint
120
+ * cannot be used to send mail to arbitrary addresses.
121
+ */
122
+ export const queueCode = internalMutation({
123
+ args: { to: v.string(), otp: v.string() },
124
+ handler: async (ctx, args) => {
125
+ // Without a mail way every request fails the same, before anything about the address is looked up.
126
+ if (!mailAvailable()) fail('INVALID', 'errors.signInNotSetUp')
127
+ const email = normalizeEmail(args.to)
128
+ const known = await ctx.runQuery(components.betterAuth.adapter.findOne, { model: 'user', where: [{ field: 'email', value: email }] })
129
+ if (!known && !(await ctx.runQuery(internal.invites.mayJoin, { email }))) return
130
+ // The person's own language (the Studio stores it on the first visit); a new person gets their newest
131
+ // invite's language, else German.
132
+ const invite = known ? null : await ctx.db.query('invites').withIndex('by_email', (q) => q.eq('email', email)).order('desc').first()
133
+ const locale = invite?.locale ?? await localeOfUser(ctx, typeof known?.id === 'string' ? known.id : undefined)
134
+ await queueMail(ctx, { to: email, subject: t(locale, 'mail.code.subject'), text: t(locale, 'mail.code.text', { code: args.otp }) }, Date.now() + CODE_LIFETIME_MS)
135
+ },
136
+ })
@@ -0,0 +1,129 @@
1
+ // Memberships of a site (SPEC 3, 2.7, 10). Owners and admins manage them; staff have no access here.
2
+ import type { Schema } from '@lupinum/ginko/internal'
3
+ import { v } from 'convex/values'
4
+ import type { Doc, Id } from './_generated/dataModel'
5
+ import { internalMutation, mutation, query, type MutationCtx, type QueryCtx } from './_generated/server'
6
+ import { actorFor, fail, type Actor } from './lib/access'
7
+ import { labeler, namer, type Who } from './lib/names'
8
+
9
+ /** Emails are compared lowercased and trimmed everywhere (invites, admins, sign-up). */
10
+ export function normalizeEmail(email: string): string {
11
+ return email.trim().toLowerCase()
12
+ }
13
+
14
+ /** Convex env `GINKO_ADMIN_EMAILS`, comma-separated (SPEC 10). */
15
+ export function adminEmails(): string[] {
16
+ return (process.env.GINKO_ADMIN_EMAILS ?? '').split(',').map(normalizeEmail).filter(Boolean)
17
+ }
18
+
19
+ /** Every grant must name an existing task of a live brick, `brick.task` (SPEC 2.7). Returns the grants without duplicates. */
20
+ export function checkGrants(schema: Schema, grants: string[]): string[] {
21
+ const refs = new Set(
22
+ Object.entries(schema.bricks)
23
+ .filter(([, brick]) => !brick.retired)
24
+ .flatMap(([id, brick]) => (brick.tasks ?? []).map((task) => `${id}.${task.id}`)),
25
+ )
26
+ for (const grant of grants) {
27
+ if (!refs.has(grant)) fail('INVALID', 'errors.grantNotFound', { grant }, { grant })
28
+ }
29
+ return [...new Set(grants)]
30
+ }
31
+
32
+ /** Owners and admins only; a staff member gets FORBIDDEN. */
33
+ async function managerOf(ctx: QueryCtx, siteSlug: string): Promise<Actor> {
34
+ const actor = await actorFor(ctx, siteSlug)
35
+ if (actor.role === 'staff') fail('FORBIDDEN', 'errors.onlyOwnersAdminsManageMembers')
36
+ return actor
37
+ }
38
+
39
+ /** An unknown or foreign membership id is NOT_FOUND, as for entries. */
40
+ async function memberOf(ctx: QueryCtx, actor: Actor, id: string): Promise<Doc<'memberships'>> {
41
+ const normalized = ctx.db.normalizeId('memberships', id)
42
+ const member = normalized ? await ctx.db.get(normalized) : null
43
+ if (!member || member.site !== actor.site._id) fail('NOT_FOUND', 'errors.memberNotFound')
44
+ return member
45
+ }
46
+
47
+ async function ownersOf(ctx: QueryCtx | MutationCtx, site: Id<'sites'>) {
48
+ const members = await ctx.db.query('memberships').withIndex('by_site', (q) => q.eq('site', site)).collect()
49
+ return members.filter((m) => m.role === 'owner')
50
+ }
51
+
52
+ /**
53
+ * The team page: members, open invites, whether the platform's support has access (`support`), and the site's live
54
+ * push keys. Push keys belong to the site and outlive their maker, so each names who made it (`by`) and, while that
55
+ * person is on the team, their membership (`member`).
56
+ */
57
+ export const list = query({
58
+ args: { site: v.string() },
59
+ handler: async (ctx, args) => {
60
+ const actor = await managerOf(ctx, args.site)
61
+ const members = await ctx.db.query('memberships').withIndex('by_site', (q) => q.eq('site', actor.site._id)).collect()
62
+ const invites = await ctx.db.query('invites').withIndex('by_site', (q) => q.eq('site', actor.site._id)).collect()
63
+ const pushKeys = await ctx.db.query('pushKeys').withIndex('by_site', (q) => q.eq('site', actor.site._id)).collect()
64
+ const memberOfUser = new Map(members.map((m) => [m.user as string, m._id]))
65
+ const names = await labeler(ctx, actor)
66
+ const nameOf = namer(ctx)
67
+ // Platform admins (the agency's support) pass every check on every site but have no membership: the page says so.
68
+ const support = (await ctx.db.query('admins').first()) !== null
69
+ // Keys made with `release:bootstrapKey` come from the platform's operators.
70
+ const by = async (createdBy: string): Promise<Who> => (createdBy === 'bootstrap' ? { kind: 'platform' } : names.who(createdBy))
71
+ return {
72
+ // `you`: the caller's own row, by user id (an email can differ from the account's), so the page offers no self-removal.
73
+ // `name`: the name the person gave themselves (account.setName), null until then.
74
+ members: await Promise.all(members.map(async (m) => ({ id: m._id, email: m.email ?? null, name: (await nameOf(m.user)) ?? null, role: m.role, grants: m.grants, you: m.user === actor.user.id }))),
75
+ invites: invites
76
+ .filter((i) => i.acceptedAt === undefined)
77
+ .map((i) => ({ id: i._id, email: i.email, role: i.role, grants: i.grants, expiresAt: i.expiresAt })),
78
+ support,
79
+ keys: await Promise.all(
80
+ pushKeys
81
+ .filter((k) => k.revokedAt === undefined)
82
+ .map(async (k) => ({
83
+ id: k._id,
84
+ label: k.label,
85
+ scopes: k.scopes,
86
+ by: await by(k.createdBy),
87
+ member: memberOfUser.get(k.createdBy) ?? null,
88
+ createdAt: k._creationTime,
89
+ lastUsedAt: k.lastUsedAt ?? null,
90
+ })),
91
+ ),
92
+ }
93
+ },
94
+ })
95
+
96
+ export const setGrants = mutation({
97
+ args: { site: v.string(), member: v.string(), grants: v.array(v.string()) },
98
+ handler: async (ctx, args) => {
99
+ const actor = await managerOf(ctx, args.site)
100
+ const member = await memberOf(ctx, actor, args.member)
101
+ if (member.role === 'owner') fail('INVALID', 'errors.ownersHaveAllRights')
102
+ const grants = checkGrants(actor.site.schema as Schema, args.grants)
103
+ await ctx.db.patch(member._id, { grants })
104
+ return { member: member._id, grants }
105
+ },
106
+ })
107
+
108
+ export const remove = mutation({
109
+ args: { site: v.string(), member: v.string() },
110
+ handler: async (ctx, args) => {
111
+ const actor = await managerOf(ctx, args.site)
112
+ const member = await memberOf(ctx, actor, args.member)
113
+ if (member.role === 'owner' && (await ownersOf(ctx, actor.site._id)).length <= 1) {
114
+ fail('INVALID', 'errors.lastOwnerCannotBeRemoved')
115
+ }
116
+ await ctx.db.delete(member._id)
117
+ return { member: member._id }
118
+ },
119
+ })
120
+
121
+ /** Admin bootstrap (SPEC 10): the first sign-in with an address from GINKO_ADMIN_EMAILS makes an admin. */
122
+ export const bootstrapAdmin = internalMutation({
123
+ args: { user: v.string(), email: v.string() },
124
+ handler: async (ctx, args) => {
125
+ if (!adminEmails().includes(normalizeEmail(args.email))) return
126
+ const existing = await ctx.db.query('admins').withIndex('by_user', (q) => q.eq('user', args.user)).unique()
127
+ if (!existing) await ctx.db.insert('admins', { user: args.user })
128
+ },
129
+ })