@obzerver/server 0.10.1 → 0.11.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/cli.js +89 -18
- package/dist/cli.js.map +1 -1
- package/dist/db.d.ts +10 -1
- package/dist/db.js +46 -6
- package/dist/db.js.map +1 -1
- package/dist/keys.d.ts +53 -0
- package/dist/keys.js +54 -0
- package/dist/keys.js.map +1 -0
- package/dist/projects.d.ts +13 -2
- package/dist/projects.js +24 -13
- package/dist/projects.js.map +1 -1
- package/dist/ratelimit.d.ts +17 -0
- package/dist/ratelimit.js +44 -0
- package/dist/ratelimit.js.map +1 -0
- package/dist/server.d.ts +20 -0
- package/dist/server.js +160 -41
- package/dist/server.js.map +1 -1
- package/package.json +5 -4
- package/public/assets/index-D1q02VSn.css +2 -0
- package/public/assets/index-HhyoqQPd.js +114 -0
- package/public/index.html +2 -2
- package/public/assets/index-B79X5QQA.js +0 -114
- package/public/assets/index-DwAs5ZtU.css +0 -2
package/dist/projects.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"projects.js","sourceRoot":"","sources":["../src/projects.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,8FAA8F;AAC9F,0BAA0B;AAC1B,EAAE;AACF,oGAAoG;AACpG,wGAAwG;AACxG,sGAAsG;AACtG,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,EAAE,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"projects.js","sourceRoot":"","sources":["../src/projects.ts"],"names":[],"mappings":"AAAA,mGAAmG;AACnG,8FAA8F;AAC9F,0BAA0B;AAC1B,EAAE;AACF,oGAAoG;AACpG,wGAAwG;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|
+
}
|
|
5
|
+
export declare class RateLimiter {
|
|
6
|
+
private readonly bucket;
|
|
7
|
+
private readonly buckets;
|
|
8
|
+
private sweeps;
|
|
9
|
+
constructor(bucket: Bucket);
|
|
10
|
+
/** Use one token for `key`. Returns 0 when allowed, otherwise seconds until a token is available. */
|
|
11
|
+
take(key: string, now?: number, cost?: number): number;
|
|
12
|
+
/** Seconds until `key` may try again, without using a token. */
|
|
13
|
+
peek(key: string, now?: number): number;
|
|
14
|
+
reset(key: string): void;
|
|
15
|
+
/** Forget buckets that have refilled completely. */
|
|
16
|
+
private sweep;
|
|
17
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// In-memory rate limits (one server process; nothing to configure). Token buckets: `capacity` requests
|
|
2
|
+
// at once, refilled at `perSecond`. take() says whether a request may go ahead, and if not, when to retry.
|
|
3
|
+
export class RateLimiter {
|
|
4
|
+
bucket;
|
|
5
|
+
buckets = new Map();
|
|
6
|
+
sweeps = 0;
|
|
7
|
+
constructor(bucket) {
|
|
8
|
+
this.bucket = bucket;
|
|
9
|
+
}
|
|
10
|
+
/** Use one token for `key`. Returns 0 when allowed, otherwise seconds until a token is available. */
|
|
11
|
+
take(key, now = Date.now(), cost = 1) {
|
|
12
|
+
const { capacity, perSecond } = this.bucket;
|
|
13
|
+
if (!(capacity > 0) || !(perSecond > 0))
|
|
14
|
+
return 0;
|
|
15
|
+
const b = this.buckets.get(key) ?? { tokens: capacity, at: now };
|
|
16
|
+
b.tokens = Math.min(capacity, b.tokens + ((now - b.at) / 1000) * perSecond);
|
|
17
|
+
b.at = now;
|
|
18
|
+
this.buckets.set(key, b);
|
|
19
|
+
if (++this.sweeps % 1000 === 0)
|
|
20
|
+
this.sweep(now);
|
|
21
|
+
if (b.tokens >= cost) {
|
|
22
|
+
b.tokens -= cost;
|
|
23
|
+
return 0;
|
|
24
|
+
}
|
|
25
|
+
return Math.max(1, Math.ceil((cost - b.tokens) / perSecond));
|
|
26
|
+
}
|
|
27
|
+
/** Seconds until `key` may try again, without using a token. */
|
|
28
|
+
peek(key, now = Date.now()) {
|
|
29
|
+
const b = this.buckets.get(key);
|
|
30
|
+
if (!b)
|
|
31
|
+
return 0;
|
|
32
|
+
const tokens = Math.min(this.bucket.capacity, b.tokens + ((now - b.at) / 1000) * this.bucket.perSecond);
|
|
33
|
+
return tokens >= 1 ? 0 : Math.max(1, Math.ceil((1 - tokens) / this.bucket.perSecond));
|
|
34
|
+
}
|
|
35
|
+
reset(key) { this.buckets.delete(key); }
|
|
36
|
+
/** Forget buckets that have refilled completely. */
|
|
37
|
+
sweep(now) {
|
|
38
|
+
const full = this.bucket.capacity / this.bucket.perSecond * 1000;
|
|
39
|
+
for (const [k, b] of this.buckets)
|
|
40
|
+
if (now - b.at > full)
|
|
41
|
+
this.buckets.delete(k);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=ratelimit.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ratelimit.js","sourceRoot":"","sources":["../src/ratelimit.ts"],"names":[],"mappings":"AAAA,uGAAuG;AACvG,2GAA2G;AAI3G,MAAM,OAAO,WAAW;IAIO;IAHZ,OAAO,GAAG,IAAI,GAAG,EAA0C,CAAC;IACrE,MAAM,GAAG,CAAC,CAAC;IAEnB,YAA6B,MAAc;QAAd,WAAM,GAAN,MAAM,CAAQ;IAAG,CAAC;IAE/C,qGAAqG;IACrG,IAAI,CAAC,GAAW,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,EAAE,IAAI,GAAG,CAAC;QAC1C,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC;QAC5C,IAAI,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC;YAAE,OAAO,CAAC,CAAC;QAClD,MAAM,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG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C,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC;IACxF,CAAC;IAED,KAAK,CAAC,GAAW,IAAU,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IAEtD,oDAAoD;IAC5C,KAAK,CAAC,GAAW;QACvB,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC;QACjE,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,IAAI,CAAC,OAAO;YAAE,IAAI,GAAG,GAAG,CAAC,CAAC,EAAE,GAAG,IAAI;gBAAE,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACnF,CAAC;CACF"}
|
package/dist/server.d.ts
CHANGED
|
@@ -8,7 +8,19 @@ export interface ServerOptions {
|
|
|
8
8
|
host?: string;
|
|
9
9
|
dbFile?: string;
|
|
10
10
|
password?: string;
|
|
11
|
+
/** SHA-256 of the dashboard password, when it is stored rather than passed in. */
|
|
12
|
+
passwordHash?: string | null;
|
|
13
|
+
/**
|
|
14
|
+
* Never serve an open dashboard on a network address: with no OBZERVER_PASSWORD, use the stored password or
|
|
15
|
+
* generate one (ObzerverServer.generatedPassword). The CLI and the Docker image turn this on.
|
|
16
|
+
* OBZERVER_PASSWORD=off opts out; listening on localhost needs no password.
|
|
17
|
+
*/
|
|
18
|
+
requirePassword?: boolean;
|
|
11
19
|
openIngest?: boolean;
|
|
20
|
+
/** Telemetry requests per second per ingest key (burst: 10× that). 0 turns the limit off. OBZERVER_INGEST_RATE, default 20. */
|
|
21
|
+
ingestRate?: number | string;
|
|
22
|
+
/** Which proxies may set X-Forwarded-For: true, false, or addresses/CIDRs. OBZERVER_TRUST_PROXY, default private networks. */
|
|
23
|
+
trustProxy?: boolean | string;
|
|
12
24
|
retentionDays?: number | string;
|
|
13
25
|
/** How long long-term roll-ups are kept, in days. Default 400 (OBZERVER_HISTORY_DAYS). */
|
|
14
26
|
historyDays?: number | string;
|
|
@@ -40,6 +52,8 @@ export interface ServerConfig {
|
|
|
40
52
|
logger: boolean;
|
|
41
53
|
publicDir: string;
|
|
42
54
|
dashboardMode: 'simple' | 'advanced';
|
|
55
|
+
ingestRate: number;
|
|
56
|
+
trustProxy: boolean | string;
|
|
43
57
|
}
|
|
44
58
|
export interface ObzerverServer {
|
|
45
59
|
app: FastifyInstance;
|
|
@@ -49,6 +63,12 @@ export interface ObzerverServer {
|
|
|
49
63
|
/** Ingest into the default project. */
|
|
50
64
|
ingest: Ingest;
|
|
51
65
|
projects: Projects;
|
|
66
|
+
/** A dashboard password generated on this start (shown once; only its hash is kept). */
|
|
67
|
+
generatedPassword: string | null;
|
|
68
|
+
/** Where the dashboard password comes from: env (OBZERVER_PASSWORD), stored (generated or set with `obzerver password`), or none. */
|
|
69
|
+
passwordSource: 'env' | 'stored' | 'none';
|
|
52
70
|
listen(): Promise<FastifyInstance>;
|
|
53
71
|
}
|
|
72
|
+
/** A password people can type: 4 groups of 5 letters and digits (about 100 bits). */
|
|
73
|
+
export declare function newPassword(): string;
|
|
54
74
|
export declare function createServer(opts?: ServerOptions): Promise<ObzerverServer>;
|
package/dist/server.js
CHANGED
|
@@ -8,7 +8,9 @@ import path from 'node:path';
|
|
|
8
8
|
import { fileURLToPath } from 'node:url';
|
|
9
9
|
import { openSecretCount, secretFindings, secretGroups } from './secrets.js';
|
|
10
10
|
import { baseline, history, historyInfo, historyTick, typical } from './history.js';
|
|
11
|
-
import { getSetting, setSetting,
|
|
11
|
+
import { getSetting, setSetting, retention, hashSecret, newMcpToken } from './db.js';
|
|
12
|
+
import { createKey, listKeys, revokeKey, rotateKey, KeyError } from './keys.js';
|
|
13
|
+
import { RateLimiter } from './ratelimit.js';
|
|
12
14
|
import { Projects, ProjectError, DEFAULT_PROJECT, currentProjectSlug } from './projects.js';
|
|
13
15
|
import { aiConfig, publicAiConfig, saveAiConfig, configFromInput, testAi, ask, AiError } from './ai.js';
|
|
14
16
|
import { createIngest } from './ingest.js';
|
|
@@ -22,6 +24,13 @@ import { listSlos, sloStatus, sloHistory, saveSlo, deleteSlo, validateSlo, toSlo
|
|
|
22
24
|
import { slugify as slugifyPage, toPage, toIncident, validatePage, savePage, deletePage, createIncident, updateIncident, pageView, publicView, renderStatusHtml, runAutoIncidents } from './status.js';
|
|
23
25
|
import { mailConfig, maskSmtpUrl, parseRecipients, sendMail, resetMailTransports, alertEmail } from './mailer.js';
|
|
24
26
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
27
|
+
const isLoopback = (host) => ['127.0.0.1', '::1', 'localhost'].includes(host) || host.startsWith('127.');
|
|
28
|
+
/** A password people can type: 4 groups of 5 letters and digits (about 100 bits). */
|
|
29
|
+
export function newPassword() {
|
|
30
|
+
const abc = 'abcdefghjkmnpqrstuvwxyz23456789';
|
|
31
|
+
const bytes = crypto.randomBytes(20);
|
|
32
|
+
return Array.from(bytes, (b) => abc[b % abc.length]).join('').match(/.{5}/g).join('-');
|
|
33
|
+
}
|
|
25
34
|
const badRequest = (msg) => Object.assign(new Error(msg), { statusCode: 400 });
|
|
26
35
|
export async function createServer(opts = {}) {
|
|
27
36
|
// Empty env vars (common with docker compose `${VAR:-}` and Kubernetes) count as unset.
|
|
@@ -43,6 +52,13 @@ export async function createServer(opts = {}) {
|
|
|
43
52
|
logger: opts.logger ?? false,
|
|
44
53
|
publicDir: opts.publicDir ?? path.resolve(here, '../public'),
|
|
45
54
|
dashboardMode: (opts.dashboardMode ?? env.OBZERVER_DASHBOARD_MODE) === 'advanced' ? 'advanced' : 'simple',
|
|
55
|
+
ingestRate: (() => { const v = Number(opts.ingestRate ?? env.OBZERVER_INGEST_RATE ?? 20); return Number.isFinite(v) && v >= 0 ? v : 20; })(),
|
|
56
|
+
trustProxy: (() => {
|
|
57
|
+
const v = opts.trustProxy ?? env.OBZERVER_TRUST_PROXY;
|
|
58
|
+
if (v === undefined)
|
|
59
|
+
return 'loopback,linklocal,uniquelocal';
|
|
60
|
+
return v === true || v === 'true' ? true : v === false || v === 'false' ? false : String(v);
|
|
61
|
+
})(),
|
|
46
62
|
};
|
|
47
63
|
config.historyHourlyDays = Math.min(config.historyHourlyDays, config.historyDays);
|
|
48
64
|
const historyCfg = { hourlyDays: config.historyHourlyDays, days: config.historyDays };
|
|
@@ -71,9 +87,24 @@ export async function createServer(opts = {}) {
|
|
|
71
87
|
const ingest = (payload) => projects.run(DEFAULT_PROJECT, () => ingestFor(DEFAULT_PROJECT)(payload));
|
|
72
88
|
const mcp = mcpHandler(db);
|
|
73
89
|
const secret = getSetting(root, 'session_secret') ?? crypto.randomBytes(32).toString('hex');
|
|
74
|
-
const app = Fastify({ logger: config.logger, bodyLimit: 25 * 1024 * 1024, trustProxy:
|
|
90
|
+
const app = Fastify({ logger: config.logger, bodyLimit: 25 * 1024 * 1024, trustProxy: config.trustProxy });
|
|
75
91
|
// ---------------------------------------------------------------- auth
|
|
76
|
-
|
|
92
|
+
// The dashboard password is kept only as a hash. Sessions are signed with it too, so changing the password
|
|
93
|
+
// signs everyone out.
|
|
94
|
+
const passwordOff = /^(off|none|false|disabled)$/i.test(config.password);
|
|
95
|
+
if (passwordOff)
|
|
96
|
+
config.password = '';
|
|
97
|
+
let generatedPassword = null;
|
|
98
|
+
let storedHash = opts.passwordHash || (config.password || passwordOff ? null : getSetting(root, 'password_hash'));
|
|
99
|
+
if (!config.password && !passwordOff && !storedHash && opts.requirePassword && !isLoopback(config.host)) {
|
|
100
|
+
generatedPassword = newPassword();
|
|
101
|
+
storedHash = hashSecret(generatedPassword);
|
|
102
|
+
setSetting(root, 'password_hash', storedHash);
|
|
103
|
+
}
|
|
104
|
+
const passwordSource = config.password ? 'env' : storedHash ? 'stored' : 'none';
|
|
105
|
+
const pwHash = config.password ? hashSecret(config.password) : storedHash;
|
|
106
|
+
const authOn = !!pwHash;
|
|
107
|
+
const sign = (exp) => `${exp}.${crypto.createHmac('sha256', secret + (pwHash ?? '')).update(String(exp)).digest('hex')}`;
|
|
77
108
|
const validSession = (cookie) => {
|
|
78
109
|
const m = cookie ? /(?:^|;\s*)obz_session=([^;]+)/.exec(cookie) : null;
|
|
79
110
|
if (!m)
|
|
@@ -82,11 +113,54 @@ export async function createServer(opts = {}) {
|
|
|
82
113
|
const expected = sign(exp);
|
|
83
114
|
return Number(exp) > Date.now() && m[1].length === expected.length && crypto.timingSafeEqual(Buffer.from(m[1]), Buffer.from(expected));
|
|
84
115
|
};
|
|
116
|
+
// Rate limits: password guesses per address, wrong keys per address, and requests per key.
|
|
117
|
+
const limits = {
|
|
118
|
+
login: new RateLimiter({ capacity: 10, perSecond: 10 / 900 }), // 10 wrong passwords per 15 minutes
|
|
119
|
+
badKey: new RateLimiter({ capacity: 30, perSecond: 30 / 600 }), // 30 wrong keys or tokens per 10 minutes
|
|
120
|
+
ingest: new RateLimiter({ capacity: config.ingestRate * 10, perSecond: config.ingestRate }),
|
|
121
|
+
read: new RateLimiter({ capacity: 120, perSecond: 10 }),
|
|
122
|
+
};
|
|
123
|
+
const tooMany = (reply, seconds) => reply.code(429).header('retry-after', String(seconds)).send({ error: `Too many requests. Try again in ${seconds} s.` });
|
|
124
|
+
const markUsed = (k) => {
|
|
125
|
+
const now = Date.now();
|
|
126
|
+
const tag = `${k.slug}:${k.id}`;
|
|
127
|
+
if ((lastUsed.get(tag) ?? 0) < now - 60000) {
|
|
128
|
+
lastUsed.set(tag, now);
|
|
129
|
+
projects.db(k.slug).run('UPDATE keys SET last_used = ? WHERE id = ?', now, k.id);
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
// Last-used stamps are written at most once a minute per key.
|
|
133
|
+
const lastUsed = new Map();
|
|
134
|
+
// Read keys: GET-only access to one project's data, never to settings, keys, projects or alert channels.
|
|
135
|
+
const READ_KEY_DENIED = ['/api/settings', '/api/projects', '/api/simple/alerts', '/api/alerts', '/api/ai'];
|
|
136
|
+
const bearerOf = (req) => (req.headers.authorization || '').replace(/^Bearer\s+/i, '').trim();
|
|
85
137
|
app.addHook('onRequest', async (req, reply) => {
|
|
86
|
-
if (!req.url.startsWith('/api/') || req.url.startsWith('/api/auth') || req.url.startsWith('/api/public/') || req.url.startsWith('/api/integrations/')
|
|
138
|
+
if (!req.url.startsWith('/api/') || req.url.startsWith('/api/auth') || req.url.startsWith('/api/public/') || req.url.startsWith('/api/integrations/'))
|
|
87
139
|
return;
|
|
88
|
-
|
|
89
|
-
|
|
140
|
+
const bearer = bearerOf(req);
|
|
141
|
+
if (bearer.startsWith('obz_')) {
|
|
142
|
+
const wait = limits.badKey.peek(req.ip);
|
|
143
|
+
if (wait)
|
|
144
|
+
return tooMany(reply, wait);
|
|
145
|
+
const k = projects.byKey(bearer);
|
|
146
|
+
if (!k || k.kind !== 'read') {
|
|
147
|
+
limits.badKey.take(req.ip);
|
|
148
|
+
return reply.code(401).send({ error: k ? 'Ingest keys only send telemetry. Read the API with a read key (obz_read_…).' : 'Invalid, revoked or expired API key' });
|
|
149
|
+
}
|
|
150
|
+
if (req.method !== 'GET' && req.method !== 'HEAD')
|
|
151
|
+
return reply.code(403).send({ error: 'Read keys can only read (GET requests)' });
|
|
152
|
+
const path = req.url.split('?')[0];
|
|
153
|
+
if (READ_KEY_DENIED.some((p) => path === p || path.startsWith(`${p}/`)))
|
|
154
|
+
return reply.code(403).send({ error: 'Read keys cannot open settings, keys, projects, alert rules or the assistant' });
|
|
155
|
+
const slow = limits.read.take(`${k.slug}:${k.id}`);
|
|
156
|
+
if (slow)
|
|
157
|
+
return tooMany(reply, slow);
|
|
158
|
+
markUsed(k);
|
|
159
|
+
req.keyProject = k.slug;
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
if (authOn && !validSession(req.headers.cookie))
|
|
163
|
+
return reply.code(401).send({ error: 'unauthorized' });
|
|
90
164
|
});
|
|
91
165
|
// Liveness/readiness for Docker, Kubernetes and load balancers. Never needs the dashboard password.
|
|
92
166
|
const started = Date.now();
|
|
@@ -107,7 +181,14 @@ export async function createServer(opts = {}) {
|
|
|
107
181
|
return done();
|
|
108
182
|
const q = req.query?.project;
|
|
109
183
|
const h = req.headers['x-obzerver-project'];
|
|
110
|
-
const
|
|
184
|
+
const asked = (Array.isArray(h) ? h[0] : h) || q;
|
|
185
|
+
// A read key belongs to one project: it decides, and naming another one is refused.
|
|
186
|
+
const keyProject = req.keyProject;
|
|
187
|
+
if (keyProject && asked && asked !== keyProject) {
|
|
188
|
+
reply.code(403).send({ error: `This key belongs to project "${keyProject}"` });
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
const slug = String(keyProject || asked || DEFAULT_PROJECT);
|
|
111
192
|
if (!projects.has(slug)) {
|
|
112
193
|
reply.code(404).send({ error: `Unknown project "${slug}"` });
|
|
113
194
|
return;
|
|
@@ -124,8 +205,9 @@ export async function createServer(opts = {}) {
|
|
|
124
205
|
app.post('/api/projects', async (req, reply) => {
|
|
125
206
|
try {
|
|
126
207
|
const p = projects.create(String(req.body?.name || ''), req.body?.slug || undefined);
|
|
127
|
-
|
|
128
|
-
|
|
208
|
+
// Shown once: only their hashes are stored.
|
|
209
|
+
const first = projects.firstSecrets(p.slug);
|
|
210
|
+
return { ...p, ingestKey: first.ingestKey, mcpToken: first.mcpToken };
|
|
129
211
|
}
|
|
130
212
|
catch (e) {
|
|
131
213
|
return reply.code(e instanceof ProjectError ? e.status : 500).send({ error: e.message });
|
|
@@ -149,21 +231,45 @@ export async function createServer(opts = {}) {
|
|
|
149
231
|
return reply.code(e instanceof ProjectError ? e.status : 500).send({ error: e.message });
|
|
150
232
|
}
|
|
151
233
|
});
|
|
152
|
-
app.get('/api/auth', async (req) => ({ required:
|
|
234
|
+
app.get('/api/auth', async (req) => ({ required: authOn, ok: !authOn || validSession(req.headers.cookie) }));
|
|
153
235
|
app.post('/api/auth/login', async (req, reply) => {
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
|
|
236
|
+
const wait = limits.login.peek(req.ip);
|
|
237
|
+
if (wait)
|
|
238
|
+
return tooMany(reply, wait);
|
|
239
|
+
const given = Buffer.from(hashSecret(String(req.body?.password || '')));
|
|
240
|
+
if (!authOn || crypto.timingSafeEqual(given, Buffer.from(pwHash))) {
|
|
241
|
+
limits.login.reset(req.ip);
|
|
157
242
|
reply.header('set-cookie', `obz_session=${sign(Date.now() + 30 * 86400e3)}; HttpOnly; Path=/; SameSite=Lax; Max-Age=${30 * 86400}`);
|
|
158
243
|
return { ok: true };
|
|
159
244
|
}
|
|
160
|
-
|
|
245
|
+
limits.login.take(req.ip);
|
|
246
|
+
return reply.code(401).send({ ok: false, error: 'Wrong password' });
|
|
161
247
|
});
|
|
162
248
|
app.post('/api/auth/logout', async (_req, reply) => { reply.header('set-cookie', 'obz_session=; Path=/; Max-Age=0'); return { ok: true }; });
|
|
163
|
-
// ---------------------------------------------------------------- ingest
|
|
164
|
-
// Last-used stamps are written at most once a minute per key.
|
|
165
|
-
const lastUsed = new Map();
|
|
166
249
|
await app.register(async (scope) => {
|
|
250
|
+
// Check the key and its rate before reading (and unzipping) the body.
|
|
251
|
+
scope.addHook('onRequest', async (req, reply) => {
|
|
252
|
+
const header = req.headers['x-obzerver-key'];
|
|
253
|
+
const key = (Array.isArray(header) ? header[0] : header) || bearerOf(req);
|
|
254
|
+
const wait = limits.badKey.peek(req.ip);
|
|
255
|
+
if (wait)
|
|
256
|
+
return tooMany(reply, wait);
|
|
257
|
+
const k = projects.byKey(key);
|
|
258
|
+
if (!k) {
|
|
259
|
+
if (config.openIngest) {
|
|
260
|
+
req.ingestKey = null;
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
limits.badKey.take(req.ip);
|
|
264
|
+
return reply.code(401).send({ error: 'invalid app key' });
|
|
265
|
+
}
|
|
266
|
+
if (k.kind !== 'ingest')
|
|
267
|
+
return reply.code(403).send({ error: 'This is a read key. Apps send telemetry with an ingest key (obz_live_…).' });
|
|
268
|
+
const slow = limits.ingest.take(`${k.slug}:${k.id}`);
|
|
269
|
+
if (slow)
|
|
270
|
+
return tooMany(reply, slow);
|
|
271
|
+
req.ingestKey = k;
|
|
272
|
+
});
|
|
167
273
|
scope.addHook('preParsing', async (req, _reply, payload) => {
|
|
168
274
|
if (req.headers['content-encoding'] !== 'gzip')
|
|
169
275
|
return payload;
|
|
@@ -171,31 +277,32 @@ export async function createServer(opts = {}) {
|
|
|
171
277
|
return payload.pipe(zlib.createGunzip());
|
|
172
278
|
});
|
|
173
279
|
scope.post('/v1/ingest', async (req, reply) => {
|
|
174
|
-
const
|
|
175
|
-
const key = (Array.isArray(header) ? header[0] : header) || (req.headers.authorization || '').replace(/^Bearer\s+/i, '');
|
|
176
|
-
const slug = projects.byIngestKey(key) ?? (config.openIngest ? DEFAULT_PROJECT : null);
|
|
177
|
-
if (!slug)
|
|
178
|
-
return reply.code(401).send({ error: 'invalid app key' });
|
|
280
|
+
const k = req.ingestKey ?? null;
|
|
179
281
|
if (!req.body || typeof req.body !== 'object')
|
|
180
282
|
return reply.code(400).send({ error: 'expected JSON body' });
|
|
181
283
|
const body = req.body;
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
});
|
|
284
|
+
const envName = body.service?.environment ?? null;
|
|
285
|
+
if (k?.environment && envName !== k.environment) {
|
|
286
|
+
return reply.code(403).send({ error: `This key only accepts the "${k.environment}" environment, and this app reports ${envName ? `"${envName}"` : 'none'}. Use that environment's key.` });
|
|
287
|
+
}
|
|
288
|
+
const slug = k?.slug ?? DEFAULT_PROJECT;
|
|
289
|
+
if (k)
|
|
290
|
+
markUsed(k);
|
|
291
|
+
return projects.run(slug, () => ({ ok: true, project: slug, accepted: ingestFor(slug)(body) }));
|
|
190
292
|
});
|
|
191
293
|
});
|
|
192
294
|
// ---------------------------------------------------------------- MCP
|
|
193
295
|
app.post('/mcp', async (req, reply) => {
|
|
194
296
|
const token = (req.headers.authorization || '').replace(/^Bearer\s+/i, '');
|
|
195
297
|
// The token decides the project: an agent only ever sees the project its token belongs to.
|
|
298
|
+
const wait = limits.badKey.peek(req.ip);
|
|
299
|
+
if (wait)
|
|
300
|
+
return tooMany(reply, wait);
|
|
196
301
|
const slug = projects.byMcpToken(token);
|
|
197
|
-
if (!slug)
|
|
302
|
+
if (!slug) {
|
|
303
|
+
limits.badKey.take(req.ip);
|
|
198
304
|
return reply.code(401).send({ jsonrpc: '2.0', id: null, error: { code: -32001, message: 'Unauthorized: pass the MCP token as a Bearer token' } });
|
|
305
|
+
}
|
|
199
306
|
const body = req.body;
|
|
200
307
|
return projects.run(slug, async () => {
|
|
201
308
|
if (Array.isArray(body)) {
|
|
@@ -518,22 +625,34 @@ export async function createServer(opts = {}) {
|
|
|
518
625
|
const origin = config.publicUrl || `${req.protocol}://${req.headers.host}`;
|
|
519
626
|
return {
|
|
520
627
|
endpoint: origin,
|
|
521
|
-
keys: db
|
|
522
|
-
mcp: { url: `${origin}/mcp`,
|
|
628
|
+
keys: listKeys(db),
|
|
629
|
+
mcp: { url: `${origin}/mcp`, tokenPrefix: getSetting(db, 'mcp_token_prefix'), tools: MCP_TOOL_NAMES },
|
|
630
|
+
ingestRate: config.ingestRate,
|
|
523
631
|
retentionDays: config.retentionDays,
|
|
524
632
|
history: historyInfo(db, historyCfg),
|
|
525
633
|
email: (() => { const m = mailConfig(root); return { configured: !!m.url, source: m.source, smtp: maskSmtpUrl(m.url), from: m.from }; })(),
|
|
526
|
-
passwordProtected:
|
|
634
|
+
passwordProtected: authOn,
|
|
635
|
+
passwordSource,
|
|
527
636
|
openIngest: config.openIngest,
|
|
528
637
|
};
|
|
529
638
|
});
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
639
|
+
// Keys are shown once, in the response that creates them.
|
|
640
|
+
app.post('/api/keys', async (req, reply) => {
|
|
641
|
+
try {
|
|
642
|
+
const { id, key, info } = createKey(db, req.body || {});
|
|
643
|
+
projects.invalidate();
|
|
644
|
+
return { id, key, info };
|
|
645
|
+
}
|
|
646
|
+
catch (e) {
|
|
647
|
+
return reply.code(e instanceof KeyError ? 400 : 500).send({ error: e.message });
|
|
648
|
+
}
|
|
649
|
+
});
|
|
650
|
+
app.post('/api/keys/:id/rotate', async (req, reply) => {
|
|
651
|
+
const r = rotateKey(db, Number(req.params.id));
|
|
533
652
|
projects.invalidate();
|
|
534
|
-
return { id, key };
|
|
653
|
+
return r ? { id: r.id, key: r.key, info: r.info } : notFound(reply);
|
|
535
654
|
});
|
|
536
|
-
app.delete('/api/keys/:id', async (req) => { db
|
|
655
|
+
app.delete('/api/keys/:id', async (req) => { revokeKey(db, Number(req.params.id)); projects.invalidate(); return { ok: true }; });
|
|
537
656
|
app.put('/api/settings/email', async (req, reply) => {
|
|
538
657
|
if (mailConfig(root).source === 'env')
|
|
539
658
|
return reply.code(409).send({ error: 'Email is configured with OBZERVER_SMTP_URL; change it there' });
|
|
@@ -685,7 +804,7 @@ export async function createServer(opts = {}) {
|
|
|
685
804
|
send({ type: 'done' });
|
|
686
805
|
reply.raw.end();
|
|
687
806
|
});
|
|
688
|
-
app.post('/api/settings/mcp-token', async () => {
|
|
807
|
+
app.post('/api/settings/mcp-token', async () => ({ token: newMcpToken(db), prefix: getSetting(db, 'mcp_token_prefix') }));
|
|
689
808
|
// ---------------------------------------------------------------- dashboard
|
|
690
809
|
if (fs.existsSync(path.join(config.publicDir, 'index.html'))) {
|
|
691
810
|
await app.register(fastifyStatic, {
|
|
@@ -715,7 +834,7 @@ export async function createServer(opts = {}) {
|
|
|
715
834
|
// Background passes run once per project, each against its own database.
|
|
716
835
|
const perProject = (label, fn) => () => projects.each(fn, (slug, e) => log(`${label} [${slug}]: ${e.message}`));
|
|
717
836
|
return {
|
|
718
|
-
app, db: root, config, alerts, ingest, projects,
|
|
837
|
+
app, db: root, config, alerts, ingest, projects, generatedPassword, passwordSource,
|
|
719
838
|
async listen() {
|
|
720
839
|
await app.listen({ port: config.port, host: config.host });
|
|
721
840
|
every(config.alertIntervalMs, perProject('alerts', () => alerts.evaluate()), 'alerts');
|