source: Klonkt/src/config/database.js@ 3d882bd

main
Last change on this file since 3d882bd was 72ec6a4, checked in by Robin <roboburr@โ€ฆ>, 6 weeks ago

Hub-modus en guardian-lite eruit

Robins besluit (31-7): een instance is een eigenaar. Twee dingen weg.

HUB-MODUS was al dood: getTenancy() gaf sinds 24-6 hardcoded 'solo'
terug, dus elke tenancy === 'hub'-tak was onbereikbaar. Nu ook echt
verwijderd: getTenancy/setTenancy zelf, de /user/:slug-routing in
resolveSite, de hub-takken in admin, zoeken, audio, posts (neighbours
en related over alle sites), download, en de push-prefix. In de views
verdwijnen de hub-tagline, de hub-navigatie, de sites- en
users-tabellen (die kwamen alleen in hub-modus gevuld en verwezen nu
naar locals die niemand meer meegeeft), de eigenaar-toewijzing bij een
site, de /user/-slugprefix, het hub-brandblok en de hub-thuisknop.

GUARDIAN-LITE was de laatste multi-user-rest: /guardian/invite gaf een
link waarmee iemand via /guardian/join een echte user plus een site met
guardian_only=1 aanmaakte. Dat zette andermans wachtwoordhash, sessie
en PRIVATE actor-sleutel in jouw database, waardoor een verhuizing of
export nooit netjes kon (shaer-qw6q). Routes, formulier, kolom en
uitnodigingstabel zijn weg. Het guardian-DASHBOARD blijft: dat is
FEP-633c en werkt voor guardians met een eigen Klonkt. Bestaande
installaties houden kolom en tabel ongebruikt; nieuwe krijgen ze niet.

Changed files:
src/services/SettingsService.js

  • getTenancy/setTenancy verwijderd; kop herschreven

src/middleware/site.js, src/middleware/render.js

  • /user/:slug-routing weg; tenancy en hubTitle uit de locals

src/routes/admin.js, admin-settings.js, audio.js, download.js,
src/routes/posts.js, search.js

  • hub-takken en hub-queries weg; postNeighbors zonder isHub

src/services/ActivityPubService.js

  • pushPrefix is nu gewoon ; getTenancy-import weg

src/routes/guardian.js

  • /invite en /join verwijderd (dashboard blijft), imports opgeschoond

src/config/database.js

  • guardian_only-kolom en ap_guardian_invites-tabel niet meer aangemaakt

src/views/pages/admin.ejs, admin-users.ejs, admin-site-edit.ejs,
src/views/pages/guardian.ejs, partials/topnav.ejs, chrome.ejs, bottom-tab.ejs

  • alle hub-takken en de uitnodigingsknop weg

remarks: 320 regels weg, 63 erbij. Suite 372 groen; alle 85 templates
compileren; en met een wegwerp-kopie van de database daadwerkelijk
gedraaid en ingelogd: /, /admin, /admin/users, /admin/sites,
/admin/settings, /admin/sites/demo/edit, /admin/media en /guardian
geven alle 200 zonder fouten in het log, en /guardian/invite en
/guardian/join geven nu 404.

-robo
Co-Authored-By: Claude Opus 4.8 <noreply@โ€ฆ>

  • Property mode set to 100644
File size: 39.0 KB
Lineย 
1import Database from 'better-sqlite3';
2import path from 'path';
3import { fileURLToPath } from 'url';
4import fs from 'fs';
5
6const __dirname = path.dirname(fileURLToPath(import.meta.url));
7const dbPath = process.env.DATABASE_PATH || path.join(__dirname, '../../storage/database.sqlite');
8
9// Ensure storage directory exists
10const storageDir = path.dirname(dbPath);
11if (!fs.existsSync(storageDir)) {
12 fs.mkdirSync(storageDir, { recursive: true });
13}
14
15// Initialize database
16const db = new Database(dbPath);
17db.pragma('journal_mode = WAL');
18db.pragma('foreign_keys = ON');
19// With WAL + several concurrent writers (request handlers, the delivery worker, the
20// background thread-crawler) a short write-lock should retry rather than throw SQLITE_BUSY.
21db.pragma('busy_timeout = 5000'); // wait up to 5s for a lock instead of failing immediately
22db.pragma('synchronous = NORMAL'); // safe with WAL (no torn writes); fewer fsyncs = faster writes
23
24export function initializeDatabase() {
25 const tableExists = db.prepare(`
26 SELECT name FROM sqlite_master WHERE type='table' AND name='users'
27 `).get();
28
29 if (!tableExists) {
30 console.log('๐Ÿ”ง Initializing database schema...');
31 const schemaPath = path.join(__dirname, '..', 'db', 'migrations', '001-init.sql');
32 const schema = fs.readFileSync(schemaPath, 'utf-8');
33 db.exec(schema);
34 console.log('โœ… Database initialized with v9-soul schema');
35 }
36
37 // Additive column migrations โ€” safe to run every boot.
38 // SQLite throws if the column already exists; we swallow that.
39 ensureColumn('sites', 'enable_audio_player', 'INTEGER DEFAULT 1');
40 // (Verwijderd 31-7-2026: sites.guardian_only en ap_guardian_invites hoorden
41 // bij de guardian-lite accounts. Bestaande installaties houden kolom en tabel
42 // ongebruikt; nieuwe krijgen ze niet meer.)
43 // FEP-633c ยง5.3: follows targeting a ward are held pending until its
44 // guardians approve (Guardian 2). Gating applies only to ward-actors.
45 db.exec(`CREATE TABLE IF NOT EXISTS ap_pending_follows (
46 id TEXT PRIMARY KEY,
47 ward_slug TEXT NOT NULL,
48 follower_uri TEXT NOT NULL,
49 follower_inbox TEXT,
50 follower_shared_inbox TEXT,
51 follower_name TEXT,
52 follower_handle TEXT,
53 follower_icon TEXT,
54 activity_json TEXT,
55 quorum TEXT DEFAULT 'any',
56 status TEXT DEFAULT 'pending',
57 created_at TEXT DEFAULT CURRENT_TIMESTAMP
58 )`);
59 db.exec(`CREATE TABLE IF NOT EXISTS ap_pending_follow_approvals (
60 follow_id TEXT NOT NULL,
61 guardian_uri TEXT NOT NULL,
62 decision TEXT NOT NULL,
63 created_at TEXT DEFAULT CURRENT_TIMESTAMP,
64 PRIMARY KEY (follow_id, guardian_uri)
65 )`);
66 // Cross-instance follow-approval (modelled on the guardian offer): the
67 // guardian-side COPY of a gated follow on a REMOTE ward, forwarded here by
68 // the ward's server as an Offer(Follow). The decision is sent back to the
69 // ward's inbox. (Local wards use ap_pending_follows directly.)
70 db.exec(`CREATE TABLE IF NOT EXISTS ap_follow_reviews (
71 id TEXT NOT NULL,
72 guardian_slug TEXT NOT NULL,
73 ward_uri TEXT NOT NULL,
74 ward_inbox TEXT,
75 follower_uri TEXT NOT NULL,
76 follower_handle TEXT,
77 follower_icon TEXT,
78 follow_json TEXT,
79 status TEXT DEFAULT 'pending',
80 created_at TEXT DEFAULT CURRENT_TIMESTAMP,
81 PRIMARY KEY (guardian_slug, id)
82 )`);
83 ensureColumn('sites', 'profile_photo', 'TEXT');
84 ensureColumn('audio_tracks', 'cover_url', 'TEXT');
85 ensureColumn('audio_tracks', 'album', 'TEXT');
86 ensureColumn('users', 'reset_token', 'TEXT');
87 ensureColumn('users', 'reset_token_expires', 'DATETIME');
88 // Google OAuth: link a Google account to a user (login via Google).
89 ensureColumn('users', 'google_sub', 'TEXT');
90 // Read-only/viewer account: can view everything but make no changes.
91 ensureColumn('users', 'readonly', 'INTEGER DEFAULT 0');
92 // Personal interface language (nl|en|de). Null = follow the default (site/env/browser).
93 ensureColumn('users', 'lang', 'TEXT');
94 // Site-level moderation toggle. 'trust' = auto-approve, 'moderate' = pending until reviewed.
95 // Circles: whether this site may appear in other sites' circles (surfacing opt-out).
96 ensureColumn('sites', 'allow_circle', 'INTEGER DEFAULT 1');
97
98 // One EXPLICIT primary/main site (= the company/label site in hub mode,
99 // the only site in solo) instead of the fragile "oldest = main" convention
100 // that was duplicated in 4 places. Backfill: mark the oldest if no primary
101 // site exists yet, so existing behaviour is preserved exactly.
102 ensureColumn('sites', 'is_primary', 'INTEGER DEFAULT 0');
103 try {
104 const hasPrimary = db.prepare('SELECT 1 FROM sites WHERE is_primary = 1 LIMIT 1').get();
105 if (!hasPrimary) {
106 const oldest = db.prepare('SELECT id FROM sites ORDER BY created_at ASC LIMIT 1').get();
107 if (oldest) db.prepare('UPDATE sites SET is_primary = 1 WHERE id = ?').run(oldest.id);
108 }
109 } catch (e) { /* sites table still empty/absent on fresh init โ€” ensurePrimarySite handles it */ }
110
111 // v9 audit additions โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”โ€”
112 // SEO/social columns the v9 template uses (most live in 001-init.sql already
113 // for fresh DBs but ensureColumn is idempotent for existing DBs).
114 ensureColumn('sites', 'twitter', 'TEXT'); // @handle (with @)
115 ensureColumn('sites', 'schema_type', "TEXT DEFAULT 'Person'"); // Person|Organization
116 ensureColumn('sites', 'publisher_name', 'TEXT');
117 ensureColumn('sites', 'publisher_url', 'TEXT');
118 ensureColumn('sites', 'publisher_logo', 'TEXT');
119 ensureColumn('sites', 'profile_enabled', 'INTEGER DEFAULT 1');
120 ensureColumn('sites', 'profile_name', 'TEXT'); // display name (falls back to title)
121 ensureColumn('sites', 'profile_bio', 'TEXT'); // short bio for header
122 ensureColumn('sites', 'profile_links', 'TEXT'); // JSON array [{platform, url}]
123 ensureColumn('sites', 'feed_view_default', "TEXT DEFAULT 'grid'"); // timeline | grid
124 ensureColumn('sites', 'feed_view_switch', 'INTEGER DEFAULT 1'); // show switcher
125 ensureColumn('sites', 'show_search', 'INTEGER DEFAULT 1');
126 ensureColumn('sites', 'show_archive_link', 'INTEGER DEFAULT 1');
127 // Gated feature (FEP-633c): may external (non-fediverse) embeds be shown to
128 // this account? NULL = auto, which means OFF for a ward and ON for anyone
129 // else. The guardians flip it; the gate itself lives server-side, so a ward
130 // never even receives the thumbnail it is not allowed to see.
131 ensureColumn('sites', 'external_embeds', 'INTEGER');
132 // The heavier sibling (FEP-633c 5.6): may a player from outside this app run
133 // INSIDE it? A preview is a picture; playback hands the screen to a third
134 // party's engine, recommendations and all. Two settings, so the guardians can
135 // allow the one without the other. NULL = auto, which means off for a ward.
136 ensureColumn('sites', 'external_playback', 'INTEGER');
137 ensureColumn('sites', 'og_theme', 'TEXT'); // OG share-card variant: NULL=auto (follow site theme) | 'light' | 'dark'
138 // FEP-7628: former identities this actor claims (JSON array of actor URIs).
139 // Publishing them as alsoKnownAs is what lets the OLD server approve a Move
140 // of its followers to this account โ€” the claim must be visible on OUR side.
141 ensureColumn('sites', 'ap_aliases', 'TEXT');
142 ensureColumn('sites', 'moved_to', 'TEXT'); // FEP-7628 slice 2: waarheen dit account vertrok
143
144 // Per-post noindex + type
145 ensureColumn('posts', 'noindex', 'INTEGER DEFAULT 0');
146 ensureColumn('posts', 'publish_at', 'DATETIME'); // release planning (premium #3): scheduled go-live
147 ensureColumn('posts', 'fan_only', 'INTEGER DEFAULT 0'); // fan-only preview (premium #3)
148 ensureColumn('posts', 'nsfw', 'INTEGER DEFAULT 0'); // sensitive content โ†’ blur + click-to-reveal; fediverse sensitive
149 ensureColumn('posts', 'cover_video_url', 'TEXT'); // muted loop MP4 for an animated cover (Safari-smooth)
150 ensureColumn('posts', 'cover_alt', 'TEXT'); // alt text / description for the cover (a11y โ†’ AS2 attachment `name`)
151 ensureColumn('posts', 'language', 'TEXT'); // BCP-47 content language โ†’ federates as AS2 contentMap (Mastodon language filter/translate)
152 ensureColumn('posts', 'content_warning', 'TEXT'); // custom CW label (empty = default "Gevoelige inhoud")
153 ensureColumn('posts', 'type', "TEXT DEFAULT 'post'"); // post | foto | video | audio
154 ensureColumn('posts', 'poll_json', 'TEXT'); // a poll WE host โ†’ federates as AS2 Question: {multiple,options[{name}],endTime,closed}
155
156 // Statistics (premium module) โ€” bare counters, cookie-free.
157 ensureColumn('posts', 'view_count', 'INTEGER DEFAULT 0'); // views per post
158 ensureColumn('audio_tracks', 'play_count', 'INTEGER DEFAULT 0'); // plays per track
159 ensureColumn('audio_tracks', 'downloadable', 'INTEGER DEFAULT 0'); // download-for-email (premium #2)
160 ensureColumn('audio_tracks', 'credit', 'TEXT'); // owner/credit (copyright holder)
161 ensureColumn('audio_tracks', 'license', 'TEXT'); // license (e.g. "CC BY 4.0", "All rights reserved")
162 ensureColumn('audio_tracks', 'link_spotify', 'TEXT'); // "open in" links per track
163 ensureColumn('audio_tracks', 'link_youtube', 'TEXT');
164 ensureColumn('audio_tracks', 'link_soundcloud', 'TEXT');
165 // Per-track: federate the actual audio file as an AS2 Audio attachment so it plays inline
166 // in EVERY fediverse client (incl. the Mastodon apps). Default 0 = gated (web player only,
167 // file not exposed). Opt-in 1 = the file is served ungated + shared on the fediverse.
168 ensureColumn('audio_tracks', 'fedi_open', 'INTEGER DEFAULT 0');
169
170 // Playlists (v9 feature) โ€” first-class entity. CREATE IF NOT EXISTS is
171 // idempotent so it's safe to run on every boot regardless of DB age.
172 db.exec(`
173 CREATE TABLE IF NOT EXISTS playlists (
174 id TEXT PRIMARY KEY,
175 site_id TEXT NOT NULL,
176 title TEXT NOT NULL,
177 artist TEXT,
178 year INTEGER,
179 cover_url TEXT,
180 kind TEXT DEFAULT 'album',
181 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
182 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
183 FOREIGN KEY (site_id) REFERENCES sites(id)
184 );
185 CREATE TABLE IF NOT EXISTS playlist_tracks (
186 playlist_id TEXT NOT NULL,
187 track_id TEXT NOT NULL,
188 position INTEGER NOT NULL DEFAULT 0,
189 PRIMARY KEY (playlist_id, track_id),
190 FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE,
191 FOREIGN KEY (track_id) REFERENCES audio_tracks(id) ON DELETE CASCADE
192 );
193 CREATE INDEX IF NOT EXISTS idx_playlist_tracks_pos
194 ON playlist_tracks(playlist_id, position);
195 `);
196
197 // Global app settings (key/value singleton). Includes the tenancy mode
198 // (solo = one site, hub = company site + /user/). Default = solo.
199 db.exec(`
200 CREATE TABLE IF NOT EXISTS app_settings (
201 key TEXT PRIMARY KEY,
202 value TEXT,
203 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
204 );
205 `);
206 db.prepare("INSERT OR IGNORE INTO app_settings (key, value) VALUES ('tenancy', 'solo')").run();
207
208 // โ”€โ”€ Statistics (premium) โ€” cookie-free โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
209 // stat_daily: pageview count per day per site (bare counter).
210 // stat_visitor_day: one row per UNIQUE visitor hash per day per site
211 // (sha256 of IP+UA+day-salt; the salt rotates daily and is never stored
212 // โ†’ no persistent identifier, no cookie, no consent required).
213 db.exec(`
214 CREATE TABLE IF NOT EXISTS stat_daily (
215 site_id TEXT NOT NULL,
216 day TEXT NOT NULL,
217 pageviews INTEGER NOT NULL DEFAULT 0,
218 PRIMARY KEY (site_id, day)
219 );
220 CREATE TABLE IF NOT EXISTS stat_visitor_day (
221 site_id TEXT NOT NULL,
222 day TEXT NOT NULL,
223 visitor_hash TEXT NOT NULL,
224 PRIMARY KEY (site_id, day, visitor_hash)
225 );
226 CREATE INDEX IF NOT EXISTS idx_stat_visitor_day ON stat_visitor_day(site_id, day);
227 CREATE TABLE IF NOT EXISTS stat_referrer (
228 site_id TEXT NOT NULL,
229 host TEXT NOT NULL,
230 count INTEGER NOT NULL DEFAULT 0,
231 PRIMARY KEY (site_id, host)
232 );
233 `);
234
235 // Newsletter / mailing list (premium). Subscribers per site; double opt-in when SMTP
236 // is configured (status 'pending' until confirmed), otherwise single opt-in ('confirmed').
237 // 'unsub' = unsubscribed. token = confirm/unsubscribe key (used in email links).
238 db.exec(`
239 CREATE TABLE IF NOT EXISTS subscribers (
240 id TEXT PRIMARY KEY,
241 site_id TEXT NOT NULL,
242 email TEXT NOT NULL,
243 status TEXT NOT NULL DEFAULT 'pending',
244 source TEXT DEFAULT 'widget',
245 token TEXT NOT NULL,
246 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
247 confirmed_at DATETIME,
248 UNIQUE(site_id, email)
249 );
250 CREATE INDEX IF NOT EXISTS idx_subscribers_site_status ON subscribers(site_id, status);
251 `);
252
253 // Sent newsletters (history + counts).
254 db.exec(`
255 CREATE TABLE IF NOT EXISTS newsletters (
256 id TEXT PRIMARY KEY,
257 site_id TEXT NOT NULL,
258 subject TEXT NOT NULL,
259 body TEXT NOT NULL,
260 sent_at DATETIME DEFAULT CURRENT_TIMESTAMP,
261 recipient_count INTEGER DEFAULT 0
262 );
263 `);
264
265 // Show agenda (premium #8): tour dates / gigs per site.
266 db.exec(`
267 CREATE TABLE IF NOT EXISTS shows (
268 id TEXT PRIMARY KEY,
269 site_id TEXT NOT NULL,
270 date TEXT NOT NULL,
271 time TEXT,
272 city TEXT NOT NULL,
273 venue TEXT,
274 country TEXT,
275 ticket_url TEXT,
276 notes TEXT,
277 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
278 );
279 CREATE INDEX IF NOT EXISTS idx_shows_site_date ON shows(site_id, date);
280 `);
281
282 // Link-in-bio click statistics (premium #6). One counter per (site, url); the
283 // link-in-bio page links via /links/go/:i which counts the click and redirects.
284 db.exec(`
285 CREATE TABLE IF NOT EXISTS link_clicks (
286 site_id TEXT NOT NULL,
287 url TEXT NOT NULL,
288 clicks INTEGER DEFAULT 0,
289 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
290 PRIMARY KEY (site_id, url)
291 );
292 `);
293
294
295 // โ”€โ”€ ActivityPub (fediverse bridge) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
296 // RSA keypair per actor (Mastodon-compatible HTTP Signatures; separate from
297 // the Cirkels Ed25519 keys). ap_followers = remote AP actors following us.
298 db.exec(`
299 CREATE TABLE IF NOT EXISTS ap_keys (
300 slug TEXT PRIMARY KEY,
301 public_pem TEXT NOT NULL,
302 private_pem TEXT NOT NULL,
303 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
304 );
305 CREATE TABLE IF NOT EXISTS ap_followers (
306 id INTEGER PRIMARY KEY AUTOINCREMENT,
307 slug TEXT NOT NULL,
308 actor_uri TEXT NOT NULL,
309 inbox TEXT,
310 shared_inbox TEXT,
311 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
312 UNIQUE(slug, actor_uri)
313 );
314 CREATE INDEX IF NOT EXISTS idx_ap_followers_slug ON ap_followers(slug);
315 CREATE TABLE IF NOT EXISTS ap_interactions (
316 id INTEGER PRIMARY KEY AUTOINCREMENT,
317 kind TEXT NOT NULL, -- 'reply' | 'like' | 'announce'
318 post_id TEXT NOT NULL,
319 object_uri TEXT NOT NULL DEFAULT '', -- remote note id (reply) or '' (like/announce)
320 actor_uri TEXT NOT NULL,
321 actor_name TEXT,
322 actor_handle TEXT,
323 actor_url TEXT,
324 actor_icon TEXT,
325 content TEXT, -- sanitized HTML (reply)
326 published TEXT,
327 parent_uri TEXT, -- the note this reply replies to (for nesting)
328 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
329 UNIQUE(kind, post_id, actor_uri, object_uri)
330 );
331 CREATE INDEX IF NOT EXISTS idx_ap_inter_post ON ap_interactions(post_id, kind);
332 -- Moderation tombstones: object URIs the site owner removed. Checked at ingest
333 -- (handleInbox) AND by the thread-crawler, so a removed reply never comes back
334 -- via thread-filling. Private notes can't be flagged via authorize_interaction
335 -- (their fetch 401s), so owner moderation acts on the locally stored copy.
336 CREATE TABLE IF NOT EXISTS ap_rejected_objects (
337 object_uri TEXT PRIMARY KEY,
338 post_id TEXT,
339 reason TEXT,
340 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
341 );
342 -- ActivityPub C2S (client-to-server): OAuth 2.0 for native/web clients (Shaer).
343 -- Public clients + PKCE (RFC 8252); tokens stored hashed; token is per user+site.
344 CREATE TABLE IF NOT EXISTS oauth_clients (
345 client_id TEXT PRIMARY KEY,
346 client_name TEXT,
347 redirect_uris TEXT NOT NULL, -- JSON array
348 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
349 );
350 CREATE TABLE IF NOT EXISTS oauth_codes (
351 code TEXT PRIMARY KEY,
352 client_id TEXT NOT NULL,
353 user_id TEXT NOT NULL,
354 site_slug TEXT NOT NULL,
355 redirect_uri TEXT NOT NULL,
356 code_challenge TEXT, -- PKCE S256 (verplicht voor public clients)
357 scope TEXT,
358 expires_at DATETIME NOT NULL,
359 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
360 );
361 CREATE TABLE IF NOT EXISTS oauth_tokens (
362 token_hash TEXT PRIMARY KEY, -- sha256(bearer); het token zelf slaan we nooit op
363 client_id TEXT NOT NULL,
364 user_id TEXT NOT NULL,
365 site_slug TEXT NOT NULL,
366 scope TEXT,
367 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
368 last_used_at DATETIME
369 );
370 -- Paid posts (klonkt-demo-aki): the site owner's own Patreon campaign.
371 -- Secrets are encrypted at rest (CryptoBox). Never reuses the instance-level
372 -- patreon_* settings, which are Klonkt Premium's separate license flow.
373 CREATE TABLE IF NOT EXISTS paid_patreon (
374 site_id TEXT PRIMARY KEY,
375 client_id TEXT,
376 client_secret_enc TEXT,
377 campaign_id TEXT,
378 access_token_enc TEXT,
379 refresh_token_enc TEXT,
380 token_exp INTEGER, -- unix seconds
381 default_min_cents INTEGER DEFAULT 0,
382 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
383 );
384 -- One row per passkey. NO patron identity is stored (design decision):
385 -- {passkey, site, proven cents, expiry}. Not traceable to a person.
386 CREATE TABLE IF NOT EXISTS paid_entitlements (
387 credential_id TEXT PRIMARY KEY, -- WebAuthn credential id (opaque, base64url)
388 site_id TEXT NOT NULL,
389 public_key TEXT NOT NULL, -- COSE public key, base64url
390 counter INTEGER DEFAULT 0,
391 transports TEXT,
392 min_cents INTEGER DEFAULT 0, -- the amount proven at link time
393 expires_at INTEGER NOT NULL, -- unix seconds; re-link after
394 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
395 );
396 -- Web Push (docs/webpush-design.md): one row per browser/device the owner
397 -- enabled notifications on. Payloads are encrypted to p256dh/auth (RFC 8291).
398 CREATE TABLE IF NOT EXISTS push_subscriptions (
399 endpoint TEXT PRIMARY KEY, -- push-service URL for this device
400 user_id TEXT NOT NULL,
401 p256dh TEXT NOT NULL, -- client public key
402 auth TEXT NOT NULL, -- client auth secret
403 alert_types TEXT, -- JSON {follow,reply,like,boost,dm}
404 ua_label TEXT,
405 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
406 last_ok_at DATETIME
407 );
408 CREATE TABLE IF NOT EXISTS ap_outbox (
409 id TEXT PRIMARY KEY, -- note path segment (uuid) โ†’ /ap/notes/<id>
410 site_slug TEXT NOT NULL,
411 post_id TEXT NOT NULL,
412 post_slug TEXT,
413 in_reply_to TEXT, -- remote status uri we reply to
414 to_actor TEXT, -- remote actor uri (mentioned)
415 to_handle TEXT,
416 content TEXT NOT NULL, -- sanitized HTML of our reply
417 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
418 );
419 CREATE INDEX IF NOT EXISTS idx_ap_outbox_post ON ap_outbox(post_id);
420 -- Your like/boost state on a REMOTE post (the interact page), so those become toggles.
421 CREATE TABLE IF NOT EXISTS ap_my_reactions (
422 site_slug TEXT NOT NULL,
423 target_uri TEXT NOT NULL,
424 kind TEXT NOT NULL, -- 'like' | 'boost'
425 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
426 UNIQUE(site_slug, target_uri, kind)
427 );
428 `);
429 ensureColumn('ap_interactions', 'parent_uri', 'TEXT'); // nesting (existing DBs)
430 ensureColumn('ap_interactions', 'acted_boost', 'INTEGER DEFAULT 0'); // owner boosted this comment (๐Ÿ”) โ†’ can undo
431 ensureColumn('ap_interactions', 'acted_like', 'INTEGER DEFAULT 0'); // owner liked this comment (โญ) โ†’ can undo
432
433 // Fediverse CLIENT: accounts WE follow (outbound) + the home timeline of their posts.
434 db.exec(`
435 CREATE TABLE IF NOT EXISTS ap_following (
436 id INTEGER PRIMARY KEY AUTOINCREMENT,
437 slug TEXT NOT NULL, -- our site that follows
438 actor_uri TEXT NOT NULL, -- the followed account's actor id
439 handle TEXT, name TEXT, icon TEXT, url TEXT,
440 inbox TEXT, -- their inbox (for Create delivery / Undo)
441 follow_id TEXT, -- the Follow activity id we sent (Accept matching)
442 status TEXT DEFAULT 'pending', -- pending | accepted
443 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
444 UNIQUE(slug, actor_uri)
445 );
446 CREATE TABLE IF NOT EXISTS ap_timeline (
447 id TEXT NOT NULL, -- the remote note's AP id
448 slug TEXT NOT NULL, -- whose home timeline (our site)
449 author_uri TEXT, author_name TEXT, author_handle TEXT, author_icon TEXT, author_url TEXT,
450 content TEXT, url TEXT, published TEXT, media_json TEXT,
451 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
452 UNIQUE(slug, id)
453 );
454 CREATE INDEX IF NOT EXISTS idx_ap_timeline_slug ON ap_timeline(slug, published);
455 CREATE TABLE IF NOT EXISTS ap_blocks (
456 id INTEGER PRIMARY KEY AUTOINCREMENT,
457 slug TEXT NOT NULL, -- our site that set the block
458 target TEXT NOT NULL, -- actor URI (actor block) or domain (domain block)
459 kind TEXT NOT NULL, -- 'actor' | 'domain'
460 label TEXT, -- display (@handle or domain)
461 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
462 UNIQUE(slug, target)
463 );
464 CREATE INDEX IF NOT EXISTS idx_ap_blocks_target ON ap_blocks(target);
465 -- Committed guardian โ†” ward relations, one row per local side. role
466 -- 'ward' = the local slug is a ward of other_uri; 'guardian' = the local
467 -- slug guards other_uri. status is always 'accepted' here now: PENDING
468 -- offers live in ap_guardian_offers below (FEP-633c multi-party handshake).
469 CREATE TABLE IF NOT EXISTS ap_guardianships (
470 id INTEGER PRIMARY KEY AUTOINCREMENT,
471 slug TEXT NOT NULL, -- our local site in this relation (guardianship module)
472 role TEXT NOT NULL, -- 'guardian' (slug guards other) | 'ward' (other guards slug)
473 other_uri TEXT NOT NULL, -- the counterpart actor URI (local or remote)
474 other_handle TEXT, -- cached @user@host for display
475 status TEXT NOT NULL, -- 'offered' (legacy) | 'accepted'
476 offer_id TEXT, -- the Offer activity id (FEP-633c section 3)
477 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
478 UNIQUE(slug, role, other_uri)
479 );
480 CREATE INDEX IF NOT EXISTS idx_ap_guardianships_slug ON ap_guardianships(slug, role, status);
481 -- The multi-party handshake (FEP-633c section 3), one row per offer this
482 -- instance is a party to. Mirrors the Shaer test daemon's Handshake:
483 -- accepts accumulate in ap_guardian_offer_accepts, and the offer commits
484 -- only when the candidate returns the handle after ward + candidate + at
485 -- least one existing guardian have accepted.
486 CREATE TABLE IF NOT EXISTS ap_guardian_offers (
487 offer_id TEXT NOT NULL, -- the Offer activity id (minted by the candidate)
488 slug TEXT NOT NULL, -- the local site tracking this handshake (each party keeps its own copy)
489 ward_uri TEXT NOT NULL, -- the ward-to-be
490 candidate_uri TEXT NOT NULL, -- the guardian-candidate (fixed initiator)
491 existing_guardians TEXT NOT NULL DEFAULT '[]', -- JSON array of the ward's current guardian URIs
492 status TEXT NOT NULL DEFAULT 'pending', -- 'pending' | 'committed' | 'void'
493 handle TEXT, -- the escalation handle returned at commit (section 6)
494 ward_handle TEXT, -- cached @ward@host for display
495 candidate_handle TEXT, -- cached @candidate@host for display
496 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
497 PRIMARY KEY (slug, offer_id)
498 );
499 CREATE INDEX IF NOT EXISTS idx_ap_guardian_offers_slug ON ap_guardian_offers(slug, status);
500 CREATE TABLE IF NOT EXISTS ap_guardian_offer_accepts (
501 offer_id TEXT NOT NULL, -- FK to ap_guardian_offers
502 slug TEXT NOT NULL, -- the local site's copy of the tally
503 party_uri TEXT NOT NULL, -- the party who accepted (ward | candidate | an existing guardian)
504 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
505 PRIMARY KEY (slug, offer_id, party_uri)
506 );
507 -- FEP-633c ยง5.6: a gated setting a ward's guardians decide together, which
508 -- has to work when they live on other servers (the ordinary case). One row
509 -- per guardian answer; the ward's server tallies (ยง3.5) and enforces.
510 -- The proposals themselves, so an Accept that only references the offer
511 -- id can still be resolved to "which feature, which value".
512 CREATE TABLE IF NOT EXISTS ap_gated_offers (
513 offer_id TEXT PRIMARY KEY,
514 slug TEXT NOT NULL, -- the ward, on this server
515 feature TEXT NOT NULL,
516 value INTEGER NOT NULL,
517 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
518 );
519 -- The guardian-side COPY of a gated-setting proposal on a ward, forwarded
520 -- here by the WARD's server (the same shape ap_follow_reviews has for a
521 -- gated follow). Without it a guardian on another server never learns a
522 -- proposal exists and can never answer it, so a threshold of two can never
523 -- be reached and every proposal expires. The answer goes back to the
524 -- ward's inbox, which tallies (5.6).
525 CREATE TABLE IF NOT EXISTS ap_gated_reviews (
526 id TEXT NOT NULL, -- the offer id, as minted by the proposer
527 guardian_slug TEXT NOT NULL, -- us, one of the ward's guardians
528 ward_uri TEXT NOT NULL,
529 ward_inbox TEXT,
530 proposer TEXT, -- who opened it (for display)
531 feature TEXT NOT NULL,
532 value INTEGER NOT NULL,
533 created_at TEXT DEFAULT CURRENT_TIMESTAMP,
534 PRIMARY KEY (guardian_slug, id)
535 );
536 -- The PROPOSER's own record of a gated proposal it sent (5.6). Without it
537 -- a guardian clicks "propose", the ward's server tallies somewhere else,
538 -- and the proposer has nowhere to even see that something is running: the
539 -- status was a button caption that did not survive a page refresh. The
540 -- ward's server answers the Offer once the decision settles (Accept when
541 -- it settled on the proposed value, Reject otherwise); that answer lands
542 -- in status. An open row past the decision window renders as expired.
543 CREATE TABLE IF NOT EXISTS ap_gated_sent (
544 offer_id TEXT PRIMARY KEY, -- as minted by us, the proposer
545 guardian_slug TEXT NOT NULL, -- us
546 ward_uri TEXT NOT NULL,
547 feature TEXT NOT NULL,
548 value INTEGER NOT NULL, -- what we proposed
549 status TEXT NOT NULL DEFAULT 'open', -- 'open' | 'accepted' | 'rejected'
550 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
551 );
552 CREATE TABLE IF NOT EXISTS ap_gated_votes (
553 slug TEXT NOT NULL, -- the WARD, on this server
554 feature TEXT NOT NULL, -- e.g. 'shaer:externalEmbeds'
555 guardian_uri TEXT NOT NULL, -- who answered (must be a committed guardian)
556 value INTEGER NOT NULL, -- the value they voted for (0/1)
557 opened_at DATETIME NOT NULL, -- when this decision opened (the window start)
558 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
559 PRIMARY KEY (slug, feature, guardian_uri)
560 );
561 -- Guardian availability (FEP-633c 3.6): one guardian's attention as seen
562 -- from one ward on this server. Never public; the ward reads it via the
563 -- owner-only guardians queue. One rule above all: one answer restores
564 -- everything, so every row here is one answer away from disappearing.
565 CREATE TABLE IF NOT EXISTS ap_guardian_attention (
566 ward_slug TEXT NOT NULL,
567 guardian_uri TEXT NOT NULL,
568 state TEXT NOT NULL DEFAULT 'active', -- 'active' | 'away' | 'dormant'
569 away_until INTEGER, -- epoch ms while declared away
570 PRIMARY KEY (ward_slug, guardian_uri)
571 );
572 -- The ONLY admissible dormancy evidence (3.6.2): directly addressed
573 -- requests that went unanswered. Calendar time alone never counts.
574 CREATE TABLE IF NOT EXISTS ap_attention_requests (
575 ward_slug TEXT NOT NULL,
576 guardian_uri TEXT NOT NULL,
577 request_id TEXT NOT NULL,
578 asked_at INTEGER NOT NULL, -- epoch ms
579 PRIMARY KEY (ward_slug, guardian_uri, request_id)
580 );
581 -- A lapse (3.6.3): the available co-guardians deciding to release a
582 -- dormant one. Irreversible, so the window always runs in full; any sign
583 -- of life from the target cancels it outright.
584 CREATE TABLE IF NOT EXISTS ap_lapses (
585 id TEXT PRIMARY KEY,
586 ward_slug TEXT NOT NULL,
587 ward_uri TEXT NOT NULL,
588 target_uri TEXT NOT NULL,
589 opened_by TEXT NOT NULL,
590 set_json TEXT NOT NULL, -- the available set at open, target excluded
591 accepts_json TEXT NOT NULL DEFAULT '[]',
592 rejects_json TEXT NOT NULL DEFAULT '[]',
593 opened_at INTEGER NOT NULL, -- epoch ms
594 window_ms INTEGER NOT NULL,
595 cancelled INTEGER NOT NULL DEFAULT 0,
596 applied INTEGER NOT NULL DEFAULT 0,
597 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
598 );
599 CREATE TABLE IF NOT EXISTS ap_delivery (
600 id INTEGER PRIMARY KEY AUTOINCREMENT,
601 slug TEXT NOT NULL, -- our site/actor that signs the delivery
602 inbox TEXT NOT NULL, -- recipient inbox URL
603 body TEXT NOT NULL, -- the activity JSON to POST
604 attempts INTEGER NOT NULL DEFAULT 0,
605 next_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
606 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
607 );
608 CREATE INDEX IF NOT EXISTS idx_ap_delivery_due ON ap_delivery(next_at);
609 CREATE TABLE IF NOT EXISTS poll_votes (
610 id INTEGER PRIMARY KEY AUTOINCREMENT,
611 post_id INTEGER NOT NULL, -- our local poll post (posts.id)
612 actor_uri TEXT NOT NULL, -- the remote voter's AP actor URI
613 choice TEXT NOT NULL, -- the chosen option's name (matches poll_json options[].name)
614 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
615 UNIQUE(post_id, actor_uri, choice)
616 );
617 CREATE INDEX IF NOT EXISTS idx_poll_votes_post ON poll_votes(post_id);
618 CREATE TABLE IF NOT EXISTS ap_mentions (
619 id INTEGER PRIMARY KEY AUTOINCREMENT,
620 slug TEXT NOT NULL, -- our mentioned site/actor
621 object_uri TEXT NOT NULL, -- the remote note that mentions us
622 note_url TEXT, -- its human URL (open/interact)
623 actor_uri TEXT, actor_name TEXT, actor_handle TEXT, actor_icon TEXT, actor_url TEXT,
624 content TEXT, -- sanitized HTML snippet of the mentioning note
625 published TEXT,
626 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
627 UNIQUE(slug, object_uri)
628 );
629 CREATE INDEX IF NOT EXISTS idx_ap_mentions_slug ON ap_mentions(slug, created_at);
630 CREATE TABLE IF NOT EXISTS ap_reports (
631 id INTEGER PRIMARY KEY AUTOINCREMENT,
632 slug TEXT NOT NULL, -- our site the report is about (its owner moderates)
633 actor_uri TEXT, -- the reporter's actor URI
634 actor_name TEXT, actor_handle TEXT, actor_icon TEXT,
635 content TEXT, -- the reason (plain text)
636 objects TEXT, -- JSON array of reported object URIs (our actor + statuses)
637 seen INTEGER DEFAULT 0,
638 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
639 );
640 CREATE INDEX IF NOT EXISTS idx_ap_reports_slug ON ap_reports(slug, created_at);
641 `);
642 // "Feature" a followed account: its posts show in the local Cirkel.
643 ensureColumn('ap_following', 'auto_boost', 'INTEGER DEFAULT 0');
644 // A timeline post you boosted (๐Ÿ”) โ€” also shown in the Cirkel (mixed by date).
645 ensureColumn('ap_timeline', 'boosted', 'INTEGER DEFAULT 0');
646 ensureColumn('ap_timeline', 'liked', 'INTEGER DEFAULT 0'); // a feed post you liked (โญ) โ†’ toggle
647 ensureColumn('ap_timeline', 'nsfw', 'INTEGER DEFAULT 0'); // remote sensitive post โ†’ blur in the Cirkel
648 ensureColumn('ap_timeline', 'cw', 'TEXT'); // remote content-warning text
649 ensureColumn('ap_timeline', 'emoji_json', 'TEXT'); // FEP-9098 custom emoji Emoji tags from the inbound note, served back as `tag`
650 ensureColumn('ap_timeline', 'link_json', 'TEXT'); // FEP-e232 object-link (quote/ref) tags from the inbound note, served back as `tag`
651 ensureColumn('ap_timeline', 'quote_json', 'TEXT'); // FEP-044f resolved quoted-post snapshot (author + content), for the embedded quote card
652 // FEP-044f: the fediverse object THIS post quotes, resolved once at publish
653 // time so buildNote (sync, also used by the outbox) needs no network.
654 ensureColumn('posts', 'quote_uri', 'TEXT'); // the quoted object's id
655 ensureColumn('posts', 'quote_actor', 'TEXT'); // its author, so we can address them
656 ensureColumn('ap_timeline', 'embed_json', 'TEXT'); // resolved EXTERNAL embed (oEmbed/provider), thumbnail-only; gated per site (sites.external_embeds)
657 ensureColumn('ap_timeline', 'author_emoji_json', 'TEXT'); // FEP-9098 custom emojis in the author's display name (shaer:author.emojis)
658 ensureColumn('ap_timeline', 'reblog_emoji_json', 'TEXT'); // FEP-9098 custom emojis in the booster's display name (shaer:booster.emojis)
659 ensureColumn('ap_timeline', 'reblog_name', 'TEXT'); // a followed account boosted this โ†’ "X boosted"
660 ensureColumn('ap_timeline', 'reblog_handle', 'TEXT'); // the booster's @handle
661 ensureColumn('ap_timeline', 'reblog_icon', 'TEXT'); // the booster's avatar
662 ensureColumn('ap_timeline', 'poll_json', 'TEXT'); // a Question (poll): {multiple,options[{name,count}],endTime,closed,voters,voted}
663
664 // Delivery health per follower โ†’ surface dead accounts for manual cleanup.
665 ensureColumn('ap_followers', 'last_delivery_at', 'DATETIME'); // last SUCCESSFUL delivery to this follower's inbox
666 ensureColumn('ap_followers', 'last_error_at', 'DATETIME'); // last time a delivery to it gave up (max retries)
667
668 // ActivityPub `source` model: content_rendered = baked display HTML (#hashtags / URLs /
669 // @mentions linkified once at save). `content` stays the raw source used for editing and
670 // re-rendering. NULL on old posts โ†’ the render route bakes on the fly as a fallback.
671 ensureColumn('posts', 'content_rendered', 'TEXT');
672
673 // AP addressing of an incoming interaction: 'public' | 'unlisted' | 'followers' | 'direct',
674 // derived from the note's to/cc at ingest. The public post page only renders public/unlisted
675 // replies; followers/direct replies surface in notifications (and later Messages) with post
676 // context instead. Existing rows default to 'public' (historically almost all were).
677 ensureColumn('ap_interactions', 'visibility', "TEXT DEFAULT 'public'");
678 ensureColumn('ap_interactions', 'emoji_json', 'TEXT'); // FEP-9098 custom emojis in a reply's content (messages + thread)
679 ensureColumn('ap_interactions', 'actor_emoji_json', 'TEXT'); // FEP-9098 custom emojis in the reply author's display name
680 // Rich replies: the reply's language (BCP47 code) โ†’ contentMap on the outgoing Note.
681 ensureColumn('ap_outbox', 'language', 'TEXT');
682 // Rich replies: JSON array [{url, mediaType, name}] โ†’ `attachment` on the Note.
683 ensureColumn('ap_outbox', 'attachments', 'TEXT');
684 ensureColumn('posts', 'ap_visibility', 'TEXT'); // public|quiet|friends|direct (C2S addressing, shaer-60b)
685 ensureColumn('posts', 'paid', 'INTEGER DEFAULT 0'); // paid post (klonkt-demo-aki)
686 ensureColumn('posts', 'paid_min_cents', 'INTEGER'); // required support; null = owner default
687 ensureColumn('paid_patreon', 'patreon_url', 'TEXT'); // owner's public Patreon page โ†’ "Word supporter" link (klonkt-demo-aki)
688 ensureColumn('ap_outbox', 'visibility', 'TEXT'); // 'direct' = private mention, never Public (shaer-tqc)
689 ensureColumn('ap_outbox', 'to_actors', 'TEXT'); // JSON array of recipient actor URIs for direct notes
690 ensureColumn('ap_outbox', 'help_request', 'INTEGER'); // FEP-633c shaer:helpRequest (ward's call for help)
691 ensureColumn('ap_mentions', 'help_request', 'INTEGER'); // inbound ward call-for-help (Guardian PWA message centre)
692 ensureColumn('ap_outbox', 'wave', 'INTEGER'); // FEP-633c shaer:wave (guardian -> ward nudge)
693 ensureColumn('ap_outbox', 'away_until', 'INTEGER'); // FEP-633c 3.6.1 shaer:away + endTime (epoch ms)
694 ensureColumn('ap_gated_offers', 'proposer', 'TEXT'); // who proposed (5.6): the settle-answer goes back to them
695 ensureColumn('posts', 'c2s_attachments', 'TEXT'); // media a C2S Note carried (JSON [{url,mediaType,name}]); buildNote federates them
696 // 30-7: C2S posts briefly got their content media copied onto the cover,
697 // which showed the same video twice on the post page. Clear the covers that
698 // duplicate their own content; idempotent, only ever touches those.
699 try {
700 db.prepare("UPDATE posts SET cover_video_url = NULL WHERE cover_video_url LIKE '/media/reply-media/%' AND instr(content, cover_video_url) > 0").run();
701 db.prepare("UPDATE posts SET cover_image_url = NULL WHERE cover_image_url LIKE '/media/reply-media/%' AND instr(content, cover_image_url) > 0").run();
702 } catch { /* posts table absent on fresh init */ }
703 ensureColumn('ap_mentions', 'wave', 'INTEGER'); // inbound guardian wave
704 // FEP-633c ยง2.2: object hint that the author is a ward. Register-only for now;
705 // used later at reddings-boei / escalation routing.
706 ensureColumn('ap_timeline', 'has_guardians', 'INTEGER');
707 ensureColumn('ap_mentions', 'has_guardians', 'INTEGER');
708 // Berichten and de Krant render a post the same way, so a mention or a reply
709 // needs the same trimmings a timeline row already has: custom emojis, the
710 // media the note carried, and the quote / link-preview card.
711 ensureColumn('ap_mentions', 'emoji_json', 'TEXT'); // FEP-9098, in the content
712 ensureColumn('ap_mentions', 'actor_emoji_json', 'TEXT'); // FEP-9098, in the display name
713 ensureColumn('ap_mentions', 'media_json', 'TEXT');
714 ensureColumn('ap_mentions', 'quote_json', 'TEXT'); // FEP-044f quoted post
715 ensureColumn('ap_mentions', 'embed_json', 'TEXT'); // external link preview
716 ensureColumn('ap_interactions', 'media_json', 'TEXT');
717 ensureColumn('ap_interactions', 'quote_json', 'TEXT');
718 ensureColumn('ap_interactions', 'embed_json', 'TEXT');
719 ensureColumn('ap_followers', 'name', 'TEXT'); // cached display name (shaer-aa3)
720 ensureColumn('ap_followers', 'handle', 'TEXT'); // @user@host
721 ensureColumn('ap_followers', 'icon', 'TEXT'); // avatar URL
722}
723
724function ensureColumn(table, column, definition) {
725 try {
726 db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
727 console.log(`๐Ÿ”ง Added column ${table}.${column}`);
728 } catch (e) {
729 // "duplicate column name" โ†’ already there. Anything else, surface it.
730 if (!/duplicate column/i.test(e.message)) {
731 console.error(`โŒ ensureColumn(${table}.${column}):`, e.message);
732 }
733 }
734}
735
736export default db;
Note: See TracBrowser for help on using the repository browser.