source: Klonkt/src/config/database.js@ 0a686a0

main
Last change on this file since 0a686a0 was 2b4252c, checked in by Robin <roboburr@…>, 7 weeks ago

Cross-instance follow-goedkeuring, gemodelleerd op de guardian-offer (§5.3)

Guardians die op een andere instance wonen kunnen nu een gated follow goedkeuren.
Zelfde gedistribueerde patroon als de adoptie-offer: de ward forwardt de follow
naar z'n guardians als een Offer(Follow); elke guardian houdt een kopie en ziet
'm in /guardian2; de guardian antwoordt met Accept/Reject naar de ward; de ward
telt quorum (bestaande follows.decide) en stuurt de gewone Accept(Follow) naar de
volger. Lokale guardians blijven zoals ze waren (push + lokale beslissing, geen
forwarding). Alles achter de shaer:followApproval-marker, dus normaal verkeer
onaangeroerd.

Changed files:
src/services/ActivityPubService.js

  • gate: remote guardian krijgt Offer(Follow) (leg 1); lokale guardian push
  • handleFollowApprovalInbox: Offer(Follow) -> review (leg 2), Accept/Reject -> decide+commit (leg 4)
  • sendFollowDecision: guardian stuurt beslissing naar de ward (leg 3)
  • dispatch-tak op shaer:followApproval vóór de handshake-dispatch

src/services/guardianship/follows.js

  • guardian-side review-store (recordReview/getReview/listReviews/removeReview)

src/config/database.js

  • ap_follow_reviews (PK slug,id): de guardian-kopie van een remote-ward-follow

src/routes/guardian2.js

  • follow-requests toont ook reviews (remote); approve op een review = sendFollowDecision

test/follow-gating.test.js

  • review-store test erbij

remarks: npm test 171/171. Spec-clausule §5.3 toegevoegd (forwarding gemodelleerd
op §3). Lokale/co-located flow ongewijzigd.

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

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