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