source: Klonkt/src/config/database.js@ b300682

main
Last change on this file since b300682 was b300682, checked in by roboburr <roboburr@…>, 3 months ago

Circles v1 — foundation: migration + signed own publication

Steps 1+2 of the Circles federation (3rd tenancy mode alongside solo/hub):

  • DB: circle_links / remote_actors / remote_posts (idempotent in initializeDatabase)
  • SettingsService: tenancy now accepts 'circle'
  • CircleFederation.js: per-instance Ed25519 keypair (app_settings) + actor/outbox builders + sign/verify (SPKI-DER pubkey, signature over raw body)
  • routes/federation.js: GET /.klonkt/actor.json + signed /.klonkt/outbox.json, mounted in server.js before resolveSite
  • docs/cirkels-v1-spec.md: full v1 spec

Still to do: CircleService.sync (pull+verify), Admin UI, /cirkel feed, hardening.
Ed25519 sign/verify round-trip verified in isolation; syntax clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@…>

  • Property mode set to 100644
File size: 6.5 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
20export function initializeDatabase() {
21 const tableExists = db.prepare(`
22 SELECT name FROM sqlite_master WHERE type='table' AND name='users'
23 `).get();
24
25 if (!tableExists) {
26 console.log('🔧 Initializing database schema...');
27 const schemaPath = path.join(__dirname, '..', 'db', 'migrations', '001-init.sql');
28 const schema = fs.readFileSync(schemaPath, 'utf-8');
29 db.exec(schema);
30 console.log('✅ Database initialized with v9-soul schema');
31 }
32
33 // Additive column migrations — safe to run every boot.
34 // SQLite throws if the column already exists; we swallow that.
35 ensureColumn('sites', 'enable_audio_player', 'INTEGER DEFAULT 1');
36 ensureColumn('sites', 'profile_photo', 'TEXT');
37 ensureColumn('audio_tracks', 'cover_url', 'TEXT');
38 ensureColumn('audio_tracks', 'album', 'TEXT');
39 ensureColumn('users', 'reset_token', 'TEXT');
40 ensureColumn('users', 'reset_token_expires', 'DATETIME');
41 // Google OAuth: koppel een Google-account aan een user (login via Google).
42 ensureColumn('users', 'google_sub', 'TEXT');
43 // Read-only/kijk-account: kan alles bekijken maar geen wijzigingen doen.
44 ensureColumn('users', 'readonly', 'INTEGER DEFAULT 0');
45 // Site-level moderation toggle. 'trust' = auto-approve, 'moderate' = pending until reviewed.
46 ensureColumn('sites', 'comments_moderation_mode', "TEXT DEFAULT 'trust'");
47 // Per-site Prutter toggle: when off, DM endpoints/UI are hidden for that site.
48 ensureColumn('sites', 'enable_prutter', 'INTEGER DEFAULT 1');
49
50 // v9 audit additions —————————————————————————————————————————
51 // SEO/social columns the v9 template uses (most live in 001-init.sql already
52 // for fresh DBs but ensureColumn is idempotent for existing DBs).
53 ensureColumn('sites', 'twitter', 'TEXT'); // @handle (with @)
54 ensureColumn('sites', 'schema_type', "TEXT DEFAULT 'Person'"); // Person|Organization
55 ensureColumn('sites', 'publisher_name', 'TEXT');
56 ensureColumn('sites', 'publisher_url', 'TEXT');
57 ensureColumn('sites', 'publisher_logo', 'TEXT');
58 ensureColumn('sites', 'profile_enabled', 'INTEGER DEFAULT 1');
59 ensureColumn('sites', 'profile_name', 'TEXT'); // display name (falls back to title)
60 ensureColumn('sites', 'profile_bio', 'TEXT'); // short bio for header
61 ensureColumn('sites', 'profile_links', 'TEXT'); // JSON array [{platform, url}]
62 ensureColumn('sites', 'feed_view_default', "TEXT DEFAULT 'timeline'"); // timeline | grid
63 ensureColumn('sites', 'feed_view_switch', 'INTEGER DEFAULT 1'); // show switcher
64 ensureColumn('sites', 'show_search', 'INTEGER DEFAULT 1');
65 ensureColumn('sites', 'show_archive_link', 'INTEGER DEFAULT 1');
66
67 // Per-post noindex + type
68 ensureColumn('posts', 'noindex', 'INTEGER DEFAULT 0');
69 ensureColumn('posts', 'type', "TEXT DEFAULT 'post'"); // post | foto | video | audio
70
71 // Playlists (v9 feature) — first-class entity. CREATE IF NOT EXISTS is
72 // idempotent so it's safe to run on every boot regardless of DB age.
73 db.exec(`
74 CREATE TABLE IF NOT EXISTS playlists (
75 id TEXT PRIMARY KEY,
76 site_id TEXT NOT NULL,
77 title TEXT NOT NULL,
78 artist TEXT,
79 year INTEGER,
80 cover_url TEXT,
81 kind TEXT DEFAULT 'album',
82 created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
83 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
84 FOREIGN KEY (site_id) REFERENCES sites(id)
85 );
86 CREATE TABLE IF NOT EXISTS playlist_tracks (
87 playlist_id TEXT NOT NULL,
88 track_id TEXT NOT NULL,
89 position INTEGER NOT NULL DEFAULT 0,
90 PRIMARY KEY (playlist_id, track_id),
91 FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE,
92 FOREIGN KEY (track_id) REFERENCES audio_tracks(id) ON DELETE CASCADE
93 );
94 CREATE INDEX IF NOT EXISTS idx_playlist_tracks_pos
95 ON playlist_tracks(playlist_id, position);
96 `);
97
98 // Globale app-instellingen (key/value singleton). O.a. de tenancy-modus
99 // (solo = één site, hub = bedrijfssite + /user/). Default = solo.
100 db.exec(`
101 CREATE TABLE IF NOT EXISTS app_settings (
102 key TEXT PRIMARY KEY,
103 value TEXT,
104 updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
105 );
106 `);
107 db.prepare("INSERT OR IGNORE INTO app_settings (key, value) VALUES ('tenancy', 'solo')").run();
108
109 // ── Cirkels (federatie) ─────────────────────────────────────
110 // Decentrale, asymmetrische verbindingen tussen solo-instances.
111 db.exec(`
112 CREATE TABLE IF NOT EXISTS circle_links (
113 id TEXT PRIMARY KEY,
114 local_site_id TEXT NOT NULL,
115 remote_url TEXT NOT NULL,
116 remote_actor_id TEXT,
117 label TEXT,
118 status TEXT DEFAULT 'active',
119 added_at DATETIME DEFAULT CURRENT_TIMESTAMP,
120 last_synced DATETIME,
121 last_error TEXT,
122 UNIQUE(local_site_id, remote_url),
123 FOREIGN KEY (local_site_id) REFERENCES sites(id)
124 );
125 CREATE TABLE IF NOT EXISTS remote_actors (
126 id TEXT PRIMARY KEY,
127 url TEXT UNIQUE NOT NULL,
128 name TEXT,
129 summary TEXT,
130 avatar TEXT,
131 public_key TEXT NOT NULL,
132 fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP
133 );
134 CREATE TABLE IF NOT EXISTS remote_posts (
135 id TEXT PRIMARY KEY,
136 actor_id TEXT NOT NULL,
137 published DATETIME,
138 title TEXT,
139 summary TEXT,
140 url TEXT,
141 media_json TEXT,
142 raw_json TEXT,
143 fetched_at DATETIME DEFAULT CURRENT_TIMESTAMP,
144 FOREIGN KEY (actor_id) REFERENCES remote_actors(id)
145 );
146 `);
147}
148
149function ensureColumn(table, column, definition) {
150 try {
151 db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`);
152 console.log(`🔧 Added column ${table}.${column}`);
153 } catch (e) {
154 // "duplicate column name" → already there. Anything else, surface it.
155 if (!/duplicate column/i.test(e.message)) {
156 console.error(`❌ ensureColumn(${table}.${column}):`, e.message);
157 }
158 }
159}
160
161export default db;
Note: See TracBrowser for help on using the repository browser.