Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-2154]): Signal Desktop ingestion (SQLCipher) — Human Activity Tracking Phase 5

Adam Eivy39fbce8db3b5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 03d3420647..34e8ced277 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -74,6 +74,7 @@
- **[issue-2160] WhatsApp import direction inference** — the WhatsApp chat backfill importer now takes an optional "your name in this chat" field. When set, messages from a sender matching that name land as `message.sent` events and everyone else as `message.received` (the same kinds email uses); left blank, messages stay neutral `message` events as before. The preview shows the sent/received split before you commit. Direction isn't part of the dedupe key, so an earlier neutral import isn't double-counted — clear the source's events and re-import to apply the classification.
- **[issue-2160] WhatsApp import optional chat label — hardens the cross-chat dedupe collision** — the WhatsApp chat backfill importer now takes an optional "chat label" field. WhatsApp exports carry no stable chat id (the filename differs between a `WhatsApp Chat - Alice.zip` and the bare `_chat.txt` extracted from it), so the content-hash dedupe key was deliberately un-scoped — which meant two DIFFERENT chats that each contained a same-named sender sending an identical message at the same timestamp granularity could collapse into a single event. Supplying a chat label (e.g. "Family group") now folds that stable, user-supplied scope into the dedupe hash so distinct chats key apart, and the label also becomes the displayed chat title. Left blank, the dedupe key is byte-identical to before, so existing imports and their idempotency are unchanged; use the same label consistently for a given chat across re-imports. (`server/services/whatsappImport.js`, `server/routes/timeline.js`, `client/src/services/apiTimeline.js`, `client/src/components/timeline/WhatsappImportPanel.jsx`)
- **[issue-2153] YouTube watch history** — YouTube killed its watch-history API, so PortOS ingests your viewing two complementary ways, both landing as `media.watch` events on the activity timeline (taste signal for the digital twin). A new **Settings → YouTube** tab scrapes your signed-in `youtube.com/feed/history` page through the managed browser — off by default and opt-in: log into YouTube in the managed browser, run "Check setup" to confirm you're signed in, set a conservative scrape interval (the history page only shows day-bucketed entries, so a few times a day is plenty), and use "Scrape now" to run immediately. Selector failures degrade to a surfaced sync-status error instead of crashing, and all the page selectors live in one place for easy repair. For reliable historical data (and a fallback whenever the scrape breaks), the **Timeline** page gains a **Google Takeout backfill** importer: upload your "YouTube and YouTube Music → history" export (the ZIP or a single `watch-history.json`) and every watch is imported with its exact timestamp. Both paths share a per-video-per-local-day dedupe key, so a Takeout backfill and the live scrape reconcile without double-counting, and re-imports/re-scrapes are always safe. Like the rest of the timeline, watches are machine-local and never federate to your peers. (`server/services/youtubeSync.js`, `server/services/youtubeImport.js`, `server/services/youtubeScheduler.js`, `server/routes/youtube.js`, `client/src/components/settings/YoutubeTab.jsx`, `client/src/components/timeline/YoutubeImportPanel.jsx`)
+- **[issue-2154] Signal Desktop ingestion** — a new **Settings → Signal** tab pulls your Signal Desktop message history into the activity timeline and your Tribe touchpoints, matching conversations to the people you track by phone number (reusing the iMessage phone match). Signal stores its chat database SQLCipher-encrypted with a key wrapped by your macOS Keychain, so PortOS decrypts a temporary **copy** of the database in-process — never touching Signal's live file — using only Node's built-in crypto (no new dependencies): it unwraps the key from the keychain, decrypts the SQLCipher pages, and reads the plaintext copy read-only. Both the legacy plaintext key and the modern keychain-wrapped key (Signal ≥6.2) are supported. It's off by default and opt-in: enable it, set a sync interval, and use "Check setup" to confirm the database and key are reachable (with an actionable message if a keychain prompt or an unsupported Signal version blocks it) or "Sync now" to run immediately. As Signal is the most fragile source — a Signal update can change its key handling or storage format — everything degrades to a clear sync-status error rather than failing hard or retry-looping. Only conversation metadata and a short preview line are stored; full message text stays in Signal's database. Like the rest of the timeline it's machine-local and never federates to your peers, and re-syncs are incremental and idempotent. (`server/lib/signalCrypto.js`, `server/services/signalSync.js`, `server/services/signalScheduler.js`, `server/routes/signal.js`, `client/src/components/settings/SignalTab.jsx`, `client/src/services/apiSignal.js`)
## Privacy Center
diff --git a/client/src/components/settings/SettingsTabsHeader.jsx b/client/src/components/settings/SettingsTabsHeader.jsx
index 314700fbbd..e677854189 100644
--- a/client/src/components/settings/SettingsTabsHeader.jsx
+++ b/client/src/components/settings/SettingsTabsHeader.jsx
@@ -25,6 +25,7 @@ export const TABS = [
{ id: 'providers', label: 'Providers', to: '/ai' },
{ id: 'security', label: 'Security', to: '/settings/security' },
{ id: 'sharing', label: 'Sharing', to: '/settings/sharing' },
+ { id: 'signal', label: 'Signal', to: '/settings/signal' },
{ id: 'spotify', label: 'Spotify', to: '/settings/spotify' },
{ id: 'telegram', label: 'Telegram', to: '/settings/telegram' },
{ id: 'voice', label: 'Voice', to: '/settings/voice' },
diff --git a/client/src/components/settings/SignalTab.jsx b/client/src/components/settings/SignalTab.jsx
new file mode 100644
index 0000000000..2494892d20
--- /dev/null
+++ b/client/src/components/settings/SignalTab.jsx
@@ -0,0 +1,202 @@
+import { useEffect, useState } from 'react';
+import { Save, Loader2, Lock, ShieldCheck, ShieldAlert, RefreshCw } from 'lucide-react';
+import toast from '../ui/Toast';
+import BrailleSpinner from '../BrailleSpinner';
+import {
+ getSettings,
+ updateSettings,
+ getSignalStatus,
+ checkSignalSetup,
+ syncSignal,
+} from '../../services/api';
+
+// Settings → Signal (#2154). Opt-in, machine-local ingestion of Signal Desktop's
+// SQLCipher-encrypted chat database into the Tribe touchpoint log + activity
+// timeline. OFF by default — reading the DB needs Signal's keychain-wrapped key.
+// Highest-fragility source: everything degrades gracefully to an actionable error.
+export function SignalTab() {
+ const [loading, setLoading] = useState(true);
+ const [enabled, setEnabled] = useState(false);
+ const [intervalMinutes, setIntervalMinutes] = useState(60);
+ const [savedEnabled, setSavedEnabled] = useState(false);
+ const [savedInterval, setSavedInterval] = useState(60);
+ const [saving, setSaving] = useState(false);
+
+ const [status, setStatus] = useState(null);
+ const [setup, setSetup] = useState(null);
+ const [checking, setChecking] = useState(false);
+ const [syncing, setSyncing] = useState(false);
+
+ useEffect(() => {
+ Promise.all([
+ getSettings({ silent: true }).catch(() => ({})),
+ getSignalStatus({ silent: true }).catch(() => null),
+ ])
+ .then(([settings, st]) => {
+ const c = settings?.signal || {};
+ const en = typeof c.enabled === 'boolean' ? c.enabled : false;
+ const iv = Number.isFinite(c.intervalMinutes) ? c.intervalMinutes : 60;
+ setEnabled(en);
+ setIntervalMinutes(iv);
+ setSavedEnabled(en);
+ setSavedInterval(iv);
+ setStatus(st);
+ })
+ .finally(() => setLoading(false));
+ }, []);
+
+ const dirty = enabled !== savedEnabled || Number(intervalMinutes) !== Number(savedInterval);
+
+ const handleSave = async () => {
+ const iv = Math.max(1, Math.min(1440, Math.floor(Number(intervalMinutes) || 60)));
+ setSaving(true);
+ const merged = await updateSettings({ signal: { enabled, intervalMinutes: iv } }).catch(() => null);
+ setSaving(false);
+ if (!merged) return;
+ setIntervalMinutes(iv);
+ setSavedEnabled(enabled);
+ setSavedInterval(iv);
+ toast.success('Saved — scheduler applies on next server restart');
+ };
+
+ const handleCheck = async () => {
+ setChecking(true);
+ const report = await checkSignalSetup({ silent: true }).catch(() => ({ ok: false, error: 'Setup check failed' }));
+ setChecking(false);
+ setSetup(report);
+ if (report?.ok) toast.success(`Signal DB reachable — ${report.messageCount ?? 0} message(s)`);
+ else toast.error(report?.error || 'Signal DB not reachable');
+ };
+
+ const handleSyncNow = async () => {
+ setSyncing(true);
+ const result = await syncSignal({ silent: true }).catch(() => ({ ok: false, error: 'Sync failed' }));
+ setSyncing(false);
+ if (result?.ok) {
+ toast.success(`Synced: ${result.recorded} event(s), ${result.touchpointsCreated} touchpoint(s)${result.hasMore ? ' — more history remains, run again' : ''}`);
+ setStatus((prev) => ({ ...(prev || {}), state: { ...(prev?.state || {}), cursorRowid: result.cursorRowid, lastResult: result, lastRunAt: new Date().toISOString() } }));
+ } else {
+ toast.error(result?.error || 'Sync failed');
+ setSetup(result);
+ }
+ };
+
+ if (loading) return <BrailleSpinner />;
+
+ const lastResult = status?.state?.lastResult;
+
+ return (
+ <div className="space-y-6">
+ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">
+ <div className="flex items-center gap-2 mb-2">
+ <Lock size={16} className="text-port-accent" />
+ <h3 className="text-lg font-semibold text-white">Signal Desktop ingestion</h3>
+ </div>
+ <p className="text-sm text-gray-400 mb-4">
+ Reads your local Signal Desktop chat database
+ (<code className="text-gray-300">~/Library/Application Support/Signal</code>) — decrypting its
+ SQLCipher store with the keychain-wrapped key — and feeds both Tribe touchpoints and the activity timeline.
+ Machine-local; nothing federates to peers. Signal never stores an API for this, so PortOS reads a
+ temporary decrypted <strong>copy</strong> and never touches the live database.
+ This is the most fragile source: if a Signal update changes its key or storage format, ingestion
+ degrades to an actionable error rather than failing hard.
+ </p>
+
+ <div className="space-y-3">
+ <label htmlFor="signal-enabled" className="flex items-center gap-2 text-sm text-gray-200 cursor-pointer">
+ <input
+ id="signal-enabled"
+ type="checkbox"
+ checked={enabled}
+ onChange={(e) => setEnabled(e.target.checked)}
+ className="w-4 h-4 accent-port-accent"
+ />
+ Enable scheduled Signal sync
+ </label>
+
+ <div>
+ <label htmlFor="signal-interval" className="block text-xs uppercase tracking-wider text-gray-500 mb-1">
+ Sync interval (minutes)
+ </label>
+ <input
+ id="signal-interval"
+ type="number"
+ min={1}
+ max={1440}
+ value={intervalMinutes}
+ onChange={(e) => setIntervalMinutes(e.target.value)}
+ className="w-32 px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"
+ />
+ </div>
+
+ <div className="flex flex-wrap gap-2 pt-1">
+ <button
+ type="button"
+ onClick={handleSave}
+ disabled={!dirty || saving}
+ className="inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg text-sm transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
+ >
+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}
+ {saving ? 'Saving...' : 'Save'}
+ </button>
+ <button
+ type="button"
+ onClick={handleCheck}
+ disabled={checking}
+ className="inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-bg border border-port-border hover:border-port-accent text-gray-200 rounded-lg text-sm transition-colors disabled:opacity-40"
+ >
+ {checking ? <Loader2 size={14} className="animate-spin" /> : <ShieldCheck size={14} />}
+ Check setup
+ </button>
+ <button
+ type="button"
+ onClick={handleSyncNow}
+ disabled={syncing}
+ className="inline-flex items-center justify-center gap-2 min-h-[40px] px-4 py-2 bg-port-bg border border-port-border hover:border-port-accent text-gray-200 rounded-lg text-sm transition-colors disabled:opacity-40"
+ >
+ {syncing ? <Loader2 size={14} className="animate-spin" /> : <RefreshCw size={14} />}
+ Sync now
+ </button>
+ </div>
+ </div>
+ </div>
+
+ {setup && (
+ <div className={`bg-port-card border rounded-lg p-4 sm:p-6 ${setup.ok ? 'border-port-success/40' : 'border-port-error/40'}`}>
+ <div className="flex items-center gap-2 mb-2">
+ {setup.ok
+ ? <ShieldCheck size={16} className="text-port-success" />
+ : <ShieldAlert size={16} className="text-port-error" />}
+ <h3 className="text-sm font-semibold text-white">{setup.ok ? 'Setup OK' : 'Setup blocked'}</h3>
+ </div>
+ {setup.ok ? (
+ <p className="text-sm text-gray-300">
+ Signal DB reachable — {setup.messageCount ?? 0} message(s){setup.keySource ? ` (key via ${setup.keySource})` : ''}.
+ </p>
+ ) : (
+ <div className="text-sm text-gray-300 space-y-2">
+ <p className="text-port-error">{setup.error}</p>
+ {setup.remediation && <p className="text-gray-400">{setup.remediation}</p>}
+ </div>
+ )}
+ </div>
+ )}
+
+ {(lastResult || status?.state?.cursorRowid > 0) && (
+ <div className="bg-port-card border border-port-border rounded-lg p-4 sm:p-6">
+ <h3 className="text-sm font-semibold text-white mb-2">Last sync</h3>
+ <dl className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-sm">
+ <div><dt className="text-gray-500 text-xs uppercase">Cursor rowid</dt><dd className="text-gray-200">{status?.state?.cursorRowid ?? 0}</dd></div>
+ <div><dt className="text-gray-500 text-xs uppercase">Events recorded</dt><dd className="text-gray-200">{lastResult?.recorded ?? '—'}</dd></div>
+ <div><dt className="text-gray-500 text-xs uppercase">Touchpoints</dt><dd className="text-gray-200">{lastResult?.touchpointsCreated ?? '—'}</dd></div>
+ <div><dt className="text-gray-500 text-xs uppercase">Scanned</dt><dd className="text-gray-200">{lastResult?.scanned ?? '—'}</dd></div>
+ <div><dt className="text-gray-500 text-xs uppercase">Key source</dt><dd className="text-gray-200">{lastResult?.keySource ?? '—'}</dd></div>
+ <div><dt className="text-gray-500 text-xs uppercase">Last run</dt><dd className="text-gray-200">{status?.state?.lastRunAt ? new Date(status.state.lastRunAt).toLocaleString() : '—'}</dd></div>
+ </dl>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export default SignalTab;
diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsx
index 97ff3046c6..de1b72b822 100644
--- a/client/src/pages/Settings.jsx
+++ b/client/src/pages/Settings.jsx
@@ -15,6 +15,7 @@ import { IMessageTab } from '../components/settings/IMessageTab';
import { MortalLoomTab } from '../components/settings/MortalLoomTab';
import { SecurityTab } from '../components/settings/SecurityTab';
import { SharingTab } from '../components/settings/SharingTab';
+import { SignalTab } from '../components/settings/SignalTab';
import { SpotifyTab } from '../components/settings/SpotifyTab';
import { YoutubeTab } from '../components/settings/YoutubeTab';
import { VoiceTab } from '../components/settings/VoiceTab';
@@ -49,6 +50,7 @@ export default function Settings() {
case 'local-llm': return <LocalLlmTab />;
case 'security': return <SecurityTab />;
case 'sharing': return <SharingTab />;
+ case 'signal': return <SignalTab />;
case 'spotify': return <SpotifyTab />;
case 'youtube': return <YoutubeTab />;
case 'voice': return <VoiceTab />;
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 06f7094b56..2e24045306 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -77,6 +77,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiTribe.js` | Tribe people (relationship rings + contacts). |
| `apiCalendar.js` | Calendar events. |
| `apiMessages.js` | Messages / notifications. |
+| `apiSignal.js` | Signal Desktop ingestion status / setup-check / sync. |
| `apiSpotify.js` | Spotify OAuth + listening-history sync. |
| `apiYoutube.js` | YouTube watch-history scrape sync + setup check. |
| `apiPersonalities.js` | Agent personality profiles. |
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 87ed68f51b..dc7ec7841e 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -23,6 +23,7 @@ export * from './apiPersonalities.js';
export * from './apiAccounts.js';
export * from './apiSchedules.js';
export * from './apiMessages.js';
+export * from './apiSignal.js';
export * from './apiSpotify.js';
export * from './apiYoutube.js';
export * from './apiCalendar.js';
diff --git a/client/src/services/apiSignal.js b/client/src/services/apiSignal.js
new file mode 100644
index 0000000000..9257bec51a
--- /dev/null
+++ b/client/src/services/apiSignal.js
@@ -0,0 +1,8 @@
+import { request } from './apiCore.js';
+
+// Signal Desktop ingestion (#2154) — read the SQLCipher-encrypted chat DB (via
+// the keychain-wrapped key) into the Tribe touchpoint log + activity timeline.
+// Machine-local; OFF by default. These wrappers drive the settings tab.
+export const getSignalStatus = (options = {}) => request('/signal/status', options);
+export const checkSignalSetup = (options = {}) => request('/signal/setup-check', options);
+export const syncSignal = (options = {}) => request('/signal/sync', { method: 'POST', ...options });
diff --git a/server/index.js b/server/index.js
index 25bf3cc067..b1c4333529 100644
--- a/server/index.js
+++ b/server/index.js
@@ -49,6 +49,7 @@ import memoryRoutes from './routes/memory.js';
import tribeRoutes from './routes/tribe.js';
import timelineRoutes from './routes/timeline.js';
import imessageRoutes from './routes/imessage.js';
+import signalRoutes from './routes/signal.js';
import spotifyRoutes from './routes/spotify.js';
import youtubeRoutes from './routes/youtube.js';
import notificationsRoutes from './routes/notifications.js';
@@ -172,6 +173,7 @@ import * as cos from './services/cos.js';
import { startBackupScheduler } from './services/backupScheduler.js';
import { startCitySnapshotScheduler } from './services/citySnapshotScheduler.js';
import { startImessageScheduler } from './services/imessageScheduler.js';
+import { startSignalScheduler } from './services/signalScheduler.js';
import { startSpotifyScheduler } from './services/spotifyScheduler.js';
import { startYoutubeScheduler } from './services/youtubeScheduler.js';
import * as telegram from './services/telegram.js';
@@ -482,6 +484,7 @@ app.use('/api/memory', memoryRoutes);
app.use('/api/tribe', tribeRoutes);
app.use('/api/timeline', timelineRoutes);
app.use('/api/imessage', imessageRoutes);
+app.use('/api/signal', signalRoutes);
app.use('/api/spotify', spotifyRoutes);
app.use('/api/youtube', youtubeRoutes);
app.use('/api/notifications', notificationsRoutes);
@@ -615,6 +618,10 @@ startCitySnapshotScheduler().catch(err => console.error(`❌ City snapshot sched
// Initialize iMessage sync scheduler — OFF by default; only polls chat.db when
// the user opts in via Settings → iMessage (needs macOS Full Disk Access) (#2151).
startImessageScheduler().catch(err => console.error(`❌ iMessage sync scheduler init failed: ${err.message}`));
+// Initialize Signal sync scheduler — OFF by default; only reads the SQLCipher
+// chat DB (via the keychain-wrapped key) when the user opts in via
+// Settings → Signal (#2154).
+startSignalScheduler().catch(err => console.error(`❌ Signal sync scheduler init failed: ${err.message}`));
// Initialize Spotify sync scheduler — OFF by default; only polls the
// recently-played API when the user connects Spotify + opts in via
// Settings → Spotify (#2152).
diff --git a/server/lib/README.md b/server/lib/README.md
index fe4d979b5f..eaee830b57 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -236,6 +236,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `pgTools.js` | `pg_dump` binary resolution shared by the backup snapshot path and the native↔Docker export path: `resolvePgDumpBinary(serverMajor)` (PORTOS_PGDUMP override → version-aware auto-select → bare `pg_dump`), plus the lower-level `pickPgDump` / `discoverPgDumpCandidates` / `resolvePgDump`. Picks the closest installed `pg_dump` whose major is ≥ the running server's. |
| `ports.js` | Canonical PORTS object (re-exported from `ecosystem.config.cjs`). |
| `platform.js` | Platform/OS detection helpers — listening-port probes plus `isAppleSilicon()` (arm64 darwin; gates MLX model features, detect at the route boundary). |
+| `signalCrypto.js` | Pure, dependency-free crypto for reading Signal Desktop's encrypted chat DB (#2154): SQLCipher-4 page decryption (`decryptSqlcipherDatabase`, `deriveSqlcipherKeys`, `sqlcipherPageHmac` — PBKDF2-SHA512 HMAC key + AES-256-CBC per page + HMAC-SHA512 verify → plaintext SQLite buffer the built-in `node:sqlite` can open) and Chromium/Electron `safeStorage` unwrap (`decryptSafeStorageValue`, `deriveSafeStorageKey` — macOS AES-128-CBC + PBKDF2-SHA1 over the keychain password). All functions return `{ ok, ... }` reports (never throw) for graceful degradation. Consumed by `services/signalSync.js`. |
| `timezone.js` | Timezone utilities for scheduling. |
| `tribeCadence.js` | Authoritative, pure Tribe care-cadence rules (single source of truth, mirrored to `client/src/lib/tribeCadence.js`): `cadenceStatus(entity)` → `{ state: external/missing/overdue/soon/steady, daysRemaining, daysOverdue }`, `daysSinceDate(dateStr)`, `DEFAULT_CADENCE_DAYS` (45), `SOON_WINDOW_DAYS` (7). Consumed by `personCadenceStatus` / `getCareSummary` in `services/tribe.js` (proactive alert + Care widget) and by the client Tribe page/map. |
| `tribeMatch.js` | Pure, deterministic matcher mapping a calendar attendee / message counterpart (`{ email, phone, name }`) to a tracked Tribe person for auto-logged touchpoints (#2033, #2151): `buildPersonMatchIndex(people)` → `{ byIdentifier, byPhone, byName }`, `matchPerson(identity, index)` (email/handle authoritative, then E.164 phone, then exact unique name fallback — no fuzzy matching), `matchPeople(identities, index)` → de-duplicated Set of personIds, `normalizeIdentifier(value)`, `normalizePhone(value)` (E.164 normalization for iMessage/Signal handles), `identityFromHandle(handle)` (classify a raw `chat.db` handle into email-or-phone). Consumed by `autoLogTouchpoints` in `services/tribe.js` from the calendar, message, and iMessage sync producers. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 40af3b53a1..fa008563a8 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -210,6 +210,7 @@ export * from './pgTimestamp.js';
export * from './pgTools.js';
export * from './platform.js';
export * from './ports.js';
+export * from './signalCrypto.js';
export * from './timezone.js';
export * from './tribeCadence.js';
export * from './tribeMatch.js';
diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.js
index 61ae903147..3dd0ff31a3 100644
--- a/server/lib/mediaValidation.js
+++ b/server/lib/mediaValidation.js
@@ -29,6 +29,16 @@ export const imessageConfigSchema = z.object({
intervalMinutes: z.number().int().min(1).max(1440).optional()
});
+// Signal Desktop ingestion config (#2154) — the `settings.signal` slice. Sync is
+// OFF by default and only reads Signal's SQLCipher-encrypted chat DB (via the
+// keychain-wrapped key) when enabled. Validated as a settings slice on
+// PUT /api/settings; service-side DEFAULT_CONFIG fills any absent field so an
+// install with no `signal` key still resolves (default cadence 60min).
+export const signalConfigSchema = z.object({
+ enabled: z.boolean().optional(),
+ intervalMinutes: z.number().int().min(1).max(1440).optional()
+});
+
// Spotify listening-history ingestion config (#2152) — the `settings.spotify`
// slice. Sync is OFF by default and only polls the recently-played API when
// enabled AND the user has completed OAuth (credentials/tokens live under
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index a3ad2e3b0d..79d006b199 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -186,6 +186,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.settings.mortalloom', path: '/settings/mortalloom', label: 'MortalLoom', section: 'Settings', aliases: ['settings-mortalloom', 'mortalloom'] },
{ id: 'nav.settings.security', path: '/settings/security', label: 'Security', section: 'Settings', aliases: ['settings-security', 'login-password', 'auth-password', 'password-settings'], keywords: ['password', 'login', 'auth', 'sign-in', 'lock', 'tailnet', 'sidecar'] },
{ id: 'nav.settings.sharing', path: '/settings/sharing', label: 'Sharing', section: 'Settings', aliases: ['settings-sharing', 'sharing-settings'], keywords: ['display name', 'bio', 'attribution', 'identity', 'source'] },
+ { id: 'nav.settings.signal', path: '/settings/signal', label: 'Signal', section: 'Settings', aliases: ['settings-signal', 'signal', 'signal-settings'], keywords: ['signal', 'signal desktop', 'messages', 'sqlcipher', 'chat', 'tribe', 'timeline', 'encrypted', 'keychain'] },
{ id: 'nav.settings.spotify', path: '/settings/spotify', label: 'Spotify', section: 'Settings', aliases: ['settings-spotify', 'spotify', 'spotify-settings'], keywords: ['spotify', 'music', 'listening', 'recently played', 'oauth', 'timeline', 'taste', 'media'] },
{ id: 'nav.settings.telegram', path: '/settings/telegram', label: 'Telegram', section: 'Settings', aliases: ['settings-telegram', 'telegram'] },
{ id: 'nav.settings.voice', path: '/settings/voice', label: 'Voice', section: 'Settings', aliases: ['settings-voice', 'voice', 'voice-settings'], keywords: ['mic', 'microphone', 'speech', 'tts', 'whisper', 'kokoro'] },
diff --git a/server/lib/signalCrypto.js b/server/lib/signalCrypto.js
new file mode 100644
index 0000000000..873f7ed7d4
--- /dev/null
+++ b/server/lib/signalCrypto.js
@@ -0,0 +1,231 @@
+/**
+ * Signal Desktop database crypto (#2154) — pure, dependency-free helpers for
+ * reading Signal's local SQLCipher-encrypted chat database.
+ *
+ * Two independent crypto schemes live here, both implemented against Node's
+ * built-in `node:crypto` (zero new dependencies, per the PortOS dependency
+ * policy — see docs/plans/2026-07-04-human-activity-tracking.md):
+ *
+ * 1. **SQLCipher 4 page decryption.** Signal stores its chat DB as a
+ * SQLCipher-4 file (`sql/db.sqlite`). `node:sqlite` cannot open it (no
+ * SQLCipher support), and shelling to a `sqlcipher` CLI would add an
+ * external tool dependency that most machines lack. Instead we decrypt the
+ * file page-by-page here (PBKDF2-SHA512 for the HMAC key + AES-256-CBC per
+ * page + HMAC-SHA512 verification) into a *plaintext* standard SQLite file,
+ * which the built-in `node:sqlite` then opens read-only. This keeps the read
+ * path self-contained and testable.
+ *
+ * 2. **Chromium `safeStorage` decryption.** Signal ≥6.2 no longer stores the DB
+ * key in plaintext; `config.json` carries an `encryptedKey` wrapped by
+ * Electron `safeStorage`, which on macOS is Chromium's `OSCrypt` scheme:
+ * AES-128-CBC with a key = PBKDF2-SHA1(keychainPassword, "saltysalt", 1003)
+ * and a fixed 16-space IV. The keychain read itself is a side effect (see
+ * services/signalSync.js); the pure AES/PBKDF2 math lives here.
+ *
+ * Everything in this file is pure (Buffers in, Buffers/objects out) so the
+ * fragile crypto is unit-tested with round-trip fixtures — no real Signal
+ * install required.
+ */
+import crypto from 'node:crypto';
+
+// ---------------------------------------------------------------------------
+// SQLCipher 4 constants (the defaults Signal Desktop ships with)
+// ---------------------------------------------------------------------------
+
+export const SQLCIPHER_PAGE_SIZE = 4096;
+export const SQLCIPHER_KDF_ITER = 256000; // PBKDF2-HMAC-SHA512 rounds for a passphrase key
+export const SQLCIPHER_FAST_KDF_ITER = 2; // rounds for the derived HMAC key
+export const SQLCIPHER_KEY_BYTES = 32; // AES-256
+export const SQLCIPHER_SALT_BYTES = 16; // leading file salt
+export const SQLCIPHER_IV_BYTES = 16; // per-page CBC IV
+export const SQLCIPHER_HMAC_BYTES = 64; // HMAC-SHA512 output
+export const SQLCIPHER_SALT_MASK = 0x3a; // HMAC salt is the file salt XOR this
+// Reserve = IV + HMAC, already a multiple of the 16-byte AES block so no padding.
+export const SQLCIPHER_RESERVE_BYTES = SQLCIPHER_IV_BYTES + SQLCIPHER_HMAC_BYTES; // 80
+// A standard (plaintext) SQLite file begins with this 16-byte magic. SQLCipher
+// overwrites page 1's first 16 bytes with the salt, so on decrypt we restore it.
+export const SQLITE_HEADER = Buffer.from('SQLite format 3\0', 'latin1');
+
+/**
+ * Return true when `key` is a 64-character hex string — the "raw key" form Signal
+ * stores (SQLCipher uses those 32 bytes directly as the AES key, skipping PBKDF2).
+ */
+export function isRawHexKey(key) {
+ return typeof key === 'string' && /^[0-9a-fA-F]{64}$/.test(key.trim());
+}
+
+/**
+ * Derive the SQLCipher encryption + HMAC keys from key material and the file salt.
+ *
+ * - Raw-key mode (Signal's case): `keyMaterial` is a 64-hex-char string → the
+ * encryption key is those 32 bytes verbatim (no PBKDF2).
+ * - Passphrase mode: `keyMaterial` is any other string/Buffer → encryption key =
+ * PBKDF2-SHA512(passphrase, salt, 256000, 32).
+ *
+ * The HMAC key is ALWAYS PBKDF2-SHA512(encKey, salt XOR 0x3a, 2, 32) — SQLCipher's
+ * "fast" derivation — regardless of mode.
+ */
+export function deriveSqlcipherKeys(keyMaterial, salt) {
+ if (!Buffer.isBuffer(salt) || salt.length !== SQLCIPHER_SALT_BYTES) {
+ throw new Error(`SQLCipher salt must be ${SQLCIPHER_SALT_BYTES} bytes`);
+ }
+ let encKey;
+ if (isRawHexKey(keyMaterial)) {
+ encKey = Buffer.from(keyMaterial.trim(), 'hex');
+ } else {
+ const pass = Buffer.isBuffer(keyMaterial) ? keyMaterial : Buffer.from(String(keyMaterial), 'utf8');
+ encKey = crypto.pbkdf2Sync(pass, salt, SQLCIPHER_KDF_ITER, SQLCIPHER_KEY_BYTES, 'sha512');
+ }
+ const hmacSalt = Buffer.from(salt.map((b) => b ^ SQLCIPHER_SALT_MASK));
+ const hmacKey = crypto.pbkdf2Sync(encKey, hmacSalt, SQLCIPHER_FAST_KDF_ITER, SQLCIPHER_KEY_BYTES, 'sha512');
+ return { encKey, hmacKey };
+}
+
+/**
+ * Compute a SQLCipher page HMAC: HMAC-SHA512(hmacKey, cipherAndIv || pageNoLE32).
+ * `cipherAndIv` is the page's encrypted body concatenated with its 16-byte IV
+ * (exactly the bytes SQLCipher authenticates); the 1-based page number is
+ * appended as a little-endian uint32 (SQLCipher's portable default).
+ */
+export function sqlcipherPageHmac(hmacKey, cipherAndIv, pageNo) {
+ const pgno = Buffer.alloc(4);
+ pgno.writeUInt32LE(pageNo >>> 0, 0);
+ return crypto.createHmac('sha512', hmacKey)
+ .update(cipherAndIv)
+ .update(pgno)
+ .digest();
+}
+
+/**
+ * Decrypt a SQLCipher-4 database buffer to a plaintext standard-SQLite buffer.
+ *
+ * Returns `{ ok: true, plaintext: Buffer }` on success, or
+ * `{ ok: false, error, reason }` on any failure (bad key, unexpected size, HMAC
+ * mismatch) — NEVER throws, so callers surface a graceful "unsupported Signal
+ * version" rather than crashing. `reason` is a machine code:
+ * - `empty` — zero-length input
+ * - `too-small` — smaller than one page
+ * - `bad-page-size` — length isn't a whole number of pages
+ * - `auth` — page-1 HMAC mismatch (wrong key / not SQLCipher-4)
+ *
+ * By default every page's HMAC is verified. Verifying only page 1 is enough to
+ * detect a wrong key, but full verification catches a corrupt/truncated copy too;
+ * pass `{ verify: 'first' }` to check page 1 only for speed on huge DBs.
+ */
+export function decryptSqlcipherDatabase(buffer, keyMaterial, { verify = 'all' } = {}) {
+ if (!buffer || buffer.length === 0) return { ok: false, error: 'Empty database file', reason: 'empty' };
+ const buf = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer);
+ if (buf.length < SQLCIPHER_PAGE_SIZE) return { ok: false, error: 'Database smaller than one page', reason: 'too-small' };
+ if (buf.length % SQLCIPHER_PAGE_SIZE !== 0) {
+ return { ok: false, error: `Database length ${buf.length} is not a whole number of ${SQLCIPHER_PAGE_SIZE}-byte pages`, reason: 'bad-page-size' };
+ }
+
+ const salt = buf.subarray(0, SQLCIPHER_SALT_BYTES);
+ let encKey;
+ let hmacKey;
+ try {
+ ({ encKey, hmacKey } = deriveSqlcipherKeys(keyMaterial, salt));
+ } catch (err) {
+ return { ok: false, error: err?.message || 'Key derivation failed', reason: 'auth' };
+ }
+
+ const totalPages = buf.length / SQLCIPHER_PAGE_SIZE;
+ const out = Buffer.alloc(buf.length);
+ const bodyEndOffset = SQLCIPHER_PAGE_SIZE - SQLCIPHER_RESERVE_BYTES; // where IV starts within a page
+
+ for (let page = 1; page <= totalPages; page += 1) {
+ const pageStart = (page - 1) * SQLCIPHER_PAGE_SIZE;
+ const bodyStart = pageStart + (page === 1 ? SQLCIPHER_SALT_BYTES : 0);
+ const ivStart = pageStart + bodyEndOffset;
+ const ciphertext = buf.subarray(bodyStart, ivStart);
+ const iv = buf.subarray(ivStart, ivStart + SQLCIPHER_IV_BYTES);
+
+ // Verify the page HMAC over ciphertext||IV. Page 1 always; the rest when
+ // verify==='all'. constant-time compare avoids a timing oracle (cheap here).
+ if (page === 1 || verify === 'all') {
+ const stored = buf.subarray(ivStart + SQLCIPHER_IV_BYTES, ivStart + SQLCIPHER_IV_BYTES + SQLCIPHER_HMAC_BYTES);
+ const computed = sqlcipherPageHmac(hmacKey, buf.subarray(bodyStart, ivStart + SQLCIPHER_IV_BYTES), page);
+ if (stored.length !== computed.length || !crypto.timingSafeEqual(stored, computed)) {
+ return {
+ ok: false,
+ error: page === 1
+ ? 'Page-1 HMAC mismatch — wrong key or not a SQLCipher-4 database'
+ : `Page-${page} HMAC mismatch — database copy is corrupt or truncated`,
+ reason: 'auth',
+ };
+ }
+ }
+
+ let plainBody;
+ try {
+ const decipher = crypto.createDecipheriv('aes-256-cbc', encKey, iv);
+ decipher.setAutoPadding(false); // SQLCipher pages are exact block multiples, no PKCS padding
+ plainBody = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
+ } catch (err) {
+ return { ok: false, error: `AES decrypt failed on page ${page}: ${err?.message || err}`, reason: 'auth' };
+ }
+
+ if (page === 1) {
+ // Restore the 16-byte SQLite magic SQLCipher replaced with the salt, then
+ // the decrypted body; the reserve region stays zero (SQLite ignores the
+ // per-page reserved bytes declared in the header byte 20 it just decrypted).
+ SQLITE_HEADER.copy(out, pageStart);
+ plainBody.copy(out, pageStart + SQLCIPHER_SALT_BYTES);
+ } else {
+ plainBody.copy(out, pageStart);
+ }
+ }
+
+ return { ok: true, plaintext: out };
+}
+
+// ---------------------------------------------------------------------------
+// Chromium safeStorage (macOS OSCrypt) — decrypt Signal's wrapped `encryptedKey`
+// ---------------------------------------------------------------------------
+
+export const SAFE_STORAGE_SALT = 'saltysalt';
+export const SAFE_STORAGE_ITER_MACOS = 1003; // Chromium's macOS PBKDF2 rounds
+export const SAFE_STORAGE_KEY_BYTES = 16; // AES-128
+export const SAFE_STORAGE_IV = Buffer.alloc(16, ' '.charCodeAt(0)); // 16 spaces
+
+/**
+ * Derive the AES-128 key Chromium/Electron `safeStorage` uses on macOS from the
+ * "Signal Safe Storage" keychain password: PBKDF2-SHA1(password, "saltysalt",
+ * 1003, 16).
+ */
+export function deriveSafeStorageKey(password) {
+ const pass = Buffer.isBuffer(password) ? password : Buffer.from(String(password), 'utf8');
+ return crypto.pbkdf2Sync(pass, SAFE_STORAGE_SALT, SAFE_STORAGE_ITER_MACOS, SAFE_STORAGE_KEY_BYTES, 'sha1');
+}
+
+/**
+ * Decrypt an Electron `safeStorage` value (Signal's `config.json.encryptedKey`,
+ * stored as hex) given the keychain password. The blob is a 3-byte version tag
+ * (`v10`/`v11`) followed by AES-128-CBC ciphertext with a fixed 16-space IV.
+ *
+ * Returns `{ ok: true, plaintext: Buffer }` (the plaintext is Signal's 64-hex-char
+ * DB key) or `{ ok: false, error, reason }` — never throws. `reason`:
+ * - `empty` — no ciphertext
+ * - `bad-prefix` — missing the `v1x` version tag
+ * - `decrypt` — wrong password / bad padding
+ */
+export function decryptSafeStorageValue(encrypted, password) {
+ if (!encrypted || encrypted.length === 0) return { ok: false, error: 'Empty encryptedKey', reason: 'empty' };
+ const buf = Buffer.isBuffer(encrypted) ? encrypted : Buffer.from(encrypted);
+ const prefix = buf.subarray(0, 3).toString('latin1');
+ if (prefix !== 'v10' && prefix !== 'v11') {
+ return { ok: false, error: `Unrecognized safeStorage version prefix "${prefix}"`, reason: 'bad-prefix' };
+ }
+ const ciphertext = buf.subarray(3);
+ if (ciphertext.length === 0 || ciphertext.length % 16 !== 0) {
+ return { ok: false, error: 'safeStorage ciphertext is empty or not block-aligned', reason: 'decrypt' };
+ }
+ const key = deriveSafeStorageKey(password);
+ try {
+ const decipher = crypto.createDecipheriv('aes-128-cbc', key, SAFE_STORAGE_IV);
+ const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
+ return { ok: true, plaintext };
+ } catch (err) {
+ return { ok: false, error: `safeStorage decrypt failed (wrong keychain password?): ${err?.message || err}`, reason: 'decrypt' };
+ }
+}
diff --git a/server/lib/signalCrypto.test.js b/server/lib/signalCrypto.test.js
new file mode 100644
index 0000000000..6e189db29d
--- /dev/null
+++ b/server/lib/signalCrypto.test.js
@@ -0,0 +1,171 @@
+import { describe, it, expect } from 'vitest';
+import crypto from 'node:crypto';
+import {
+ isRawHexKey,
+ deriveSqlcipherKeys,
+ sqlcipherPageHmac,
+ decryptSqlcipherDatabase,
+ deriveSafeStorageKey,
+ decryptSafeStorageValue,
+ SQLCIPHER_PAGE_SIZE,
+ SQLCIPHER_SALT_BYTES,
+ SQLCIPHER_RESERVE_BYTES,
+ SQLCIPHER_IV_BYTES,
+ SQLITE_HEADER,
+ SAFE_STORAGE_IV,
+} from './signalCrypto.js';
+
+// Re-implement SQLCipher-4 *encryption* here so the decryptor can be verified
+// against a known-good round trip — no real Signal DB required. This mirrors the
+// exact page layout decryptSqlcipherDatabase expects.
+function encryptSqlcipherDatabase(plaintext, rawKeyHex, salt) {
+ const { encKey, hmacKey } = deriveSqlcipherKeys(rawKeyHex, salt);
+ const totalPages = plaintext.length / SQLCIPHER_PAGE_SIZE;
+ const out = Buffer.alloc(plaintext.length);
+ const bodyEndOffset = SQLCIPHER_PAGE_SIZE - SQLCIPHER_RESERVE_BYTES;
+ for (let page = 1; page <= totalPages; page += 1) {
+ const pageStart = (page - 1) * SQLCIPHER_PAGE_SIZE;
+ const bodyStart = pageStart + (page === 1 ? SQLCIPHER_SALT_BYTES : 0);
+ const body = plaintext.subarray(bodyStart, pageStart + bodyEndOffset);
+ const iv = crypto.randomBytes(SQLCIPHER_IV_BYTES);
+ const cipher = crypto.createCipheriv('aes-256-cbc', encKey, iv);
+ cipher.setAutoPadding(false);
+ const ciphertext = Buffer.concat([cipher.update(body), cipher.final()]);
+ if (page === 1) salt.copy(out, pageStart);
+ ciphertext.copy(out, bodyStart);
+ iv.copy(out, pageStart + bodyEndOffset);
+ const hmac = sqlcipherPageHmac(hmacKey, Buffer.concat([ciphertext, iv]), page);
+ hmac.copy(out, pageStart + bodyEndOffset + SQLCIPHER_IV_BYTES);
+ }
+ return out;
+}
+
+// A plaintext "database" whose reserve regions are already zero and whose page 1
+// begins with the SQLite magic — so a decrypt round trip is byte-identical (the
+// decryptor restores the magic + zero-fills the reserve).
+function makePlaintextDb(pages) {
+ const buf = Buffer.alloc(pages * SQLCIPHER_PAGE_SIZE);
+ const bodyEndOffset = SQLCIPHER_PAGE_SIZE - SQLCIPHER_RESERVE_BYTES;
+ for (let page = 1; page <= pages; page += 1) {
+ const pageStart = (page - 1) * SQLCIPHER_PAGE_SIZE;
+ const bodyStart = pageStart + (page === 1 ? SQLCIPHER_SALT_BYTES : 0);
+ // Deterministic body content so the assertion is meaningful.
+ for (let i = bodyStart; i < pageStart + bodyEndOffset; i += 1) buf[i] = (i * 31 + 7) & 0xff;
+ if (page === 1) SQLITE_HEADER.copy(buf, pageStart);
+ }
+ return buf;
+}
+
+describe('signalCrypto — SQLCipher key derivation', () => {
+ it('detects a 64-hex-char raw key', () => {
+ expect(isRawHexKey('a'.repeat(64))).toBe(true);
+ expect(isRawHexKey('A0'.repeat(32))).toBe(true);
+ expect(isRawHexKey('xyz')).toBe(false);
+ expect(isRawHexKey('a'.repeat(63))).toBe(false);
+ expect(isRawHexKey(null)).toBe(false);
+ });
+
+ it('uses the raw 32 bytes verbatim as the encryption key (no PBKDF2)', () => {
+ const hex = '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff';
+ const salt = Buffer.alloc(16, 5);
+ const { encKey } = deriveSqlcipherKeys(hex, salt);
+ expect(encKey.toString('hex')).toBe(hex);
+ });
+
+ it('derives a distinct HMAC key via the fast 2-round PBKDF2 over the salt XOR 0x3a', () => {
+ const hex = 'a'.repeat(64);
+ const salt = Buffer.alloc(16, 9);
+ const { encKey, hmacKey } = deriveSqlcipherKeys(hex, salt);
+ const hmacSalt = Buffer.from(salt.map((b) => b ^ 0x3a));
+ const expected = crypto.pbkdf2Sync(encKey, hmacSalt, 2, 32, 'sha512');
+ expect(hmacKey.equals(expected)).toBe(true);
+ expect(hmacKey.equals(encKey)).toBe(false);
+ });
+
+ it('rejects a wrong-length salt', () => {
+ expect(() => deriveSqlcipherKeys('a'.repeat(64), Buffer.alloc(8))).toThrow();
+ });
+});
+
+describe('signalCrypto — SQLCipher page decryption', () => {
+ const rawKeyHex = crypto.randomBytes(32).toString('hex');
+
+ it('round-trips a multi-page database to plaintext', () => {
+ const salt = crypto.randomBytes(16);
+ const plain = makePlaintextDb(3);
+ const encrypted = encryptSqlcipherDatabase(plain, rawKeyHex, salt);
+ // The encrypted page 1 leads with the salt, NOT the SQLite magic.
+ expect(encrypted.subarray(0, 16).equals(salt)).toBe(true);
+ const result = decryptSqlcipherDatabase(encrypted, rawKeyHex);
+ expect(result.ok).toBe(true);
+ expect(result.plaintext.subarray(0, 16).equals(SQLITE_HEADER)).toBe(true);
+ expect(result.plaintext.equals(plain)).toBe(true);
+ });
+
+ it('fails cleanly (reason=auth) on the wrong key — never throws', () => {
+ const salt = crypto.randomBytes(16);
+ const encrypted = encryptSqlcipherDatabase(makePlaintextDb(1), rawKeyHex, salt);
+ const wrong = crypto.randomBytes(32).toString('hex');
+ const result = decryptSqlcipherDatabase(encrypted, wrong);
+ expect(result.ok).toBe(false);
+ expect(result.reason).toBe('auth');
+ });
+
+ it('reports empty / too-small / bad-page-size without throwing', () => {
+ expect(decryptSqlcipherDatabase(Buffer.alloc(0), rawKeyHex).reason).toBe('empty');
+ expect(decryptSqlcipherDatabase(Buffer.alloc(100), rawKeyHex).reason).toBe('too-small');
+ expect(decryptSqlcipherDatabase(Buffer.alloc(SQLCIPHER_PAGE_SIZE + 10), rawKeyHex).reason).toBe('bad-page-size');
+ });
+
+ it('detects a corrupted (bit-flipped) page via HMAC in full-verify mode', () => {
+ const salt = crypto.randomBytes(16);
+ const encrypted = encryptSqlcipherDatabase(makePlaintextDb(2), rawKeyHex, salt);
+ encrypted[SQLCIPHER_PAGE_SIZE + 20] ^= 0xff; // corrupt page 2 body
+ const result = decryptSqlcipherDatabase(encrypted, rawKeyHex, { verify: 'all' });
+ expect(result.ok).toBe(false);
+ expect(result.reason).toBe('auth');
+ });
+});
+
+describe('signalCrypto — Chromium safeStorage decryption', () => {
+ const password = 'a-random-keychain-password';
+
+ function encryptSafeStorage(plaintextStr, prefix = 'v10') {
+ const key = deriveSafeStorageKey(password);
+ const cipher = crypto.createCipheriv('aes-128-cbc', key, SAFE_STORAGE_IV);
+ const body = Buffer.concat([cipher.update(Buffer.from(plaintextStr, 'utf8')), cipher.final()]);
+ return Buffer.concat([Buffer.from(prefix, 'latin1'), body]);
+ }
+
+ it('recovers the wrapped DB key string (v10)', () => {
+ const dbKey = crypto.randomBytes(32).toString('hex');
+ const blob = encryptSafeStorage(dbKey);
+ const result = decryptSafeStorageValue(blob, password);
+ expect(result.ok).toBe(true);
+ expect(result.plaintext.toString('utf8')).toBe(dbKey);
+ });
+
+ it('recovers a v11-prefixed value too', () => {
+ const blob = encryptSafeStorage('hello-signal', 'v11');
+ const result = decryptSafeStorageValue(blob, password);
+ expect(result.ok).toBe(true);
+ expect(result.plaintext.toString('utf8')).toBe('hello-signal');
+ });
+
+ it('fails cleanly on a missing version prefix', () => {
+ const result = decryptSafeStorageValue(Buffer.from('nope-not-versioned-aaaa'), password);
+ expect(result.ok).toBe(false);
+ expect(result.reason).toBe('bad-prefix');
+ });
+
+ it('fails cleanly (reason=decrypt) on the wrong password — never throws', () => {
+ const blob = encryptSafeStorage('secret');
+ const result = decryptSafeStorageValue(blob, 'wrong-password');
+ expect(result.ok).toBe(false);
+ expect(result.reason).toBe('decrypt');
+ });
+
+ it('reports an empty value', () => {
+ expect(decryptSafeStorageValue(Buffer.alloc(0), password).reason).toBe('empty');
+ });
+});
diff --git a/server/routes/settings.js b/server/routes/settings.js
index a45e5c407e..dfa2504e65 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -10,7 +10,7 @@ import {
} from '../services/mediaJobQueue/index.js';
import { asyncHandler } from '../lib/errorHandler.js';
import { isPlainObject } from '../lib/objects.js';
-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, validateRequest } from '../lib/validation.js';
+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, validateRequest } from '../lib/validation.js';
const router = Router();
@@ -158,6 +158,11 @@ router.put('/', asyncHandler(async (req, res) => {
if (req.body?.imessage !== undefined) {
validateRequest(imessageConfigSchema.partial(), req.body.imessage);
}
+ // Signal ingestion config (#2154) — validate the slice when present so a
+ // malformed enabled/interval can't reach disk and break the sync scheduler.
+ if (req.body?.signal !== undefined) {
+ validateRequest(signalConfigSchema.partial(), req.body.signal);
+ }
// Spotify ingestion config (#2152) — validate the slice when present so a
// malformed enabled/interval can't reach disk and break the sync scheduler.
if (req.body?.spotify !== undefined) {
diff --git a/server/routes/signal.js b/server/routes/signal.js
new file mode 100644
index 0000000000..1216fa42e7
--- /dev/null
+++ b/server/routes/signal.js
@@ -0,0 +1,31 @@
+import { Router } from 'express';
+
+import { asyncHandler } from '../lib/errorHandler.js';
+import * as signalSync from '../services/signalSync.js';
+
+const router = Router();
+
+// Setup check — resolve the DB key, decrypt a snapshot, and probe the schema.
+// Reports an actionable error (missing install, key failure, unsupported schema)
+// when blocked. Never throws (checkSetup returns a report), so a keychain denial
+// or an unsupported Signal version surfaces as a clean JSON error the UI renders.
+router.get('/setup-check', asyncHandler(async (req, res) => {
+ const report = await signalSync.checkSetup();
+ res.json(report);
+}));
+
+// Status — current config (enabled/interval) + machine-local cursor state. No DB
+// open / key read, so this is cheap and safe to poll from the settings tab.
+router.get('/status', asyncHandler(async (req, res) => {
+ const status = await signalSync.getStatus();
+ res.json(status);
+}));
+
+// Run one incremental sync pass now (explicit user action). Returns the pass
+// summary, or an actionable error report when the key/DB can't be read.
+router.post('/sync', asyncHandler(async (req, res) => {
+ const result = await signalSync.runSync();
+ res.json(result);
+}));
+
+export default router;
diff --git a/server/services/signalScheduler.js b/server/services/signalScheduler.js
new file mode 100644
index 0000000000..3ab93dec5f
--- /dev/null
+++ b/server/services/signalScheduler.js
@@ -0,0 +1,55 @@
+/**
+ * Signal Desktop Sync Scheduler (#2154)
+ *
+ * Registers an interval job that periodically runs the incremental Signal
+ * ingestion (see signalSync.js). Mirrors the imessageScheduler pattern.
+ *
+ * OFF by default: the scheduler is only registered when the user has opted in via
+ * Settings → Signal (`settings.signal.enabled`). Reading the SQLCipher DB needs
+ * the keychain-wrapped key + a DB snapshot, so we never poll it silently. The
+ * interval value is locked in at registration (changing it needs a restart), but
+ * the `enabled` toggle is re-read on every tick so disabling from settings stops
+ * runs without a restart.
+ *
+ * No LLM calls happen on this path — ingestion is deterministic — so the
+ * no-cold-bootstrap AI policy does not gate it; the opt-in is purely about
+ * key/DB access + user intent.
+ */
+
+import { schedule } from './eventScheduler.js';
+import { getSignalConfig, runSync } from './signalSync.js';
+
+const EVENT_ID = 'signal-sync';
+
+/**
+ * Start the Signal sync scheduler. No-ops when disabled in settings.
+ */
+export async function startSignalScheduler() {
+ const { enabled, intervalMinutes } = await getSignalConfig();
+
+ if (!enabled) {
+ console.log('🔒 Signal sync scheduler: disabled in settings — skipping');
+ return;
+ }
+
+ const intervalMs = intervalMinutes * 60 * 1000;
+
+ schedule({
+ id: EVENT_ID,
+ type: 'interval',
+ intervalMs,
+ handler: async () => {
+ // Re-read settings each run so an `enabled: false` toggle takes effect
+ // without a restart (the interval value itself is locked at registration).
+ const current = await getSignalConfig();
+ if (!current.enabled) {
+ console.log('🔒 Signal sync scheduler: disabled since registration — skipping run');
+ return;
+ }
+ await runSync();
+ },
+ metadata: { source: 'signalScheduler' },
+ });
+
+ console.log(`🔒 Signal sync scheduler: registered every ${intervalMinutes}min`);
+}
diff --git a/server/services/signalSync.js b/server/services/signalSync.js
new file mode 100644
index 0000000000..a3a5d89631
--- /dev/null
+++ b/server/services/signalSync.js
@@ -0,0 +1,537 @@
+/**
+ * Signal Desktop ingestion (#2154) — read the local Signal Desktop chat database
+ * and feed both the Tribe touchpoint log and the machine-local human-activity
+ * timeline (#2150), reusing the iMessage phone-matching path (#2151).
+ *
+ * Signal is the **highest-fragility source** in the activity-tracking design: its
+ * chat DB is SQLCipher-encrypted and the key handling changes across Signal
+ * versions. Everything here is built for **graceful degradation** — an unknown
+ * schema, a missing key, or a failed decryption surfaces an actionable sync-status
+ * error and NEVER crashes or retry-loops.
+ *
+ * Design constraints (docs/plans/2026-07-04-human-activity-tracking.md):
+ *
+ * - **Zero new dependencies.** The SQLCipher-4 page decryption + Chromium
+ * safeStorage key-unwrap are implemented in pure `node:crypto`
+ * (`server/lib/signalCrypto.js`) — `node:sqlite` cannot open a SQLCipher file
+ * and shelling to a `sqlcipher` CLI would add a tool most machines lack. We
+ * decrypt to a plaintext temp copy, then read THAT with the built-in
+ * `node:sqlite` (readOnly). The macOS keychain read shells to the system
+ * `security` CLI (no dependency).
+ * - **Never touch Signal's live file.** The DB is copied to a temp snapshot before
+ * decryption; the original `db.sqlite` is opened only for the `cp`.
+ * - **Machine-local.** The incremental cursor lives in a `data/` JSON file — the DB
+ * and its rowids are per-machine. Derived events land in the already-machine-local
+ * `human_activity_events` table (excluded from peer sync).
+ * - **LLM-free + idempotent.** Deterministic identity matching via `tribeMatch`;
+ * every event/touchpoint carries a stable dedupe key (`signal:<messageId>`) so
+ * re-syncs are no-ops.
+ * - **Off by default.** Enabled only from Settings → Signal — reading the chat DB
+ * and the keychain entry needs user intent.
+ *
+ * The pure mappers (instant conversion, candidate mapping) are exported and
+ * unit-tested with fixtures — no real Signal DB required.
+ */
+import { DatabaseSync } from 'node:sqlite';
+import { promisify } from 'node:util';
+import { execFile } from 'node:child_process';
+import { copyFile, mkdtemp, writeFile, rm } from 'node:fs/promises';
+import { statSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { expandHome, dataPath, atomicWrite, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';
+import { getUserTimezone } from '../lib/timezone.js';
+import { identityFromHandle } from '../lib/tribeMatch.js';
+import { decryptSqlcipherDatabase, decryptSafeStorageValue, isRawHexKey } from '../lib/signalCrypto.js';
+import { shortSummary, localDayKey } from './humanActivity.js';
+import { getSettings } from './settings.js';
+
+const execFileAsync = promisify(execFile);
+
+// ---------------------------------------------------------------------------
+// Constants
+// ---------------------------------------------------------------------------
+
+// Default Signal Desktop locations on macOS. Overridable via env for tests /
+// non-default layouts. `expandHome` resolves the leading `~/`.
+const DEFAULT_SIGNAL_DIR = '~/Library/Application Support/Signal';
+const CONFIG_REL = 'config.json';
+const DB_REL = 'sql/db.sqlite';
+
+// macOS keychain generic-password entry Electron safeStorage writes for Signal:
+// service "<appName> Safe Storage", account "<appName>".
+const KEYCHAIN_SERVICE = 'Signal Safe Storage';
+const KEYCHAIN_ACCOUNT = 'Signal';
+
+const STATE_FILE = 'signal-sync-state.json';
+
+// Config defaults — surfaced via getSignalConfig(). Sync is OFF by default; the
+// user opts in from Settings → Signal.
+const DEFAULT_CONFIG = {
+ enabled: false,
+ intervalMinutes: 60,
+};
+
+// How many messages to pull per sync pass. Bounds memory + keeps a first sync on
+// a huge history from blocking; the rowid cursor means the next pass resumes.
+const SCAN_LIMIT = 5000;
+
+// ---------------------------------------------------------------------------
+// Path helpers
+// ---------------------------------------------------------------------------
+
+function signalDir() {
+ return expandHome(process.env.SIGNAL_DIR || DEFAULT_SIGNAL_DIR);
+}
+function configPath() {
+ return process.env.SIGNAL_CONFIG_PATH || join(signalDir(), CONFIG_REL);
+}
+function dbPath() {
+ return process.env.SIGNAL_DB_PATH || join(signalDir(), DB_REL);
+}
+
+// ---------------------------------------------------------------------------
+// Pure mappers (exported for unit tests — no DB, no filesystem, no side effects)
+// ---------------------------------------------------------------------------
+
+/**
+ * Convert a Signal millisecond-epoch timestamp (`sent_at` / `received_at`) to a
+ * JS Date, or `null` when unusable. Signal stores whole milliseconds since the
+ * Unix epoch, so no Apple-epoch offset math is needed (unlike iMessage).
+ */
+export function signalTimestampToDate(value) {
+ if (value == null) return null;
+ const n = typeof value === 'bigint' ? Number(value) : Number(value);
+ if (!Number.isFinite(n) || n <= 0) return null;
+ const d = new Date(n);
+ return Number.isNaN(d.getTime()) ? null : d;
+}
+
+/**
+ * Map a Signal message record to a `type` we ingest, or `null` to skip. Only
+ * real person-to-person messages become activity — Signal's `messages.type`
+ * also carries `call-history`, `group-v2-change`, `verified-change`, etc.
+ */
+export function signalActivityKind(type, isFromMe) {
+ if (type === 'outgoing') return 'message.sent';
+ if (type === 'incoming') return 'message.received';
+ // Some rows omit `type` but set an explicit direction — fall back to that.
+ if (!type && typeof isFromMe === 'boolean') return isFromMe ? 'message.sent' : 'message.received';
+ return null;
+}
+
+/**
+ * Map one normalized Signal message record to a human-activity candidate, or
+ * `null`. `msg`: { messageId, rowid, at: Date, text, type, isFromMe,
+ * conversationId, conversationName, handles: string[] (e164s) }.
+ * Dedupe key is `signal:<messageId>` (one activity event per message).
+ */
+export function signalActivityCandidate(msg) {
+ if (!msg?.messageId || !(msg.at instanceof Date) || Number.isNaN(msg.at.getTime())) return null;
+ const kind = signalActivityKind(msg.type, msg.isFromMe);
+ if (!kind) return null;
+ const isFromMe = kind === 'message.sent';
+ const participants = (msg.handles || [])
+ .map(identityFromHandle)
+ .filter((p) => p && (p.email || p.phone));
+ const counterpart = isFromMe ? '' : (msg.handles?.[0] || '');
+ return {
+ source: 'signal',
+ accountId: null,
+ kind,
+ happenedAt: msg.at.toISOString(),
+ title: msg.conversationName || counterpart || 'Signal',
+ summary: shortSummary(msg.text || ''),
+ participants,
+ dedupeKey: `signal:${msg.messageId}`,
+ metadata: {
+ conversationId: msg.conversationId || null,
+ handle: counterpart || null,
+ rowid: msg.rowid ?? null,
+ },
+ };
+}
+
+export function signalActivityCandidates(messages = []) {
+ return (messages || []).map(signalActivityCandidate).filter(Boolean);
+}
+
+/**
+ * Group message records into Tribe touchpoint candidates — one per (conversation,
+ * local day) so a busy thread logs a single daily touchpoint per matched person.
+ * Mirrors `imessageTouchpointCandidates`. Dedupe key is
+ * `signal:<conversationId>:<localDay>` (mirrors the `imsg:`/`msg:` convention).
+ */
+export function signalTouchpointCandidates(messages = [], timezone) {
+ const byKey = new Map();
+ for (const msg of messages || []) {
+ if (!(msg?.at instanceof Date) || Number.isNaN(msg.at.getTime())) continue;
+ if (!msg.conversationId) continue;
+ const day = localDayKey(msg.at, timezone);
+ if (!day) continue;
+ const key = `${msg.conversationId}\u0000${day}`;
+ let entry = byKey.get(key);
+ if (!entry) {
+ entry = { conversationId: msg.conversationId, day, at: msg.at, name: msg.conversationName || '', handles: new Set() };
+ byKey.set(key, entry);
+ }
+ for (const h of msg.handles || []) if (h) entry.handles.add(h);
+ if (msg.at > entry.at) entry.at = msg.at;
+ }
+ const out = [];
+ for (const entry of byKey.values()) {
+ const identities = [...entry.handles]
+ .map(identityFromHandle)
+ .filter((p) => p && (p.email || p.phone));
+ if (identities.length === 0) continue;
+ out.push({
+ identities,
+ source: 'signal',
+ happenedAt: entry.at.toISOString(),
+ channel: 'Signal',
+ summary: entry.name || 'Signal conversation',
+ dedupeKey: `signal:${entry.conversationId}:${entry.day}`,
+ metadata: { conversationId: entry.conversationId, day: entry.day },
+ });
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Config + machine-local cursor state
+// ---------------------------------------------------------------------------
+
+export async function getSignalConfig() {
+ const settings = await getSettings().catch(() => ({}));
+ const c = settings?.signal || {};
+ return {
+ enabled: typeof c.enabled === 'boolean' ? c.enabled : DEFAULT_CONFIG.enabled,
+ intervalMinutes: Number.isFinite(c.intervalMinutes) && c.intervalMinutes >= 1
+ ? Math.floor(c.intervalMinutes)
+ : DEFAULT_CONFIG.intervalMinutes,
+ };
+}
+
+function stateFilePath() {
+ return dataPath(STATE_FILE);
+}
+
+// Machine-local incremental cursor. NOT federated — the Signal DB and its rowids
+// are per-machine, so this state must never sync to a peer.
+export async function readSyncState() {
+ const raw = await tryReadFile(stateFilePath());
+ const parsed = raw ? safeJSONParse(raw, null, { allowArray: false }) : null;
+ return {
+ cursorRowid: Number.isFinite(parsed?.cursorRowid) ? parsed.cursorRowid : 0,
+ lastRunAt: parsed?.lastRunAt || null,
+ lastResult: parsed?.lastResult || null,
+ };
+}
+
+async function writeSyncState(state) {
+ await atomicWrite(stateFilePath(), JSON.stringify(state, null, 2));
+}
+
+// ---------------------------------------------------------------------------
+// Key retrieval (side-effecting: reads config.json + shells to the keychain).
+// Runs outside the request lifecycle, so try/catch is sanctioned — a native
+// error must not crash the process; we return a structured report instead.
+// ---------------------------------------------------------------------------
+
+// Read the "Signal Safe Storage" keychain password via the system `security`
+// CLI (execFile — no shell, no injection surface). Returns the password string
+// or throws (caller maps to a graceful report).
+async function readKeychainPassword() {
+ if (process.env.SIGNAL_KEYCHAIN_PASSWORD) return process.env.SIGNAL_KEYCHAIN_PASSWORD; // test hook
+ const { stdout } = await execFileAsync('security', [
+ 'find-generic-password', '-w', '-s', KEYCHAIN_SERVICE, '-a', KEYCHAIN_ACCOUNT,
+ ], { timeout: 15000 });
+ const pw = String(stdout || '').replace(/\n$/, '');
+ if (!pw) throw new Error('Keychain returned an empty Signal Safe Storage password');
+ return pw;
+}
+
+/**
+ * Resolve the SQLCipher DB key (64-hex-char string) from Signal's config.json.
+ * Handles both the legacy plaintext `key` and the modern safeStorage-wrapped
+ * `encryptedKey` (Signal ≥6.2). Returns `{ ok, key }` or `{ ok:false, error,
+ * remediation }` — never throws.
+ */
+export async function resolveDbKey() {
+ const cfgPath = configPath();
+ const raw = await tryReadFile(cfgPath);
+ if (raw == null) {
+ return {
+ ok: false,
+ error: `Signal config not found at ${cfgPath}`,
+ remediation: 'Signal Desktop does not appear to be installed for this user (no config.json).',
+ };
+ }
+ const cfg = safeJSONParse(raw, null, { allowArray: false });
+ if (!cfg || typeof cfg !== 'object') {
+ return { ok: false, error: `Could not parse ${cfgPath}`, remediation: 'Signal config.json is malformed.' };
+ }
+
+ // Legacy plaintext key.
+ if (typeof cfg.key === 'string' && cfg.key.trim()) {
+ const key = cfg.key.trim();
+ if (!isRawHexKey(key)) {
+ return { ok: false, error: 'Signal config.json `key` is not a 64-hex-char SQLCipher key', remediation: 'Unrecognized Signal key format — this Signal version is not yet supported.' };
+ }
+ return { ok: true, key, source: 'plaintext' };
+ }
+
+ // Modern safeStorage-wrapped key.
+ if (typeof cfg.encryptedKey === 'string' && cfg.encryptedKey.trim()) {
+ let password;
+ try {
+ password = await readKeychainPassword();
+ } catch (err) {
+ return {
+ ok: false,
+ error: `Could not read the Signal Safe Storage keychain entry: ${err?.message || err}`,
+ remediation: 'Grant the process running PortOS access to the "Signal Safe Storage" keychain item (approve the keychain prompt), then retry. On PM2, the daemon must run under your login session.',
+ };
+ }
+ const encrypted = Buffer.from(cfg.encryptedKey.trim(), 'hex');
+ const decrypted = decryptSafeStorageValue(encrypted, password);
+ if (!decrypted.ok) {
+ return { ok: false, error: `Signal key unwrap failed: ${decrypted.error}`, remediation: 'Signal key decryption failed — the keychain password may be wrong or this Signal version uses an unsupported scheme.' };
+ }
+ const key = decrypted.plaintext.toString('utf8').trim();
+ if (!isRawHexKey(key)) {
+ return { ok: false, error: 'Unwrapped Signal key is not a 64-hex-char SQLCipher key', remediation: 'Unrecognized Signal key format — this Signal version is not yet supported.' };
+ }
+ return { ok: true, key, source: 'safeStorage' };
+ }
+
+ return { ok: false, error: 'Signal config.json has neither `key` nor `encryptedKey`', remediation: 'This Signal version stores its key in an unsupported way.' };
+}
+
+// ---------------------------------------------------------------------------
+// DB access — copy → decrypt → open plaintext with node:sqlite (readOnly).
+// ---------------------------------------------------------------------------
+
+// Copy the live DB to a temp snapshot, decrypt it to a sibling plaintext file,
+// and return both paths for cleanup. Never touches Signal's live file beyond the
+// read for `cp`. Returns { ok, plaintextPath, tmpDir } or an error report.
+async function openDecryptedSnapshot(key) {
+ const src = dbPath();
+ try { statSync(src); } catch (err) {
+ const missing = err?.code === 'ENOENT';
+ return {
+ ok: false,
+ error: missing ? `Signal database not found at ${src}` : `Cannot access ${src}: ${err?.message || err}`,
+ remediation: missing ? 'Signal Desktop has no chat database yet (never opened, or a different profile).' : 'Could not read the Signal database file — check file permissions for the process running PortOS.',
+ };
+ }
+ const tmp = await mkdtemp(join(tmpdir(), 'portos-signal-'));
+ const encPath = join(tmp, 'db.enc.sqlite');
+ const plainPath = join(tmp, 'db.plain.sqlite');
+ await copyFile(src, encPath);
+ const encBuf = await tryReadFile(encPath, { encoding: null });
+ if (!encBuf || !encBuf.length) {
+ await rm(tmp, { recursive: true, force: true });
+ return { ok: false, error: 'Signal database snapshot is empty', remediation: 'The Signal database copy was empty — try again with Signal closed.' };
+ }
+ const decrypted = decryptSqlcipherDatabase(encBuf, key, { verify: 'first' });
+ if (!decrypted.ok) {
+ await rm(tmp, { recursive: true, force: true });
+ return {
+ ok: false,
+ error: `Signal database decryption failed: ${decrypted.error}`,
+ remediation: 'Signal database decryption failed — the key or SQLCipher format may have changed in this Signal version (not yet supported).',
+ };
+ }
+ await writeFile(plainPath, decrypted.plaintext);
+ return { ok: true, plaintextPath: plainPath, tmpDir: tmp };
+}
+
+// Confirm the decrypted DB carries the Signal schema we understand. On an
+// unexpected shape return a structured error so the UI reports "unsupported
+// version" instead of throwing mid-query.
+function verifySchema(db) {
+ const tables = new Set(
+ db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map((r) => r.name),
+ );
+ for (const t of ['messages', 'conversations']) {
+ if (!tables.has(t)) return { ok: false, error: `Signal schema missing expected table "${t}"` };
+ }
+ const cols = new Set(db.prepare('PRAGMA table_info(messages)').all().map((r) => r.name));
+ for (const c of ['id', 'conversationId', 'type', 'sent_at', 'received_at', 'body']) {
+ if (!cols.has(c)) return { ok: false, error: `Signal "messages" table missing expected column "${c}"` };
+ }
+ return { ok: true };
+}
+
+// Read a batch of messages after `cursorRowid` plus the conversation→e164 map.
+// Returns normalized message records (the shape the pure mappers consume) and the
+// max rowid seen. Kept separate from runSync so the SQL boundary is small.
+function readMessages(db, cursorRowid, limit) {
+ // Conversation metadata: private conversations carry an `e164` (phone) we can
+ // match to a tracked person; group rows don't (their members live in JSON).
+ const convById = new Map();
+ for (const r of db.prepare('SELECT id, e164, type, name, profileName FROM conversations').all()) {
+ if (!r.id) continue;
+ convById.set(r.id, { e164: r.e164 || '', type: r.type || '', name: r.name || r.profileName || '' });
+ }
+
+ const rows = db.prepare(
+ `SELECT m.rowid AS rowid, m.id AS id, m.conversationId AS conversation_id,
+ m.type AS type, m.sent_at AS sent_at, m.received_at AS received_at, m.body AS body
+ FROM messages m
+ WHERE m.rowid > ?
+ ORDER BY m.rowid ASC
+ LIMIT ?`,
+ ).all(cursorRowid, limit);
+
+ let maxRowid = cursorRowid;
+ const messages = [];
+ for (const row of rows) {
+ const rowid = Number(row.rowid);
+ if (rowid > maxRowid) maxRowid = rowid;
+ const at = signalTimestampToDate(row.sent_at) || signalTimestampToDate(row.received_at);
+ if (!at) continue;
+ const conv = row.conversation_id ? convById.get(row.conversation_id) : null;
+ const handles = conv?.e164 ? [conv.e164] : [];
+ messages.push({
+ messageId: row.id,
+ rowid,
+ at,
+ text: row.body || '',
+ type: row.type || '',
+ conversationId: row.conversation_id || null,
+ conversationName: conv?.name || '',
+ handles,
+ });
+ }
+ return { messages, maxRowid, scanned: rows.length };
+}
+
+/**
+ * Attempt to resolve the key + open the decrypted DB and probe the schema.
+ * Returns a structured report — never throws — so the setup-check route can
+ * render an actionable error (missing install, key failure, unsupported schema).
+ */
+export async function checkSetup() {
+ const keyResult = await resolveDbKey();
+ if (!keyResult.ok) {
+ return { ok: false, dbPath: dbPath(), error: keyResult.error, remediation: keyResult.remediation };
+ }
+ const snapshot = await openDecryptedSnapshot(keyResult.key);
+ if (!snapshot.ok) {
+ return { ok: false, dbPath: dbPath(), error: snapshot.error, remediation: snapshot.remediation };
+ }
+ let db;
+ try {
+ db = new DatabaseSync(snapshot.plaintextPath, { readOnly: true });
+ const schema = verifySchema(db);
+ if (!schema.ok) {
+ return { ok: false, dbPath: dbPath(), error: schema.error, remediation: 'This Signal database schema is not yet supported.' };
+ }
+ const row = db.prepare('SELECT COUNT(*) AS n FROM messages').get();
+ return { ok: true, dbPath: dbPath(), keySource: keyResult.source, messageCount: Number(row?.n || 0) };
+ } catch (err) {
+ return { ok: false, dbPath: dbPath(), error: err?.message || 'Failed to open decrypted Signal DB', remediation: 'The decrypted Signal database could not be opened — the SQLCipher format may have changed.' };
+ } finally {
+ try { db?.close(); } catch { /* already closed / never opened */ }
+ await rm(snapshot.tmpDir, { recursive: true, force: true }).catch(() => {});
+ }
+}
+
+/**
+ * Run one incremental sync pass: resolve the key, decrypt a DB snapshot, read new
+ * messages after the stored rowid cursor, record activity events + Tribe
+ * touchpoints, and advance the cursor. Returns a summary. Safe to call repeatedly
+ * — dedupe keys make re-ingestion a no-op. Runs outside the request lifecycle
+ * (scheduler / explicit endpoint), so every failure is try/catch-guarded and
+ * returns an error report instead of throwing.
+ *
+ * Re-entrancy guarded: a manual "Sync now" overlapping a scheduler tick would
+ * double-read the same cursor — so concurrent callers share the in-flight pass.
+ */
+let syncInFlight = null;
+export async function runSync() {
+ if (syncInFlight) return syncInFlight;
+ syncInFlight = doRunSync().finally(() => { syncInFlight = null; });
+ return syncInFlight;
+}
+
+async function doRunSync() {
+ const state = await readSyncState();
+
+ const keyResult = await resolveDbKey();
+ if (!keyResult.ok) {
+ console.error(`❌ Signal sync: ${keyResult.error}`);
+ return { ok: false, error: keyResult.error, remediation: keyResult.remediation };
+ }
+
+ const snapshot = await openDecryptedSnapshot(keyResult.key);
+ if (!snapshot.ok) {
+ console.error(`❌ Signal sync: ${snapshot.error}`);
+ return { ok: false, error: snapshot.error, remediation: snapshot.remediation };
+ }
+
+ let db;
+ let batch;
+ try {
+ db = new DatabaseSync(snapshot.plaintextPath, { readOnly: true });
+ const schema = verifySchema(db);
+ if (!schema.ok) {
+ console.error(`❌ Signal sync: ${schema.error}`);
+ return { ok: false, error: schema.error, remediation: 'This Signal database schema is not yet supported.' };
+ }
+ batch = readMessages(db, state.cursorRowid, SCAN_LIMIT);
+ } catch (err) {
+ console.error(`❌ Signal sync failed reading DB: ${err?.message || err}`);
+ return { ok: false, error: err?.message || 'Failed to read Signal DB' };
+ } finally {
+ try { db?.close(); } catch { /* noop */ }
+ await rm(snapshot.tmpDir, { recursive: true, force: true }).catch(() => {});
+ }
+
+ const timezone = await getUserTimezone();
+ const { recordEvents } = await import('./humanActivity.js');
+ const tribe = await import('./tribe.js');
+
+ const activityCandidates = signalActivityCandidates(batch.messages);
+ const touchpointCandidates = signalTouchpointCandidates(batch.messages, timezone);
+
+ // Persistence failures must NOT advance the cursor: the dedupe keys make
+ // re-processing the batch a harmless no-op, but skipping past unpersisted
+ // messages loses them permanently. Hold the cursor so the batch retries.
+ let persistFailed = false;
+ const activityResult = await recordEvents(activityCandidates).catch((err) => {
+ console.error(`❌ Signal activity record failed: ${err?.message || err}`);
+ persistFailed = true;
+ return { recorded: 0, skipped: activityCandidates.length };
+ });
+ const touchpointResult = await tribe.autoLogTouchpoints(touchpointCandidates).catch((err) => {
+ console.error(`❌ Signal touchpoint log failed: ${err?.message || err}`);
+ persistFailed = true;
+ return { created: 0, matched: 0 };
+ });
+
+ const nextCursor = persistFailed ? state.cursorRowid : batch.maxRowid;
+ const result = {
+ ok: !persistFailed,
+ ...(persistFailed ? { error: 'Persistence failed — cursor held so the batch retries next sync' } : {}),
+ scanned: batch.scanned,
+ recorded: activityResult.recorded,
+ touchpointsCreated: touchpointResult.created,
+ touchpointsMatched: touchpointResult.matched,
+ cursorRowid: nextCursor,
+ keySource: keyResult.source,
+ hasMore: batch.scanned === SCAN_LIMIT,
+ };
+ await writeSyncState({ cursorRowid: nextCursor, lastRunAt: new Date().toISOString(), lastResult: result });
+ console.log(`🔒 Signal sync: scanned ${result.scanned}, recorded ${result.recorded} event(s), ${result.touchpointsCreated} touchpoint(s), cursor→${result.cursorRowid}${result.hasMore ? ' (more remaining)' : ''}${persistFailed ? ' — PERSIST FAILED, cursor held' : ''}`);
+ return result;
+}
+
+// Status for the settings UI: config + cursor state (no DB open / key read).
+export async function getStatus() {
+ const [config, state] = await Promise.all([getSignalConfig(), readSyncState()]);
+ return { config, state };
+}
diff --git a/server/services/signalSync.test.js b/server/services/signalSync.test.js
new file mode 100644
index 0000000000..a5dbe07197
--- /dev/null
+++ b/server/services/signalSync.test.js
@@ -0,0 +1,137 @@
+import { describe, it, expect } from 'vitest';
+import {
+ signalTimestampToDate,
+ signalActivityKind,
+ signalActivityCandidate,
+ signalActivityCandidates,
+ signalTouchpointCandidates,
+} from './signalSync.js';
+
+describe('signalSync pure helpers', () => {
+ describe('signalTimestampToDate', () => {
+ it('converts a millisecond epoch value', () => {
+ const ms = Date.UTC(2024, 5, 1, 12, 0, 0);
+ expect(signalTimestampToDate(ms).getTime()).toBe(ms);
+ });
+ it('accepts a bigint (node:sqlite may return BigInt)', () => {
+ const ms = Date.UTC(2024, 0, 2, 3, 4, 5);
+ expect(signalTimestampToDate(BigInt(ms)).getTime()).toBe(ms);
+ });
+ it('returns null for 0 / null / non-finite / negative', () => {
+ expect(signalTimestampToDate(0)).toBeNull();
+ expect(signalTimestampToDate(null)).toBeNull();
+ expect(signalTimestampToDate(undefined)).toBeNull();
+ expect(signalTimestampToDate(-5)).toBeNull();
+ expect(signalTimestampToDate('nope')).toBeNull();
+ });
+ });
+
+ describe('signalActivityKind', () => {
+ it('maps outgoing/incoming to sent/received', () => {
+ expect(signalActivityKind('outgoing')).toBe('message.sent');
+ expect(signalActivityKind('incoming')).toBe('message.received');
+ });
+ it('falls back to the direction flag when type is absent', () => {
+ expect(signalActivityKind('', true)).toBe('message.sent');
+ expect(signalActivityKind(null, false)).toBe('message.received');
+ });
+ it('skips non-message types (call-history, group updates, etc.)', () => {
+ expect(signalActivityKind('call-history')).toBeNull();
+ expect(signalActivityKind('group-v2-change')).toBeNull();
+ expect(signalActivityKind('verified-change')).toBeNull();
+ });
+ });
+
+ describe('signalActivityCandidate', () => {
+ const base = {
+ messageId: 'abc-123',
+ rowid: 42,
+ at: new Date('2024-06-01T12:00:00Z'),
+ text: 'hey there, long time',
+ type: 'incoming',
+ conversationId: 'conv-1',
+ conversationName: 'Jane Doe',
+ handles: ['+15551234567'],
+ };
+
+ it('maps an incoming message to a message.received activity event', () => {
+ const c = signalActivityCandidate(base);
+ expect(c).toMatchObject({
+ source: 'signal',
+ kind: 'message.received',
+ happenedAt: '2024-06-01T12:00:00.000Z',
+ title: 'Jane Doe',
+ dedupeKey: 'signal:abc-123',
+ });
+ expect(c.participants).toEqual([{ phone: '+15551234567' }]);
+ expect(c.metadata.conversationId).toBe('conv-1');
+ expect(c.metadata.rowid).toBe(42);
+ });
+
+ it('maps an outgoing message to message.sent and drops the counterpart handle from the title', () => {
+ const c = signalActivityCandidate({ ...base, type: 'outgoing', conversationName: '' });
+ expect(c.kind).toBe('message.sent');
+ // No conversation name + outgoing → counterpart is empty → title falls back.
+ expect(c.title).toBe('Signal');
+ expect(c.metadata.handle).toBeNull();
+ });
+
+ it('returns null for messages without an id, a bad date, or a skipped type', () => {
+ expect(signalActivityCandidate({ ...base, messageId: '' })).toBeNull();
+ expect(signalActivityCandidate({ ...base, at: new Date('nope') })).toBeNull();
+ expect(signalActivityCandidate({ ...base, type: 'call-history', isFromMe: undefined })).toBeNull();
+ });
+
+ it('summarizes long bodies (metadata + short summary, not full body)', () => {
+ const long = 'x'.repeat(500);
+ const c = signalActivityCandidate({ ...base, text: long });
+ expect(c.summary.length).toBeLessThanOrEqual(161);
+ });
+ });
+
+ describe('signalActivityCandidates', () => {
+ it('filters out unmappable rows', () => {
+ const out = signalActivityCandidates([
+ { messageId: 'a', rowid: 1, at: new Date('2024-06-01T00:00:00Z'), type: 'incoming', conversationId: 'c', handles: ['+15550000000'] },
+ { messageId: '', rowid: 2, at: new Date('2024-06-01T00:00:00Z'), type: 'incoming', conversationId: 'c' },
+ { messageId: 'b', rowid: 3, at: new Date('2024-06-01T00:00:00Z'), type: 'call-history', conversationId: 'c' },
+ ]);
+ expect(out).toHaveLength(1);
+ expect(out[0].dedupeKey).toBe('signal:a');
+ });
+ });
+
+ describe('signalTouchpointCandidates', () => {
+ const tz = 'America/Los_Angeles';
+
+ it('groups a busy thread into one touchpoint per conversation per local day', () => {
+ const messages = [
+ { messageId: 'm1', at: new Date('2024-06-01T18:00:00Z'), conversationId: 'conv-1', conversationName: 'Jane', handles: ['+15551234567'] },
+ { messageId: 'm2', at: new Date('2024-06-01T19:30:00Z'), conversationId: 'conv-1', conversationName: 'Jane', handles: ['+15551234567'] },
+ { messageId: 'm3', at: new Date('2024-06-02T20:00:00Z'), conversationId: 'conv-1', conversationName: 'Jane', handles: ['+15551234567'] },
+ ];
+ const out = signalTouchpointCandidates(messages, tz);
+ expect(out).toHaveLength(2); // two distinct local days
+ expect(out.every((t) => t.source === 'signal' && t.channel === 'Signal')).toBe(true);
+ // Latest instant of the day is retained.
+ const day1 = out.find((t) => t.dedupeKey.endsWith(':2024-06-01'));
+ expect(day1.happenedAt).toBe('2024-06-01T19:30:00.000Z');
+ expect(day1.identities).toEqual([{ phone: '+15551234567' }]);
+ });
+
+ it('skips conversations with no matchable handle', () => {
+ const out = signalTouchpointCandidates([
+ { messageId: 'm1', at: new Date('2024-06-01T18:00:00Z'), conversationId: 'group-1', conversationName: 'A Group', handles: [] },
+ ], tz);
+ expect(out).toHaveLength(0);
+ });
+
+ it('skips messages missing a conversationId or a valid date', () => {
+ const out = signalTouchpointCandidates([
+ { messageId: 'm1', at: new Date('2024-06-01T18:00:00Z'), conversationId: null, handles: ['+15551234567'] },
+ { messageId: 'm2', at: new Date('bad'), conversationId: 'c', handles: ['+15551234567'] },
+ ], tz);
+ expect(out).toHaveLength(0);
+ });
+ });
+});