@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.
- package/CHANGELOG.md +13 -0
- package/LICENSE +21 -0
- package/README.md +176 -2
- package/convex/_generated/api.d.ts +185 -0
- package/convex/_generated/api.js +23 -0
- package/convex/_generated/dataModel.d.ts +60 -0
- package/convex/_generated/server.d.ts +162 -0
- package/convex/_generated/server.js +101 -0
- package/convex/account.ts +110 -0
- package/convex/agent.ts +814 -0
- package/convex/auth.config.ts +4 -0
- package/convex/auth.ts +62 -0
- package/convex/backup.ts +94 -0
- package/convex/betterAuth/_generated/api.ts +56 -0
- package/convex/betterAuth/_generated/component.ts +431 -0
- package/convex/betterAuth/_generated/dataModel.ts +60 -0
- package/convex/betterAuth/_generated/server.ts +169 -0
- package/convex/betterAuth/adapter.ts +7 -0
- package/convex/betterAuth/convex.config.ts +3 -0
- package/convex/betterAuth/schema.ts +102 -0
- package/convex/betterAuth/schemaMetadata.ts +697 -0
- package/convex/betterAuth/schemaOptions.ts +13 -0
- package/convex/betterAuth/schemaPlugins.ts +13 -0
- package/convex/bundle.ts +183 -0
- package/convex/changes.ts +136 -0
- package/convex/cleanup.ts +44 -0
- package/convex/connect.ts +143 -0
- package/convex/convex.config.ts +7 -0
- package/convex/crons.ts +14 -0
- package/convex/demo.ts +72 -0
- package/convex/entries.ts +1770 -0
- package/convex/facts.ts +129 -0
- package/convex/files.ts +631 -0
- package/convex/http.ts +21 -0
- package/convex/image.ts +45 -0
- package/convex/images.ts +54 -0
- package/convex/invites.ts +227 -0
- package/convex/lib/access.ts +180 -0
- package/convex/lib/agentTools.ts +331 -0
- package/convex/lib/content.ts +317 -0
- package/convex/lib/corpus.ts +83 -0
- package/convex/lib/diff.ts +50 -0
- package/convex/lib/fail.ts +27 -0
- package/convex/lib/files.ts +70 -0
- package/convex/lib/history.ts +103 -0
- package/convex/lib/i18n.ts +52 -0
- package/convex/lib/input.ts +57 -0
- package/convex/lib/library.ts +28 -0
- package/convex/lib/lifecycle.ts +100 -0
- package/convex/lib/list.ts +112 -0
- package/convex/lib/migrations.ts +126 -0
- package/convex/lib/names.ts +56 -0
- package/convex/lib/pending.ts +84 -0
- package/convex/lib/policy.ts +155 -0
- package/convex/lib/publicness.ts +87 -0
- package/convex/lib/reminders.ts +27 -0
- package/convex/lib/search.ts +132 -0
- package/convex/lib/siteUrl.ts +95 -0
- package/convex/lib/status.ts +109 -0
- package/convex/lib/translation.ts +56 -0
- package/convex/lib/trees.ts +43 -0
- package/convex/lib/write.ts +296 -0
- package/convex/mail.ts +136 -0
- package/convex/members.ts +129 -0
- package/convex/migrations.ts +105 -0
- package/convex/navigation.ts +276 -0
- package/convex/ops.ts +50 -0
- package/convex/proposals.ts +753 -0
- package/convex/refresh.ts +163 -0
- package/convex/release.ts +435 -0
- package/convex/reminders.ts +116 -0
- package/convex/retention.ts +121 -0
- package/convex/routes/bundle.ts +62 -0
- package/convex/routes/connect.ts +80 -0
- package/convex/routes/export.ts +23 -0
- package/convex/routes/file.ts +34 -0
- package/convex/routes/key.ts +53 -0
- package/convex/routes/mcp.ts +300 -0
- package/convex/routes/release.ts +66 -0
- package/convex/routes/upload.ts +94 -0
- package/convex/schema.ts +443 -0
- package/convex/search.ts +58 -0
- package/convex/seed.ts +624 -0
- package/convex/siteDeletion.ts +78 -0
- package/convex/sites.ts +393 -0
- package/convex/tasks.ts +51 -0
- package/convex/tsconfig.json +27 -0
- package/convex/uploads.ts +429 -0
- package/convex/uploadsNode.ts +86 -0
- package/convex/views.ts +111 -0
- package/i18n/de.json +364 -0
- package/i18n/en.json +364 -0
- package/i18n/es.json +364 -0
- package/i18n/fr.json +364 -0
- package/package.json +45 -3
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { jwt } from 'better-auth/plugins'
|
|
2
|
+
|
|
3
|
+
// Only plugins that change the auth schema. Email OTP adds no tables, so it is not listed.
|
|
4
|
+
// The organization plugin is not used: memberships and invites are Ginko tables (SPEC 3).
|
|
5
|
+
export function createAuthSchemaPlugins(authIssuer: string) {
|
|
6
|
+
return [
|
|
7
|
+
jwt({
|
|
8
|
+
disableSettingJwtHeader: true,
|
|
9
|
+
jwks: { disablePrivateKeyEncryption: false, gracePeriod: 21 * 60, keyPairConfig: { alg: 'RS256' } },
|
|
10
|
+
jwt: { audience: authIssuer, expirationTime: '10m', issuer: authIssuer },
|
|
11
|
+
}),
|
|
12
|
+
]
|
|
13
|
+
}
|
package/convex/bundle.ts
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// Bundle reads for the public endpoint (SPEC 6). The HTTP layer lives in routes/bundle.ts;
|
|
2
|
+
// the bundle itself is built by the core `servedBundle`, never here.
|
|
3
|
+
import type { Json } from '@lupinum/ginko'
|
|
4
|
+
import { servedBundle, todayIn, type Bundle, type FileInfo, type MarkdownTrees, type Schema, type StoredEntry } from '@lupinum/ginko/internal'
|
|
5
|
+
import { v } from 'convex/values'
|
|
6
|
+
import type { Doc, Id } from './_generated/dataModel'
|
|
7
|
+
import { internalMutation, internalQuery, type QueryCtx } from './_generated/server'
|
|
8
|
+
import { newOrder } from './lib/content'
|
|
9
|
+
import { readTrees } from './lib/trees'
|
|
10
|
+
|
|
11
|
+
/** SPEC 6: 600 requests per minute and site. */
|
|
12
|
+
export const RATE_LIMIT = 600
|
|
13
|
+
export const RATE_WINDOW_MS = 60_000
|
|
14
|
+
|
|
15
|
+
export function windowOf(now: number): number {
|
|
16
|
+
return Math.floor(now / RATE_WINDOW_MS)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Header with which a site's own server proves it is the site: the refresh token it already shares with the platform (`sites:setRefreshToken`). */
|
|
20
|
+
export const SITE_TOKEN_HEADER = 'x-ginko-site-token'
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Counts one request in the current minute window. Returns RATE_LIMITED for the 601st.
|
|
24
|
+
* The limit is public and per site, so strangers can use it up; the site's own server, which sends
|
|
25
|
+
* the site's refresh token, is not counted, so nobody can block the site's fetches.
|
|
26
|
+
* An unknown site is reported without a counter row.
|
|
27
|
+
*/
|
|
28
|
+
export const admit = internalMutation({
|
|
29
|
+
args: { slug: v.string(), token: v.optional(v.string()) },
|
|
30
|
+
handler: async (ctx, { slug, token }): Promise<'OK' | 'SITE_NOT_FOUND' | 'RATE_LIMITED'> => {
|
|
31
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', slug)).unique()
|
|
32
|
+
if (!site || site.deleting) return 'SITE_NOT_FOUND'
|
|
33
|
+
if (token !== undefined && site.refreshToken !== undefined && sameSecret(token, site.refreshToken)) return 'OK'
|
|
34
|
+
const window = windowOf(Date.now())
|
|
35
|
+
const row = await ctx.db.query('rateWindows').withIndex('by_site_kind_window', (q) => q.eq('site', site._id).eq('kind', undefined).eq('window', window)).unique()
|
|
36
|
+
if (row && row.count >= RATE_LIMIT) return 'RATE_LIMITED'
|
|
37
|
+
if (row) await ctx.db.patch(row._id, { count: row.count + 1 })
|
|
38
|
+
else await ctx.db.insert('rateWindows', { site: site._id, window, count: 1 })
|
|
39
|
+
return 'OK'
|
|
40
|
+
},
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
/** Compares two secrets in time that does not depend on where they differ. */
|
|
44
|
+
function sameSecret(a: string, b: string): boolean {
|
|
45
|
+
if (a.length !== b.length) return false
|
|
46
|
+
let diff = 0
|
|
47
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)
|
|
48
|
+
return diff === 0
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The bundle of one site and locale. `minRev` is `<schemaRev>.<contentRev>` as numbers;
|
|
53
|
+
* a smaller stored number answers STALE, so a refresh never caches older content.
|
|
54
|
+
*/
|
|
55
|
+
export const build = internalQuery({
|
|
56
|
+
args: {
|
|
57
|
+
slug: v.string(),
|
|
58
|
+
locale: v.string(),
|
|
59
|
+
/** The public site asks for file URLs on its own address (`/__ginko/file/…`) instead of live storage URLs. */
|
|
60
|
+
stableFiles: v.optional(v.boolean()),
|
|
61
|
+
minRev: v.optional(v.object({ schemaRev: v.number(), contentRev: v.number() })),
|
|
62
|
+
},
|
|
63
|
+
handler: async (ctx, { slug, locale, minRev, stableFiles }): Promise<Bundle | 'SITE_NOT_FOUND' | 'STALE'> => {
|
|
64
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', slug)).unique()
|
|
65
|
+
if (!site || site.deleting) return 'SITE_NOT_FOUND'
|
|
66
|
+
if (minRev && (site.schemaRev < minRev.schemaRev || site.contentRev < minRev.contentRev)) return 'STALE'
|
|
67
|
+
return bundleOf(ctx, site, locale, undefined, [], stableFiles)
|
|
68
|
+
},
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
/** The storage URL of `storage` when it belongs to a ready upload of `slug` (original, processed copy or variant); else null. */
|
|
72
|
+
export const fileUrl = internalQuery({
|
|
73
|
+
args: { slug: v.string(), upload: v.string(), storage: v.string() },
|
|
74
|
+
handler: async (ctx, { slug, upload, storage }): Promise<string | null> => {
|
|
75
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', slug)).unique()
|
|
76
|
+
if (!site || site.deleting) return null
|
|
77
|
+
const id = ctx.db.normalizeId('uploads', upload)
|
|
78
|
+
const row = id ? await ctx.db.get(id) : null
|
|
79
|
+
if (!row || row.site !== site._id || row.status !== 'ready') return null
|
|
80
|
+
const allowed = new Set<string>([row.processedId ?? row.storageId, ...(row.variants ?? []).map((variant) => variant.storageId)])
|
|
81
|
+
if (!allowed.has(storage)) return null
|
|
82
|
+
const storageId = ctx.db.system.normalizeId('_storage', storage)
|
|
83
|
+
return storageId ? ctx.storage.getUrl(storageId) : null
|
|
84
|
+
},
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
/** A file on the site's own address; the site's `/__ginko/file/:upload/:storage` route forwards it to the platform's `/file/<site>/…`. */
|
|
88
|
+
export function stableFileUrl(upload: Id<'uploads'>, storageId: Id<'_storage'>): string {
|
|
89
|
+
return `/__ginko/file/${upload}/${storageId}`
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** An entry that is not stored yet, with a temporary id, as the link check sees it. */
|
|
93
|
+
export interface NewItem { brick: string; id: string; data: Record<string, Json> }
|
|
94
|
+
|
|
95
|
+
/** The stored trees of a row: its `entryTrees`, else the legacy `trees` on the row (until `entries:migrateStorage` ran). */
|
|
96
|
+
async function storedTrees(ctx: QueryCtx, row: Doc<'entries'>): Promise<MarkdownTrees | undefined> {
|
|
97
|
+
return (await readTrees(ctx, row._id)) ?? (row.trees === undefined ? undefined : (JSON.parse(row.trees) as MarkdownTrees))
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The newest `updatedAt` of the served entries (ISO), or the site's creation time when it has none. */
|
|
101
|
+
function latestChange(entries: Record<string, StoredEntry[]>, fallback: number): string {
|
|
102
|
+
let latest = new Date(fallback).toISOString()
|
|
103
|
+
for (const list of Object.values(entries)) for (const { updatedAt } of list) if (updatedAt && updatedAt > latest) latest = updatedAt
|
|
104
|
+
return latest
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The bundle of a site that is known to exist; the agent door's link check builds one per language with it. */
|
|
108
|
+
export async function bundleOf(ctx: QueryCtx, site: Doc<'sites'>, locale: string, overrides?: ReadonlyMap<string, Record<string, Json>>, added: readonly NewItem[] = [], stableFiles = false): Promise<Bundle> {
|
|
109
|
+
const schema = site.schema as Schema
|
|
110
|
+
// A missing locale parameter (empty string) means the main language, not an unknown locale.
|
|
111
|
+
const requestedLocale = locale === '' ? schema.locales[0]! : locale
|
|
112
|
+
const entries: Record<string, StoredEntry[]> = {}
|
|
113
|
+
for (const key of Object.keys(schema.bricks)) {
|
|
114
|
+
// Live rows only, through the index: the trash is never read (servedBundle sorts the items itself).
|
|
115
|
+
const rows = await ctx.db.query('entries').withIndex('by_site_brick_deleted', (q) => q.eq('site', site._id).eq('brick', key).eq('deletedAt', undefined)).collect()
|
|
116
|
+
// Drafts never leave the platform (SPEC 15); their slugs stay reserved in the slugs table.
|
|
117
|
+
// An override (a save that is about to happen) replaces the stored data and also lets a draft through: the link check reads the state after the write.
|
|
118
|
+
const live = rows.filter((row) => row.state !== 'draft' || overrides?.has(row._id))
|
|
119
|
+
// An overridden row's stored trees belong to its old data: its texts are parsed, as are those of a row without trees.
|
|
120
|
+
const list: StoredEntry[] = await Promise.all(live.map(async (row) => {
|
|
121
|
+
const override = overrides?.get(row._id)
|
|
122
|
+
const trees = override === undefined ? await storedTrees(ctx, row) : undefined
|
|
123
|
+
// `contentAt` is when the entry last changed for the public; an entry from before it counts from its creation.
|
|
124
|
+
const updatedAt = new Date(row.contentAt ?? row._creationTime).toISOString()
|
|
125
|
+
return { id: row._id, order: row.order, data: override ?? row.data, prints: row.prints, ...(trees ? { trees } : {}), updatedAt }
|
|
126
|
+
}))
|
|
127
|
+
// An entry that does not exist yet (a create that is only proposed) joins its collection where entries.create puts it.
|
|
128
|
+
const brick = schema.bricks[key]!
|
|
129
|
+
for (const item of added) {
|
|
130
|
+
if (item.brick === key && brick.kind === 'collection') list.push({ id: item.id, order: newOrder(key, brick, list.map((e) => e.order ?? 0)), data: item.data, prints: {}, updatedAt: new Date().toISOString() })
|
|
131
|
+
}
|
|
132
|
+
entries[key] = list
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Files: only ready uploads, with the URL of the processed copy when there is one.
|
|
136
|
+
const files = new Map<string, FileInfo>()
|
|
137
|
+
const uploads = await ctx.db.query('uploads').withIndex('by_site', (q) => q.eq('site', site._id)).collect()
|
|
138
|
+
for (const upload of uploads) {
|
|
139
|
+
if (upload.status !== 'ready') continue
|
|
140
|
+
// A stable URL names the storage id, which the file route checks against the upload; it never calls the storage.
|
|
141
|
+
const fileUrl = async (storageId: Id<'_storage'>) => (stableFiles ? stableFileUrl(upload._id, storageId) : ctx.storage.getUrl(storageId))
|
|
142
|
+
const url = await fileUrl(upload.processedId ?? upload.storageId)
|
|
143
|
+
if (!url) continue
|
|
144
|
+
const variants: { width: number; url: string }[] = []
|
|
145
|
+
for (const variant of upload.variants ?? []) {
|
|
146
|
+
const variantUrl = await fileUrl(variant.storageId)
|
|
147
|
+
if (variantUrl) variants.push({ width: variant.width, url: variantUrl })
|
|
148
|
+
}
|
|
149
|
+
variants.sort((a, b) => a.width - b.width)
|
|
150
|
+
files.set(upload._id, {
|
|
151
|
+
url, name: upload.name, size: upload.size,
|
|
152
|
+
...(upload.width !== undefined ? { width: upload.width } : {}),
|
|
153
|
+
...(upload.height !== undefined ? { height: upload.height } : {}),
|
|
154
|
+
...(variants.length ? { variants } : {}),
|
|
155
|
+
...(upload.focus ? { focus: upload.focus } : {}),
|
|
156
|
+
...(upload.alt && Object.keys(upload.alt).length ? { alt: upload.alt } : {}),
|
|
157
|
+
})
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const bundle = await servedBundle({
|
|
161
|
+
schema,
|
|
162
|
+
requestedLocale,
|
|
163
|
+
entries,
|
|
164
|
+
files: (id) => files.get(id),
|
|
165
|
+
schemaRev: site.schemaRev,
|
|
166
|
+
contentRev: site.contentRev,
|
|
167
|
+
// The newest content change, not the clock: the same content must give the same bundle, byte for byte, or every
|
|
168
|
+
// ISR revalidation of a site page stores a "changed" page and is billed as a write (ISR efficiency plan).
|
|
169
|
+
generatedAt: latestChange(entries, site._creationTime),
|
|
170
|
+
today: todayIn(schema.timeZone),
|
|
171
|
+
})
|
|
172
|
+
// Addresses an entry had before entries.changeSlug: the site forwards them to its page there (301).
|
|
173
|
+
for (const row of await ctx.db.query('slugs').withIndex('by_site_old', (q) => q.eq('site', site._id).eq('old', true)).collect()) {
|
|
174
|
+
const brick = schema.bricks[row.brick]
|
|
175
|
+
const route = brick?.kind === 'collection' ? brick.route?.[row.locale] : undefined
|
|
176
|
+
const served = bundle.bricks[row.brick]
|
|
177
|
+
const item = route && served?.kind === 'collection' ? served.items.find((i) => i.id === row.entry) : undefined
|
|
178
|
+
if (!route || !item?.urls?.[row.locale]) continue
|
|
179
|
+
const urls = (item.oldUrls ??= {})
|
|
180
|
+
;(urls[row.locale] ??= []).push(route.replace('[slug]', row.slug))
|
|
181
|
+
}
|
|
182
|
+
return bundle
|
|
183
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// The change log of a site, newest first (SPEC 3). Any admin or member of the site may read it (SPEC 2.7).
|
|
2
|
+
import type { Json } from '@lupinum/ginko'
|
|
3
|
+
import type { Schema } from '@lupinum/ginko/internal'
|
|
4
|
+
import { paginationOptsValidator } from 'convex/server'
|
|
5
|
+
import { v } from 'convex/values'
|
|
6
|
+
import type { Doc, Id } from './_generated/dataModel'
|
|
7
|
+
import { query, type QueryCtx } from './_generated/server'
|
|
8
|
+
import { labeler } from './lib/names'
|
|
9
|
+
import { actorFor, createdBy, fail, type Actor } from './lib/access'
|
|
10
|
+
import { diffFields } from './lib/diff'
|
|
11
|
+
import { undoBlockOf, type UndoBlock } from './lib/history'
|
|
12
|
+
|
|
13
|
+
const PAGE_SIZE = 50
|
|
14
|
+
/**
|
|
15
|
+
* A change row stores the `before` and `after` of its fields and the prints, up to 2 x 480 KiB (SITE_BUDGET.entryBytes).
|
|
16
|
+
* A page of 50 such rows would pass Convex's 16 MiB read limit, so a page also ends once it has read this much
|
|
17
|
+
* and hands out the cursor for the rest.
|
|
18
|
+
*/
|
|
19
|
+
const PAGE_BYTES = 2 * 1024 * 1024
|
|
20
|
+
|
|
21
|
+
type ReadEntry = (id: Id<'entries'>) => Promise<Doc<'entries'> | null>
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The rows without before/after/prints (those are for undo and the release, not for the list: the
|
|
25
|
+
* history page shows the message), with who did it and who approved it as data (`Who`, lib/names.ts) and,
|
|
26
|
+
* for a change through the agent door, the label of that person's key (SPEC 16). `inTrash`: a removal whose entry is
|
|
27
|
+
* still in the trash (not restored, not deleted for good), so the Studio links there only while it is. `own` marks a
|
|
28
|
+
* save of an entry the reader created: staff undo and revert it with their create task (lib/access.ts `authorize`),
|
|
29
|
+
* as entries.get says.
|
|
30
|
+
*/
|
|
31
|
+
async function summaries(ctx: QueryCtx, actor: Actor, rows: Doc<'changes'>[]) {
|
|
32
|
+
const names = await labeler(ctx, actor)
|
|
33
|
+
// Each entry is read once; the entries of a site fit in its storage budget, so this stays well under the read
|
|
34
|
+
// limit, and the list follows later saves, restores and removals live.
|
|
35
|
+
const read = new Map<Id<'entries'>, Promise<Doc<'entries'> | null>>()
|
|
36
|
+
const readEntry: ReadEntry = (id) => {
|
|
37
|
+
if (!read.has(id)) read.set(id, ctx.db.get(id))
|
|
38
|
+
return read.get(id)!
|
|
39
|
+
}
|
|
40
|
+
const { blocks, own } = await saveFacts(ctx, actor, rows, readEntry)
|
|
41
|
+
const out = []
|
|
42
|
+
for (const { before: _before, after: _after, printsBefore: _printsBefore, printsAfter: _printsAfter, ...change } of rows) {
|
|
43
|
+
const inTrash = change.kind === 'remove' && !!change.entry && !!(await readEntry(change.entry))?.deletedAt
|
|
44
|
+
out.push({
|
|
45
|
+
...change, who: await names.who(change.actor), agent: await names.key(change.agentKey), undoBlocked: blocks.get(change._id) ?? null, inTrash,
|
|
46
|
+
// An applied proposal: the owner or admin who approved it ("Freigabe: …").
|
|
47
|
+
approver: change.approvedBy ? await names.who(change.approvedBy) : null,
|
|
48
|
+
...(own.has(change._id) ? { own: true as const } : {}),
|
|
49
|
+
})
|
|
50
|
+
}
|
|
51
|
+
return out
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* For each save on the page: why it can no longer be undone (undoBlockOf, the rule the undo mutation uses), and
|
|
56
|
+
* whether the reader created its entry (`createdBy`).
|
|
57
|
+
*/
|
|
58
|
+
async function saveFacts(ctx: QueryCtx, actor: Actor, rows: Doc<'changes'>[], readEntry: ReadEntry): Promise<{ blocks: Map<Id<'changes'>, UndoBlock>; own: Set<Id<'changes'>> }> {
|
|
59
|
+
const blocks = new Map<Id<'changes'>, UndoBlock>()
|
|
60
|
+
const own = new Set<Id<'changes'>>()
|
|
61
|
+
if (!rows.some((row) => row.kind === 'save' && row.entry)) return { blocks, own }
|
|
62
|
+
const migrated = await ctx.db.query('migrationsApplied').withIndex('by_site_id', (q) => q.eq('site', actor.site._id)).collect()
|
|
63
|
+
for (const change of rows) {
|
|
64
|
+
if (change.kind !== 'save' || !change.entry) continue
|
|
65
|
+
const entry = await readEntry(change.entry)
|
|
66
|
+
const block = undoBlockOf(change, entry, migrated)
|
|
67
|
+
if (block) blocks.set(change._id, block)
|
|
68
|
+
if (createdBy(actor, entry)) own.add(change._id)
|
|
69
|
+
}
|
|
70
|
+
return { blocks, own }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* A paginated query (`useConvexPaginatedQuery` in the Studio): a page holds at most 50 rows. `entry`, `brick` and
|
|
75
|
+
* `by` narrow the list on the server, so a page is rows of the filter and the cursor walks on in it; without them
|
|
76
|
+
* it is the whole site. `by: 'me'` is what the signed-in person did (also
|
|
77
|
+
* through their own agent key), `by: 'ai'` everything done through the agent door.
|
|
78
|
+
*/
|
|
79
|
+
export const list = query({
|
|
80
|
+
args: {
|
|
81
|
+
site: v.string(), paginationOpts: paginationOptsValidator, entry: v.optional(v.string()), brick: v.optional(v.string()),
|
|
82
|
+
by: v.optional(v.union(v.literal('me'), v.literal('ai'))),
|
|
83
|
+
},
|
|
84
|
+
handler: async (ctx, args) => {
|
|
85
|
+
const actor = await actorFor(ctx, args.site)
|
|
86
|
+
const siteId = actor.site._id
|
|
87
|
+
const entry = args.entry === undefined ? undefined : ctx.db.normalizeId('entries', args.entry)
|
|
88
|
+
if (args.entry !== undefined && !entry) fail('NOT_FOUND', 'errors.entryNotFound')
|
|
89
|
+
const brick = args.brick
|
|
90
|
+
const by = args.by
|
|
91
|
+
const me = actor.user.id
|
|
92
|
+
// The index narrows by entry, else by who, else by brick; what it does not cover is a filter on the same walk.
|
|
93
|
+
const rows = entry
|
|
94
|
+
? ctx.db.query('changes').withIndex('by_entry', (q) => q.eq('entry', entry)).order('desc')
|
|
95
|
+
.filter((q) => q.and(
|
|
96
|
+
q.eq(q.field('site'), siteId),
|
|
97
|
+
brick === undefined ? true : q.eq(q.field('brick'), brick),
|
|
98
|
+
by === undefined ? true : by === 'me' ? q.eq(q.field('actor'), me) : q.eq(q.field('via'), 'agent'),
|
|
99
|
+
))
|
|
100
|
+
: by !== undefined
|
|
101
|
+
? (by === 'me'
|
|
102
|
+
? ctx.db.query('changes').withIndex('by_site_actor_at', (q) => q.eq('site', siteId).eq('actor', me))
|
|
103
|
+
: ctx.db.query('changes').withIndex('by_site_via_at', (q) => q.eq('site', siteId).eq('via', 'agent')))
|
|
104
|
+
.order('desc').filter((q) => (brick === undefined ? true : q.eq(q.field('brick'), brick)))
|
|
105
|
+
: brick !== undefined
|
|
106
|
+
? ctx.db.query('changes').withIndex('by_site_brick_at', (q) => q.eq('site', siteId).eq('brick', brick)).order('desc')
|
|
107
|
+
: ctx.db.query('changes').withIndex('by_site_at', (q) => q.eq('site', siteId)).order('desc')
|
|
108
|
+
const opts = args.paginationOpts
|
|
109
|
+
let result
|
|
110
|
+
try {
|
|
111
|
+
result = await rows.paginate({ ...opts, numItems: Math.min(opts.numItems, PAGE_SIZE), maximumBytesRead: PAGE_BYTES })
|
|
112
|
+
} catch (error) {
|
|
113
|
+
// The cursor comes from the client; the database refuses one it did not hand out.
|
|
114
|
+
if (opts.cursor === null) throw error
|
|
115
|
+
fail('INVALID', 'errors.pageMarkerInvalid')
|
|
116
|
+
}
|
|
117
|
+
return { ...result, page: await summaries(ctx, actor, result.page) }
|
|
118
|
+
},
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
/** One change as in `list`, plus its field-level `diff` (SPEC 4.2 "Verlauf"). A change of another site does not exist. */
|
|
122
|
+
export const get = query({
|
|
123
|
+
args: { site: v.string(), change: v.string() },
|
|
124
|
+
handler: async (ctx, args) => {
|
|
125
|
+
const actor = await actorFor(ctx, args.site)
|
|
126
|
+
const id = ctx.db.normalizeId('changes', args.change)
|
|
127
|
+
const change = id ? await ctx.db.get(id) : null
|
|
128
|
+
if (!change || change.site !== actor.site._id) fail('NOT_FOUND', 'errors.changeNotFound')
|
|
129
|
+
const schema = actor.site.schema as Schema
|
|
130
|
+
const brick = Object.hasOwn(schema.bricks, change.brick) ? schema.bricks[change.brick] : undefined
|
|
131
|
+
// before/after hold exactly the changed roots; a change without fields (publish, remove) has no field diff.
|
|
132
|
+
const diff = diffFields(brick?.fields, (change.before ?? {}) as Record<string, Json>, (change.after ?? {}) as Record<string, Json>, schema.locales[0]!)
|
|
133
|
+
const [summary] = await summaries(ctx, actor, [change])
|
|
134
|
+
return { ...summary!, diff }
|
|
135
|
+
},
|
|
136
|
+
})
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Daily clean-up of stale personal data that no feature reads any more (GDPR storage limitation):
|
|
2
|
+
// expired Better Auth sessions and verification rows (sign-in codes), invitations that expired more than 30 days ago, and
|
|
3
|
+
// expired `ginko connect` requests with their wrong-code counters.
|
|
4
|
+
// The outbox (mails in plain text) is cleaned by `retention.daily` after a day, so it is not repeated here.
|
|
5
|
+
import { internal, components } from './_generated/api'
|
|
6
|
+
import { internalMutation, type MutationCtx } from './_generated/server'
|
|
7
|
+
import { CONNECT, dropExpired as dropExpiredConnects } from './connect'
|
|
8
|
+
|
|
9
|
+
const DAY = 24 * 60 * 60 * 1000
|
|
10
|
+
export const INVITES_KEPT = 30 * DAY
|
|
11
|
+
/** Rows per kind and run; a full batch schedules the next run at once. */
|
|
12
|
+
const BATCH = 100
|
|
13
|
+
|
|
14
|
+
/** Deletes up to `BATCH` Better Auth rows of `model` that expired before `now`. Returns whether more may be left. */
|
|
15
|
+
async function dropExpired(ctx: MutationCtx, model: 'session' | 'verification', now: number): Promise<boolean> {
|
|
16
|
+
const page = await ctx.runQuery(components.betterAuth.adapter.findMany, {
|
|
17
|
+
model, where: [{ field: 'expiresAt', operator: 'lt', value: now }], select: ['id'], paginationOpts: { cursor: null, numItems: BATCH },
|
|
18
|
+
})
|
|
19
|
+
const ids = page.page.map((row) => String(row.id))
|
|
20
|
+
// Deleted by id: `deleteMany` refuses to touch more than 128 rows at once, and by user id it only invalidates sessions.
|
|
21
|
+
if (ids.length) await ctx.runMutation(components.betterAuth.adapter.deleteMany, { model, where: [{ field: 'id', operator: 'in', value: ids }] })
|
|
22
|
+
return ids.length === BATCH
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const daily = internalMutation({
|
|
26
|
+
args: {},
|
|
27
|
+
handler: async (ctx): Promise<null> => {
|
|
28
|
+
const now = Date.now()
|
|
29
|
+
const more = [
|
|
30
|
+
await dropExpired(ctx, 'session', now),
|
|
31
|
+
await dropExpired(ctx, 'verification', now),
|
|
32
|
+
]
|
|
33
|
+
const invites = await ctx.db.query('invites').withIndex('by_expires', (q) => q.lt('expiresAt', now - INVITES_KEPT)).take(BATCH)
|
|
34
|
+
for (const invite of invites) await ctx.db.delete(invite._id)
|
|
35
|
+
more.push(invites.length === BATCH)
|
|
36
|
+
// `ginko connect`: requests after their 10 minutes (connect/start also removes some), and old wrong-code counters.
|
|
37
|
+
more.push((await dropExpiredConnects(ctx, now, BATCH)) === BATCH)
|
|
38
|
+
const tries = await ctx.db.query('connectTries').withIndex('by_window', (q) => q.lt('window', now - CONNECT.windowMs)).take(BATCH)
|
|
39
|
+
for (const row of tries) await ctx.db.delete(row._id)
|
|
40
|
+
more.push(tries.length === BATCH)
|
|
41
|
+
if (more.some(Boolean)) await ctx.scheduler.runAfter(0, internal.cleanup.daily, {})
|
|
42
|
+
return null
|
|
43
|
+
},
|
|
44
|
+
})
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// `ginko connect`: a device authorization flow that gives a website folder a publishing key without anyone copying it.
|
|
2
|
+
// 1. The computer opens a request (routes/connect.ts → `open`): the device code goes back to it once, only its SHA-256
|
|
3
|
+
// is stored; the short user code is shown in its terminal.
|
|
4
|
+
// 2. A signed-in owner or admin types that code in the Studio (`lookup`), picks a site and confirms (`approve`) or
|
|
5
|
+
// declines (`decline`). The approval stores who, which site and when. It makes no key.
|
|
6
|
+
// 3. The computer's next poll with the device code (`redeem`) makes the key in that same transaction, marks the
|
|
7
|
+
// request used and returns the key once. Every request that cannot give a key answers the same "not valid".
|
|
8
|
+
// Wrong codes count per person: after 5 in a fixed 10-minute window, the rest of that window is refused.
|
|
9
|
+
import { v } from 'convex/values'
|
|
10
|
+
import type { Doc } from './_generated/dataModel'
|
|
11
|
+
import { internalMutation, mutation, type MutationCtx } from './_generated/server'
|
|
12
|
+
import { currentUser, memberOf } from './lib/access'
|
|
13
|
+
import { insertPushKey, ownerOf, PUBLISHING_SCOPES } from './release'
|
|
14
|
+
|
|
15
|
+
export const CONNECT = {
|
|
16
|
+
lifetimeMs: 10 * 60_000,
|
|
17
|
+
intervalSeconds: 2,
|
|
18
|
+
/** Pending requests in the whole deployment; `start` is public and the backend sees no trusted client IP. */
|
|
19
|
+
maxPending: 200,
|
|
20
|
+
wrongCodes: 5,
|
|
21
|
+
windowMs: 10 * 60_000,
|
|
22
|
+
labelMax: 60,
|
|
23
|
+
} as const
|
|
24
|
+
|
|
25
|
+
/** No 0/O, 1/I/L. 31 symbols, 8 of them: about 8.5 × 10¹¹ codes against 5 guesses per person and window. */
|
|
26
|
+
export const USER_CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789'
|
|
27
|
+
const USER_CODE = new RegExp(`^[${USER_CODE_ALPHABET}]{8}$`)
|
|
28
|
+
|
|
29
|
+
/** What a person typed (any case, with or without the hyphen or spaces) as the stored form, or undefined. */
|
|
30
|
+
export function normalizeCode(input: string): string | undefined {
|
|
31
|
+
const code = input.toUpperCase().replace(/[\s-]/g, '')
|
|
32
|
+
return USER_CODE.test(code) ? code : undefined
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Deletes up to `limit` requests whose lifetime ended. Returns how many. */
|
|
36
|
+
export async function dropExpired(ctx: MutationCtx, now: number, limit: number): Promise<number> {
|
|
37
|
+
const rows = await ctx.db.query('connectRequests').withIndex('by_expires', (q) => q.lt('expiresAt', now)).take(limit)
|
|
38
|
+
for (const row of rows) await ctx.db.delete(row._id)
|
|
39
|
+
return rows.length
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Stores a new request. The HTTP route made both codes (an action has real randomness) and sends only the device
|
|
44
|
+
* code's hash. Refuses when 200 requests are pending; removes up to 20 expired rows first, so the table cannot grow.
|
|
45
|
+
*/
|
|
46
|
+
export const open = internalMutation({
|
|
47
|
+
args: { deviceHash: v.string(), userCode: v.string(), label: v.string() },
|
|
48
|
+
handler: async (ctx, args): Promise<{ ok: true; expiresAt: number } | { ok: false; reason: 'full' | 'taken' }> => {
|
|
49
|
+
const now = Date.now()
|
|
50
|
+
await dropExpired(ctx, now, 20)
|
|
51
|
+
const pending = await ctx.db.query('connectRequests').withIndex('by_state_expires', (q) => q.eq('state', 'pending').gt('expiresAt', now)).take(CONNECT.maxPending)
|
|
52
|
+
if (pending.length >= CONNECT.maxPending) return { ok: false, reason: 'full' }
|
|
53
|
+
const same = await ctx.db.query('connectRequests').withIndex('by_code', (q) => q.eq('userCode', args.userCode)).collect()
|
|
54
|
+
if (same.some((row) => row.expiresAt > now)) return { ok: false, reason: 'taken' }
|
|
55
|
+
const expiresAt = now + CONNECT.lifetimeMs
|
|
56
|
+
await ctx.db.insert('connectRequests', { deviceHash: args.deviceHash, userCode: args.userCode, label: args.label, expiresAt, state: 'pending' })
|
|
57
|
+
return { ok: true, expiresAt }
|
|
58
|
+
},
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
type Refused = { ok: false; reason: 'invalid' | 'limited' }
|
|
62
|
+
|
|
63
|
+
const windowOf = (now: number) => Math.floor(now / CONNECT.windowMs) * CONNECT.windowMs
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The live, pending request of a typed code for this person, or why not. A wrong code is counted; at 5 wrong codes in
|
|
67
|
+
* the window every further attempt is refused, a right code too. The caller must not throw after a refusal: a thrown
|
|
68
|
+
* error would roll the count back.
|
|
69
|
+
*/
|
|
70
|
+
async function pendingFor(ctx: MutationCtx, user: string, typed: string): Promise<Doc<'connectRequests'> | Refused> {
|
|
71
|
+
const now = Date.now()
|
|
72
|
+
const window = windowOf(now)
|
|
73
|
+
const tries = await ctx.db.query('connectTries').withIndex('by_user_window', (q) => q.eq('user', user).eq('window', window)).unique()
|
|
74
|
+
if (tries && tries.count >= CONNECT.wrongCodes) return { ok: false, reason: 'limited' }
|
|
75
|
+
const code = normalizeCode(typed)
|
|
76
|
+
const rows = code ? await ctx.db.query('connectRequests').withIndex('by_code', (q) => q.eq('userCode', code)).collect() : []
|
|
77
|
+
const live = rows.find((row) => row.state === 'pending' && row.expiresAt > now)
|
|
78
|
+
if (live) return live
|
|
79
|
+
if (tries) await ctx.db.patch(tries._id, { count: tries.count + 1 })
|
|
80
|
+
else await ctx.db.insert('connectTries', { user, window, count: 1 })
|
|
81
|
+
return { ok: false, reason: 'invalid' }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Step 2a: the typed code names a request. Shows its label and when it started, before the person picks a site. */
|
|
85
|
+
export const lookup = mutation({
|
|
86
|
+
args: { code: v.string() },
|
|
87
|
+
handler: async (ctx, args): Promise<{ ok: true; label: string; startedAt: number } | Refused> => {
|
|
88
|
+
const user = await currentUser(ctx)
|
|
89
|
+
const request = await pendingFor(ctx, user.id, args.code)
|
|
90
|
+
if ('ok' in request) return request
|
|
91
|
+
return { ok: true, label: request.label, startedAt: request.expiresAt - CONNECT.lifetimeMs }
|
|
92
|
+
},
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
/** Step 2b: confirm. Needs the right `release.createPushKey` needs on that site. Stores the approval, makes no key. */
|
|
96
|
+
export const approve = mutation({
|
|
97
|
+
args: { code: v.string(), site: v.string() },
|
|
98
|
+
handler: async (ctx, args): Promise<{ ok: true } | Refused> => {
|
|
99
|
+
const user = await currentUser(ctx)
|
|
100
|
+
const request = await pendingFor(ctx, user.id, args.code)
|
|
101
|
+
if ('ok' in request) return request
|
|
102
|
+
const actor = await ownerOf(ctx, args.site)
|
|
103
|
+
await ctx.db.patch(request._id, { state: 'approved', site: actor.site._id, approvedBy: actor.user.id, approvedAt: Date.now() })
|
|
104
|
+
return { ok: true }
|
|
105
|
+
},
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
/** Step 2b: decline. The computer's next poll then answers "not valid". */
|
|
109
|
+
export const decline = mutation({
|
|
110
|
+
args: { code: v.string() },
|
|
111
|
+
handler: async (ctx, args): Promise<{ ok: true } | Refused> => {
|
|
112
|
+
const user = await currentUser(ctx)
|
|
113
|
+
const request = await pendingFor(ctx, user.id, args.code)
|
|
114
|
+
if ('ok' in request) return request
|
|
115
|
+
await ctx.db.patch(request._id, { state: 'declined' })
|
|
116
|
+
return { ok: true }
|
|
117
|
+
},
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Step 3: a poll with the device code's hash. An approved request becomes a publishing key here, with the scopes and
|
|
122
|
+
* storage of a Team-page key, created by the approver; the request is used and the key returned once. The approver
|
|
123
|
+
* must still hold the right. Unknown, expired, declined and used requests give the same answer.
|
|
124
|
+
*/
|
|
125
|
+
export const redeem = internalMutation({
|
|
126
|
+
args: { deviceHash: v.string() },
|
|
127
|
+
handler: async (ctx, args): Promise<{ state: 'pending' } | { state: 'invalid' } | { state: 'connected'; site: string; key: string }> => {
|
|
128
|
+
const row = await ctx.db.query('connectRequests').withIndex('by_device', (q) => q.eq('deviceHash', args.deviceHash)).unique()
|
|
129
|
+
if (!row || row.expiresAt <= Date.now()) return { state: 'invalid' }
|
|
130
|
+
if (row.state === 'pending') return { state: 'pending' }
|
|
131
|
+
if (row.state !== 'approved' || !row.site || !row.approvedBy) return { state: 'invalid' }
|
|
132
|
+
const site = await ctx.db.get(row.site)
|
|
133
|
+
const actor = site ? await memberOf(ctx, site, { id: row.approvedBy }) : null
|
|
134
|
+
if (!site || !actor || actor.role === 'staff') {
|
|
135
|
+
await ctx.db.patch(row._id, { state: 'declined' })
|
|
136
|
+
return { state: 'invalid' }
|
|
137
|
+
}
|
|
138
|
+
const label = `connect: ${row.label}`.slice(0, CONNECT.labelMax).trim()
|
|
139
|
+
const { key } = await insertPushKey(ctx, site, { label, scopes: [...PUBLISHING_SCOPES], createdBy: row.approvedBy })
|
|
140
|
+
await ctx.db.patch(row._id, { state: 'used' })
|
|
141
|
+
return { state: 'connected', site: site.slug, key }
|
|
142
|
+
},
|
|
143
|
+
})
|
package/convex/crons.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { cronJobs } from 'convex/server'
|
|
2
|
+
import { internal } from './_generated/api'
|
|
3
|
+
|
|
4
|
+
const crons = cronJobs()
|
|
5
|
+
crons.daily('retention', { hourUTC: 2, minuteUTC: 0 }, internal.retention.daily, {})
|
|
6
|
+
crons.daily('stale personal data', { hourUTC: 3, minuteUTC: 0 }, internal.cleanup.daily, {})
|
|
7
|
+
crons.interval('stuck uploads', { minutes: 10 }, internal.uploads.requeueStale, {})
|
|
8
|
+
crons.daily('upload sweep', { hourUTC: 2, minuteUTC: 30 }, internal.uploads.sweep, {})
|
|
9
|
+
// Retired auth signing keys stay published for 21 minutes after a rotation; this deletes them afterwards (up to 64 per
|
|
10
|
+
// run, never the current key). Rotations are rare, so a daily run catches up.
|
|
11
|
+
crons.daily('auth signing keys', { hourUTC: 3, minuteUTC: 30 }, internal.auth.pruneSigningKeys, {})
|
|
12
|
+
// Hourly because sites live in different time zones: each run handles the sites whose 17:00 hour on the day before the week starts it is.
|
|
13
|
+
crons.cron('week reminders', '5 * * * *', internal.reminders.sweep, {})
|
|
14
|
+
export default crons
|
package/convex/demo.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// Demo content for a hosted demo site (Phase 10): fills a site that nobody has edited yet with a
|
|
2
|
+
// corpus (contracts/<site>/data.json) and invites the demo people (`.test` addresses, whose codes
|
|
3
|
+
// stay in the outbox, SPEC 10). It never overwrites edited content: a site with a collection entry
|
|
4
|
+
// or an edited entry is refused. Internal, so only a holder of the deployment's deploy or admin key
|
|
5
|
+
// reaches it (`npx convex run demo:fill`). `dropGuests` ends the access a demo gave (demo reset).
|
|
6
|
+
import { v } from 'convex/values'
|
|
7
|
+
import { internalMutation } from './_generated/server'
|
|
8
|
+
import { fail } from './lib/access'
|
|
9
|
+
import { insertCorpus, invitePeople, type Corpus } from './lib/corpus'
|
|
10
|
+
import { dropTrees } from './lib/trees'
|
|
11
|
+
|
|
12
|
+
export const fill = internalMutation({
|
|
13
|
+
args: {
|
|
14
|
+
site: v.string(),
|
|
15
|
+
corpus: v.any(),
|
|
16
|
+
people: v.array(v.object({ email: v.string(), role: v.union(v.literal('owner'), v.literal('staff')), grants: v.array(v.string()) })),
|
|
17
|
+
},
|
|
18
|
+
handler: async (ctx, args) => {
|
|
19
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', args.site)).unique()
|
|
20
|
+
if (!site) fail('SITE_NOT_FOUND', 'errors.siteNotBootstrapped')
|
|
21
|
+
for (const person of args.people) {
|
|
22
|
+
if (!/\.test$/i.test(person.email.trim())) fail('INVALID', 'errors.demoEmailMustBeTest', { email: person.email })
|
|
23
|
+
}
|
|
24
|
+
const entries = await ctx.db.query('entries').withIndex('by_site_brick_order', (q) => q.eq('site', site._id)).collect()
|
|
25
|
+
if (entries.some((e) => e.kind === 'item' || e.rev > 1)) {
|
|
26
|
+
fail('FORBIDDEN', 'errors.siteAlreadyHasContent')
|
|
27
|
+
}
|
|
28
|
+
// The first release made the singles from their defaults; untouched, the corpus takes their place.
|
|
29
|
+
for (const entry of entries) {
|
|
30
|
+
await dropTrees(ctx, entry._id)
|
|
31
|
+
await ctx.db.delete(entry._id)
|
|
32
|
+
}
|
|
33
|
+
const { count } = await insertCorpus(ctx, site, args.corpus as Corpus)
|
|
34
|
+
const links = await invitePeople(ctx, site, args.people, 'demo')
|
|
35
|
+
return { entries: count, links }
|
|
36
|
+
},
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The demo reset's second step (`pnpm templates demo-reset`, after `ops:import --reset`): ends the access of everyone a
|
|
41
|
+
* demo let in. Deletes the site's memberships and open invites whose address does not end in `.test`, and its expired
|
|
42
|
+
* invites. Kept: the `.test` demo people, and the platform admins, who need no membership. Separate from
|
|
43
|
+
* `seed:importClear`, whose local use (`ops:import --reset`) replaces content only. Same guard as that clear: a local
|
|
44
|
+
* backend or the demo platform (GINKO_DEMO=1), never the client platform. Answers counts only: the workflow log of a public
|
|
45
|
+
* repository is readable by anyone, and any part of an address can name a prospect.
|
|
46
|
+
*/
|
|
47
|
+
export const dropGuests = internalMutation({
|
|
48
|
+
args: { site: v.string() },
|
|
49
|
+
handler: async (ctx, args) => {
|
|
50
|
+
if (process.env.GINKO_LOCAL !== '1' && process.env.GINKO_DEMO !== '1') fail('FORBIDDEN', 'errors.localOrDemoOnly')
|
|
51
|
+
const site = await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', args.site)).unique()
|
|
52
|
+
if (!site) fail('SITE_NOT_FOUND', 'errors.siteMissing')
|
|
53
|
+
// A membership without an address (made before memberships stored one) cannot be proven a demo person: it goes.
|
|
54
|
+
const isGuest = (email: string | undefined) => !email || !/\.test$/i.test(email)
|
|
55
|
+
let members = 0
|
|
56
|
+
let invites = 0
|
|
57
|
+
for (const member of await ctx.db.query('memberships').withIndex('by_site', (q) => q.eq('site', site._id)).collect()) {
|
|
58
|
+
if (!isGuest(member.email)) continue
|
|
59
|
+
await ctx.db.delete(member._id)
|
|
60
|
+
members++
|
|
61
|
+
}
|
|
62
|
+
const now = Date.now()
|
|
63
|
+
for (const invite of await ctx.db.query('invites').withIndex('by_site', (q) => q.eq('site', site._id)).collect()) {
|
|
64
|
+
const open = invite.acceptedAt === undefined && invite.expiresAt > now
|
|
65
|
+
// Accepted invites are history of a membership; only open guest invites and expired ones go.
|
|
66
|
+
if (invite.acceptedAt !== undefined || (open && !isGuest(invite.email))) continue
|
|
67
|
+
if (open) invites++
|
|
68
|
+
await ctx.db.delete(invite._id)
|
|
69
|
+
}
|
|
70
|
+
return { members, invites }
|
|
71
|
+
},
|
|
72
|
+
})
|