source: Klonkt/src/config/database.js@ 05665bc

main
Last change on this file since 05665bc was 05665bc, checked in by Robin <roboburr@…>, 7 weeks ago

Guardian 2: losse guardians via uitnodiging (guardian-only accounts)

Stap 1 van het uitbouwplan op /guardian2. Een familie nodigt oma uit met een
link; zij kiest naam + wachtwoord en heeft daarmee een guardian-only account:
user + minimale site met guardian_only=1. Omdat alles in Klonkt al per slug
werkt (actor, WebFinger, inbox, offers, push, deze PWA) is zij daarmee meteen
een volwaardige guardian-actor, zonder CMS eromheen.

Changed files:
src/config/database.js

  • sites.guardian_only vlag; tabel ap_guardian_invites (token, eenmalig)

src/routes/guardian2.js

  • POST /invite (link minten, ingelogd), GET/POST /join/:token (naam+wachtwoord, user+site aanmaken, sessie, redirect naar de PWA)

src/views/pages/guardian2.ejs

  • Invite a guardian-knop in de header

remarks: npm test 164/164; join met ongeldig token geeft 404. Nog te doen op v2:
guardian-only sites uit listings houden, push per account, meekijken/follow-
goedkeuring.

-robo
Co-Authored-By: Claude Opus 4.8 <noreply@…>

  • Property mode set to 100644
File size: 28.3 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 // Guardian 2: losse guardians. Een guardian-only account is user + minimale
41 // site (alleen de actor telt); de vlag houdt CMS/listings erbuiten.
42 ensureColumn('sites', 'guardian_only', 'INTEGER DEFAULT 0');
43 db.exec(`CREATE TABLE IF NOT EXISTS ap_guardian_invites (
44 token TEXT PRIMARY KEY,
45 created_by TEXT NOT NULL,
46 created_at TEXT DEFAULT CURRENT_TIMESTAMP,
47 used_by TEXT,
48 used_at TEXT
49 )`);
50 ensureColumn('sites', 'profile_photo', 'TEXT');
51 ensureColumn('audio_tracks', 'cover_url', 'TEXT');
52 ensureColumn('audio_tracks', 'album', 'TEXT');
53 ensureColumn('users', 'reset_token', 'TEXT');
54 ensureColumn('users', 'reset_token_expires', 'DATETIME');
55 // Google OAuth: link a Google account to a user (login via Google).
56 ensureColumn('users', 'google_sub', 'TEXT');
57 // Read-only/viewer account: can view everything but make no changes.
58 ensureColumn('users', 'readonly', 'INTEGER DEFAULT 0');
59 // Personal interface language (nl|en|de). Null = follow the default (site/env/browser).
60 ensureColumn('users', 'lang', 'TEXT');
61 // Site-level moderation toggle. 'trust' = auto-approve, 'moderate' = pending until reviewed.
62 // Circles: whether this site may appear in other sites' circles (surfacing opt-out).
63 ensureColumn('sites', 'allow_circle', 'INTEGER DEFAULT 1');
64
65 // One EXPLICIT primary/main site (= the company/label site in hub mode,
66 // the only site in solo) instead of the fragile "oldest = main" convention
67 // that was duplicated in 4 places. Backfill: mark the oldest if no primary
68 // site exists yet, so existing behaviour is preserved exactly.
69 ensureColumn('sites', 'is_primary', 'INTEGER DEFAULT 0');
70 try {
71 const hasPrimary = db.prepare('SELECT 1 FROM sites WHERE is_primary = 1 LIMIT 1').get();
72 if (!hasPrimary) {
73 const oldest = db.prepare('SELECT id FROM sites ORDER BY created_at ASC LIMIT 1').get();
74 if (oldest) db.prepare('UPDATE sites SET is_primary = 1 WHERE id = ?').run(oldest.id);
75 }
76 } catch (e) { /* sites table still empty/absent on fresh init — ensurePrimarySite handles it */ }
77
78 // v9 audit additions —————————————————————————————————————————
79 // SEO/social columns the v9 template uses (most live in 001-init.sql already
80 // for fresh DBs but ensureColumn is idempotent for existing DBs).
81 ensureColumn('sites', 'twitter', 'TEXT'); // @handle (with @)
82 ensureColumn('sites', 'schema_type', "TEXT DEFAULT 'Person'"); // Person|Organization
83 ensureColumn('sites', 'publisher_name', 'TEXT');
84 ensureColumn('sites', 'publisher_url', 'TEXT');
85 ensureColumn('sites', 'publisher_logo', 'TEXT');
86 ensureColumn('sites', 'profile_enabled', 'INTEGER DEFAULT 1');
87 ensureColumn('sites', 'profile_name', 'TEXT'); // display name (falls back to title)
88 ensureColumn('sites', 'profile_bio', 'TEXT'); // short bio for header
89 ensureColumn('sites', 'profile_links', 'TEXT'); // JSON array [{platform, url}]
90 ensureColumn('sites', 'feed_view_default', "TEXT DEFAULT 'grid'"); // timeline | grid
91 ensureColumn('sites', 'feed_view_switch', 'INTEGER DEFAULT 1'); // show switcher
92 ensureColumn('sites', 'show_search', 'INTEGER DEFAULT 1');
93 ensureColumn('sites', 'show_archive_link', 'INTEGER DEFAULT 1');
94 ensureColumn('sites', 'og_theme', 'TEXT'); // OG share-card variant: NULL=auto (follow site theme) | 'light' | 'dark'
95
96 // Per-post noindex + type
97 ensureColumn('posts', 'noindex', 'INTEGER DEFAULT 0');
98 ensureColumn('posts', 'publish_at', 'DATETIME'); // release planning (premium #3): scheduled go-live
99 ensureColumn('posts', 'fan_only', 'INTEGER DEFAULT 0'); // fan-only preview (premium #3)
100 ensureColumn('posts', 'nsfw', 'INTEGER DEFAULT 0'); // sensitive content → blur + click-to-reveal; fediverse sensitive
101 ensureColumn('posts', 'cover_video_url', 'TEXT'); // muted loop MP4 for an animated cover (Safari-smooth)
102 ensureColumn('posts', 'cover_alt', 'TEXT'); // alt text / description for the cover (a11y → AS2 attachment `name`)
103 ensureColumn('posts', 'language', 'TEXT'); // BCP-47 content language → federates as AS2 contentMap (Mastodon language filter/translate)
104 ensureColumn('posts', 'content_warning', 'TEXT'); // custom CW label (empty = default "Gevoelige inhoud")
105 ensureColumn('posts', 'type', "TEXT DEFAULT 'post'"); // post | foto | video | audio
106 ensureColumn('posts', 'poll_json', 'TEXT'); // a poll WE host → federates as AS2 Question: {multiple,options[{name}],endTime,closed}
107
108 // Statistics (premium module) — bare counters, cookie-free.
109 ensureColumn('posts', 'view_count', 'INTEGER DEFAULT 0'); // views per post
110 ensureColumn('audio_tracks', 'play_count', 'INTEGER DEFAULT 0'); // plays per track
111 ensureColumn('audio_tracks', 'downloadable', 'INTEGER DEFAULT 0'); // download-for-email (premium #2)
112 ensureColumn('audio_tracks', 'credit', 'TEXT'); // owner/credit (copyright holder)
113 ensureColumn('audio_tracks', 'license', 'TEXT'); // license (e.g. "CC BY 4.0", "All rights reserved")
114 ensureColumn('audio_tracks', 'link_spotify', 'TEXT'); // "open in" links per track
115 ensureColumn('audio_tracks', 'link_youtube', 'TEXT');
116 ensureColumn('audio_tracks', 'link_soundcloud', 'TEXT');
117 // Per-track: federate the actual audio file as an AS2 Audio attachment so it plays inline
118 // in EVERY fediverse client (incl. the Mastodon apps). Default 0 = gated (web player only,
119 // file not exposed). Opt-in 1 = the file is served ungated + shared on the fediverse.
120 ensureColumn('audio_tracks', 'fedi_open', 'INTEGER DEFAULT 0');
121
122 // Playlists (v9 feature) — first-class entity. CREATE IF NOT EXISTS is
123 // idempotent so it's safe to run on every boot regardless of DB age.
124 db.exec(`
125 CREATE TABLE IF NOT EXISTS playlists (
126 id TEXT PRIMARY KEY,
127 site_id TEXT NOT NULL,
128 title TEXT NOT NULL,
129 artist TEXT,
130 year INTEGER,
131 cover_url TEXT,
132 kind TEXT DEFAULT 'album',
133 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
134 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
135 FOREIGN KEY (site_id) REFERENCES sites(id)
136 );
137 CREATE TABLE IF NOT EXISTS playlist_tracks (
138 playlist_id TEXT NOT NULL,
139 track_id TEXT NOT NULL,
140 position INTEGER NOT NULL DEFAULT 0,
141 PRIMARY KEY (playlist_id, track_id),
142 FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE,
143 FOREIGN KEY (track_id) REFERENCES audio_tracks(id) ON DELETE CASCADE
144 );
145 CREATE INDEX IF NOT EXISTS idx_playlist_tracks_pos
146 ON playlist_tracks(playlist_id, position);
147 `);
148
149 // Global app settings (key/value singleton). Includes the tenancy mode
150 // (solo = one site, hub = company site + /user/). Default = solo.
151 db.exec(`
152 CREATE TABLE IF NOT EXISTS app_settings (
153 key TEXT PRIMARY KEY,
154 value TEXT,
155 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
156 );
157 `);
158 db.prepare("INSERT OR IGNORE INTO app_settings (key, value) VALUES ('tenancy', 'solo')").run();
159
160 // ── Statistics (premium) — cookie-free ──────────────────────
161 // stat_daily: pageview count per day per site (bare counter).
162 // stat_visitor_day: one row per UNIQUE visitor hash per day per site
163 // (sha256 of IP+UA+day-salt; the salt rotates daily and is never stored
164 // → no persistent identifier, no cookie, no consent required).
165 db.exec(`
166 CREATE TABLE IF NOT EXISTS stat_daily (
167 site_id TEXT NOT NULL,
168 day TEXT NOT NULL,
169 pageviews INTEGER NOT NULL DEFAULT 0,
170 PRIMARY KEY (site_id, day)
171 );
172 CREATE TABLE IF NOT EXISTS stat_visitor_day (
173 site_id TEXT NOT NULL,
174 day TEXT NOT NULL,
175 visitor_hash TEXT NOT NULL,
176 PRIMARY KEY (site_id, day, visitor_hash)
177 );
178 CREATE INDEX IF NOT EXISTS idx_stat_visitor_day ON stat_visitor_day(site_id, day);
179 CREATE TABLE IF NOT EXISTS stat_referrer (
180 site_id TEXT NOT NULL,
181 host TEXT NOT NULL,
182 count INTEGER NOT NULL DEFAULT 0,
183 PRIMARY KEY (site_id, host)
184 );
185 `);
186
187 // Newsletter / mailing list (premium). Subscribers per site; double opt-in when SMTP
188 // is configured (status 'pending' until confirmed), otherwise single opt-in ('confirmed').
189 // 'unsub' = unsubscribed. token = confirm/unsubscribe key (used in email links).
190 db.exec(`
191 CREATE TABLE IF NOT EXISTS subscribers (
192 id TEXT PRIMARY KEY,
193 site_id TEXT NOT NULL,
194 email TEXT NOT NULL,
195 status TEXT NOT NULL DEFAULT 'pending',
196 source TEXT DEFAULT 'widget',
197 token TEXT NOT NULL,
198 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
199 confirmed_at DATETIME,
200 UNIQUE(site_id, email)
201 );
202 CREATE INDEX IF NOT EXISTS idx_subscribers_site_status ON subscribers(site_id, status);
203 `);
204
205 // Sent newsletters (history + counts).
206 db.exec(`
207 CREATE TABLE IF NOT EXISTS newsletters (
208 id TEXT PRIMARY KEY,
209 site_id TEXT NOT NULL,
210 subject TEXT NOT NULL,
211 body TEXT NOT NULL,
212 sent_at DATETIME DEFAULT CURRENT_TIMESTAMP,
213 recipient_count INTEGER DEFAULT 0
214 );
215 `);
216
217 // Show agenda (premium #8): tour dates / gigs per site.
218 db.exec(`
219 CREATE TABLE IF NOT EXISTS shows (
220 id TEXT PRIMARY KEY,
221 site_id TEXT NOT NULL,
222 date TEXT NOT NULL,
223 time TEXT,
224 city TEXT NOT NULL,
225 venue TEXT,
226 country TEXT,
227 ticket_url TEXT,
228 notes TEXT,
229 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
230 );
231 CREATE INDEX IF NOT EXISTS idx_shows_site_date ON shows(site_id, date);
232 `);
233
234 // Link-in-bio click statistics (premium #6). One counter per (site, url); the
235 // link-in-bio page links via /links/go/:i which counts the click and redirects.
236 db.exec(`
237 CREATE TABLE IF NOT EXISTS link_clicks (
238 site_id TEXT NOT NULL,
239 url TEXT NOT NULL,
240 clicks INTEGER DEFAULT 0,
241 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
242 PRIMARY KEY (site_id, url)
243 );
244 `);
245
246
247 // ── ActivityPub (fediverse bridge) ──────────────────────────
248 // RSA keypair per actor (Mastodon-compatible HTTP Signatures; separate from
249 // the Cirkels Ed25519 keys). ap_followers = remote AP actors following us.
250 db.exec(`
251 CREATE TABLE IF NOT EXISTS ap_keys (
252 slug TEXT PRIMARY KEY,
253 public_pem TEXT NOT NULL,
254 private_pem TEXT NOT NULL,
255 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
256 );
257 CREATE TABLE IF NOT EXISTS ap_followers (
258 id INTEGER PRIMARY KEY AUTOINCREMENT,
259 slug TEXT NOT NULL,
260 actor_uri TEXT NOT NULL,
261 inbox TEXT,
262 shared_inbox TEXT,
263 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
264 UNIQUE(slug, actor_uri)
265 );
266 CREATE INDEX IF NOT EXISTS idx_ap_followers_slug ON ap_followers(slug);
267 CREATE TABLE IF NOT EXISTS ap_interactions (
268 id INTEGER PRIMARY KEY AUTOINCREMENT,
269 kind TEXT NOT NULL, -- 'reply' | 'like' | 'announce'
270 post_id TEXT NOT NULL,
271 object_uri TEXT NOT NULL DEFAULT '', -- remote note id (reply) or '' (like/announce)
272 actor_uri TEXT NOT NULL,
273 actor_name TEXT,
274 actor_handle TEXT,
275 actor_url TEXT,
276 actor_icon TEXT,
277 content TEXT, -- sanitized HTML (reply)
278 published TEXT,
279 parent_uri TEXT, -- the note this reply replies to (for nesting)
280 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
281 UNIQUE(kind, post_id, actor_uri, object_uri)
282 );
283 CREATE INDEX IF NOT EXISTS idx_ap_inter_post ON ap_interactions(post_id, kind);
284 -- Moderation tombstones: object URIs the site owner removed. Checked at ingest
285 -- (handleInbox) AND by the thread-crawler, so a removed reply never comes back
286 -- via thread-filling. Private notes can't be flagged via authorize_interaction
287 -- (their fetch 401s), so owner moderation acts on the locally stored copy.
288 CREATE TABLE IF NOT EXISTS ap_rejected_objects (
289 object_uri TEXT PRIMARY KEY,
290 post_id TEXT,
291 reason TEXT,
292 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
293 );
294 -- ActivityPub C2S (client-to-server): OAuth 2.0 for native/web clients (Shaer).
295 -- Public clients + PKCE (RFC 8252); tokens stored hashed; token is per user+site.
296 CREATE TABLE IF NOT EXISTS oauth_clients (
297 client_id TEXT PRIMARY KEY,
298 client_name TEXT,
299 redirect_uris TEXT NOT NULL, -- JSON array
300 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
301 );
302 CREATE TABLE IF NOT EXISTS oauth_codes (
303 code TEXT PRIMARY KEY,
304 client_id TEXT NOT NULL,
305 user_id TEXT NOT NULL,
306 site_slug TEXT NOT NULL,
307 redirect_uri TEXT NOT NULL,
308 code_challenge TEXT, -- PKCE S256 (verplicht voor public clients)
309 scope TEXT,
310 expires_at DATETIME NOT NULL,
311 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
312 );
313 CREATE TABLE IF NOT EXISTS oauth_tokens (
314 token_hash TEXT PRIMARY KEY, -- sha256(bearer); het token zelf slaan we nooit op
315 client_id TEXT NOT NULL,
316 user_id TEXT NOT NULL,
317 site_slug TEXT NOT NULL,
318 scope TEXT,
319 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
320 last_used_at DATETIME
321 );
322 -- Paid posts (klonkt-demo-aki): the site owner's own Patreon campaign.
323 -- Secrets are encrypted at rest (CryptoBox). Never reuses the instance-level
324 -- patreon_* settings, which are Klonkt Premium's separate license flow.
325 CREATE TABLE IF NOT EXISTS paid_patreon (
326 site_id TEXT PRIMARY KEY,
327 client_id TEXT,
328 client_secret_enc TEXT,
329 campaign_id TEXT,
330 access_token_enc TEXT,
331 refresh_token_enc TEXT,
332 token_exp INTEGER, -- unix seconds
333 default_min_cents INTEGER DEFAULT 0,
334 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
335 );
336 -- One row per passkey. NO patron identity is stored (design decision):
337 -- {passkey, site, proven cents, expiry}. Not traceable to a person.
338 CREATE TABLE IF NOT EXISTS paid_entitlements (
339 credential_id TEXT PRIMARY KEY, -- WebAuthn credential id (opaque, base64url)
340 site_id TEXT NOT NULL,
341 public_key TEXT NOT NULL, -- COSE public key, base64url
342 counter INTEGER DEFAULT 0,
343 transports TEXT,
344 min_cents INTEGER DEFAULT 0, -- the amount proven at link time
345 expires_at INTEGER NOT NULL, -- unix seconds; re-link after
346 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
347 );
348 -- Web Push (docs/webpush-design.md): one row per browser/device the owner
349 -- enabled notifications on. Payloads are encrypted to p256dh/auth (RFC 8291).
350 CREATE TABLE IF NOT EXISTS push_subscriptions (
351 endpoint TEXT PRIMARY KEY, -- push-service URL for this device
352 user_id TEXT NOT NULL,
353 p256dh TEXT NOT NULL, -- client public key
354 auth TEXT NOT NULL, -- client auth secret
355 alert_types TEXT, -- JSON {follow,reply,like,boost,dm}
356 ua_label TEXT,
357 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
358 last_ok_at DATETIME
359 );
360 CREATE TABLE IF NOT EXISTS ap_outbox (
361 id TEXT PRIMARY KEY, -- note path segment (uuid) → /ap/notes/<id>
362 site_slug TEXT NOT NULL,
363 post_id TEXT NOT NULL,
364 post_slug TEXT,
365 in_reply_to TEXT, -- remote status uri we reply to
366 to_actor TEXT, -- remote actor uri (mentioned)
367 to_handle TEXT,
368 content TEXT NOT NULL, -- sanitized HTML of our reply
369 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
370 );
371 CREATE INDEX IF NOT EXISTS idx_ap_outbox_post ON ap_outbox(post_id);
372 -- Your like/boost state on a REMOTE post (the interact page), so those become toggles.
373 CREATE TABLE IF NOT EXISTS ap_my_reactions (
374 site_slug TEXT NOT NULL,
375 target_uri TEXT NOT NULL,
376 kind TEXT NOT NULL, -- 'like' | 'boost'
377 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
378 UNIQUE(site_slug, target_uri, kind)
379 );
380 `);
381 ensureColumn('ap_interactions', 'parent_uri', 'TEXT'); // nesting (existing DBs)
382 ensureColumn('ap_interactions', 'acted_boost', 'INTEGER DEFAULT 0'); // owner boosted this comment (🔁) → can undo
383 ensureColumn('ap_interactions', 'acted_like', 'INTEGER DEFAULT 0'); // owner liked this comment (⭐) → can undo
384
385 // Fediverse CLIENT: accounts WE follow (outbound) + the home timeline of their posts.
386 db.exec(`
387 CREATE TABLE IF NOT EXISTS ap_following (
388 id INTEGER PRIMARY KEY AUTOINCREMENT,
389 slug TEXT NOT NULL, -- our site that follows
390 actor_uri TEXT NOT NULL, -- the followed account's actor id
391 handle TEXT, name TEXT, icon TEXT, url TEXT,
392 inbox TEXT, -- their inbox (for Create delivery / Undo)
393 follow_id TEXT, -- the Follow activity id we sent (Accept matching)
394 status TEXT DEFAULT 'pending', -- pending | accepted
395 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
396 UNIQUE(slug, actor_uri)
397 );
398 CREATE TABLE IF NOT EXISTS ap_timeline (
399 id TEXT NOT NULL, -- the remote note's AP id
400 slug TEXT NOT NULL, -- whose home timeline (our site)
401 author_uri TEXT, author_name TEXT, author_handle TEXT, author_icon TEXT, author_url TEXT,
402 content TEXT, url TEXT, published TEXT, media_json TEXT,
403 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
404 UNIQUE(slug, id)
405 );
406 CREATE INDEX IF NOT EXISTS idx_ap_timeline_slug ON ap_timeline(slug, published);
407 CREATE TABLE IF NOT EXISTS ap_blocks (
408 id INTEGER PRIMARY KEY AUTOINCREMENT,
409 slug TEXT NOT NULL, -- our site that set the block
410 target TEXT NOT NULL, -- actor URI (actor block) or domain (domain block)
411 kind TEXT NOT NULL, -- 'actor' | 'domain'
412 label TEXT, -- display (@handle or domain)
413 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
414 UNIQUE(slug, target)
415 );
416 CREATE INDEX IF NOT EXISTS idx_ap_blocks_target ON ap_blocks(target);
417 -- Committed guardian ↔ ward relations, one row per local side. role
418 -- 'ward' = the local slug is a ward of other_uri; 'guardian' = the local
419 -- slug guards other_uri. status is always 'accepted' here now: PENDING
420 -- offers live in ap_guardian_offers below (FEP-633c multi-party handshake).
421 CREATE TABLE IF NOT EXISTS ap_guardianships (
422 id INTEGER PRIMARY KEY AUTOINCREMENT,
423 slug TEXT NOT NULL, -- our local site in this relation (guardianship module)
424 role TEXT NOT NULL, -- 'guardian' (slug guards other) | 'ward' (other guards slug)
425 other_uri TEXT NOT NULL, -- the counterpart actor URI (local or remote)
426 other_handle TEXT, -- cached @user@host for display
427 status TEXT NOT NULL, -- 'offered' (legacy) | 'accepted'
428 offer_id TEXT, -- the Offer activity id (FEP-633c section 3)
429 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
430 UNIQUE(slug, role, other_uri)
431 );
432 CREATE INDEX IF NOT EXISTS idx_ap_guardianships_slug ON ap_guardianships(slug, role, status);
433 -- The multi-party handshake (FEP-633c section 3), one row per offer this
434 -- instance is a party to. Mirrors the Shaer test daemon's Handshake:
435 -- accepts accumulate in ap_guardian_offer_accepts, and the offer commits
436 -- only when the candidate returns the handle after ward + candidate + at
437 -- least one existing guardian have accepted.
438 CREATE TABLE IF NOT EXISTS ap_guardian_offers (
439 offer_id TEXT NOT NULL, -- the Offer activity id (minted by the candidate)
440 slug TEXT NOT NULL, -- the local site tracking this handshake (each party keeps its own copy)
441 ward_uri TEXT NOT NULL, -- the ward-to-be
442 candidate_uri TEXT NOT NULL, -- the guardian-candidate (fixed initiator)
443 existing_guardians TEXT NOT NULL DEFAULT '[]', -- JSON array of the ward's current guardian URIs
444 status TEXT NOT NULL DEFAULT 'pending', -- 'pending' | 'committed' | 'void'
445 handle TEXT, -- the escalation handle returned at commit (section 6)
446 ward_handle TEXT, -- cached @ward@host for display
447 candidate_handle TEXT, -- cached @candidate@host for display
448 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
449 PRIMARY KEY (slug, offer_id)
450 );
451 CREATE INDEX IF NOT EXISTS idx_ap_guardian_offers_slug ON ap_guardian_offers(slug, status);
452 CREATE TABLE IF NOT EXISTS ap_guardian_offer_accepts (
453 offer_id TEXT NOT NULL, -- FK to ap_guardian_offers
454 slug TEXT NOT NULL, -- the local site's copy of the tally
455 party_uri TEXT NOT NULL, -- the party who accepted (ward | candidate | an existing guardian)
456 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
457 PRIMARY KEY (slug, offer_id, party_uri)
458 );
459 CREATE TABLE IF NOT EXISTS ap_delivery (
460 id INTEGER PRIMARY KEY AUTOINCREMENT,
461 slug TEXT NOT NULL, -- our site/actor that signs the delivery
462 inbox TEXT NOT NULL, -- recipient inbox URL
463 body TEXT NOT NULL, -- the activity JSON to POST
464 attempts INTEGER NOT NULL DEFAULT 0,
465 next_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
466 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
467 );
468 CREATE INDEX IF NOT EXISTS idx_ap_delivery_due ON ap_delivery(next_at);
469 CREATE TABLE IF NOT EXISTS poll_votes (
470 id INTEGER PRIMARY KEY AUTOINCREMENT,
471 post_id INTEGER NOT NULL, -- our local poll post (posts.id)
472 actor_uri TEXT NOT NULL, -- the remote voter's AP actor URI
473 choice TEXT NOT NULL, -- the chosen option's name (matches poll_json options[].name)
474 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
475 UNIQUE(post_id, actor_uri, choice)
476 );
477 CREATE INDEX IF NOT EXISTS idx_poll_votes_post ON poll_votes(post_id);
478 CREATE TABLE IF NOT EXISTS ap_mentions (
479 id INTEGER PRIMARY KEY AUTOINCREMENT,
480 slug TEXT NOT NULL, -- our mentioned site/actor
481 object_uri TEXT NOT NULL, -- the remote note that mentions us
482 note_url TEXT, -- its human URL (open/interact)
483 actor_uri TEXT, actor_name TEXT, actor_handle TEXT, actor_icon TEXT, actor_url TEXT,
484 content TEXT, -- sanitized HTML snippet of the mentioning note
485 published TEXT,
486 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
487 UNIQUE(slug, object_uri)
488 );
489 CREATE INDEX IF NOT EXISTS idx_ap_mentions_slug ON ap_mentions(slug, created_at);
490 CREATE TABLE IF NOT EXISTS ap_reports (
491 id INTEGER PRIMARY KEY AUTOINCREMENT,
492 slug TEXT NOT NULL, -- our site the report is about (its owner moderates)
493 actor_uri TEXT, -- the reporter's actor URI
494 actor_name TEXT, actor_handle TEXT, actor_icon TEXT,
495 content TEXT, -- the reason (plain text)
496 objects TEXT, -- JSON array of reported object URIs (our actor + statuses)
497 seen INTEGER DEFAULT 0,
498 created_at DATETIME DEFAULT CURRENT_TIMESTAMP
499 );
500 CREATE INDEX IF NOT EXISTS idx_ap_reports_slug ON ap_reports(slug, created_at);
501 `);
502 // "Feature" a followed account: its posts show in the local Cirkel.
503 ensureColumn('ap_following', 'auto_boost', 'INTEGER DEFAULT 0');
504 // A timeline post you boosted (🔁) — also shown in the Cirkel (mixed by date).
505 ensureColumn('ap_timeline', 'boosted', 'INTEGER DEFAULT 0');
506 ensureColumn('ap_timeline', 'liked', 'INTEGER DEFAULT 0'); // a feed post you liked (⭐) → toggle
507 ensureColumn('ap_timeline', 'nsfw', 'INTEGER DEFAULT 0'); // remote sensitive post → blur in the Cirkel
508 ensureColumn('ap_timeline', 'cw', 'TEXT'); // remote content-warning text
509 ensureColumn('ap_timeline', 'reblog_name', 'TEXT'); // a followed account boosted this → "X boosted"
510 ensureColumn('ap_timeline', 'reblog_handle', 'TEXT'); // the booster's @handle
511 ensureColumn('ap_timeline', 'reblog_icon', 'TEXT'); // the booster's avatar
512 ensureColumn('ap_timeline', 'poll_json', 'TEXT'); // a Question (poll): {multiple,options[{name,count}],endTime,closed,voters,voted}
513
514 // Delivery health per follower → surface dead accounts for manual cleanup.
515 ensureColumn('ap_followers', 'last_delivery_at', 'DATETIME'); // last SUCCESSFUL delivery to this follower's inbox
516 ensureColumn('ap_followers', 'last_error_at', 'DATETIME'); // last time a delivery to it gave up (max retries)
517
518 // ActivityPub `source` model: content_rendered = baked display HTML (#hashtags / URLs /
519 // @mentions linkified once at save). `content` stays the raw source used for editing and
520 // re-rendering. NULL on old posts → the render route bakes on the fly as a fallback.
521 ensureColumn('posts', 'content_rendered', 'TEXT');
522
523 // AP addressing of an incoming interaction: 'public' | 'unlisted' | 'followers' | 'direct',
524 // derived from the note's to/cc at ingest. The public post page only renders public/unlisted
525 // replies; followers/direct replies surface in notifications (and later Messages) with post
526 // context instead. Existing rows default to 'public' (historically almost all were).
527 ensureColumn('ap_interactions', 'visibility', "TEXT DEFAULT 'public'");
528 // Rich replies: the reply's language (BCP47 code) → contentMap on the outgoing Note.
529 ensureColumn('ap_outbox', 'language', 'TEXT');
530 // Rich replies: JSON array [{url, mediaType, name}] → `attachment` on the Note.
531 ensureColumn('ap_outbox', 'attachments', 'TEXT');
532 ensureColumn('posts', 'ap_visibility', 'TEXT'); // public|quiet|friends|direct (C2S addressing, shaer-60b)
533 ensureColumn('posts', 'paid', 'INTEGER DEFAULT 0'); // paid post (klonkt-demo-aki)
534 ensureColumn('posts', 'paid_min_cents', 'INTEGER'); // required support; null = owner default
535 ensureColumn('paid_patreon', 'patreon_url', 'TEXT'); // owner's public Patreon page → "Word supporter" link (klonkt-demo-aki)
536 ensureColumn('ap_outbox', 'visibility', 'TEXT'); // 'direct' = private mention, never Public (shaer-tqc)
537 ensureColumn('ap_outbox', 'to_actors', 'TEXT'); // JSON array of recipient actor URIs for direct notes
538 ensureColumn('ap_outbox', 'help_request', 'INTEGER'); // FEP-633c shaer:helpRequest (ward's call for help)
539 ensureColumn('ap_mentions', 'help_request', 'INTEGER'); // inbound ward call-for-help (Guardian PWA message centre)
540 ensureColumn('ap_followers', 'name', 'TEXT'); // cached display name (shaer-aa3)
541 ensureColumn('ap_followers', 'handle', 'TEXT'); // @user@host
542 ensureColumn('ap_followers', 'icon', 'TEXT'); // avatar URL
543}
544
545function ensureColumn(table, column, definition) {
546 try {
547 db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
548 console.log(`🔧 Added column ${table}.${column}`);
549 } catch (e) {
550 // "duplicate column name" → already there. Anything else, surface it.
551 if (!/duplicate column/i.test(e.message)) {
552 console.error(`❌ ensureColumn(${table}.${column}):`, e.message);
553 }
554 }
555}
556
557export default db;
Note: See TracBrowser for help on using the repository browser.