@obzerver/server 0.0.0-stage → 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/LICENSE +21 -0
- package/dist/alerts.d.ts +67 -0
- package/dist/alerts.js +281 -0
- package/dist/alerts.js.map +1 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +107 -0
- package/dist/cli.js.map +1 -0
- package/dist/db.d.ts +34 -0
- package/dist/db.js +209 -0
- package/dist/db.js.map +1 -0
- package/dist/ingest.d.ts +23 -0
- package/dist/ingest.js +116 -0
- package/dist/ingest.js.map +1 -0
- package/dist/issues.d.ts +60 -0
- package/dist/issues.js +127 -0
- package/dist/issues.js.map +1 -0
- package/dist/mailer.d.ts +32 -0
- package/dist/mailer.js +82 -0
- package/dist/mailer.js.map +1 -0
- package/dist/mcp.d.ts +22 -0
- package/dist/mcp.js +190 -0
- package/dist/mcp.js.map +1 -0
- package/dist/projects.d.ts +49 -0
- package/dist/projects.js +184 -0
- package/dist/projects.js.map +1 -0
- package/dist/queries.d.ts +624 -0
- package/dist/queries.js +857 -0
- package/dist/queries.js.map +1 -0
- package/dist/seed.d.ts +14 -0
- package/dist/seed.js +487 -0
- package/dist/seed.js.map +1 -0
- package/dist/server.d.ts +45 -0
- package/dist/server.js +628 -0
- package/dist/server.js.map +1 -0
- package/dist/slos.d.ts +100 -0
- package/dist/slos.js +172 -0
- package/dist/slos.js.map +1 -0
- package/dist/status.d.ts +147 -0
- package/dist/status.js +264 -0
- package/dist/status.js.map +1 -0
- package/dist/trackers.d.ts +201 -0
- package/dist/trackers.js +585 -0
- package/dist/trackers.js.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +7 -0
- package/dist/version.js.map +1 -0
- package/package.json +35 -4
- package/public/assets/index-C4xcvzwn.css +1 -0
- package/public/assets/index-Dnpzem0I.js +513 -0
- package/public/index.html +15 -0
- package/README.md +0 -3
package/dist/server.js
ADDED
|
@@ -0,0 +1,628 @@
|
|
|
1
|
+
import { VERSION } from './version.js';
|
|
2
|
+
import Fastify from 'fastify';
|
|
3
|
+
import fastifyStatic from '@fastify/static';
|
|
4
|
+
import zlib from 'node:zlib';
|
|
5
|
+
import crypto from 'node:crypto';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { getSetting, setSetting, randomKey, retention } from './db.js';
|
|
10
|
+
import { Projects, ProjectError, DEFAULT_PROJECT, currentProjectSlug } from './projects.js';
|
|
11
|
+
import { createIngest } from './ingest.js';
|
|
12
|
+
import { createAlerts, RULE_TYPES, isRuleType, toRule } from './alerts.js';
|
|
13
|
+
import { mcpHandler, MCP_TOOL_NAMES } from './mcp.js';
|
|
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';
|
|
16
|
+
import * as Q from './queries.js';
|
|
17
|
+
import { listSlos, sloStatus, sloHistory, saveSlo, deleteSlo, validateSlo, toSlo, burnRulesFor } from './slos.js';
|
|
18
|
+
import { slugify as slugifyPage, toPage, toIncident, validatePage, savePage, deletePage, createIncident, updateIncident, pageView, publicView, renderStatusHtml, runAutoIncidents } from './status.js';
|
|
19
|
+
import { mailConfig, maskSmtpUrl, parseRecipients, sendMail, resetMailTransports, alertEmail } from './mailer.js';
|
|
20
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
21
|
+
const badRequest = (msg) => Object.assign(new Error(msg), { statusCode: 400 });
|
|
22
|
+
export async function createServer(opts = {}) {
|
|
23
|
+
// Empty env vars (common with docker compose `${VAR:-}` and Kubernetes) count as unset.
|
|
24
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([, v]) => v !== ''));
|
|
25
|
+
const positive = (v, fallback) => (Number.isFinite(v) && v > 0 ? v : fallback);
|
|
26
|
+
const config = {
|
|
27
|
+
port: Number(opts.port ?? env.PORT ?? env.OBZERVER_PORT ?? 4319),
|
|
28
|
+
host: opts.host ?? env.HOST ?? '0.0.0.0',
|
|
29
|
+
dbFile: opts.dbFile ?? env.OBZERVER_DB ?? path.resolve(process.cwd(), '.obzerver/obzerver.db'),
|
|
30
|
+
password: opts.password ?? env.OBZERVER_PASSWORD ?? '',
|
|
31
|
+
openIngest: opts.openIngest ?? env.OBZERVER_OPEN_INGEST === 'true',
|
|
32
|
+
retentionDays: positive(Number(opts.retentionDays ?? env.OBZERVER_RETENTION_DAYS ?? 7), 7),
|
|
33
|
+
publicUrl: opts.publicUrl ?? env.OBZERVER_PUBLIC_URL ?? null,
|
|
34
|
+
defaultKey: opts.defaultKey ?? env.OBZERVER_DEFAULT_KEY ?? null,
|
|
35
|
+
alertIntervalMs: Number(opts.alertIntervalMs ?? 30000),
|
|
36
|
+
ticketSyncMs: positive(Number(opts.ticketSyncMs ?? (Number(env.OBZERVER_TICKET_SYNC_SECONDS) * 1000)), 120000),
|
|
37
|
+
logger: opts.logger ?? false,
|
|
38
|
+
publicDir: opts.publicDir ?? path.resolve(here, '../public'),
|
|
39
|
+
};
|
|
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();
|
|
44
|
+
const log = (m) => process.stdout.write(`[obzerver] ${m}\n`);
|
|
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));
|
|
63
|
+
const mcp = mcpHandler(db);
|
|
64
|
+
const secret = getSetting(root, 'session_secret') ?? crypto.randomBytes(32).toString('hex');
|
|
65
|
+
const app = Fastify({ logger: config.logger, bodyLimit: 25 * 1024 * 1024, trustProxy: true });
|
|
66
|
+
// ---------------------------------------------------------------- auth
|
|
67
|
+
const sign = (exp) => `${exp}.${crypto.createHmac('sha256', secret).update(String(exp)).digest('hex')}`;
|
|
68
|
+
const validSession = (cookie) => {
|
|
69
|
+
const m = cookie ? /(?:^|;\s*)obz_session=([^;]+)/.exec(cookie) : null;
|
|
70
|
+
if (!m)
|
|
71
|
+
return false;
|
|
72
|
+
const [exp] = m[1].split('.');
|
|
73
|
+
const expected = sign(exp);
|
|
74
|
+
return Number(exp) > Date.now() && m[1].length === expected.length && crypto.timingSafeEqual(Buffer.from(m[1]), Buffer.from(expected));
|
|
75
|
+
};
|
|
76
|
+
app.addHook('onRequest', async (req, reply) => {
|
|
77
|
+
if (!req.url.startsWith('/api/') || req.url.startsWith('/api/auth') || req.url.startsWith('/api/public/') || req.url.startsWith('/api/integrations/') || !config.password)
|
|
78
|
+
return;
|
|
79
|
+
if (!validSession(req.headers.cookie))
|
|
80
|
+
await reply.code(401).send({ error: 'unauthorized' });
|
|
81
|
+
});
|
|
82
|
+
// Liveness/readiness for Docker, Kubernetes and load balancers. Never needs the dashboard password.
|
|
83
|
+
const started = Date.now();
|
|
84
|
+
app.get('/healthz', async (_req, reply) => {
|
|
85
|
+
try {
|
|
86
|
+
db.get('SELECT 1');
|
|
87
|
+
return { ok: true, version: VERSION, uptime: Math.round((Date.now() - started) / 1000) };
|
|
88
|
+
}
|
|
89
|
+
catch (e) {
|
|
90
|
+
return reply.code(503).send({ ok: false, version: VERSION, error: e.message });
|
|
91
|
+
}
|
|
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
|
+
});
|
|
143
|
+
app.get('/api/auth', async (req) => ({ required: !!config.password, ok: !config.password || validSession(req.headers.cookie) }));
|
|
144
|
+
app.post('/api/auth/login', async (req, reply) => {
|
|
145
|
+
const a = Buffer.from(String(req.body?.password || ''));
|
|
146
|
+
const b = Buffer.from(config.password);
|
|
147
|
+
if (!config.password || (a.length === b.length && crypto.timingSafeEqual(a, b))) {
|
|
148
|
+
reply.header('set-cookie', `obz_session=${sign(Date.now() + 30 * 86400e3)}; HttpOnly; Path=/; SameSite=Lax; Max-Age=${30 * 86400}`);
|
|
149
|
+
return { ok: true };
|
|
150
|
+
}
|
|
151
|
+
return reply.code(401).send({ ok: false });
|
|
152
|
+
});
|
|
153
|
+
app.post('/api/auth/logout', async (_req, reply) => { reply.header('set-cookie', 'obz_session=; Path=/; Max-Age=0'); return { ok: true }; });
|
|
154
|
+
// ---------------------------------------------------------------- ingest
|
|
155
|
+
// Last-used stamps are written at most once a minute per key.
|
|
156
|
+
const lastUsed = new Map();
|
|
157
|
+
await app.register(async (scope) => {
|
|
158
|
+
scope.addHook('preParsing', async (req, _reply, payload) => {
|
|
159
|
+
if (req.headers['content-encoding'] !== 'gzip')
|
|
160
|
+
return payload;
|
|
161
|
+
delete req.headers['content-length'];
|
|
162
|
+
return payload.pipe(zlib.createGunzip());
|
|
163
|
+
});
|
|
164
|
+
scope.post('/v1/ingest', async (req, reply) => {
|
|
165
|
+
const header = req.headers['x-obzerver-key'];
|
|
166
|
+
const key = (Array.isArray(header) ? header[0] : header) || (req.headers.authorization || '').replace(/^Bearer\s+/i, '');
|
|
167
|
+
const slug = projects.byIngestKey(key) ?? (config.openIngest ? DEFAULT_PROJECT : null);
|
|
168
|
+
if (!slug)
|
|
169
|
+
return reply.code(401).send({ error: 'invalid app key' });
|
|
170
|
+
if (!req.body || typeof req.body !== 'object')
|
|
171
|
+
return reply.code(400).send({ error: 'expected JSON 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
|
+
});
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
// ---------------------------------------------------------------- MCP
|
|
184
|
+
app.post('/mcp', async (req, reply) => {
|
|
185
|
+
const token = (req.headers.authorization || '').replace(/^Bearer\s+/i, '');
|
|
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)
|
|
189
|
+
return reply.code(401).send({ jsonrpc: '2.0', id: null, error: { code: -32001, message: 'Unauthorized: pass the MCP token as a Bearer token' } });
|
|
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
|
+
});
|
|
199
|
+
});
|
|
200
|
+
const notAllowed = async (_req, reply) => reply.code(405).header('allow', 'POST').send();
|
|
201
|
+
app.get('/mcp', notAllowed);
|
|
202
|
+
app.delete('/mcp', notAllowed);
|
|
203
|
+
// ---------------------------------------------------------------- read API
|
|
204
|
+
const w = (q) => Q.windowOf(q);
|
|
205
|
+
const notFound = (reply) => reply.code(404).send({ error: 'not found' });
|
|
206
|
+
app.get('/api/health', async () => ({ ok: true }));
|
|
207
|
+
app.get('/api/meta', async () => Q.meta(db));
|
|
208
|
+
app.get('/api/overview', async (req) => Q.overview(db, w(req.query)));
|
|
209
|
+
app.get('/api/operations', async (req) => Q.operations(db, w(req.query), req.query.kind || 'http'));
|
|
210
|
+
app.get('/api/operation', async (req, reply) => {
|
|
211
|
+
const { name, kind, service, sort, filter, limit, offset } = req.query;
|
|
212
|
+
if (!name)
|
|
213
|
+
return reply.code(400).send({ error: 'name required' });
|
|
214
|
+
return Q.operation(db, w(req.query), { name, kind: kind || 'http', service, sort, filter, limit, offset });
|
|
215
|
+
});
|
|
216
|
+
app.get('/api/executions/:id', async (req, reply) => Q.execution(db, req.params.id) ?? notFound(reply));
|
|
217
|
+
app.get('/api/executions/:id/prompt', async (req, reply) => {
|
|
218
|
+
const prompt = Q.agentPrompt(db, req.params.id);
|
|
219
|
+
return prompt ? { prompt } : notFound(reply);
|
|
220
|
+
});
|
|
221
|
+
app.get('/api/traces', async (req) => Q.traces(db, w(req.query), { q: req.query.q, failed: req.query.failed, minDuration: req.query.minDuration, kind: req.query.kind, limit: req.query.limit }));
|
|
222
|
+
app.get('/api/traces/:traceId', async (req, reply) => Q.traceById(db, req.params.traceId) ?? notFound(reply));
|
|
223
|
+
app.get('/api/errors', async (req) => Q.errorGroups(db, w(req.query), { handled: req.query.handled ?? '0', status: req.query.status }));
|
|
224
|
+
app.get('/api/errors/:fp', async (req, reply) => Q.errorGroup(db, w(req.query), req.params.fp) ?? notFound(reply));
|
|
225
|
+
app.patch('/api/errors/:fp', async (req) => {
|
|
226
|
+
const status = ['open', 'resolved', 'ignored'].includes(req.body?.status ?? '') ? req.body.status : 'open';
|
|
227
|
+
db.run('UPDATE error_groups SET status = ?, resolved_at = ? WHERE fingerprint = ?', status, status === 'resolved' ? Date.now() : null, req.params.fp);
|
|
228
|
+
return { ok: true };
|
|
229
|
+
});
|
|
230
|
+
app.get('/api/logs', async (req) => Q.logs(db, w(req.query), { level: req.query.level, q: req.query.q, traceId: req.query.traceId, before: req.query.before, limit: req.query.limit }));
|
|
231
|
+
app.get('/api/functions', async (req) => Q.functions(db, w(req.query)));
|
|
232
|
+
app.get('/api/queries', async (req) => Q.queries(db, w(req.query)));
|
|
233
|
+
app.get('/api/outbound', async (req) => Q.outbound(db, w(req.query)));
|
|
234
|
+
app.get('/api/users', async (req) => Q.users(db, w(req.query), { groupBy: req.query.groupBy }));
|
|
235
|
+
app.get('/api/users/:id', async (req) => Q.user(db, w(req.query), req.params.id));
|
|
236
|
+
app.get('/api/runtime', async (req) => Q.runtime(db, w(req.query)));
|
|
237
|
+
app.get('/api/runtime/spike', async (req) => Q.runtimeSpike(db, { service: req.query.service || '', instance: req.query.instance, ts: Number(req.query.ts), windowMs: Number(req.query.windowMs) || 60000 }));
|
|
238
|
+
app.get('/api/metrics', async (req) => Q.metricsList(db, w(req.query)));
|
|
239
|
+
app.get('/api/metrics/:name', async (req) => Q.metricSeries(db, w(req.query), req.params.name));
|
|
240
|
+
app.get('/api/releases', async (req) => Q.releases(db, w(req.query)));
|
|
241
|
+
app.get('/api/releases/:service/:version', async (req, reply) => Q.releaseVerdict(db, req.params.service, req.params.version) ?? notFound(reply));
|
|
242
|
+
app.get('/api/map', async (req) => Q.serviceMap(db, w(req.query)));
|
|
243
|
+
// ---------------------------------------------------------------- alerts
|
|
244
|
+
const ruleRow = (r) => ({ ...r, ...toRule(r) });
|
|
245
|
+
app.get('/api/alerts', async () => ({ types: RULE_TYPES, rules: db.all('SELECT * FROM alert_rules ORDER BY id').map(ruleRow) }));
|
|
246
|
+
app.get('/api/alerts/events', async (req) => db.all(`SELECT e.*, r.name rule, r.type FROM alert_events e LEFT JOIN alert_rules r ON r.id = e.rule_id
|
|
247
|
+
${req.query.rule ? 'WHERE e.rule_id = ?' : ''} ORDER BY e.ts DESC LIMIT 200`, ...(req.query.rule ? [Number(req.query.rule)] : []))
|
|
248
|
+
.map((e) => ({ ...e, deliveries: JSON.parse(e.deliveries || '[]') })));
|
|
249
|
+
app.post('/api/alerts/events/read', async () => { db.run('UPDATE alert_events SET read = 1 WHERE read = 0'); return { ok: true }; });
|
|
250
|
+
const saveRule = (b = {}, id) => {
|
|
251
|
+
if (!isRuleType(b.type))
|
|
252
|
+
throw badRequest('unknown rule type');
|
|
253
|
+
const vals = [String(b.name || RULE_TYPES[b.type].label), b.type, JSON.stringify(b.params || {}), JSON.stringify(b.channels || [{ type: 'inapp' }]), b.enabled === false ? 0 : 1, b.create_issue ? 1 : 0];
|
|
254
|
+
if (id) {
|
|
255
|
+
db.run('UPDATE alert_rules SET name = ?, type = ?, params = ?, channels = ?, enabled = ?, create_issue = ? WHERE id = ?', ...vals, id);
|
|
256
|
+
return id;
|
|
257
|
+
}
|
|
258
|
+
return db.run('INSERT INTO alert_rules(name, type, params, channels, enabled, create_issue, created) VALUES(?, ?, ?, ?, ?, ?, ?)', ...vals, Date.now()).lastId;
|
|
259
|
+
};
|
|
260
|
+
app.post('/api/alerts', async (req) => ({ id: saveRule(req.body) }));
|
|
261
|
+
app.put('/api/alerts/:id', async (req) => ({ id: saveRule(req.body, Number(req.params.id)) }));
|
|
262
|
+
app.delete('/api/alerts/:id', async (req) => { db.run('DELETE FROM alert_rules WHERE id = ?', Number(req.params.id)); return { ok: true }; });
|
|
263
|
+
app.post('/api/alerts/:id/test', async (req, reply) => {
|
|
264
|
+
const r = db.get('SELECT * FROM alert_rules WHERE id = ?', Number(req.params.id));
|
|
265
|
+
return r ? { deliveries: await alerts.test(toRule(r)) } : notFound(reply);
|
|
266
|
+
});
|
|
267
|
+
app.post('/api/alerts/evaluate', async () => { await alerts.evaluate(); return { ok: true }; });
|
|
268
|
+
// ---------------------------------------------------------------- issues
|
|
269
|
+
app.get('/api/issues', async (req) => db.all(`SELECT * FROM issues ${req.query.status ? 'WHERE status = ?' : ''}
|
|
270
|
+
ORDER BY CASE status WHEN 'open' THEN 0 WHEN 'in_progress' THEN 1 WHEN 'verifying' THEN 2 ELSE 3 END, updated DESC`, ...(req.query.status ? [req.query.status] : [])).map(issueRow));
|
|
271
|
+
app.get('/api/issues/:id', async (req, reply) => {
|
|
272
|
+
const r = db.get('SELECT * FROM issues WHERE id = ?', Number(req.params.id));
|
|
273
|
+
if (!r)
|
|
274
|
+
return notFound(reply);
|
|
275
|
+
const issue = issueRow(r);
|
|
276
|
+
let incident = null;
|
|
277
|
+
if (issue.sourceType === 'error' && issue.sourceRef) {
|
|
278
|
+
const g = db.get('SELECT * FROM error_groups WHERE fingerprint = ?', issue.sourceRef);
|
|
279
|
+
if (g) {
|
|
280
|
+
const users = db.all('SELECT DISTINCT user_id FROM errors WHERE fingerprint = ? AND user_id IS NOT NULL LIMIT 200', issue.sourceRef).map((x) => x.user_id);
|
|
281
|
+
incident = {
|
|
282
|
+
error: `${g.class}: ${g.message}`, operation: g.operation, start: g.first_seen, end: g.status === 'resolved' ? g.resolved_at : null,
|
|
283
|
+
lastSeen: g.last_seen, introducedIn: g.first_version, occurrences: g.count, users,
|
|
284
|
+
customers: [...new Set(users.filter((u) => u.includes('@')).map((u) => u.split('@')[1]))],
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return { ...issue, incident };
|
|
289
|
+
});
|
|
290
|
+
const appendTimeline = (timeline, text) => {
|
|
291
|
+
let t = [];
|
|
292
|
+
try {
|
|
293
|
+
t = JSON.parse(timeline || '[]');
|
|
294
|
+
}
|
|
295
|
+
catch { /* reset */ }
|
|
296
|
+
t.push({ ts: Date.now(), text });
|
|
297
|
+
return JSON.stringify(t);
|
|
298
|
+
};
|
|
299
|
+
app.post('/api/issues', async (req) => {
|
|
300
|
+
const b = req.body || {};
|
|
301
|
+
const now = Date.now();
|
|
302
|
+
const r = db.run(`INSERT INTO issues(title, status, severity, owner, due, description, source_type, source_ref, service, created, updated, timeline)
|
|
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}` : ''}` }]));
|
|
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 };
|
|
317
|
+
});
|
|
318
|
+
app.patch('/api/issues/:id', async (req, reply) => {
|
|
319
|
+
const r = db.get('SELECT * FROM issues WHERE id = ?', Number(req.params.id));
|
|
320
|
+
if (!r)
|
|
321
|
+
return notFound(reply);
|
|
322
|
+
const b = req.body || {};
|
|
323
|
+
const fields = { title: 'title', status: 'status', severity: 'severity', owner: 'owner', due: 'due', description: 'description', fixVersion: 'fix_version' };
|
|
324
|
+
const changes = [];
|
|
325
|
+
for (const [key, col] of Object.entries(fields)) {
|
|
326
|
+
const v = b[key];
|
|
327
|
+
if (v === undefined || v === r[col])
|
|
328
|
+
continue;
|
|
329
|
+
changes.push(`${col.replace('_', ' ')} → ${v ?? '—'}`);
|
|
330
|
+
db.run(`UPDATE issues SET ${col} = ? WHERE id = ?`, v, r.id);
|
|
331
|
+
}
|
|
332
|
+
const resolving = (b.status === 'resolved' || b.status === 'verifying') && !['verifying', 'resolved', 'closed'].includes(r.status);
|
|
333
|
+
if (b.status === 'resolved' || b.status === 'verifying') {
|
|
334
|
+
const measurable = MEASURABLE.has(r.source_type);
|
|
335
|
+
db.run('UPDATE issues SET status = ?, resolved_at = ? WHERE id = ?', measurable ? 'verifying' : 'resolved', Date.now(), r.id);
|
|
336
|
+
if (measurable)
|
|
337
|
+
changes.push('verification started');
|
|
338
|
+
}
|
|
339
|
+
if (b.comment)
|
|
340
|
+
changes.push(`comment: ${b.comment}`);
|
|
341
|
+
const timeline = changes.length ? appendTimeline(r.timeline, changes.join('; ')) : r.timeline;
|
|
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));
|
|
374
|
+
return { ok: true };
|
|
375
|
+
});
|
|
376
|
+
app.delete('/api/issues/:id', async (req) => { db.run('DELETE FROM issues WHERE id = ?', Number(req.params.id)); return { ok: true }; });
|
|
377
|
+
app.get('/api/issues/:id/verify', async (req) => verifyFix(db, req.params.id, req.query.version));
|
|
378
|
+
// ---------------------------------------------------------------- SLOs
|
|
379
|
+
app.get('/api/slos', async () => listSlos(db));
|
|
380
|
+
app.get('/api/slos/:id', async (req, reply) => {
|
|
381
|
+
const r = db.get('SELECT * FROM slos WHERE id = ?', Number(req.params.id));
|
|
382
|
+
if (!r)
|
|
383
|
+
return notFound(reply);
|
|
384
|
+
const slo = toSlo(r);
|
|
385
|
+
const rules = burnRulesFor(db, slo.id).map(ruleRow);
|
|
386
|
+
const ids = rules.map((x) => x.id);
|
|
387
|
+
const events = ids.length ? db.all(`SELECT e.*, r.name rule FROM alert_events e LEFT JOIN alert_rules r ON r.id = e.rule_id WHERE e.rule_id IN (${ids.map(() => '?').join(',')}) ORDER BY e.ts DESC LIMIT 50`, ...ids) : [];
|
|
388
|
+
return { ...sloStatus(db, slo, Date.now(), rules.some((x) => x.state === 'firing')), history: sloHistory(db, slo), rules, events, retentionDays: config.retentionDays };
|
|
389
|
+
});
|
|
390
|
+
app.post('/api/slos', async (req, reply) => {
|
|
391
|
+
const err = validateSlo(req.body || {});
|
|
392
|
+
return err ? reply.code(400).send({ error: err }) : { id: saveSlo(db, req.body) };
|
|
393
|
+
});
|
|
394
|
+
app.put('/api/slos/:id', async (req, reply) => {
|
|
395
|
+
if (!db.get('SELECT id FROM slos WHERE id = ?', Number(req.params.id)))
|
|
396
|
+
return notFound(reply);
|
|
397
|
+
const err = validateSlo(req.body || {});
|
|
398
|
+
return err ? reply.code(400).send({ error: err }) : { id: saveSlo(db, req.body, Number(req.params.id)) };
|
|
399
|
+
});
|
|
400
|
+
app.delete('/api/slos/:id', async (req) => { deleteSlo(db, Number(req.params.id)); return { ok: true }; });
|
|
401
|
+
// ---------------------------------------------------------------- status pages
|
|
402
|
+
const summary = (row) => {
|
|
403
|
+
const v = pageView(db, toPage(row));
|
|
404
|
+
return { ...v.page, overall: v.overall, activeIncidents: v.active.length, components: v.components.map(({ days: _d, ...c }) => c) };
|
|
405
|
+
};
|
|
406
|
+
app.get('/api/status-pages', async () => db.all('SELECT * FROM status_pages ORDER BY title').map(summary));
|
|
407
|
+
app.get('/api/status-pages/:id', async (req, reply) => {
|
|
408
|
+
const r = db.get('SELECT * FROM status_pages WHERE id = ?', Number(req.params.id));
|
|
409
|
+
if (!r)
|
|
410
|
+
return notFound(reply);
|
|
411
|
+
const v = pageView(db, toPage(r));
|
|
412
|
+
const incidents = db.all('SELECT * FROM incidents WHERE page_id = ? ORDER BY created DESC LIMIT 100', r.id).map(toIncident);
|
|
413
|
+
return { ...v, incidents, publicUrl: `${config.publicUrl || ''}/status/${v.page.slug}` };
|
|
414
|
+
});
|
|
415
|
+
app.post('/api/status-pages', async (req, reply) => {
|
|
416
|
+
const err = validatePage(db, req.body || {}) || slugTakenElsewhere(req.body?.slug || req.body?.title);
|
|
417
|
+
return err ? reply.code(400).send({ error: err }) : { id: savePage(db, req.body) };
|
|
418
|
+
});
|
|
419
|
+
app.put('/api/status-pages/:id', async (req, reply) => {
|
|
420
|
+
const id = Number(req.params.id);
|
|
421
|
+
if (!db.get('SELECT id FROM status_pages WHERE id = ?', id))
|
|
422
|
+
return notFound(reply);
|
|
423
|
+
const err = validatePage(db, req.body || {}, id) || slugTakenElsewhere(req.body?.slug || req.body?.title);
|
|
424
|
+
return err ? reply.code(400).send({ error: err }) : { id: savePage(db, req.body, id) };
|
|
425
|
+
});
|
|
426
|
+
app.delete('/api/status-pages/:id', async (req) => { deletePage(db, Number(req.params.id)); return { ok: true }; });
|
|
427
|
+
app.post('/api/status-pages/:id/incidents', async (req, reply) => {
|
|
428
|
+
const id = Number(req.params.id);
|
|
429
|
+
if (!db.get('SELECT id FROM status_pages WHERE id = ?', id))
|
|
430
|
+
return notFound(reply);
|
|
431
|
+
if (!req.body?.title?.trim())
|
|
432
|
+
return reply.code(400).send({ error: 'title is required' });
|
|
433
|
+
return { id: createIncident(db, id, { ...req.body, title: req.body.title }) };
|
|
434
|
+
});
|
|
435
|
+
app.patch('/api/incidents/:id', async (req, reply) => (updateIncident(db, Number(req.params.id), req.body || {}) ? { ok: true } : notFound(reply)));
|
|
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;
|
|
447
|
+
// Public, unauthenticated: only published pages, only names and states.
|
|
448
|
+
const publicPage = (slug) => {
|
|
449
|
+
const r = db.get('SELECT * FROM status_pages WHERE slug = ? AND published = 1', slug);
|
|
450
|
+
return r ? publicView(pageView(db, toPage(r))) : null;
|
|
451
|
+
};
|
|
452
|
+
app.get('/api/public/status/:slug', async (req, reply) => {
|
|
453
|
+
const project = projectOfPage(req.params.slug);
|
|
454
|
+
const v = project ? projects.run(project, () => publicPage(req.params.slug)) : null;
|
|
455
|
+
if (!v)
|
|
456
|
+
return notFound(reply);
|
|
457
|
+
reply.header('access-control-allow-origin', '*').header('cache-control', 'public, max-age=30');
|
|
458
|
+
return v;
|
|
459
|
+
});
|
|
460
|
+
app.get('/status/:slug', async (req, reply) => {
|
|
461
|
+
const project = projectOfPage(req.params.slug);
|
|
462
|
+
const v = project ? projects.run(project, () => publicPage(req.params.slug)) : null;
|
|
463
|
+
reply.header('cache-control', 'public, max-age=30');
|
|
464
|
+
if (!v)
|
|
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>');
|
|
466
|
+
return reply.type('text/html; charset=utf-8').send(renderStatusHtml(v));
|
|
467
|
+
});
|
|
468
|
+
// ---------------------------------------------------------------- settings
|
|
469
|
+
app.get('/api/settings', async (req) => {
|
|
470
|
+
const origin = config.publicUrl || `${req.protocol}://${req.headers.host}`;
|
|
471
|
+
return {
|
|
472
|
+
endpoint: origin,
|
|
473
|
+
keys: db.all('SELECT id, name, key, created, last_used, revoked FROM keys ORDER BY id'),
|
|
474
|
+
mcp: { url: `${origin}/mcp`, token: getSetting(db, 'mcp_token'), tools: MCP_TOOL_NAMES },
|
|
475
|
+
retentionDays: config.retentionDays,
|
|
476
|
+
email: (() => { const m = mailConfig(root); return { configured: !!m.url, source: m.source, smtp: maskSmtpUrl(m.url), from: m.from }; })(),
|
|
477
|
+
passwordProtected: !!config.password,
|
|
478
|
+
openIngest: config.openIngest,
|
|
479
|
+
};
|
|
480
|
+
});
|
|
481
|
+
app.post('/api/keys', async (req) => {
|
|
482
|
+
const key = randomKey('obz_live');
|
|
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 };
|
|
486
|
+
});
|
|
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 }; });
|
|
488
|
+
app.put('/api/settings/email', async (req, reply) => {
|
|
489
|
+
if (mailConfig(root).source === 'env')
|
|
490
|
+
return reply.code(409).send({ error: 'Email is configured with OBZERVER_SMTP_URL; change it there' });
|
|
491
|
+
const url = String(req.body?.smtpUrl || '').trim();
|
|
492
|
+
if (url && !/^smtps?:\/\//.test(url))
|
|
493
|
+
return reply.code(400).send({ error: 'SMTP URL must start with smtp:// or smtps://' });
|
|
494
|
+
// An unchanged masked URL means "keep the stored one".
|
|
495
|
+
if (!url.includes('••••'))
|
|
496
|
+
setSetting(root, 'smtp_url', url);
|
|
497
|
+
setSetting(root, 'mail_from', String(req.body?.from || '').trim());
|
|
498
|
+
resetMailTransports();
|
|
499
|
+
return { ok: true };
|
|
500
|
+
});
|
|
501
|
+
app.post('/api/settings/email/test', async (req, reply) => {
|
|
502
|
+
const to = parseRecipients(req.body?.to);
|
|
503
|
+
if (!to.length)
|
|
504
|
+
return reply.code(400).send({ error: 'Enter at least one valid email address' });
|
|
505
|
+
try {
|
|
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() }) });
|
|
507
|
+
return { ok: true, messageId: r.messageId };
|
|
508
|
+
}
|
|
509
|
+
catch (e) {
|
|
510
|
+
return reply.code(502).send({ error: e.message });
|
|
511
|
+
}
|
|
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
|
+
});
|
|
586
|
+
app.post('/api/settings/mcp-token', async () => { const token = randomKey('obz_mcp'); setSetting(db, 'mcp_token', token); return { token }; });
|
|
587
|
+
// ---------------------------------------------------------------- dashboard
|
|
588
|
+
if (fs.existsSync(path.join(config.publicDir, 'index.html'))) {
|
|
589
|
+
await app.register(fastifyStatic, {
|
|
590
|
+
root: config.publicDir,
|
|
591
|
+
wildcard: true,
|
|
592
|
+
setHeaders: (res, file) => { res.setHeader('cache-control', file.includes(`${path.sep}assets${path.sep}`) ? 'public, max-age=31536000, immutable' : 'no-cache'); },
|
|
593
|
+
});
|
|
594
|
+
app.setNotFoundHandler((req, reply) => {
|
|
595
|
+
if (req.url.startsWith('/api/') || req.url.startsWith('/v1/') || req.url.startsWith('/assets/') || req.url.startsWith('/status/') || req.method !== 'GET')
|
|
596
|
+
return reply.code(404).send({ error: 'not found' });
|
|
597
|
+
reply.header('cache-control', 'no-cache');
|
|
598
|
+
return reply.sendFile('index.html');
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
else {
|
|
602
|
+
app.get('/', async () => ({ name: 'obzerver', note: 'Dashboard not built. Run `npm run build` at the repo root.' }));
|
|
603
|
+
}
|
|
604
|
+
// ---------------------------------------------------------------- background
|
|
605
|
+
const timers = [];
|
|
606
|
+
const every = (ms, fn, label) => {
|
|
607
|
+
const t = setInterval(() => { Promise.resolve().then(fn).catch((e) => log(`${label}: ${e.message}`)); }, ms);
|
|
608
|
+
t.unref();
|
|
609
|
+
timers.push(t);
|
|
610
|
+
};
|
|
611
|
+
app.addHook('onClose', async () => { for (const t of timers)
|
|
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}`));
|
|
615
|
+
return {
|
|
616
|
+
app, db: root, config, alerts, ingest, projects,
|
|
617
|
+
async listen() {
|
|
618
|
+
await app.listen({ port: config.port, host: config.host });
|
|
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');
|
|
624
|
+
return app;
|
|
625
|
+
},
|
|
626
|
+
};
|
|
627
|
+
}
|
|
628
|
+
//# sourceMappingURL=server.js.map
|