source: Klonkt/src/config/database.js@ 5c373b8

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

Guardian 2: follow-goedkeuring (FEP-633c §5.3)

Een Follow op een ward wordt niet meer automatisch geaccepteerd: hij wacht op
goedkeuring van de guardians. Afgebakend zoals de spec: gating geldt ALLEEN voor
ward-actors (die guardians hebben); een gewone site zonder guardians accepteert
als vanouds, geen gedragswijziging. Een gecommitte guardian die zelf volgt wordt
wel meteen geaccepteerd (Barts regel: die heeft geen gate nodig, en zo werkt het
meekijken). Quorum per ward: 'any' (default, één volstaat), 'all' of 'none'; een
enkele reject weigert.

De guardian ziet de verzoeken in /guardian2 (ward en guardian zitten op dezelfde
familie-Klonkt, dus lokaal leesbaar) en tikt Accept/Deny. Bij goedkeuring stuurt
Klonkt de Accept(Follow) en legt de follower vast, zodat bezorging (ook
followers-only) begint. Cross-instance federatie van de goedkeuring is een latere
verfijning (de daemon heeft het patroon).

Changed files:
src/services/ActivityPubService.js

  • inbound Follow: gate voor ward-actors; acceptGatedFollow/rejectGatedFollow

src/config/database.js

  • ap_pending_follows + ap_pending_follow_approvals

src/services/guardianship/index.js

  • follows-module geexporteerd

src/routes/guardian2.js

  • GET /api/follow-requests, POST /api/follow/:id (guardian-gecheckt)

src/views/pages/guardian2.ejs, src/assets/js/guardian2.js

src/services/i18n.js

  • guardian2 follow_title/follow_sub (nl/en/de)

New file:
src/services/guardianship/follows.js

  • de gating-store + quorum-beslissing (any/all), pure en testbaar

test/follow-gating.test.js

  • any/all-quorum en single-reject

remarks: npm test 167/167. v1 /guardian en niet-ward-sites onaangeraakt.

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

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