@obzerver/server 0.3.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -6,14 +6,16 @@ import crypto from 'node:crypto';
6
6
  import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
- import { Db, bootstrap, getSetting, setSetting, randomKey, retention } from './db.js';
9
+ import { getSetting, setSetting, randomKey, retention } from './db.js';
10
+ import { Projects, ProjectError, DEFAULT_PROJECT, currentProjectSlug } from './projects.js';
10
11
  import { createIngest } from './ingest.js';
11
12
  import { createAlerts, RULE_TYPES, isRuleType, toRule } from './alerts.js';
12
13
  import { mcpHandler, MCP_TOOL_NAMES } from './mcp.js';
13
14
  import { issueRow, verifyFix, runVerification, MEASURABLE } from './issues.js';
15
+ import { PROVIDERS, PROVIDER_LABEL, TrackerError, createTicket, syncTickets, onIssueResolved, onVerification, publicTrackerSettings, saveTrackerSettings, testTracker, trackerSettings, verifyGithubSignature, verifyLinearSignature, handleGithubEvent, handleLinearEvent, } from './trackers.js';
14
16
  import * as Q from './queries.js';
15
17
  import { listSlos, sloStatus, sloHistory, saveSlo, deleteSlo, validateSlo, toSlo, burnRulesFor } from './slos.js';
16
- import { toPage, toIncident, validatePage, savePage, deletePage, createIncident, updateIncident, pageView, publicView, renderStatusHtml, runAutoIncidents } from './status.js';
18
+ import { slugify as slugifyPage, toPage, toIncident, validatePage, savePage, deletePage, createIncident, updateIncident, pageView, publicView, renderStatusHtml, runAutoIncidents } from './status.js';
17
19
  import { mailConfig, maskSmtpUrl, parseRecipients, sendMail, resetMailTransports, alertEmail } from './mailer.js';
18
20
  const here = path.dirname(fileURLToPath(import.meta.url));
19
21
  const badRequest = (msg) => Object.assign(new Error(msg), { statusCode: 400 });
@@ -31,16 +33,35 @@ export async function createServer(opts = {}) {
31
33
  publicUrl: opts.publicUrl ?? env.OBZERVER_PUBLIC_URL ?? null,
32
34
  defaultKey: opts.defaultKey ?? env.OBZERVER_DEFAULT_KEY ?? null,
33
35
  alertIntervalMs: Number(opts.alertIntervalMs ?? 30000),
36
+ ticketSyncMs: positive(Number(opts.ticketSyncMs ?? (Number(env.OBZERVER_TICKET_SYNC_SECONDS) * 1000)), 120000),
34
37
  logger: opts.logger ?? false,
35
38
  publicDir: opts.publicDir ?? path.resolve(here, '../public'),
36
39
  };
37
- const db = new Db(config.dbFile);
38
- bootstrap(db, { defaultKey: config.defaultKey });
40
+ // One SQLite file per project; `db` resolves to the current request's project (see projects.ts).
41
+ const projects = new Projects(config.dbFile, { defaultKey: config.defaultKey });
42
+ const root = projects.root;
43
+ const db = projects.scoped();
39
44
  const log = (m) => process.stdout.write(`[obzerver] ${m}\n`);
40
- const alerts = createAlerts(db, { publicUrl: config.publicUrl, log });
41
- const ingest = createIngest(db, { onNewErrorGroup: (g) => { void alerts.onNewErrorGroup(g); } });
45
+ // Issues opened by alerts also get a ticket when auto-create is on.
46
+ const autoTicket = (issueId) => {
47
+ const provider = trackerSettings(db).autoCreate;
48
+ if (provider)
49
+ createTicket(db, issueId, provider, config.publicUrl).catch((e) => log(`auto ticket #${issueId}: ${e.message}`));
50
+ };
51
+ const alerts = createAlerts(db, { publicUrl: config.publicUrl, log, onIssueOpened: autoTicket, mailDb: root });
52
+ // Ingest prepares statements against one database, so there is one per project.
53
+ const ingests = new Map();
54
+ const ingestFor = (slug) => {
55
+ let i = ingests.get(slug);
56
+ if (!i) {
57
+ i = createIngest(projects.db(slug), { onNewErrorGroup: (g) => { void alerts.onNewErrorGroup(g); } });
58
+ ingests.set(slug, i);
59
+ }
60
+ return i;
61
+ };
62
+ const ingest = (payload) => projects.run(DEFAULT_PROJECT, () => ingestFor(DEFAULT_PROJECT)(payload));
42
63
  const mcp = mcpHandler(db);
43
- const secret = getSetting(db, 'session_secret') ?? crypto.randomBytes(32).toString('hex');
64
+ const secret = getSetting(root, 'session_secret') ?? crypto.randomBytes(32).toString('hex');
44
65
  const app = Fastify({ logger: config.logger, bodyLimit: 25 * 1024 * 1024, trustProxy: true });
45
66
  // ---------------------------------------------------------------- auth
46
67
  const sign = (exp) => `${exp}.${crypto.createHmac('sha256', secret).update(String(exp)).digest('hex')}`;
@@ -53,7 +74,7 @@ export async function createServer(opts = {}) {
53
74
  return Number(exp) > Date.now() && m[1].length === expected.length && crypto.timingSafeEqual(Buffer.from(m[1]), Buffer.from(expected));
54
75
  };
55
76
  app.addHook('onRequest', async (req, reply) => {
56
- if (!req.url.startsWith('/api/') || req.url.startsWith('/api/auth') || req.url.startsWith('/api/public/') || !config.password)
77
+ if (!req.url.startsWith('/api/') || req.url.startsWith('/api/auth') || req.url.startsWith('/api/public/') || req.url.startsWith('/api/integrations/') || !config.password)
57
78
  return;
58
79
  if (!validSession(req.headers.cookie))
59
80
  await reply.code(401).send({ error: 'unauthorized' });
@@ -69,6 +90,56 @@ export async function createServer(opts = {}) {
69
90
  return reply.code(503).send({ ok: false, version: VERSION, error: e.message });
70
91
  }
71
92
  });
93
+ // Dashboard API calls name their project with the x-obzerver-project header (or ?project=). Runs after the
94
+ // body is parsed so the handler and everything it awaits see that project's database.
95
+ const GLOBAL_API = ['/api/auth', '/api/public/', '/api/integrations/', '/api/projects'];
96
+ app.addHook('preHandler', (req, reply, done) => {
97
+ if (!req.url.startsWith('/api/') || GLOBAL_API.some((p) => req.url.startsWith(p)))
98
+ return done();
99
+ const q = req.query?.project;
100
+ const h = req.headers['x-obzerver-project'];
101
+ const slug = String((Array.isArray(h) ? h[0] : h) || q || DEFAULT_PROJECT);
102
+ if (!projects.has(slug)) {
103
+ reply.code(404).send({ error: `Unknown project "${slug}"` });
104
+ return;
105
+ }
106
+ projects.run(slug, () => done());
107
+ });
108
+ // ---------------------------------------------------------------- projects
109
+ app.get('/api/projects', async () => projects.list().map((p) => {
110
+ const d = projects.db(p.slug);
111
+ const apps = d.get('SELECT COUNT(*) n FROM services').n;
112
+ const last = d.get('SELECT MAX(last_seen) t FROM services').t;
113
+ return { ...p, apps, lastSeen: last };
114
+ }));
115
+ app.post('/api/projects', async (req, reply) => {
116
+ try {
117
+ const p = projects.create(String(req.body?.name || ''), req.body?.slug || undefined);
118
+ const key = projects.db(p.slug).get('SELECT key FROM keys WHERE revoked = 0 ORDER BY id LIMIT 1').key;
119
+ return { ...p, ingestKey: key };
120
+ }
121
+ catch (e) {
122
+ return reply.code(e instanceof ProjectError ? e.status : 500).send({ error: e.message });
123
+ }
124
+ });
125
+ app.patch('/api/projects/:slug', async (req, reply) => {
126
+ try {
127
+ return projects.rename(req.params.slug, String(req.body?.name || ''));
128
+ }
129
+ catch (e) {
130
+ return reply.code(e instanceof ProjectError ? e.status : 500).send({ error: e.message });
131
+ }
132
+ });
133
+ app.delete('/api/projects/:slug', async (req, reply) => {
134
+ try {
135
+ projects.remove(req.params.slug);
136
+ ingests.delete(req.params.slug);
137
+ return { ok: true };
138
+ }
139
+ catch (e) {
140
+ return reply.code(e instanceof ProjectError ? e.status : 500).send({ error: e.message });
141
+ }
142
+ });
72
143
  app.get('/api/auth', async (req) => ({ required: !!config.password, ok: !config.password || validSession(req.headers.cookie) }));
73
144
  app.post('/api/auth/login', async (req, reply) => {
74
145
  const a = Buffer.from(String(req.body?.password || ''));
@@ -81,21 +152,8 @@ export async function createServer(opts = {}) {
81
152
  });
82
153
  app.post('/api/auth/logout', async (_req, reply) => { reply.header('set-cookie', 'obz_session=; Path=/; Max-Age=0'); return { ok: true }; });
83
154
  // ---------------------------------------------------------------- ingest
84
- const keyCache = new Map();
85
- const checkKey = (key) => {
86
- if (config.openIngest)
87
- return true;
88
- if (!key)
89
- return false;
90
- const hit = keyCache.get(key);
91
- if (hit && hit.until > Date.now())
92
- return hit.ok;
93
- const row = db.get('SELECT id FROM keys WHERE key = ? AND revoked = 0', key);
94
- if (row)
95
- db.run('UPDATE keys SET last_used = ? WHERE id = ?', Date.now(), row.id);
96
- keyCache.set(key, { ok: !!row, until: Date.now() + 30000 });
97
- return !!row;
98
- };
155
+ // Last-used stamps are written at most once a minute per key.
156
+ const lastUsed = new Map();
99
157
  await app.register(async (scope) => {
100
158
  scope.addHook('preParsing', async (req, _reply, payload) => {
101
159
  if (req.headers['content-encoding'] !== 'gzip')
@@ -106,24 +164,38 @@ export async function createServer(opts = {}) {
106
164
  scope.post('/v1/ingest', async (req, reply) => {
107
165
  const header = req.headers['x-obzerver-key'];
108
166
  const key = (Array.isArray(header) ? header[0] : header) || (req.headers.authorization || '').replace(/^Bearer\s+/i, '');
109
- if (!checkKey(key))
167
+ const slug = projects.byIngestKey(key) ?? (config.openIngest ? DEFAULT_PROJECT : null);
168
+ if (!slug)
110
169
  return reply.code(401).send({ error: 'invalid app key' });
111
170
  if (!req.body || typeof req.body !== 'object')
112
171
  return reply.code(400).send({ error: 'expected JSON body' });
113
- return { ok: true, accepted: ingest(req.body) };
172
+ const body = req.body;
173
+ return projects.run(slug, () => {
174
+ const now = Date.now();
175
+ if (key && (lastUsed.get(key) ?? 0) < now - 60000) {
176
+ lastUsed.set(key, now);
177
+ db.run('UPDATE keys SET last_used = ? WHERE key = ?', now, key);
178
+ }
179
+ return { ok: true, project: slug, accepted: ingestFor(slug)(body) };
180
+ });
114
181
  });
115
182
  });
116
183
  // ---------------------------------------------------------------- MCP
117
184
  app.post('/mcp', async (req, reply) => {
118
185
  const token = (req.headers.authorization || '').replace(/^Bearer\s+/i, '');
119
- if (token !== getSetting(db, 'mcp_token'))
186
+ // The token decides the project: an agent only ever sees the project its token belongs to.
187
+ const slug = projects.byMcpToken(token);
188
+ if (!slug)
120
189
  return reply.code(401).send({ jsonrpc: '2.0', id: null, error: { code: -32001, message: 'Unauthorized: pass the MCP token as a Bearer token' } });
121
- if (Array.isArray(req.body)) {
122
- const out = (await Promise.all(req.body.map(mcp))).filter(Boolean);
123
- return out.length ? out : reply.code(202).send();
124
- }
125
- const res = await mcp(req.body);
126
- return res ?? reply.code(202).send();
190
+ const body = req.body;
191
+ return projects.run(slug, async () => {
192
+ if (Array.isArray(body)) {
193
+ const out = (await Promise.all(body.map(mcp))).filter(Boolean);
194
+ return out.length ? out : reply.code(202).send();
195
+ }
196
+ const res = await mcp(body);
197
+ return res ?? reply.code(202).send();
198
+ });
127
199
  });
128
200
  const notAllowed = async (_req, reply) => reply.code(405).header('allow', 'POST').send();
129
201
  app.get('/mcp', notAllowed);
@@ -229,7 +301,19 @@ export async function createServer(opts = {}) {
229
301
  const now = Date.now();
230
302
  const r = db.run(`INSERT INTO issues(title, status, severity, owner, due, description, source_type, source_ref, service, created, updated, timeline)
231
303
  VALUES(?, 'open', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, String(b.title || 'Untitled issue'), b.severity || 'medium', b.owner || null, b.due || null, b.description || null, b.sourceType || null, b.sourceRef || null, b.service || null, now, now, JSON.stringify([{ ts: now, text: `Created${b.sourceType ? ` from ${b.sourceType}` : ''}` }]));
232
- return { id: r.lastId };
304
+ const id = Number(r.lastId);
305
+ if (b.tracker) {
306
+ if (!PROVIDERS.includes(b.tracker))
307
+ throw badRequest(`tracker must be one of ${PROVIDERS.join(', ')}`);
308
+ try {
309
+ const ticket = await createTicket(db, id, b.tracker, config.publicUrl);
310
+ return { id, ticket };
311
+ }
312
+ catch (e) {
313
+ return { id, ticketError: e.message };
314
+ }
315
+ }
316
+ return { id };
233
317
  });
234
318
  app.patch('/api/issues/:id', async (req, reply) => {
235
319
  const r = db.get('SELECT * FROM issues WHERE id = ?', Number(req.params.id));
@@ -245,6 +329,7 @@ export async function createServer(opts = {}) {
245
329
  changes.push(`${col.replace('_', ' ')} → ${v ?? '—'}`);
246
330
  db.run(`UPDATE issues SET ${col} = ? WHERE id = ?`, v, r.id);
247
331
  }
332
+ const resolving = (b.status === 'resolved' || b.status === 'verifying') && !['verifying', 'resolved', 'closed'].includes(r.status);
248
333
  if (b.status === 'resolved' || b.status === 'verifying') {
249
334
  const measurable = MEASURABLE.has(r.source_type);
250
335
  db.run('UPDATE issues SET status = ?, resolved_at = ? WHERE id = ?', measurable ? 'verifying' : 'resolved', Date.now(), r.id);
@@ -255,6 +340,37 @@ export async function createServer(opts = {}) {
255
340
  changes.push(`comment: ${b.comment}`);
256
341
  const timeline = changes.length ? appendTimeline(r.timeline, changes.join('; ')) : r.timeline;
257
342
  db.run('UPDATE issues SET updated = ?, timeline = ? WHERE id = ?', Date.now(), timeline, r.id);
343
+ if (resolving)
344
+ await onIssueResolved(db, r.id, log);
345
+ return { ok: true };
346
+ });
347
+ // Ticket in GitHub or Linear: create and link, or pull its state now.
348
+ app.post('/api/issues/:id/ticket', async (req, reply) => {
349
+ const provider = req.body?.provider;
350
+ if (!provider || !PROVIDERS.includes(provider))
351
+ return reply.code(400).send({ error: `provider must be one of ${PROVIDERS.join(', ')}` });
352
+ try {
353
+ return await createTicket(db, Number(req.params.id), provider, config.publicUrl);
354
+ }
355
+ catch (e) {
356
+ return reply.code(e instanceof TrackerError ? e.status : 500).send({ error: e.message });
357
+ }
358
+ });
359
+ app.post('/api/issues/:id/ticket/sync', async (req, reply) => {
360
+ const r = db.get('SELECT ext_provider FROM issues WHERE id = ?', Number(req.params.id));
361
+ if (!r?.ext_provider)
362
+ return reply.code(404).send({ error: 'Issue has no linked ticket' });
363
+ try {
364
+ db.run('UPDATE issues SET ext_synced = 0 WHERE id = ?', Number(req.params.id));
365
+ await syncTickets(db, log);
366
+ return issueRow(db.get('SELECT * FROM issues WHERE id = ?', Number(req.params.id)));
367
+ }
368
+ catch (e) {
369
+ return reply.code(502).send({ error: e.message });
370
+ }
371
+ });
372
+ app.delete('/api/issues/:id/ticket', async (req) => {
373
+ db.run('UPDATE issues SET ext_provider = NULL, ext_id = NULL, ext_key = NULL, ext_url = NULL, ext_state = NULL, ext_synced = NULL WHERE id = ?', Number(req.params.id));
258
374
  return { ok: true };
259
375
  });
260
376
  app.delete('/api/issues/:id', async (req) => { db.run('DELETE FROM issues WHERE id = ?', Number(req.params.id)); return { ok: true }; });
@@ -297,14 +413,14 @@ export async function createServer(opts = {}) {
297
413
  return { ...v, incidents, publicUrl: `${config.publicUrl || ''}/status/${v.page.slug}` };
298
414
  });
299
415
  app.post('/api/status-pages', async (req, reply) => {
300
- const err = validatePage(db, req.body || {});
416
+ const err = validatePage(db, req.body || {}) || slugTakenElsewhere(req.body?.slug || req.body?.title);
301
417
  return err ? reply.code(400).send({ error: err }) : { id: savePage(db, req.body) };
302
418
  });
303
419
  app.put('/api/status-pages/:id', async (req, reply) => {
304
420
  const id = Number(req.params.id);
305
421
  if (!db.get('SELECT id FROM status_pages WHERE id = ?', id))
306
422
  return notFound(reply);
307
- const err = validatePage(db, req.body || {}, id);
423
+ const err = validatePage(db, req.body || {}, id) || slugTakenElsewhere(req.body?.slug || req.body?.title);
308
424
  return err ? reply.code(400).send({ error: err }) : { id: savePage(db, req.body, id) };
309
425
  });
310
426
  app.delete('/api/status-pages/:id', async (req) => { deletePage(db, Number(req.params.id)); return { ok: true }; });
@@ -318,20 +434,32 @@ export async function createServer(opts = {}) {
318
434
  });
319
435
  app.patch('/api/incidents/:id', async (req, reply) => (updateIncident(db, Number(req.params.id), req.body || {}) ? { ok: true } : notFound(reply)));
320
436
  app.delete('/api/incidents/:id', async (req) => { db.run('DELETE FROM incidents WHERE id = ?', Number(req.params.id)); return { ok: true }; });
437
+ // Status page URLs (/status/<slug>) are global, so a slug may exist in one project only.
438
+ const slugTakenElsewhere = (wanted) => {
439
+ const slug = slugifyPage(wanted || '');
440
+ if (!slug)
441
+ return null;
442
+ const mine = currentProjectSlug();
443
+ const other = projects.list().find((p) => p.slug !== mine && projects.db(p.slug).get('SELECT 1 FROM status_pages WHERE slug = ?', slug));
444
+ return other ? `The status page address "${slug}" is used by another project` : null;
445
+ };
446
+ const projectOfPage = (slug) => projects.list().find((p) => projects.db(p.slug).get('SELECT 1 FROM status_pages WHERE slug = ? AND published = 1', slug))?.slug ?? null;
321
447
  // Public, unauthenticated: only published pages, only names and states.
322
448
  const publicPage = (slug) => {
323
449
  const r = db.get('SELECT * FROM status_pages WHERE slug = ? AND published = 1', slug);
324
450
  return r ? publicView(pageView(db, toPage(r))) : null;
325
451
  };
326
452
  app.get('/api/public/status/:slug', async (req, reply) => {
327
- const v = publicPage(req.params.slug);
453
+ const project = projectOfPage(req.params.slug);
454
+ const v = project ? projects.run(project, () => publicPage(req.params.slug)) : null;
328
455
  if (!v)
329
456
  return notFound(reply);
330
457
  reply.header('access-control-allow-origin', '*').header('cache-control', 'public, max-age=30');
331
458
  return v;
332
459
  });
333
460
  app.get('/status/:slug', async (req, reply) => {
334
- const v = publicPage(req.params.slug);
461
+ const project = projectOfPage(req.params.slug);
462
+ const v = project ? projects.run(project, () => publicPage(req.params.slug)) : null;
335
463
  reply.header('cache-control', 'public, max-age=30');
336
464
  if (!v)
337
465
  return reply.code(404).type('text/html').send('<!doctype html><meta charset="utf-8"><title>Not found</title><p style="font-family:sans-serif;padding:40px">Status page not found.</p>');
@@ -345,26 +473,28 @@ export async function createServer(opts = {}) {
345
473
  keys: db.all('SELECT id, name, key, created, last_used, revoked FROM keys ORDER BY id'),
346
474
  mcp: { url: `${origin}/mcp`, token: getSetting(db, 'mcp_token'), tools: MCP_TOOL_NAMES },
347
475
  retentionDays: config.retentionDays,
348
- email: (() => { const m = mailConfig(db); return { configured: !!m.url, source: m.source, smtp: maskSmtpUrl(m.url), from: m.from }; })(),
476
+ email: (() => { const m = mailConfig(root); return { configured: !!m.url, source: m.source, smtp: maskSmtpUrl(m.url), from: m.from }; })(),
349
477
  passwordProtected: !!config.password,
350
478
  openIngest: config.openIngest,
351
479
  };
352
480
  });
353
481
  app.post('/api/keys', async (req) => {
354
482
  const key = randomKey('obz_live');
355
- return { id: db.run('INSERT INTO keys(name, key, created) VALUES(?, ?, ?)', String(req.body?.name || 'key'), key, Date.now()).lastId, key };
483
+ const id = db.run('INSERT INTO keys(name, key, created) VALUES(?, ?, ?)', String(req.body?.name || 'key'), key, Date.now()).lastId;
484
+ projects.invalidate();
485
+ return { id, key };
356
486
  });
357
- app.delete('/api/keys/:id', async (req) => { db.run('UPDATE keys SET revoked = 1 WHERE id = ?', Number(req.params.id)); keyCache.clear(); return { ok: true }; });
487
+ app.delete('/api/keys/:id', async (req) => { db.run('UPDATE keys SET revoked = 1 WHERE id = ?', Number(req.params.id)); projects.invalidate(); return { ok: true }; });
358
488
  app.put('/api/settings/email', async (req, reply) => {
359
- if (mailConfig(db).source === 'env')
489
+ if (mailConfig(root).source === 'env')
360
490
  return reply.code(409).send({ error: 'Email is configured with OBZERVER_SMTP_URL; change it there' });
361
491
  const url = String(req.body?.smtpUrl || '').trim();
362
492
  if (url && !/^smtps?:\/\//.test(url))
363
493
  return reply.code(400).send({ error: 'SMTP URL must start with smtp:// or smtps://' });
364
494
  // An unchanged masked URL means "keep the stored one".
365
495
  if (!url.includes('••••'))
366
- setSetting(db, 'smtp_url', url);
367
- setSetting(db, 'mail_from', String(req.body?.from || '').trim());
496
+ setSetting(root, 'smtp_url', url);
497
+ setSetting(root, 'mail_from', String(req.body?.from || '').trim());
368
498
  resetMailTransports();
369
499
  return { ok: true };
370
500
  });
@@ -373,13 +503,86 @@ export async function createServer(opts = {}) {
373
503
  if (!to.length)
374
504
  return reply.code(400).send({ error: 'Enter at least one valid email address' });
375
505
  try {
376
- const r = await sendMail(db, { to, ...alertEmail({ ruleName: 'Test email', state: 'test', message: 'Email delivery from Obzerver works.', link: config.publicUrl, ts: Date.now() }) });
506
+ const r = await sendMail(root, { to, ...alertEmail({ ruleName: 'Test email', state: 'test', message: 'Email delivery from Obzerver works.', link: config.publicUrl, ts: Date.now() }) });
377
507
  return { ok: true, messageId: r.messageId };
378
508
  }
379
509
  catch (e) {
380
510
  return reply.code(502).send({ error: e.message });
381
511
  }
382
512
  });
513
+ app.get('/api/settings/trackers', async () => publicTrackerSettings(db));
514
+ app.put('/api/settings/trackers', async (req, reply) => {
515
+ const b = req.body || {};
516
+ const src = trackerSettings(db).source;
517
+ for (const p of PROVIDERS)
518
+ if (b[p] !== undefined && src[p] === 'env')
519
+ return reply.code(409).send({ error: `${PROVIDER_LABEL[p]} is configured with environment variables; change it there` });
520
+ try {
521
+ saveTrackerSettings(db, b);
522
+ return publicTrackerSettings(db);
523
+ }
524
+ catch (e) {
525
+ return reply.code(e instanceof TrackerError ? e.status : 500).send({ error: e.message });
526
+ }
527
+ });
528
+ app.post('/api/settings/trackers/:provider/test', async (req, reply) => {
529
+ if (!PROVIDERS.includes(req.params.provider))
530
+ return reply.code(404).send({ error: 'unknown tracker' });
531
+ try {
532
+ return await testTracker(db, req.params.provider, req.body || {});
533
+ }
534
+ catch (e) {
535
+ return reply.code(e instanceof TrackerError ? e.status : 500).send({ error: e.message });
536
+ }
537
+ });
538
+ // Webhooks from trackers: authenticated by their signature, not the dashboard password. Raw body kept for the HMAC.
539
+ await app.register(async (hooks) => {
540
+ hooks.addContentTypeParser('application/json', { parseAs: 'buffer' }, (_req, body, done) => done(null, body));
541
+ const githubHook = async (req, reply, slug) => {
542
+ if (!projects.has(slug))
543
+ return reply.code(404).send({ error: `Unknown project "${slug}"` });
544
+ return projects.run(slug, () => githubWebhook(req, reply));
545
+ };
546
+ hooks.post('/api/integrations/github/webhook', (req, reply) => githubHook(req, reply, DEFAULT_PROJECT));
547
+ hooks.post('/api/integrations/:project/github/webhook', (req, reply) => githubHook(req, reply, req.params.project));
548
+ const githubWebhook = async (req, reply) => {
549
+ const raw = req.body;
550
+ if (!verifyGithubSignature(trackerSettings(db).githubWebhookSecret, raw, req.headers['x-hub-signature-256']))
551
+ return reply.code(401).send({ error: 'bad signature' });
552
+ let payload;
553
+ try {
554
+ payload = JSON.parse(raw.toString('utf8'));
555
+ }
556
+ catch {
557
+ return reply.code(400).send({ error: 'invalid JSON' });
558
+ }
559
+ const result = handleGithubEvent(db, req.headers['x-github-event'], payload);
560
+ return { ok: true, result };
561
+ };
562
+ const linearHook = async (req, reply, slug) => {
563
+ if (!projects.has(slug))
564
+ return reply.code(404).send({ error: `Unknown project "${slug}"` });
565
+ return projects.run(slug, () => linearWebhook(req, reply));
566
+ };
567
+ hooks.post('/api/integrations/linear/webhook', (req, reply) => linearHook(req, reply, DEFAULT_PROJECT));
568
+ hooks.post('/api/integrations/:project/linear/webhook', (req, reply) => linearHook(req, reply, req.params.project));
569
+ const linearWebhook = async (req, reply) => {
570
+ const raw = req.body;
571
+ if (!verifyLinearSignature(trackerSettings(db).linearWebhookSecret, raw, req.headers['linear-signature']))
572
+ return reply.code(401).send({ error: 'bad signature' });
573
+ let payload;
574
+ try {
575
+ payload = JSON.parse(raw.toString('utf8'));
576
+ }
577
+ catch {
578
+ return reply.code(400).send({ error: 'invalid JSON' });
579
+ }
580
+ // Linear signs a timestamp too: refuse replays older than 5 minutes.
581
+ if (typeof payload.webhookTimestamp === 'number' && Math.abs(Date.now() - payload.webhookTimestamp) > 5 * 60000)
582
+ return reply.code(401).send({ error: 'stale webhook' });
583
+ return { ok: true, result: handleLinearEvent(db, payload) };
584
+ };
585
+ });
383
586
  app.post('/api/settings/mcp-token', async () => { const token = randomKey('obz_mcp'); setSetting(db, 'mcp_token', token); return { token }; });
384
587
  // ---------------------------------------------------------------- dashboard
385
588
  if (fs.existsSync(path.join(config.publicDir, 'index.html'))) {
@@ -406,15 +609,18 @@ export async function createServer(opts = {}) {
406
609
  timers.push(t);
407
610
  };
408
611
  app.addHook('onClose', async () => { for (const t of timers)
409
- clearInterval(t); db.close(); });
612
+ clearInterval(t); projects.close(); });
613
+ // Background passes run once per project, each against its own database.
614
+ const perProject = (label, fn) => () => projects.each(fn, (slug, e) => log(`${label} [${slug}]: ${e.message}`));
410
615
  return {
411
- app, db, config, alerts, ingest,
616
+ app, db: root, config, alerts, ingest, projects,
412
617
  async listen() {
413
618
  await app.listen({ port: config.port, host: config.host });
414
- every(config.alertIntervalMs, () => alerts.evaluate(), 'alerts');
415
- every(60000, () => runVerification(db), 'verify');
416
- every(60000, () => runAutoIncidents(db, Date.now(), log), 'status');
417
- every(3600e3, () => retention(db, config.retentionDays), 'retention');
619
+ every(config.alertIntervalMs, perProject('alerts', () => alerts.evaluate()), 'alerts');
620
+ every(60000, perProject('verify', () => onVerification(db, runVerification(db), log)), 'verify');
621
+ every(config.ticketSyncMs, perProject('tickets', () => syncTickets(db, log)), 'tickets');
622
+ every(60000, perProject('status', () => runAutoIncidents(db, Date.now(), log)), 'status');
623
+ every(3600e3, perProject('retention', () => retention(db, config.retentionDays)), 'retention');
418
624
  return app;
419
625
  },
420
626
  };