source: Klonkt/src/config/database.js@ 780a7c6

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

Guardianship Fase 0+1: de echte multi-party handshake (FEP-633c §3)

De eerste versie committeerde na één accept. Nu de spec: geen enkele partij
maakt een voogdij alleen, en een nieuwe guardian erbij kan niet zonder
toestemming van de bestaande. Daemon als blauwdruk, zodat Klonkt en de
test-daemon exact hetzelfde gedragen en de Shaer-clients één contract lezen.

Fase 0 (datamodel): ap_guardian_offers (per lokale partij een kopie van de
handshake, PK slug+offer_id) + ap_guardian_offer_accepts (de accept-tally).
ap_guardianships houdt alleen nog de GECOMMITTE relaties.

Fase 1 (state-machine): offers.js is een getrouwe port van de daemon-Handshake
(accepts over ward+candidate+existing; ready = ward && candidate && (geen
existing OF >=1 existing); een Reject voidt). handshake.js orchestreert het
gedistribueerd: de kandidaat adresseert de Offer aan ward + alle bestaande
guardians (§3.1.1); elke Accept wordt aan alle andere partijen gebroadcast, dus
elke instance-kopie convergeert; zodra een kopie compleet is committeert die
lokaal (ward schrijft shaer:guardians, guardian schrijft z'n ward), met de
kandidaat-inbox als handle (§6). Volgorde-onafhankelijk.

Ook: §1 wederzijdse uitsluiting (een ward is nooit ook guardian in het
actor-doc), de queues vullen nu de echte accept-tally (needsMyAccept/
readyToCommit/acceptedBy/existingGuardians), en de PWA + Berichten beantwoorden
via de C2S Accept/Reject-pijplijn per offer-id. De co-guardian ziet een
mede-voogdij-aanvraag met accepteer/weiger in de PWA.

Changed files:
src/config/database.js

  • tabellen ap_guardian_offers + ap_guardian_offer_accepts

src/services/guardianship/offers.js (NEW)

  • de handshake-state-machine (daemon-port), per-instance in SQLite

src/services/guardianship/relations.js

  • alleen commit-writers + actor-props (§1 uitsluiting)

src/services/guardianship/handshake.js

  • gedistribueerde multi-party C2S/S2S orchestratie

src/services/guardianship/queues.js

  • offers-queue uit de state-machine

src/services/guardianship/index.js

  • exports bijgewerkt

src/services/ActivityPubService.js

  • wire localSlug + fetchActor; inbound-routing naar alle lokale partijen

src/routes/guardian.js

  • dashboard toont offers met tally; POST /guardian/offer (accept/reject)

src/routes/posts.js

  • Berichten toont ward-offers uit de state-machine; accept via offer-id

src/views/pages/messages.ejs, src/assets/js/guardian.js, src/assets/css/guardian.css

  • offer-kaarten per state (mijn aanvraag / mede-voogdij / wachten)

src/services/i18n.js

  • accept/reject/complete/coguard + co-guardian push (nl/en/de)

test/guardianship.test.js

  • multi-party: eerste guardian, co-approval bestaande guardian, reject voidt, ward-mag-niet-guarden, vaste initiator

remarks: Fase 2 (follow-gating), 3 (hasGuardians + Not-a-Teapot), 4 (Undo/
emancipatie) volgen. 164 tests groen.

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

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