@briefkasten/server 0.0.0-stage → 0.1.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.
@@ -0,0 +1,2439 @@
1
+ import { API, API_PREFIX, BriefkastenError, BriefkastenEvent, COUNTERS, ConfigEnvelope, DEFAULT_PROJECT, DEFAULT_TENANT, DeviceFlowError, ERROR_STATUS, KNOWN_ADAPTERS, Limits, MODES, READERS, REFRESH_GRANT, Route, SSE_HEARTBEAT, STREAM_PATH, TENANT_HEADER, TenantStatus, Token, USAGE_DIMENSIONS, WS_BEARER_PREFIX, WS_PROTOCOL, applyMutation, base62Token, compileFilter, constantTimeEqual, encodeSse, eventId, fromBase64Url, inQuery, keptHeaders, matchesFilters, messageOf, pathParameters, randomBytes, randomToken, readBody, recordOf, sampleOf, sha256Hex, sourceSecret, tenantOfDesired, userCode, verifyEd25519, verifyEnvelope, withDefaultProject, zodErrorSummary } from "briefkasten";
2
+ import { z } from "zod";
3
+ //#region src/auth.ts
4
+ /**
5
+ * Who presents a token, and how a person gets one. Three kinds of token reach the gateway:
6
+ *
7
+ * - static tokens from the config, kept as SHA-256 hashes (subscribers, managers, admins);
8
+ * - sessions, made by signing in (an access token for an hour, a refresh token for 30 days),
9
+ * kept hashed in the key-value store;
10
+ * - signed tokens from a control plane (`bks1.<payload>.<signature>`, Ed25519 with the
11
+ * control plane's keys), which the gateway checks without storing anything.
12
+ */
13
+ const ACCESS_PREFIX = "bka";
14
+ const REFRESH_PREFIX = "bkr";
15
+ const SIGNED_PREFIX = "bks1.";
16
+ const SECOND = 1e3;
17
+ const ACCESS_SECONDS = 3600;
18
+ const REFRESH_DAYS = 30;
19
+ const DAY_SECONDS = 86400;
20
+ const CODE_MINUTES = 10;
21
+ const MINUTE$1 = 60 * SECOND;
22
+ const CODE_ATTEMPTS = 5;
23
+ const DEVICE_INTERVAL = 5;
24
+ /** Static tokens: the config's tokens by hash. */
25
+ function staticVerifier(state) {
26
+ return { async verify(token) {
27
+ return state().tokens.get(await sha256Hex(token));
28
+ } };
29
+ }
30
+ const SessionRecord = z.object({
31
+ tenant: z.string(),
32
+ name: z.string()
33
+ });
34
+ function parsedRecord(text, schema) {
35
+ if (text === void 0) return;
36
+ const result = schema.safeParse(JSON.parse(text));
37
+ return result.success ? result.data : void 0;
38
+ }
39
+ /** Sessions from signing in. */
40
+ function sessionVerifier(kv) {
41
+ return { async verify(token) {
42
+ if (!token.startsWith(`${ACCESS_PREFIX}_`)) return;
43
+ const record = parsedRecord(await kv.get(`session:access:${await sha256Hex(token)}`), SessionRecord);
44
+ return record === void 0 ? void 0 : {
45
+ kind: "tenant",
46
+ tenant: record.tenant,
47
+ scope: "manage",
48
+ name: record.name,
49
+ project: null,
50
+ filters: []
51
+ };
52
+ } };
53
+ }
54
+ const SignedPayload = z.object({
55
+ tenant: z.string(),
56
+ scope: z.enum(["manage", "subscribe"]),
57
+ name: z.string(),
58
+ project: z.string().nullable().default(null),
59
+ filters: z.array(z.string()).default([]),
60
+ /** Expiry, epoch seconds. */
61
+ exp: z.number(),
62
+ kid: z.string()
63
+ });
64
+ /** Signed tokens from a control plane: `bks1.<base64url payload>.<base64url signature>`. */
65
+ function signedVerifier(state, now) {
66
+ return { async verify(token) {
67
+ const keys = state().settings.controlPlane?.keys ?? {};
68
+ if (!token.startsWith(SIGNED_PREFIX)) return;
69
+ const [payload = "", signature = ""] = token.slice(5).split(".");
70
+ let claims;
71
+ try {
72
+ claims = parsedRecord(new TextDecoder().decode(fromBase64Url(payload)), SignedPayload);
73
+ } catch {
74
+ return;
75
+ }
76
+ const key = claims === void 0 ? void 0 : keys[claims.kid];
77
+ if (claims === void 0 || key === void 0 || claims.exp * SECOND <= now()) return;
78
+ if (!await verifyEd25519(key, payload, signature)) return;
79
+ return {
80
+ kind: "tenant",
81
+ tenant: claims.tenant,
82
+ scope: claims.scope,
83
+ name: claims.name,
84
+ project: claims.project,
85
+ filters: claims.filters
86
+ };
87
+ } };
88
+ }
89
+ /** The first verifier that knows the token. */
90
+ async function verifyToken(verifiers, token) {
91
+ for (const verifier of verifiers) {
92
+ const principal = await verifier.verify(token);
93
+ if (principal !== void 0) return principal;
94
+ }
95
+ }
96
+ const EmailRequest = z.object({
97
+ email: z.string(),
98
+ tenant: z.string().nullable(),
99
+ code: z.string(),
100
+ attempts: z.number()
101
+ });
102
+ const DeviceRequest = z.object({
103
+ userCode: z.string(),
104
+ status: z.enum(["pending", "approved"]),
105
+ lastPoll: z.number(),
106
+ tenant: z.string().nullable(),
107
+ name: z.string().nullable()
108
+ });
109
+ function normalizedCode(code) {
110
+ return code.toUpperCase().replaceAll(/[^A-Z0-9]/g, "");
111
+ }
112
+ /** Signing in: email codes, RFC 8628 device codes, refresh and sign-out. */
113
+ var Login = class {
114
+ deps;
115
+ constructor(deps) {
116
+ this.deps = deps;
117
+ }
118
+ methods() {
119
+ const { auth } = this.deps.state().settings;
120
+ const methods = [];
121
+ if (auth.email && this.deps.mailer !== void 0) methods.push("email_code");
122
+ if (auth.device) methods.push("device_code");
123
+ methods.push("token");
124
+ return methods;
125
+ }
126
+ require(method) {
127
+ if (!this.methods().includes(method)) throw new BriefkastenError("unavailable", `this instance does not offer ${method.replace("_", " ")} sign-in`);
128
+ }
129
+ expiry(minutes) {
130
+ return this.deps.runtime.now() + minutes * MINUTE$1;
131
+ }
132
+ /** The tenant an email owns, if any. */
133
+ ownerOf(email) {
134
+ const wanted = email.toLowerCase();
135
+ for (const tenant of this.deps.state().tenants.values()) if (tenant.owners.some((owner) => owner.toLowerCase() === wanted)) return tenant.name;
136
+ return null;
137
+ }
138
+ /**
139
+ * Mails a code when the address owns a tenant. The answer is the same either way, so the
140
+ * endpoint does not tell who owns a tenant.
141
+ */
142
+ async emailStart(email) {
143
+ this.require("email_code");
144
+ const request = randomToken("req", this.deps.runtime.random);
145
+ const code = userCode(this.deps.runtime.random);
146
+ const tenant = this.ownerOf(email);
147
+ const expiresAt = this.expiry(CODE_MINUTES);
148
+ await this.deps.kv.put(`login:${await sha256Hex(request)}`, JSON.stringify({
149
+ email,
150
+ tenant,
151
+ code: await sha256Hex(normalizedCode(code)),
152
+ attempts: 0
153
+ }), expiresAt);
154
+ if (tenant !== null) await this.deps.mailer?.send({
155
+ to: email,
156
+ subject: `Your briefkasten sign-in code: ${code}`,
157
+ text: `Your sign-in code is ${code}. It expires in ${CODE_MINUTES} minutes.\n\nIf you did not ask for it, ignore this message.`
158
+ });
159
+ return {
160
+ login_id: request,
161
+ email,
162
+ expires_in: 600,
163
+ message: `we've sent you an email with an auth code [expires in ${CODE_MINUTES}m]`
164
+ };
165
+ }
166
+ async emailVerify(request, code) {
167
+ this.require("email_code");
168
+ const key = `login:${await sha256Hex(request)}`;
169
+ const record = parsedRecord(await this.deps.kv.get(key), EmailRequest);
170
+ if (record === void 0) throw new BriefkastenError("unauthorized", "the sign-in request expired: start again");
171
+ if (!constantTimeEqual(record.code, await sha256Hex(normalizedCode(code))) || record.tenant === null) {
172
+ const attempts = record.attempts + 1;
173
+ if (attempts >= CODE_ATTEMPTS) await this.deps.kv.delete(key);
174
+ else await this.deps.kv.put(key, JSON.stringify({
175
+ ...record,
176
+ attempts
177
+ }), this.expiry(CODE_MINUTES));
178
+ throw new BriefkastenError("unauthorized", "the code is wrong");
179
+ }
180
+ await this.deps.kv.delete(key);
181
+ return {
182
+ status: "signed_in",
183
+ ...await this.session(record.tenant, record.email),
184
+ tenant: record.tenant,
185
+ welcome: `welcome to briefkasten [${record.tenant}, self-hosted]`
186
+ };
187
+ }
188
+ /** A new session: an access token and a refresh token, both kept hashed. */
189
+ async session(tenant, name) {
190
+ const access = randomToken(ACCESS_PREFIX, this.deps.runtime.random);
191
+ const refresh = randomToken(REFRESH_PREFIX, this.deps.runtime.random);
192
+ const record = JSON.stringify({
193
+ tenant,
194
+ name
195
+ });
196
+ const now = this.deps.runtime.now();
197
+ await this.deps.kv.put(`session:access:${await sha256Hex(access)}`, record, now + ACCESS_SECONDS * SECOND);
198
+ await this.deps.kv.put(`session:refresh:${await sha256Hex(refresh)}`, record, now + REFRESH_DAYS * DAY_SECONDS * SECOND);
199
+ return {
200
+ access_token: access,
201
+ token_type: "Bearer",
202
+ expires_in: ACCESS_SECONDS,
203
+ refresh_token: refresh
204
+ };
205
+ }
206
+ /** Trades a refresh token for a new session; the old refresh token stops working. */
207
+ async refresh(token) {
208
+ const key = `session:refresh:${await sha256Hex(token)}`;
209
+ const record = parsedRecord(await this.deps.kv.get(key), SessionRecord);
210
+ if (record === void 0) throw new BriefkastenError("unauthorized", "the session ended: sign in again");
211
+ await this.deps.kv.delete(key);
212
+ return this.session(record.tenant, record.name);
213
+ }
214
+ async logout(token) {
215
+ await this.deps.kv.delete(`session:refresh:${await sha256Hex(token)}`);
216
+ }
217
+ async deviceStart() {
218
+ this.require("device_code");
219
+ const deviceCode = randomToken("dev", this.deps.runtime.random);
220
+ const code = userCode(this.deps.runtime.random);
221
+ const expiresAt = this.expiry(CODE_MINUTES);
222
+ const key = await sha256Hex(deviceCode);
223
+ await this.deps.kv.put(`device:${key}`, JSON.stringify({
224
+ userCode: code,
225
+ status: "pending",
226
+ lastPoll: 0,
227
+ tenant: null,
228
+ name: null
229
+ }), expiresAt);
230
+ await this.deps.kv.put(`device-user:${normalizedCode(code)}`, key, expiresAt);
231
+ const base = (this.deps.state().settings.server.publicUrl ?? "").replace(/\/+$/, "");
232
+ return {
233
+ device_code: deviceCode,
234
+ user_code: code,
235
+ verification_uri: `${base}/device`,
236
+ verification_uri_complete: `${base}/device?code=${encodeURIComponent(code)}`,
237
+ expires_in: 600,
238
+ interval: DEVICE_INTERVAL
239
+ };
240
+ }
241
+ /** RFC 8628 §3.4–3.5: the session once approved, else why not yet. */
242
+ async deviceToken(deviceCode) {
243
+ this.require("device_code");
244
+ const key = `device:${await sha256Hex(deviceCode)}`;
245
+ const record = parsedRecord(await this.deps.kv.get(key), DeviceRequest);
246
+ if (record === void 0) throw new DeviceFlowError("expired_token");
247
+ const now = this.deps.runtime.now();
248
+ if (record.status === "approved" && record.tenant !== null && record.name !== null) {
249
+ await this.deps.kv.delete(key);
250
+ return this.session(record.tenant, record.name);
251
+ }
252
+ const early = now - record.lastPoll < DEVICE_INTERVAL * SECOND;
253
+ await this.deps.kv.put(key, JSON.stringify({
254
+ ...record,
255
+ lastPoll: now
256
+ }), this.expiry(CODE_MINUTES));
257
+ throw new DeviceFlowError(early ? "slow_down" : "authorization_pending");
258
+ }
259
+ /** A signed-in manager approves a device sign-in by the code the device shows. */
260
+ async deviceApprove(principal, code) {
261
+ this.require("device_code");
262
+ if (principal.kind !== "tenant") throw new BriefkastenError("forbidden", "a device signs in to a tenant: approve it with a tenant's token");
263
+ const pointer = await this.deps.kv.get(`device-user:${normalizedCode(code)}`);
264
+ const key = `device:${pointer ?? ""}`;
265
+ const record = parsedRecord(await this.deps.kv.get(key), DeviceRequest);
266
+ if (pointer === void 0 || record === void 0) throw new BriefkastenError("not_found", "no device sign-in with that code (it may have expired)");
267
+ await this.deps.kv.put(key, JSON.stringify({
268
+ ...record,
269
+ status: "approved",
270
+ tenant: principal.tenant,
271
+ name: principal.name
272
+ }), this.expiry(CODE_MINUTES));
273
+ }
274
+ };
275
+ //#endregion
276
+ //#region src/config-store.ts
277
+ /**
278
+ * The config sources of a `multi` instance: its settings come from its file, its tenants from a
279
+ * store. Either the instance keeps them itself (a control plane pushes them through the API, and
280
+ * tenants are created and changed through it), or it pulls them from a control plane and only
281
+ * routes by them. Both keep the last accepted tenants in the key-value store, so the instance
282
+ * keeps routing when the control plane is down.
283
+ */
284
+ const PREFIX = "tenant:";
285
+ const StoredTenant = z.object({
286
+ name: z.string(),
287
+ status: TenantStatus,
288
+ plan: z.string(),
289
+ limits: Limits,
290
+ version: z.number(),
291
+ owners: z.array(z.string()),
292
+ projects: z.record(z.string(), z.object({
293
+ sources: z.record(z.string(), z.object({
294
+ adapter: z.string(),
295
+ options: z.record(z.string(), z.unknown()),
296
+ secret: z.string()
297
+ })),
298
+ routes: z.array(Route)
299
+ })),
300
+ tokens: z.record(z.string(), Token)
301
+ });
302
+ async function storedTenants(kv) {
303
+ return (await kv.list(PREFIX)).flatMap((entry) => {
304
+ const parsed = StoredTenant.safeParse(JSON.parse(entry.value));
305
+ return parsed.success ? [parsed.data] : [];
306
+ });
307
+ }
308
+ async function storedTenant(kv, name) {
309
+ const text = await kv.get(`${PREFIX}${name}`);
310
+ const parsed = text === void 0 ? void 0 : StoredTenant.safeParse(JSON.parse(text));
311
+ if (parsed?.success !== true) throw new BriefkastenError("not_found", `no tenant ${name}`);
312
+ return parsed.data;
313
+ }
314
+ function keep(kv, tenant) {
315
+ return kv.put(`${PREFIX}${tenant.name}`, JSON.stringify(tenant));
316
+ }
317
+ /** Tenants the instance keeps itself, changed through the management API. */
318
+ function storeConfigSource(options) {
319
+ const { kv } = options;
320
+ return {
321
+ load: async () => ({
322
+ settings: await options.settings(),
323
+ tenants: await storedTenants(kv)
324
+ }),
325
+ readOnly: () => Promise.resolve(void 0),
326
+ async apply(name, mutation) {
327
+ const tenant = await storedTenant(kv, name);
328
+ const shape = applyMutation(tenant, mutation, {
329
+ secret: (value) => value,
330
+ token: (token) => token
331
+ });
332
+ await keep(kv, {
333
+ ...tenant,
334
+ ...shape,
335
+ version: tenant.version + 1
336
+ });
337
+ },
338
+ tenants: {
339
+ create: (tenant) => keep(kv, tenant),
340
+ async update(name, patch) {
341
+ const tenant = await storedTenant(kv, name);
342
+ await keep(kv, {
343
+ ...tenant,
344
+ ...patch,
345
+ version: tenant.version + 1
346
+ });
347
+ },
348
+ async delete(name) {
349
+ await kv.delete(`${PREFIX}${name}`);
350
+ },
351
+ async replace(config) {
352
+ const tenant = tenantOfDesired(config);
353
+ await keep(kv, tenant);
354
+ return tenant.version;
355
+ }
356
+ }
357
+ };
358
+ }
359
+ const Pulled = z.object({ tenants: z.array(ConfigEnvelope) });
360
+ /**
361
+ * Tenants pulled from a control plane (`GET <url>` answers `{ tenants: [envelope, ...] }`), each
362
+ * signed. The management API cannot change them: the control plane owns them.
363
+ */
364
+ function pulledConfigSource(options) {
365
+ const { kv } = options;
366
+ const send = options.fetch ?? ((request) => fetch(request));
367
+ async function pull(settings) {
368
+ const request = new Request(options.url, { headers: options.token === void 0 ? {} : { authorization: `Bearer ${options.token}` } });
369
+ const response = await send(request);
370
+ if (!response.ok) throw new Error(`the control plane answered ${response.status}`);
371
+ const pulled = Pulled.parse(await response.json());
372
+ const keys = settings.controlPlane?.keys ?? {};
373
+ const names = /* @__PURE__ */ new Set();
374
+ for (const envelope of pulled.tenants) {
375
+ const config = await verifyEnvelope(envelope, keys);
376
+ names.add(config.tenant);
377
+ await keep(kv, tenantOfDesired(config));
378
+ }
379
+ for (const tenant of await storedTenants(kv)) if (!names.has(tenant.name)) await kv.delete(`${PREFIX}${tenant.name}`);
380
+ }
381
+ return {
382
+ async load() {
383
+ const settings = await options.settings();
384
+ try {
385
+ await pull(settings);
386
+ } catch (error) {
387
+ options.log(`pulling tenants from ${options.url} failed, keeping the last ones: ${messageOf(error)}`);
388
+ }
389
+ return {
390
+ settings,
391
+ tenants: await storedTenants(kv)
392
+ };
393
+ },
394
+ readOnly: () => Promise.resolve("this instance's tenants come from its control plane: change them there"),
395
+ apply: () => Promise.reject(new BriefkastenError("read_only", "this instance's tenants come from its control plane: change them there"))
396
+ };
397
+ }
398
+ function json$1(status, value) {
399
+ return new Response(JSON.stringify(value), {
400
+ status,
401
+ headers: { "content-type": "application/json" }
402
+ });
403
+ }
404
+ function errorResponse(error) {
405
+ if (error instanceof DeviceFlowError) return json$1(400, { error: error.code });
406
+ if (error instanceof BriefkastenError) return json$1(error.status, { error: {
407
+ code: error.code,
408
+ message: error.message
409
+ } });
410
+ return json$1(500, { error: {
411
+ code: "internal",
412
+ message: messageOf(error)
413
+ } });
414
+ }
415
+ function pathOf(url) {
416
+ const trimmed = url.pathname.replace(/\/+$/, "");
417
+ return trimmed.length === 0 ? "/" : trimmed;
418
+ }
419
+ /** The bearer token of a request: the header, or a WebSocket's `bearer.<token>` subprotocol. */
420
+ function bearerOf(request) {
421
+ const header = request.headers.get("authorization");
422
+ if (header?.startsWith("Bearer ") === true) {
423
+ const token = header.slice(7).trim();
424
+ return token.length > 0 ? token : void 0;
425
+ }
426
+ return (request.headers.get("sec-websocket-protocol") ?? "").split(",").map((each) => each.trim()).find((each) => each.startsWith(WS_BEARER_PREFIX))?.slice(WS_BEARER_PREFIX.length);
427
+ }
428
+ function compile(id) {
429
+ const operation = API[id];
430
+ const source = operation.path.replaceAll(/:(\w+)/g, "([^/]+)");
431
+ return {
432
+ id,
433
+ operation,
434
+ pattern: new RegExp(`^${source}$`),
435
+ names: pathParameters(operation.path)
436
+ };
437
+ }
438
+ function isOperationId(id) {
439
+ return Object.hasOwn(API, id);
440
+ }
441
+ /** Literal paths first, so `/tenants/usage` is never read as the tenant `usage`. */
442
+ const ROUTES = Object.keys(API).filter(isOperationId).map(compile).toSorted((a, b) => a.names.length - b.names.length);
443
+ /** Where a `multi` instance's subscribers connect out: `/t/<tenant>/stream`. */
444
+ const TENANT_STREAM = /^\/t\/([^/]+)\/stream$/;
445
+ /** The tenant a request names in the `Briefkasten-Tenant` header, if any. */
446
+ function namedTenant(request) {
447
+ const name = request.headers.get(TENANT_HEADER)?.trim();
448
+ return name === void 0 || name === "" ? void 0 : name;
449
+ }
450
+ /** An operation's input: the query or the JSON body, then the path's parameters. */
451
+ async function inputOf(request, url, compiled, match) {
452
+ const input = {};
453
+ if (inQuery(compiled.operation.method)) for (const [key, value] of url.searchParams) input[key] = value;
454
+ else {
455
+ const body = await request.json().catch(() => {
456
+ throw new BriefkastenError("bad_request", "the body must be JSON");
457
+ });
458
+ if (typeof body !== "object" || body === null || Array.isArray(body)) throw new BriefkastenError("bad_request", "the body must be a JSON object");
459
+ Object.assign(input, body);
460
+ }
461
+ compiled.names.forEach((name, index) => {
462
+ input[name] = decodeURIComponent(String(match[index + 1]));
463
+ });
464
+ return input;
465
+ }
466
+ const DEVICE_PAGE = `<!doctype html><meta charset="utf-8"><title>briefkasten sign-in</title>
467
+ <body style="font-family:system-ui;max-width:32rem;margin:4rem auto;line-height:1.5">
468
+ <h1>Approve a device</h1>
469
+ <p>On a machine where you are signed in to this instance, run:</p>
470
+ <pre>briefkasten login --approve &lt;the code the device shows&gt;</pre>
471
+ </body>`;
472
+ /**
473
+ * Who may call an operation: anyone for a public one, else a valid token; an admin token for an
474
+ * admin operation (in an instance with tenants), a manage token for a manager's.
475
+ */
476
+ function allowed(operation, principal, tenants) {
477
+ if (operation.access === "public") return principal;
478
+ if (principal === void 0) throw new BriefkastenError("unauthorized", "a bearer token is required");
479
+ const admin = principal.kind === "admin";
480
+ if (operation.access === "admin") {
481
+ if (!admin) throw new BriefkastenError("forbidden", "this needs an admin token");
482
+ if (!tenants) throw new BriefkastenError("unavailable", "tenants exist only in multi mode");
483
+ }
484
+ if (operation.access === "manage" && !admin && principal.scope !== "manage") throw new BriefkastenError("forbidden", "this needs a manage token");
485
+ return principal;
486
+ }
487
+ //#endregion
488
+ //#region src/sse.ts
489
+ /** A comment line every 25 seconds keeps proxies from closing an idle stream. */
490
+ const HEARTBEAT_MS = 25e3;
491
+ /** A session as Server-Sent Events: its items as frames, until either side ends it. */
492
+ function sseResponse(session) {
493
+ const encoder = new TextEncoder();
494
+ const stream = new ReadableStream({
495
+ start: async (controller) => {
496
+ const heartbeat = setInterval(() => {
497
+ try {
498
+ controller.enqueue(encoder.encode(SSE_HEARTBEAT));
499
+ } catch {}
500
+ }, HEARTBEAT_MS);
501
+ try {
502
+ for await (const item of session.items) controller.enqueue(encoder.encode(encodeSse(item)));
503
+ } finally {
504
+ clearInterval(heartbeat);
505
+ session.close();
506
+ try {
507
+ controller.close();
508
+ } catch {}
509
+ }
510
+ },
511
+ cancel: () => {
512
+ session.close();
513
+ }
514
+ });
515
+ return new Response(stream, {
516
+ status: 200,
517
+ headers: {
518
+ "content-type": "text/event-stream; charset=utf-8",
519
+ "cache-control": "no-cache, no-transform",
520
+ connection: "keep-alive",
521
+ "x-accel-buffering": "no"
522
+ }
523
+ });
524
+ }
525
+ //#endregion
526
+ //#region src/state.ts
527
+ function stateOf(loaded) {
528
+ const tokens = /* @__PURE__ */ new Map();
529
+ for (const [name, token] of Object.entries(loaded.settings.admins)) tokens.set(token.tokenSha256, {
530
+ kind: "admin",
531
+ name
532
+ });
533
+ for (const tenant of loaded.tenants) for (const [name, token] of Object.entries(tenant.tokens)) if (token.scope !== "admin") tokens.set(token.tokenSha256, {
534
+ kind: "tenant",
535
+ tenant: tenant.name,
536
+ scope: token.scope,
537
+ name,
538
+ project: token.project,
539
+ filters: token.filters
540
+ });
541
+ return {
542
+ settings: loaded.settings,
543
+ tenants: new Map(loaded.tenants.map((tenant) => [tenant.name, withDefaultProject(tenant)])),
544
+ tokens
545
+ };
546
+ }
547
+ /** The tenant a request means: the one it names, or the implicit one. */
548
+ function tenantOf(state, name) {
549
+ return state.tenants.get(name ?? DEFAULT_TENANT);
550
+ }
551
+ /**
552
+ * The source a hook address names. A hook path without the project (`/webhooks/:source`) finds
553
+ * the source by name across the tenant's projects; names are unique there in that case.
554
+ */
555
+ function findSource(state, address) {
556
+ const tenant = tenantOf(state, address.tenant);
557
+ if (tenant === void 0) return;
558
+ for (const [project, value] of Object.entries(tenant.projects)) {
559
+ const source = value.sources[address.source];
560
+ if (source !== void 0 && (address.project === void 0 || address.project === project)) return {
561
+ tenant,
562
+ project,
563
+ name: address.source,
564
+ source
565
+ };
566
+ }
567
+ }
568
+ /** Every source of every tenant. */
569
+ function allSources(state) {
570
+ return [...state.tenants.values()].flatMap((tenant) => Object.entries(tenant.projects).flatMap(([project, value]) => Object.entries(value.sources).map(([name, source]) => ({
571
+ tenant,
572
+ project,
573
+ name,
574
+ source
575
+ }))));
576
+ }
577
+ /** The URL providers post a source's deliveries to. */
578
+ function hookUrlOf(settings, ref) {
579
+ return `${(settings.server.publicUrl ?? "").replace(/\/+$/, "")}${settings.hooks.render({
580
+ tenant: ref.tenant.name,
581
+ project: ref.project,
582
+ source: ref.name
583
+ })}`;
584
+ }
585
+ /**
586
+ * The adapter instances, made on first use and made again when a source's adapter, options or
587
+ * secret change.
588
+ */
589
+ var Instances = class {
590
+ registry;
591
+ mounted = /* @__PURE__ */ new Map();
592
+ constructor(registry) {
593
+ this.registry = registry;
594
+ }
595
+ /** The adapter a source names; refuses an unknown adapter or options it does not accept. */
596
+ async adapterOf(id, options) {
597
+ const adapter = await this.registry.resolve(id);
598
+ if (adapter === void 0) throw new BriefkastenError("bad_request", `unknown adapter ${id}: install @briefkasten/adapter-${id}`);
599
+ const parsed = adapter.optionsSchema.safeParse(options);
600
+ if (!parsed.success) throw new BriefkastenError("bad_request", `invalid options for ${id}: ${messageOf(parsed.error)}`);
601
+ return adapter;
602
+ }
603
+ async get(ref) {
604
+ const where = `${ref.tenant.name}/${ref.project}/${ref.name}`;
605
+ const key = JSON.stringify([
606
+ ref.source.adapter,
607
+ ref.source.options,
608
+ ref.source.secret
609
+ ]);
610
+ const known = this.mounted.get(where);
611
+ if (known?.key === key) return known.value;
612
+ const adapter = await this.adapterOf(ref.source.adapter, ref.source.options);
613
+ const value = {
614
+ adapter,
615
+ instance: adapter.create(adapter.optionsSchema.parse(ref.source.options), {
616
+ tenant: ref.tenant.name,
617
+ project: ref.project,
618
+ source: ref.name,
619
+ secret: ref.source.secret
620
+ })
621
+ };
622
+ this.mounted.set(where, {
623
+ key,
624
+ value
625
+ });
626
+ return value;
627
+ }
628
+ };
629
+ //#endregion
630
+ //#region src/ingest.ts
631
+ /**
632
+ * A provider's delivery, from the request to the subscribers: find the source the hook path
633
+ * names, check the size, the rate and the budget, let the adapter verify and normalise it, keep
634
+ * every event (and every refused delivery, for history), count it, and hand it to the open
635
+ * sessions that want it.
636
+ */
637
+ const HTTP_UNAUTHORIZED = 401;
638
+ const HTTP_FORBIDDEN = 403;
639
+ const HTTP_BAD_REQUEST = 400;
640
+ const REASON_LIMIT = 300;
641
+ /** The gateway's own refusal of a delivery, in the API's error shape (`{ error: { code, message } }`). */
642
+ function refusal(code, message, extra = {}) {
643
+ return new Response(JSON.stringify({ error: {
644
+ code,
645
+ message
646
+ } }), {
647
+ status: ERROR_STATUS[code],
648
+ headers: {
649
+ "content-type": "application/json",
650
+ ...extra
651
+ }
652
+ });
653
+ }
654
+ /** A refusal must say why: the provider shows a retry, the gateway only a status. */
655
+ async function reasonOf$1(response) {
656
+ return (await response.clone().text().catch(() => "")).replaceAll("\n", " ").slice(0, REASON_LIMIT);
657
+ }
658
+ var Ingest = class {
659
+ deps;
660
+ constructor(deps) {
661
+ this.deps = deps;
662
+ }
663
+ meter(ref, event, counts) {
664
+ return this.deps.store.meter({
665
+ tenant: ref.tenant.name,
666
+ at: this.deps.runtime.now(),
667
+ project: ref.project,
668
+ source: ref.name,
669
+ event,
670
+ counts
671
+ });
672
+ }
673
+ /** The stored form of an event, before it is kept. */
674
+ stored(ref, adapter, event, extra) {
675
+ const now = this.deps.runtime.now();
676
+ return {
677
+ id: eventId(now, this.deps.runtime.random),
678
+ tenant: ref.tenant.name,
679
+ project: ref.project,
680
+ adapter,
681
+ source: ref.name,
682
+ target: event?.target ?? "",
683
+ event: event?.event ?? "unverified",
684
+ at: new Date(now).toISOString(),
685
+ body: event?.body ?? {},
686
+ verification: extra.verification,
687
+ held: extra.held,
688
+ sizeBytes: extra.size,
689
+ headers: keptHeaders(extra.headers),
690
+ ...extra.test === true ? { test: true } : {}
691
+ };
692
+ }
693
+ /** Publishes an event as if the source had received it (the API's `emit`); answers its id. */
694
+ async emit(ref, adapter, event, held) {
695
+ const size = new TextEncoder().encode(JSON.stringify(event.body)).byteLength;
696
+ const stored = this.stored(ref, adapter, event, {
697
+ verification: {
698
+ ok: true,
699
+ method: "emit",
700
+ reason: null
701
+ },
702
+ held,
703
+ size,
704
+ headers: new Headers()
705
+ });
706
+ await this.publish(stored);
707
+ await this.meter(ref, event.event, {
708
+ events: 1,
709
+ bytes: size
710
+ });
711
+ return stored.id;
712
+ }
713
+ /** Keeps and hands out one event a source received or `emit` made. */
714
+ async publish(event) {
715
+ await this.deps.store.append(event);
716
+ await this.deps.budget.add(event.tenant, 1);
717
+ if (!event.held) this.deps.fanout.publish(event);
718
+ }
719
+ /** Handles a delivery to a hook path; nothing when the path is not a hook. */
720
+ async handle(request, path) {
721
+ const state = this.deps.state();
722
+ const address = state.settings.hooks.match(path);
723
+ if (address === void 0) return;
724
+ const ref = findSource(state, address);
725
+ if (ref === void 0) {
726
+ this.deps.log(`${path}: no such source`);
727
+ return refusal("not_found", `unknown source ${address.source}`);
728
+ }
729
+ const where = `${ref.tenant.name}/${ref.project}/${ref.name}`;
730
+ if (ref.tenant.status === "suspended") return refusal("tenant_suspended", "this tenant is suspended");
731
+ const body = await readBody(request, state.settings.maxBodyBytes);
732
+ if (body === void 0) {
733
+ this.deps.log(`${where}: refused a body over ${state.settings.maxBodyBytes} bytes`);
734
+ return refusal("too_large", `the body is larger than ${state.settings.maxBodyBytes} bytes`);
735
+ }
736
+ const { limits } = ref.tenant;
737
+ if (!this.deps.limiter.take(where, limits.ratePerSourcePerMinute)) {
738
+ await this.meter(ref, "", { rateLimited: 1 });
739
+ return refusal("rate_limited", "too many deliveries for this source: try again in a minute", { "retry-after": "60" });
740
+ }
741
+ const fits = await this.deps.budget.fits(ref.tenant.name, limits.eventsPerMonth);
742
+ if (!fits && limits.overLimit === "refuse") {
743
+ await this.meter(ref, "", { rateLimited: 1 });
744
+ return refusal("rate_limited", "this tenant used its events for the month");
745
+ }
746
+ await this.deps.capture?.(ref.name, body, request.headers).catch((error) => {
747
+ this.deps.log(`${where}: capture failed: ${messageOf(error)}`);
748
+ });
749
+ return (await this.verify(ref, request, {
750
+ path,
751
+ rest: address.rest
752
+ }, body, {
753
+ held: !fits,
754
+ test: false
755
+ })).response;
756
+ }
757
+ /**
758
+ * Runs a sample delivery through the source's adapter exactly like a provider's, marked as a
759
+ * test: verified, kept, counted and handed out. Answers what it kept (a refused delivery too).
760
+ */
761
+ async inject(ref, delivery, held) {
762
+ const path = this.deps.state().settings.hooks.render({
763
+ tenant: ref.tenant.name,
764
+ project: ref.project,
765
+ source: ref.name
766
+ });
767
+ const request = new Request(`http://briefkasten.local${path}`, {
768
+ method: "POST",
769
+ headers: delivery.headers
770
+ });
771
+ const body = new TextEncoder().encode(delivery.body);
772
+ return (await this.verify(ref, request, {
773
+ path,
774
+ rest: ""
775
+ }, body, {
776
+ held,
777
+ test: true
778
+ })).kept;
779
+ }
780
+ async verify(ref, request, { path, rest }, body, { held, test }) {
781
+ const where = `${ref.tenant.name}/${ref.project}/${ref.name}`;
782
+ const { adapter, instance } = await this.deps.instances.get(ref);
783
+ const replayed = new Request(request.url, {
784
+ method: request.method,
785
+ headers: request.headers,
786
+ body
787
+ });
788
+ let result;
789
+ try {
790
+ result = await instance.handleWebhook(replayed, { rest });
791
+ } catch (error) {
792
+ const reason = messageOf(error);
793
+ this.deps.log(`${where}: ${request.method} ${path} -> refused: ${reason}`);
794
+ return {
795
+ response: refusal("bad_request", reason),
796
+ kept: []
797
+ };
798
+ }
799
+ const status = result.response.status;
800
+ const reason = status >= HTTP_BAD_REQUEST ? await reasonOf$1(result.response) : "";
801
+ const names = result.events.map((each) => ` ${each.event}`).join(",");
802
+ this.deps.log(`${where}: ${test ? "test " : ""}${request.method} ${path} -> ${status}, ${result.events.length} event(s)${names}${reason === "" ? "" : ` — ${reason}`}`);
803
+ if (status === HTTP_UNAUTHORIZED || status === HTTP_FORBIDDEN) {
804
+ const refused = this.stored(ref, adapter.id, void 0, {
805
+ verification: {
806
+ ok: false,
807
+ method: adapter.id,
808
+ reason
809
+ },
810
+ held: false,
811
+ size: body.byteLength,
812
+ headers: request.headers,
813
+ test
814
+ });
815
+ await this.deps.store.append(refused);
816
+ await this.meter(ref, "", {
817
+ verificationFailures: 1,
818
+ bytes: body.byteLength
819
+ });
820
+ return {
821
+ response: result.response,
822
+ kept: [refused]
823
+ };
824
+ }
825
+ const kept = [];
826
+ for (const each of result.events) {
827
+ const event = this.stored(ref, adapter.id, each, {
828
+ verification: {
829
+ ok: true,
830
+ method: adapter.id,
831
+ reason: null
832
+ },
833
+ held,
834
+ size: body.byteLength,
835
+ headers: request.headers,
836
+ test
837
+ });
838
+ await this.publish(event);
839
+ await this.meter(ref, each.event, {
840
+ events: 1,
841
+ bytes: body.byteLength
842
+ });
843
+ kept.push(event);
844
+ }
845
+ return {
846
+ response: result.response,
847
+ kept
848
+ };
849
+ }
850
+ };
851
+ //#endregion
852
+ //#region src/limits.ts
853
+ /**
854
+ * The limits a tenant's config sets (PLAN §7): a rate per source and a monthly budget. The
855
+ * gateway only enforces and counts; a control plane decides the numbers.
856
+ */
857
+ const MINUTE = 6e4;
858
+ /** Fixed one-minute windows, per key. */
859
+ var RateLimiter = class {
860
+ now;
861
+ windows = /* @__PURE__ */ new Map();
862
+ constructor(now) {
863
+ this.now = now;
864
+ }
865
+ /** Takes one from the key's window; false when the window already has `perMinute`. */
866
+ take(key, perMinute) {
867
+ if (perMinute === null) return true;
868
+ const minute = Math.floor(this.now() / MINUTE);
869
+ const window = this.windows.get(key);
870
+ if (window === void 0 || window.minute !== minute) {
871
+ this.windows.set(key, {
872
+ minute,
873
+ count: 1
874
+ });
875
+ return true;
876
+ }
877
+ if (window.count >= perMinute) return false;
878
+ window.count += 1;
879
+ return true;
880
+ }
881
+ };
882
+ /** The first moment of the UTC month `at` is in. */
883
+ function monthStart(at) {
884
+ const date = new Date(at);
885
+ return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1);
886
+ }
887
+ /** Events accepted this month, per tenant: read once from the meter, then counted along. */
888
+ var Budget = class {
889
+ store;
890
+ now;
891
+ counts = /* @__PURE__ */ new Map();
892
+ constructor(store, now) {
893
+ this.store = store;
894
+ this.now = now;
895
+ }
896
+ /** This month's count of a tenant, read from the meter when the month is new to it. */
897
+ async entry(tenant) {
898
+ const month = monthStart(this.now());
899
+ const known = this.counts.get(tenant);
900
+ if (known?.month === month) return known;
901
+ const entry = {
902
+ month,
903
+ count: (await this.store.usage(tenant, {
904
+ from: month,
905
+ to: this.now(),
906
+ by: []
907
+ })).reduce((sum, row) => sum + row.events, 0)
908
+ };
909
+ this.counts.set(tenant, entry);
910
+ return entry;
911
+ }
912
+ async used(tenant) {
913
+ return (await this.entry(tenant)).count;
914
+ }
915
+ /** Whether one more event fits under `limit` (`null`: no limit). */
916
+ async fits(tenant, limit) {
917
+ return limit === null || await this.used(tenant) < limit;
918
+ }
919
+ async add(tenant, events) {
920
+ (await this.entry(tenant)).count += events;
921
+ }
922
+ forget(tenant) {
923
+ this.counts.delete(tenant);
924
+ }
925
+ };
926
+ //#endregion
927
+ //#region src/routing.ts
928
+ /**
929
+ * Who gets an event. A subscriber token gets the events of its tenant that its own scope allows
930
+ * (its project, its filters) and that its project's routes send it. A project without routes
931
+ * sends every event to every subscriber.
932
+ */
933
+ function globMatches(glob, value) {
934
+ return glob === void 0 || compileFilter(glob).test(value);
935
+ }
936
+ function routeSends(route, event, subscriber) {
937
+ return route.to.includes(subscriber) && globMatches(route.match.source, event.source) && globMatches(route.match.event, event.event) && globMatches(route.match.target, event.target);
938
+ }
939
+ /** Whether the project's routes send the event to the subscriber. */
940
+ function routedTo(tenant, event, subscriber) {
941
+ const routes = tenant.projects[event.project]?.routes ?? [];
942
+ return routes.length === 0 || routes.some((route) => routeSends(route, event, subscriber));
943
+ }
944
+ /** Whether a token's own scope (its project, its filters) allows the event. */
945
+ function tokenAllows(token, event) {
946
+ return (token.project === null || token.project === event.project) && matchesFilters(token.filters, event);
947
+ }
948
+ /** The names of the subscribers an event goes to. */
949
+ function subscribersOf(tenant, event) {
950
+ return Object.entries(tenant.tokens).filter(([name, token]) => token.scope === "subscribe" && tokenAllows(token, event) && routedTo(tenant, event, name)).map(([name]) => name);
951
+ }
952
+ //#endregion
953
+ //#region src/management-scope.ts
954
+ /** The caller, for an operation that needs one (the gateway checked access already). */
955
+ function need(context) {
956
+ if (context.principal === void 0) throw new BriefkastenError("unauthorized", "a bearer token is required");
957
+ return context.principal;
958
+ }
959
+ /** Where a tenant's subscribers connect out: its `multi` stream, else the instance's stream. */
960
+ function streamUrlOf(settings, tenant) {
961
+ const base = (settings.server.publicUrl ?? "").replace(/\/+$/, "");
962
+ return MODES[settings.mode].tenants ? `${base}/t/${encodeURIComponent(tenant)}/stream` : `${base}${STREAM_PATH}`;
963
+ }
964
+ const SECRET_KEY = /secret|token|password|key/i;
965
+ const HIDDEN = "(hidden)";
966
+ /** Options with every value under a secret-looking key hidden. */
967
+ function redacted(options) {
968
+ return Object.fromEntries(Object.entries(options).map(([key, value]) => [key, SECRET_KEY.test(key) ? HIDDEN : value]));
969
+ }
970
+ function sourceView(settings, ref) {
971
+ return {
972
+ project: ref.project,
973
+ name: ref.name,
974
+ adapter: ref.source.adapter,
975
+ options: redacted(ref.source.options),
976
+ hookUrl: hookUrlOf(settings, ref)
977
+ };
978
+ }
979
+ /** A kept token as the API shows it; a token's id on a self-hosted instance is its name. */
980
+ function tokenView(name, token) {
981
+ return token.scope === "subscribe" ? {
982
+ id: name,
983
+ kind: "subscriber",
984
+ name,
985
+ project: token.project,
986
+ filters: [...token.filters],
987
+ createdAt: token.createdAt
988
+ } : {
989
+ id: name,
990
+ kind: "management",
991
+ name,
992
+ scopes: [token.scope],
993
+ createdAt: token.createdAt
994
+ };
995
+ }
996
+ function timeOf(text, fallback, name) {
997
+ if (text === void 0) return fallback;
998
+ const parsed = Date.parse(text);
999
+ if (Number.isNaN(parsed)) throw new BriefkastenError("bad_request", `${name}: not a date or time: ${text}`);
1000
+ return parsed;
1001
+ }
1002
+ function summary(detail) {
1003
+ const { headers: _headers, body: _body, deliveryLog: _log, ...rest } = detail;
1004
+ return rest;
1005
+ }
1006
+ function tenantView(tenant) {
1007
+ return {
1008
+ name: tenant.name,
1009
+ status: tenant.status,
1010
+ plan: tenant.plan,
1011
+ limits: tenant.limits,
1012
+ version: tenant.version,
1013
+ projects: Object.keys(tenant.projects).length
1014
+ };
1015
+ }
1016
+ function sourceCount(tenant) {
1017
+ return Object.values(tenant.projects).reduce((sum, project) => sum + Object.keys(project.sources).length, 0);
1018
+ }
1019
+ function scopeOf(deps) {
1020
+ const { store } = deps;
1021
+ /** The tenant a call acts on. */
1022
+ function tenantFor(context) {
1023
+ const principal = need(context);
1024
+ const state = deps.state();
1025
+ let name;
1026
+ if (principal.kind === "tenant") {
1027
+ if (context.tenant !== void 0 && context.tenant !== principal.tenant) throw new BriefkastenError("forbidden", "this token belongs to another tenant");
1028
+ name = principal.tenant;
1029
+ } else if (context.tenant !== void 0) name = context.tenant;
1030
+ else if (MODES[state.settings.mode].tenants) throw new BriefkastenError("bad_request", `an admin token names the tenant: the ${TENANT_HEADER} header`);
1031
+ else name = DEFAULT_TENANT;
1032
+ const tenant = tenantOf(state, name);
1033
+ if (tenant === void 0) throw new BriefkastenError("not_found", `no tenant ${name}`);
1034
+ return tenant;
1035
+ }
1036
+ /** Refuses a project a token limited to another project may not touch. */
1037
+ function checkProject(context, project) {
1038
+ const principal = need(context);
1039
+ if (principal.kind === "tenant" && principal.project !== null && principal.project !== project) throw new BriefkastenError("forbidden", `this token is limited to project ${principal.project}`);
1040
+ }
1041
+ function checkUnlimited(context) {
1042
+ const principal = need(context);
1043
+ if (principal.kind === "tenant" && principal.project !== null) throw new BriefkastenError("forbidden", `this token is limited to project ${principal.project}`);
1044
+ }
1045
+ function projectOf(tenant, context, project) {
1046
+ checkProject(context, project);
1047
+ const found = tenant.projects[project];
1048
+ if (found === void 0) throw new BriefkastenError("not_found", `no project ${project}`);
1049
+ return found;
1050
+ }
1051
+ function sourceRef(tenant, context, project, source) {
1052
+ const found = projectOf(tenant, context, project).sources[source];
1053
+ if (found === void 0) throw new BriefkastenError("not_found", `no source ${source} in project ${project}`);
1054
+ return {
1055
+ tenant,
1056
+ project,
1057
+ name: source,
1058
+ source: found
1059
+ };
1060
+ }
1061
+ async function change(tenant, mutation) {
1062
+ await deps.config.apply(tenant.name, mutation);
1063
+ await deps.reload();
1064
+ const updated = tenantOf(deps.state(), tenant.name);
1065
+ if (updated === void 0) throw new BriefkastenError("not_found", `no tenant ${tenant.name}`);
1066
+ return updated;
1067
+ }
1068
+ function admin() {
1069
+ const tenants = deps.config.tenants;
1070
+ if (tenants === void 0) throw new BriefkastenError("unavailable", "tenants exist only in multi mode");
1071
+ return tenants;
1072
+ }
1073
+ async function summaryOf(tenant, event) {
1074
+ const log = await store.deliveries(tenant.name, event.id);
1075
+ const delivered = new Set(log.filter((each) => each.status === "delivered").map((each) => each.subscriber));
1076
+ const routed = event.verification.ok && !event.held ? subscribersOf(tenant, event) : [];
1077
+ const first = log.find((each) => each.status === "delivered");
1078
+ return {
1079
+ id: event.id,
1080
+ project: event.project,
1081
+ adapter: event.adapter,
1082
+ source: event.source,
1083
+ event: event.event,
1084
+ target: event.target === "" ? null : event.target,
1085
+ at: event.at,
1086
+ sizeBytes: event.sizeBytes,
1087
+ verification: event.verification,
1088
+ held: event.held,
1089
+ test: event.test === true,
1090
+ deliveries: {
1091
+ delivered: delivered.size,
1092
+ failed: log.filter((each) => each.status === "failed").length,
1093
+ pending: routed.filter((name) => !delivered.has(name)).length
1094
+ },
1095
+ latencyMs: first?.latencyMs ?? null,
1096
+ headers: { ...event.headers },
1097
+ body: event.body,
1098
+ deliveryLog: [...log]
1099
+ };
1100
+ }
1101
+ async function eventOf(tenant, id) {
1102
+ const event = await store.get(tenant.name, id);
1103
+ if (event === void 0) throw new BriefkastenError("not_found", `no event ${id}`);
1104
+ return event;
1105
+ }
1106
+ /** Closes a suspended tenant's open streams: it gets nothing more until it is active again. */
1107
+ function suspended(tenant) {
1108
+ if (tenant.status === "suspended") deps.fanout.closeTenant(tenant.name, "suspended");
1109
+ }
1110
+ /** Hands out held events, oldest first, while the budget allows. */
1111
+ async function releaseHeld(tenant) {
1112
+ deps.budget.forget(tenant.name);
1113
+ const limit = tenant.limits.eventsPerMonth;
1114
+ if (limit !== null && await deps.budget.used(tenant.name) > limit) return;
1115
+ for (const event of await store.held(tenant.name, 50)) {
1116
+ await store.release(tenant.name, event.id);
1117
+ deps.fanout.publish({
1118
+ ...event,
1119
+ held: false
1120
+ });
1121
+ }
1122
+ }
1123
+ function tenantByName(name) {
1124
+ const tenant = tenantOf(deps.state(), name);
1125
+ if (tenant === void 0) throw new BriefkastenError("not_found", `no tenant ${name}`);
1126
+ return tenant;
1127
+ }
1128
+ /** The window and grouping a usage query asks for: the month so far, ungrouped, by default. */
1129
+ function windowOf(input) {
1130
+ const now = deps.runtime.now();
1131
+ const by = input.by ?? [];
1132
+ return {
1133
+ from: new Date(timeOf(input.from, monthStart(now), "from")).toISOString(),
1134
+ to: new Date(timeOf(input.to, now, "to")).toISOString(),
1135
+ by: USAGE_DIMENSIONS.filter((dimension) => by.includes(dimension))
1136
+ };
1137
+ }
1138
+ /** A tenant's usage rows in a window; latency is not measured yet, so it is unknown. */
1139
+ async function rowsOf(tenant, window) {
1140
+ return (await store.usage(tenant, {
1141
+ from: Date.parse(window.from),
1142
+ to: Date.parse(window.to),
1143
+ by: window.by
1144
+ })).map((row) => ({
1145
+ ...row,
1146
+ latencyP50Ms: null,
1147
+ latencyP95Ms: null
1148
+ }));
1149
+ }
1150
+ return {
1151
+ tenantFor,
1152
+ checkProject,
1153
+ checkUnlimited,
1154
+ projectOf,
1155
+ sourceRef,
1156
+ change,
1157
+ admin,
1158
+ summaryOf,
1159
+ eventOf,
1160
+ suspended,
1161
+ releaseHeld,
1162
+ tenantByName,
1163
+ windowOf,
1164
+ rowsOf
1165
+ };
1166
+ }
1167
+ //#endregion
1168
+ //#region src/management-events.ts
1169
+ /** The handlers of events, usage and tenants. */
1170
+ function eventAndTenantHandlers(deps, scope) {
1171
+ const { store } = deps;
1172
+ const { tenantFor, checkProject, checkUnlimited, sourceRef, admin, summaryOf, eventOf, suspended, releaseHeld, tenantByName, windowOf, rowsOf } = scope;
1173
+ return {
1174
+ "events.list": async (input, context) => {
1175
+ const tenant = tenantFor(context);
1176
+ if (input.project !== void 0) checkProject(context, input.project);
1177
+ else checkUnlimited(context);
1178
+ const limit = input.limit ?? 50;
1179
+ const events = await store.list(tenant.name, {
1180
+ ...input.project === void 0 ? {} : { project: input.project },
1181
+ ...input.source === void 0 ? {} : { source: input.source },
1182
+ ...input.event === void 0 ? {} : { event: input.event },
1183
+ ...input.since === void 0 ? {} : { since: input.since },
1184
+ ...input.before === void 0 ? {} : { before: input.before },
1185
+ ...input.verified === void 0 ? {} : { verified: input.verified === "true" },
1186
+ limit
1187
+ });
1188
+ const summaries = await Promise.all(events.map(async (event) => summary(await summaryOf(tenant, event))));
1189
+ const last = events.at(-1);
1190
+ return {
1191
+ events: summaries,
1192
+ next: last !== void 0 && events.length === limit ? last.id : null
1193
+ };
1194
+ },
1195
+ "events.get": async (input, context) => {
1196
+ const tenant = tenantFor(context);
1197
+ const event = await eventOf(tenant, input.id);
1198
+ checkProject(context, event.project);
1199
+ return summaryOf(tenant, event);
1200
+ },
1201
+ "events.redeliver": async (input, context) => {
1202
+ const tenant = tenantFor(context);
1203
+ const event = await eventOf(tenant, input.id);
1204
+ checkProject(context, event.project);
1205
+ if (!event.verification.ok) throw new BriefkastenError("bad_request", "a delivery that failed verification is never handed out");
1206
+ if (event.held) await store.release(tenant.name, event.id);
1207
+ return { queued: deps.fanout.publish({
1208
+ ...event,
1209
+ held: false
1210
+ }, {
1211
+ redelivery: !event.held,
1212
+ ...input.subscriber === void 0 ? {} : { subscriber: input.subscriber }
1213
+ }) };
1214
+ },
1215
+ "events.emit": async (input, context) => {
1216
+ const tenant = tenantFor(context);
1217
+ const ref = sourceRef(tenant, context, input.project, input.source);
1218
+ const adapter = await deps.instances.adapterOf(ref.source.adapter, ref.source.options);
1219
+ if (adapter.arbitraryEvents !== true && adapter.events[input.event] === void 0) throw new BriefkastenError("bad_request", `${adapter.id} has no event ${input.event} (it has ${Object.keys(adapter.events).join(", ")})`);
1220
+ const fits = await deps.budget.fits(tenant.name, tenant.limits.eventsPerMonth);
1221
+ if (!fits && tenant.limits.overLimit === "refuse") throw new BriefkastenError("rate_limited", "this tenant used its events for the month");
1222
+ return { id: await deps.ingest.emit(ref, adapter.id, {
1223
+ event: input.event,
1224
+ target: input.target,
1225
+ body: input.body ?? {}
1226
+ }, !fits) };
1227
+ },
1228
+ usage: async (input, context) => {
1229
+ const tenant = tenantFor(context);
1230
+ checkUnlimited(context);
1231
+ const window = windowOf(input);
1232
+ return {
1233
+ tenant: tenant.name,
1234
+ ...window,
1235
+ rows: await rowsOf(tenant.name, window)
1236
+ };
1237
+ },
1238
+ "tenants.usage": async (input) => {
1239
+ admin();
1240
+ const window = windowOf(input);
1241
+ const names = input.tenant === void 0 ? [...deps.state().tenants.keys()] : [input.tenant];
1242
+ const rows = await Promise.all(names.map(async (tenant) => (await rowsOf(tenant, window)).map((row) => ({
1243
+ tenant,
1244
+ ...row
1245
+ }))));
1246
+ return {
1247
+ ...window,
1248
+ rows: rows.flat()
1249
+ };
1250
+ },
1251
+ "tenants.list": () => Promise.resolve({ tenants: [...deps.state().tenants.values()].map(tenantView) }),
1252
+ "tenants.create": async (input) => {
1253
+ const tenants = admin();
1254
+ if (tenantOf(deps.state(), input.name) !== void 0) throw new BriefkastenError("conflict", `tenant ${input.name} exists`);
1255
+ await tenants.create({
1256
+ name: input.name,
1257
+ status: "active",
1258
+ plan: input.plan ?? "default",
1259
+ limits: input.limits ?? deps.state().settings.limits,
1260
+ version: 1,
1261
+ owners: input.owners ?? [],
1262
+ projects: { [DEFAULT_PROJECT]: {
1263
+ sources: {},
1264
+ routes: []
1265
+ } },
1266
+ tokens: {}
1267
+ });
1268
+ await deps.reload();
1269
+ return tenantView(tenantByName(input.name));
1270
+ },
1271
+ "tenants.update": async (input) => {
1272
+ const tenants = admin();
1273
+ tenantByName(input.tenant);
1274
+ await tenants.update(input.tenant, {
1275
+ ...input.status === void 0 ? {} : { status: input.status },
1276
+ ...input.plan === void 0 ? {} : { plan: input.plan },
1277
+ ...input.limits === void 0 ? {} : { limits: input.limits }
1278
+ });
1279
+ await deps.reload();
1280
+ const tenant = tenantByName(input.tenant);
1281
+ suspended(tenant);
1282
+ await releaseHeld(tenant);
1283
+ return tenantView(tenant);
1284
+ },
1285
+ "tenants.delete": async (input) => {
1286
+ const tenants = admin();
1287
+ tenantByName(input.tenant);
1288
+ await tenants.delete(input.tenant);
1289
+ deps.fanout.closeTenant(input.tenant, "deleted");
1290
+ await store.dropTenant(input.tenant);
1291
+ deps.budget.forget(input.tenant);
1292
+ await deps.reload();
1293
+ return { deleted: true };
1294
+ },
1295
+ "tenants.config": async (input) => {
1296
+ const tenants = admin();
1297
+ const keys = deps.state().settings.controlPlane?.keys;
1298
+ if (keys === void 0 || Object.keys(keys).length === 0) throw new BriefkastenError("unavailable", "set controlPlane.keys to accept a control plane's configs");
1299
+ const config = await verifyEnvelope({
1300
+ config: input.config,
1301
+ signature: input.signature
1302
+ }, keys);
1303
+ if (config.tenant !== input.tenant) throw new BriefkastenError("bad_request", `the config is for tenant ${config.tenant}, not ${input.tenant}`);
1304
+ const current = tenantOf(deps.state(), input.tenant);
1305
+ if (current !== void 0 && current.version >= config.version) return { version: current.version };
1306
+ const version = await tenants.replace(config);
1307
+ await deps.reload();
1308
+ const tenant = tenantOfDesired(config);
1309
+ suspended(tenant);
1310
+ await releaseHeld(tenant);
1311
+ return { version };
1312
+ }
1313
+ };
1314
+ }
1315
+ //#endregion
1316
+ //#region src/management.ts
1317
+ /**
1318
+ * What every management operation does, once, whoever calls it: the HTTP API, the CLI's local
1319
+ * target, the MCP server. Access (who may call) is checked before a handler runs; a handler
1320
+ * checks what depends on the data (the tenant, the project a token is limited to, the limits).
1321
+ */
1322
+ function createHandlers(deps) {
1323
+ const shared = scopeOf(deps);
1324
+ const { tenantFor, checkUnlimited, projectOf, sourceRef, change, summaryOf } = shared;
1325
+ return {
1326
+ "auth.methods": () => Promise.resolve({
1327
+ instance: "self-hosted",
1328
+ methods: [...deps.login.methods()]
1329
+ }),
1330
+ "auth.email.start": (input) => deps.login.emailStart(input.email),
1331
+ "auth.email.verify": (input) => deps.login.emailVerify(input.login_id, input.code),
1332
+ "auth.mfa": () => Promise.reject(new BriefkastenError("unavailable", "a self-hosted instance signs in without a second factor")),
1333
+ "auth.token": (input) => input.grant_type === REFRESH_GRANT ? deps.login.refresh(String(input.refresh_token)) : deps.login.deviceToken(String(input.device_code)),
1334
+ "auth.logout": async (input) => {
1335
+ await deps.login.logout(input.refresh_token);
1336
+ return { ok: true };
1337
+ },
1338
+ "auth.device.start": () => deps.login.deviceStart(),
1339
+ "auth.device.approve": async (input, context) => {
1340
+ await deps.login.deviceApprove(need(context), input.user_code);
1341
+ return { approved: true };
1342
+ },
1343
+ whoami: (_input, context) => {
1344
+ const { settings } = deps.state();
1345
+ const who = need(context);
1346
+ const instance = {
1347
+ kind: "self-hosted",
1348
+ mode: settings.mode,
1349
+ url: settings.server.publicUrl ?? "",
1350
+ hooksUrl: settings.server.publicUrl ?? ""
1351
+ };
1352
+ const scope = who.kind === "admin" ? "admin" : who.scope;
1353
+ const principal = {
1354
+ kind: scope,
1355
+ scopes: [scope],
1356
+ readOnly: false
1357
+ };
1358
+ if (who.kind === "admin") return Promise.resolve({
1359
+ instance,
1360
+ account: null,
1361
+ tenant: null,
1362
+ plan: {
1363
+ id: "self-hosted",
1364
+ name: "self-hosted"
1365
+ },
1366
+ limits: null,
1367
+ billing: false,
1368
+ principal
1369
+ });
1370
+ const tenant = tenantFor(context);
1371
+ return Promise.resolve({
1372
+ instance,
1373
+ account: who.name.includes("@") ? {
1374
+ id: who.name,
1375
+ email: who.name
1376
+ } : null,
1377
+ tenant: {
1378
+ id: tenant.name,
1379
+ status: tenant.status
1380
+ },
1381
+ plan: {
1382
+ id: tenant.plan,
1383
+ name: tenant.plan
1384
+ },
1385
+ limits: tenant.limits,
1386
+ billing: false,
1387
+ principal
1388
+ });
1389
+ },
1390
+ "projects.list": (_input, context) => {
1391
+ const tenant = tenantFor(context);
1392
+ const principal = need(context);
1393
+ return Promise.resolve({ projects: Object.entries(tenant.projects).filter(([name]) => principal.kind === "admin" || principal.project === null || principal.project === name).map(([name, project]) => ({
1394
+ name,
1395
+ sources: Object.keys(project.sources).length
1396
+ })) });
1397
+ },
1398
+ "projects.create": async (input, context) => {
1399
+ const tenant = tenantFor(context);
1400
+ checkUnlimited(context);
1401
+ if (!MODES[deps.state().settings.mode].projects) throw new BriefkastenError("bad_request", "single mode has one project: use personal mode for more");
1402
+ await change(tenant, {
1403
+ kind: "project.create",
1404
+ project: input.name
1405
+ });
1406
+ return { name: input.name };
1407
+ },
1408
+ "projects.delete": async (input, context) => {
1409
+ const tenant = tenantFor(context);
1410
+ checkUnlimited(context);
1411
+ if (!MODES[deps.state().settings.mode].projects) throw new BriefkastenError("bad_request", "single mode has one project, which cannot be deleted");
1412
+ await change(tenant, {
1413
+ kind: "project.delete",
1414
+ project: input.project
1415
+ });
1416
+ return { deleted: true };
1417
+ },
1418
+ "sources.list": (input, context) => {
1419
+ const tenant = tenantFor(context);
1420
+ const project = projectOf(tenant, context, input.project);
1421
+ const { settings } = deps.state();
1422
+ return Promise.resolve({ sources: Object.entries(project.sources).map(([name, source]) => sourceView(settings, {
1423
+ tenant,
1424
+ project: input.project,
1425
+ name,
1426
+ source
1427
+ })) });
1428
+ },
1429
+ "sources.create": async (input, context) => {
1430
+ const tenant = tenantFor(context);
1431
+ const name = input.name ?? input.adapter;
1432
+ projectOf(tenant, context, input.project);
1433
+ const options = input.options ?? {};
1434
+ await deps.instances.adapterOf(input.adapter, options);
1435
+ const { limits } = tenant;
1436
+ if (limits.sources !== null && sourceCount(tenant) >= limits.sources) throw new BriefkastenError("limit", `the plan allows ${limits.sources} sources`);
1437
+ const { settings } = deps.state();
1438
+ const taken = Object.entries(tenant.projects).find(([, project]) => project.sources[name] !== void 0);
1439
+ if (!settings.hooks.hasProject && taken !== void 0) throw new BriefkastenError("conflict", `source ${name} exists in project ${taken[0]}, and hook URLs (${settings.hooks.template}) name only the source`);
1440
+ const secret = input.secret ?? sourceSecret(deps.runtime.random);
1441
+ const updated = await change(tenant, {
1442
+ kind: "source.create",
1443
+ project: input.project,
1444
+ source: name,
1445
+ adapter: input.adapter,
1446
+ options,
1447
+ secret
1448
+ });
1449
+ const ref = sourceRef(updated, context, input.project, name);
1450
+ await deps.startSource(ref);
1451
+ return {
1452
+ ...sourceView(settings, ref),
1453
+ secret
1454
+ };
1455
+ },
1456
+ "sources.update": async (input, context) => {
1457
+ const tenant = tenantFor(context);
1458
+ const current = sourceRef(tenant, context, input.project, input.source);
1459
+ if (input.options !== void 0) await deps.instances.adapterOf(current.source.adapter, input.options);
1460
+ const rotated = input.rotateSecret === true ? sourceSecret(deps.runtime.random) : void 0;
1461
+ const secret = rotated ?? input.secret;
1462
+ const updated = await change(tenant, {
1463
+ kind: "source.update",
1464
+ project: input.project,
1465
+ source: input.source,
1466
+ ...input.options === void 0 ? {} : { options: input.options },
1467
+ ...secret === void 0 ? {} : { secret }
1468
+ });
1469
+ const ref = sourceRef(updated, context, input.project, input.source);
1470
+ await deps.startSource(ref);
1471
+ return {
1472
+ ...sourceView(deps.state().settings, ref),
1473
+ secret: rotated ?? null
1474
+ };
1475
+ },
1476
+ "sources.delete": async (input, context) => {
1477
+ const tenant = tenantFor(context);
1478
+ sourceRef(tenant, context, input.project, input.source);
1479
+ await change(tenant, {
1480
+ kind: "source.delete",
1481
+ project: input.project,
1482
+ source: input.source
1483
+ });
1484
+ return { deleted: true };
1485
+ },
1486
+ "sources.test": async (input, context) => {
1487
+ const tenant = tenantFor(context);
1488
+ const ref = sourceRef(tenant, context, input.project, input.source);
1489
+ const adapter = await deps.instances.adapterOf(ref.source.adapter, ref.source.options);
1490
+ const sample = sampleOf(adapter, input.event);
1491
+ if (sample === void 0) {
1492
+ const known = (adapter.samples ?? []).map((each) => each.event);
1493
+ throw new BriefkastenError("bad_request", known.length === 0 ? `${adapter.id} has no samples` : `${adapter.id} has no sample ${String(input.event)}; it has: ${known.join(", ")}`);
1494
+ }
1495
+ const now = deps.runtime.now();
1496
+ const delivery = await sample.delivery({
1497
+ secret: ref.source.secret,
1498
+ now,
1499
+ id: randomToken("dlv", deps.runtime.random)
1500
+ });
1501
+ const fits = await deps.budget.fits(tenant.name, tenant.limits.eventsPerMonth);
1502
+ if (!fits && tenant.limits.overLimit === "refuse") throw new BriefkastenError("rate_limited", "this tenant used its events for the month");
1503
+ const [first] = await deps.ingest.inject(ref, delivery, !fits);
1504
+ if (first === void 0) throw new BriefkastenError("bad_request", `${adapter.id} made no event of the sample ${sample.event}`);
1505
+ return { event: summary(await summaryOf(tenant, first)) };
1506
+ },
1507
+ "adapters.list": async () => {
1508
+ const ids = /* @__PURE__ */ new Set([...KNOWN_ADAPTERS, ...[...deps.state().tenants.values()].flatMap((tenant) => Object.values(tenant.projects).flatMap((project) => Object.values(project.sources).map((source) => source.adapter)))]);
1509
+ return { adapters: (await Promise.all([...ids].map((id) => deps.adapters.resolve(id)))).flatMap((adapter) => adapter === void 0 ? [] : [{
1510
+ id: adapter.id,
1511
+ name: adapter.name ?? adapter.id,
1512
+ samples: (adapter.samples ?? []).map(({ event, title }) => ({
1513
+ event,
1514
+ title
1515
+ }))
1516
+ }]) };
1517
+ },
1518
+ "routes.get": (input, context) => {
1519
+ const tenant = tenantFor(context);
1520
+ return Promise.resolve({ routes: [...projectOf(tenant, context, input.project).routes] });
1521
+ },
1522
+ "routes.put": async (input, context) => {
1523
+ const tenant = tenantFor(context);
1524
+ projectOf(tenant, context, input.project);
1525
+ await change(tenant, {
1526
+ kind: "routes.set",
1527
+ project: input.project,
1528
+ routes: input.routes
1529
+ });
1530
+ return { routes: input.routes };
1531
+ },
1532
+ "tokens.list": (input, context) => {
1533
+ const tenant = tenantFor(context);
1534
+ checkUnlimited(context);
1535
+ return Promise.resolve({ tokens: Object.entries(tenant.tokens).map(([name, token]) => tokenView(name, token)).filter((token) => input.kind === void 0 || token.kind === input.kind) });
1536
+ },
1537
+ "tokens.create": async (input, context) => {
1538
+ const tenant = tenantFor(context);
1539
+ checkUnlimited(context);
1540
+ const project = input.project ?? null;
1541
+ if (project !== null) projectOf(tenant, context, project);
1542
+ const subscriber = input.kind === "subscriber";
1543
+ const { limits } = tenant;
1544
+ const subscribers = Object.values(tenant.tokens).filter((token) => token.scope === "subscribe").length;
1545
+ if (subscriber && limits.subscribers !== null && subscribers >= limits.subscribers) throw new BriefkastenError("limit", `the plan allows ${limits.subscribers} subscribers`);
1546
+ if (tenant.tokens[input.name] !== void 0) throw new BriefkastenError("conflict", `a token named ${input.name} exists`);
1547
+ const token = base62Token(subscriber ? "bk_sub" : "bk_pat", deps.runtime.random);
1548
+ const kept = {
1549
+ scope: subscriber ? "subscribe" : "manage",
1550
+ project,
1551
+ filters: input.filters ?? [],
1552
+ tokenSha256: await sha256Hex(token),
1553
+ createdAt: new Date(deps.runtime.now()).toISOString()
1554
+ };
1555
+ await change(tenant, {
1556
+ kind: "token.create",
1557
+ name: input.name,
1558
+ token: kept
1559
+ });
1560
+ const view = tokenView(input.name, kept);
1561
+ return view.kind === "subscriber" ? {
1562
+ ...view,
1563
+ token,
1564
+ streamUrl: streamUrlOf(deps.state().settings, tenant.name)
1565
+ } : {
1566
+ ...view,
1567
+ token
1568
+ };
1569
+ },
1570
+ "tokens.delete": async (input, context) => {
1571
+ const tenant = tenantFor(context);
1572
+ checkUnlimited(context);
1573
+ if (tenant.tokens[input.id] === void 0) throw new BriefkastenError("not_found", `no token ${input.id}`);
1574
+ await change(tenant, {
1575
+ kind: "token.delete",
1576
+ name: input.id
1577
+ });
1578
+ return { deleted: true };
1579
+ },
1580
+ ...eventAndTenantHandlers(deps, shared)
1581
+ };
1582
+ }
1583
+ //#endregion
1584
+ //#region src/stream.ts
1585
+ /**
1586
+ * The live side of the stream: open sessions, and an event's way to each that wants it. The
1587
+ * stored side (catch-up after `since`) is the event store's; a session reads the store first,
1588
+ * then what arrived live meanwhile, so a reconnecting client misses nothing still kept.
1589
+ */
1590
+ /** How many stored events a catch-up reads at a time. */
1591
+ const PAGE = 200;
1592
+ var Fanout = class {
1593
+ listeners = /* @__PURE__ */ new Set();
1594
+ add(listener) {
1595
+ this.listeners.add(listener);
1596
+ return () => {
1597
+ this.listeners.delete(listener);
1598
+ };
1599
+ }
1600
+ /**
1601
+ * Hands the event to every open session of its tenant that wants it (only `subscriber`'s
1602
+ * when given); answers how many took it.
1603
+ */
1604
+ publish(event, options = {}) {
1605
+ let count = 0;
1606
+ for (const listener of this.listeners) {
1607
+ const named = options.subscriber === void 0 || listener.subscriber === options.subscriber;
1608
+ if (listener.tenant === event.tenant && named && listener.wants(event)) {
1609
+ listener.push({
1610
+ event,
1611
+ redelivery: options.redelivery ?? false
1612
+ });
1613
+ count += 1;
1614
+ }
1615
+ }
1616
+ return count;
1617
+ }
1618
+ /** Ends every open session of a tenant, saying why. */
1619
+ closeTenant(tenant, reason) {
1620
+ for (const listener of this.listeners) if (listener.tenant === tenant) listener.end(reason);
1621
+ }
1622
+ size() {
1623
+ return this.listeners.size;
1624
+ }
1625
+ };
1626
+ /**
1627
+ * The event a stream carries: the stored event without what only the gateway keeps (its headers),
1628
+ * with its summary as it is when it is sent. Its deliveries are still to come then, so they are
1629
+ * none and its latency unknown; `events.get` answers them later.
1630
+ */
1631
+ function streamEvent(event) {
1632
+ return {
1633
+ id: event.id,
1634
+ tenant: event.tenant,
1635
+ project: event.project,
1636
+ adapter: event.adapter,
1637
+ source: event.source,
1638
+ target: event.target,
1639
+ event: event.event,
1640
+ at: event.at,
1641
+ body: event.body,
1642
+ sizeBytes: event.sizeBytes,
1643
+ verification: event.verification,
1644
+ held: event.held,
1645
+ test: event.test === true,
1646
+ deliveries: {
1647
+ delivered: 0,
1648
+ failed: 0,
1649
+ pending: 0
1650
+ },
1651
+ latencyMs: null
1652
+ };
1653
+ }
1654
+ /** Opens a session: the stored events after `since`, then the live ones, each once. */
1655
+ function openSession(deps, request) {
1656
+ const wants = (event) => (request.project === void 0 || event.project === request.project) && matchesFilters(request.filters, event) && request.allowed(event);
1657
+ const queue = [];
1658
+ let endedBy;
1659
+ let wake;
1660
+ let closed = false;
1661
+ const remove = deps.fanout.add({
1662
+ tenant: request.tenant,
1663
+ ...request.subscriber === void 0 ? {} : { subscriber: request.subscriber },
1664
+ wants,
1665
+ push: (entry) => {
1666
+ queue.push(entry);
1667
+ wake?.();
1668
+ },
1669
+ end: (reason) => {
1670
+ endedBy = reason;
1671
+ close();
1672
+ }
1673
+ });
1674
+ const record = (entry) => {
1675
+ const subscriber = request.subscriber;
1676
+ if (subscriber === void 0) return;
1677
+ const now = deps.now();
1678
+ deps.delivered(entry.event);
1679
+ deps.store.deliveries(request.tenant, entry.event.id).then((log) => {
1680
+ const delivery = {
1681
+ subscriber,
1682
+ attempt: log.filter((each) => each.subscriber === subscriber).length + 1,
1683
+ at: new Date(now).toISOString(),
1684
+ status: "delivered",
1685
+ latencyMs: Math.max(0, now - Date.parse(entry.event.at)),
1686
+ error: null,
1687
+ redelivery: entry.redelivery
1688
+ };
1689
+ return deps.store.recordDelivery(request.tenant, entry.event.id, delivery);
1690
+ }).catch((error) => {
1691
+ deps.log(`recording a delivery failed: ${messageOf(error)}`);
1692
+ });
1693
+ };
1694
+ async function* items() {
1695
+ const seen = /* @__PURE__ */ new Set();
1696
+ try {
1697
+ let cursor = request.since;
1698
+ while (cursor !== void 0) {
1699
+ const page = await deps.store.after(request.tenant, cursor, PAGE);
1700
+ if (!page.found) yield {
1701
+ kind: "gap",
1702
+ since: cursor
1703
+ };
1704
+ for (const event of page.events) if (wants(event)) {
1705
+ seen.add(event.id);
1706
+ record({
1707
+ event,
1708
+ redelivery: false
1709
+ });
1710
+ yield {
1711
+ kind: "event",
1712
+ event: streamEvent(event)
1713
+ };
1714
+ }
1715
+ cursor = page.events.length === PAGE ? page.events.at(-1)?.id : void 0;
1716
+ }
1717
+ for (;;) {
1718
+ if (closed) break;
1719
+ const entry = queue.shift();
1720
+ if (entry === void 0) {
1721
+ await new Promise((resolve) => {
1722
+ wake = resolve;
1723
+ });
1724
+ wake = void 0;
1725
+ } else if (entry.redelivery || !seen.has(entry.event.id)) {
1726
+ record(entry);
1727
+ yield {
1728
+ kind: "event",
1729
+ event: streamEvent(entry.event)
1730
+ };
1731
+ }
1732
+ }
1733
+ } finally {
1734
+ closed = true;
1735
+ remove();
1736
+ }
1737
+ }
1738
+ function close() {
1739
+ closed = true;
1740
+ remove();
1741
+ wake?.();
1742
+ }
1743
+ return {
1744
+ items: items(),
1745
+ close,
1746
+ ended: () => endedBy
1747
+ };
1748
+ }
1749
+ //#endregion
1750
+ //#region src/gateway.ts
1751
+ const PRUNE_MS = 6e5;
1752
+ const DAY_MS = 864e5;
1753
+ async function createGateway(deps) {
1754
+ const runtime = deps.runtime ?? {
1755
+ now: Date.now,
1756
+ random: randomBytes
1757
+ };
1758
+ const log = deps.log ?? (() => void 0);
1759
+ let state = stateOf(await deps.config.load());
1760
+ const current = () => state;
1761
+ const fanout = new Fanout();
1762
+ const instances = new Instances(deps.adapters);
1763
+ const budget = new Budget(deps.store, runtime.now);
1764
+ const ingest = new Ingest({
1765
+ state: current,
1766
+ instances,
1767
+ store: deps.store,
1768
+ fanout,
1769
+ limiter: new RateLimiter(runtime.now),
1770
+ budget,
1771
+ runtime,
1772
+ log,
1773
+ ...deps.capture === void 0 ? {} : { capture: deps.capture }
1774
+ });
1775
+ const login = new Login({
1776
+ kv: deps.kv,
1777
+ runtime,
1778
+ state: current,
1779
+ ...deps.mailer === void 0 ? {} : { mailer: deps.mailer }
1780
+ });
1781
+ const verifiers = [
1782
+ staticVerifier(current),
1783
+ sessionVerifier(deps.kv),
1784
+ signedVerifier(current, runtime.now),
1785
+ ...deps.verifiers ?? []
1786
+ ];
1787
+ async function startSource(ref) {
1788
+ try {
1789
+ const { instance } = await instances.get(ref);
1790
+ const { publicUrl } = state.settings.server;
1791
+ await instance.start?.({
1792
+ source: ref.name,
1793
+ ...publicUrl === void 0 ? {} : { hookUrl: hookUrlOf(state.settings, ref) }
1794
+ });
1795
+ } catch (error) {
1796
+ log(`${ref.tenant.name}/${ref.project}/${ref.name}: start failed: ${messageOf(error)}`);
1797
+ }
1798
+ }
1799
+ async function reload() {
1800
+ state = stateOf(await deps.config.load());
1801
+ }
1802
+ const handlers = createHandlers({
1803
+ state: current,
1804
+ config: deps.config,
1805
+ reload,
1806
+ instances,
1807
+ adapters: deps.adapters,
1808
+ store: deps.store,
1809
+ fanout,
1810
+ ingest,
1811
+ login,
1812
+ budget,
1813
+ runtime,
1814
+ startSource
1815
+ });
1816
+ async function invoke(id, raw, context) {
1817
+ const parsed = READERS[id].readInput(raw);
1818
+ if (!parsed.success) throw new BriefkastenError("bad_request", zodErrorSummary(parsed.error));
1819
+ return await handlers[id](parsed.data, context);
1820
+ }
1821
+ async function principalOf(request) {
1822
+ const token = bearerOf(request);
1823
+ return token === void 0 ? void 0 : await verifyToken(verifiers, token);
1824
+ }
1825
+ async function api(request, url, path) {
1826
+ for (const compiled of ROUTES) {
1827
+ const match = compiled.pattern.exec(path);
1828
+ if (match === null || compiled.operation.method !== request.method) continue;
1829
+ const principal = allowed(compiled.operation, await principalOf(request), MODES[state.settings.mode].tenants);
1830
+ const input = await inputOf(request, url, compiled, match);
1831
+ const tenant = compiled.operation.tenant ? namedTenant(request) : void 0;
1832
+ const context = {
1833
+ ...principal === void 0 ? {} : { principal },
1834
+ ...tenant === void 0 ? {} : { tenant }
1835
+ };
1836
+ return json$1(200, await invoke(compiled.id, input, context));
1837
+ }
1838
+ throw new BriefkastenError("not_found", `no route ${request.method} ${path}`);
1839
+ }
1840
+ /** The stream's tenant and who may see what, for a request. */
1841
+ async function openStream(request) {
1842
+ try {
1843
+ const url = new URL(request.url);
1844
+ const path = pathOf(url);
1845
+ const principal = await principalOf(request);
1846
+ if (principal === void 0) throw new BriefkastenError("unauthorized", "a bearer token is required");
1847
+ const inPath = TENANT_STREAM.exec(path);
1848
+ const named = inPath === null ? namedTenant(request) : decodeURIComponent(String(inPath[1]));
1849
+ let tenantName;
1850
+ if (principal.kind === "admin") {
1851
+ if (named === void 0) throw new BriefkastenError("bad_request", `an admin token names the tenant: the ${TENANT_HEADER} header`);
1852
+ tenantName = named;
1853
+ } else {
1854
+ if (named !== void 0 && named !== principal.tenant) throw new BriefkastenError("forbidden", "this token belongs to another tenant");
1855
+ tenantName = principal.tenant;
1856
+ }
1857
+ const tenant = state.tenants.get(tenantName);
1858
+ if (tenant === void 0) throw new BriefkastenError("not_found", `no tenant ${tenantName}`);
1859
+ if (tenant.status === "suspended") throw new BriefkastenError("tenant_suspended", "this tenant is suspended");
1860
+ const since = (request.headers.get("last-event-id") ?? url.searchParams.get("since") ?? "").trim();
1861
+ const project = url.searchParams.get("project") ?? void 0;
1862
+ const filters = url.searchParams.getAll("filter").flatMap((value) => value.split(",")).map((value) => value.trim()).filter((value) => value.length > 0);
1863
+ const subscriber = principal.kind === "tenant" && principal.scope === "subscribe" ? principal.name : void 0;
1864
+ return {
1865
+ kind: "session",
1866
+ session: openSession({
1867
+ store: deps.store,
1868
+ fanout,
1869
+ now: runtime.now,
1870
+ log,
1871
+ delivered: (event) => {
1872
+ deps.store.meter({
1873
+ tenant: event.tenant,
1874
+ at: runtime.now(),
1875
+ project: event.project,
1876
+ source: event.source,
1877
+ event: event.event,
1878
+ counts: { deliveries: 1 }
1879
+ });
1880
+ }
1881
+ }, {
1882
+ tenant: tenantName,
1883
+ ...subscriber === void 0 ? {} : { subscriber },
1884
+ allowed: (event) => {
1885
+ if (principal.kind === "admin") return true;
1886
+ const live = state.tenants.get(tenantName);
1887
+ return live !== void 0 && tokenAllows(principal, event) && (subscriber === void 0 || routedTo(live, event, subscriber));
1888
+ },
1889
+ filters,
1890
+ ...project === void 0 ? {} : { project },
1891
+ ...since.length > 0 ? { since } : {}
1892
+ }),
1893
+ ...(request.headers.get("sec-websocket-protocol") ?? "").split(",").map((each) => each.trim()).includes(WS_PROTOCOL) ? { protocol: WS_PROTOCOL } : {}
1894
+ };
1895
+ } catch (error) {
1896
+ return {
1897
+ kind: "refused",
1898
+ response: errorResponse(error)
1899
+ };
1900
+ }
1901
+ }
1902
+ async function sse(request) {
1903
+ const opening = await openStream(request);
1904
+ if (opening.kind === "refused") return opening.response;
1905
+ return sseResponse(opening.session);
1906
+ }
1907
+ function health() {
1908
+ return json$1(200, {
1909
+ ok: true,
1910
+ ...deps.version === void 0 ? {} : { version: deps.version }
1911
+ });
1912
+ }
1913
+ /** Whether a request asks for a stream this listener serves. */
1914
+ function isStream(request, path, internal) {
1915
+ return request.method === "GET" && (internal && path === STREAM_PATH || MODES[state.settings.mode].tenants && TENANT_STREAM.test(path));
1916
+ }
1917
+ async function publicRoute(request) {
1918
+ const path = pathOf(new URL(request.url));
1919
+ if (request.method === "GET" && path === "/health") return health();
1920
+ if (isStream(request, path, false)) return sse(request);
1921
+ if (request.method === "POST") {
1922
+ const response = await ingest.handle(request, path).catch(errorResponse);
1923
+ if (response !== void 0) return response;
1924
+ }
1925
+ return json$1(404, { error: {
1926
+ code: "not_found",
1927
+ message: "not found"
1928
+ } });
1929
+ }
1930
+ function route(request) {
1931
+ const url = new URL(request.url);
1932
+ const path = pathOf(url);
1933
+ if (isStream(request, path, true)) return sse(request);
1934
+ if (path.startsWith(`${API_PREFIX}/`)) return api(request, url, path.slice(API_PREFIX.length)).catch(errorResponse);
1935
+ if (request.method === "GET" && path === "/device") return Promise.resolve(new Response(DEVICE_PAGE, {
1936
+ status: 200,
1937
+ headers: { "content-type": "text/html; charset=utf-8" }
1938
+ }));
1939
+ return publicRoute(request);
1940
+ }
1941
+ let timer;
1942
+ async function prune() {
1943
+ for (const tenant of state.tenants.values()) await deps.store.prune(tenant.name, runtime.now() - tenant.limits.retentionDays * DAY_MS);
1944
+ }
1945
+ return {
1946
+ fetch: route,
1947
+ publicFetch: publicRoute,
1948
+ openStream,
1949
+ call: (id, input, principal, tenant) => invoke(id, input, {
1950
+ principal,
1951
+ ...tenant === void 0 ? {} : { tenant }
1952
+ }),
1953
+ hooks: () => allSources(state).map((ref) => ({
1954
+ tenant: ref.tenant.name,
1955
+ project: ref.project,
1956
+ source: ref.name,
1957
+ adapter: ref.source.adapter,
1958
+ hookUrl: hookUrlOf(state.settings, ref)
1959
+ })),
1960
+ start: async () => {
1961
+ for (const ref of allSources(state)) await startSource(ref);
1962
+ await prune();
1963
+ timer = setInterval(() => {
1964
+ prune().catch((error) => {
1965
+ log(`pruning failed: ${messageOf(error)}`);
1966
+ });
1967
+ }, PRUNE_MS);
1968
+ },
1969
+ reload,
1970
+ close: () => {
1971
+ clearInterval(timer);
1972
+ return Promise.resolve();
1973
+ }
1974
+ };
1975
+ }
1976
+ //#endregion
1977
+ //#region src/mail.ts
1978
+ const RESEND_URL = "https://api.resend.com/emails";
1979
+ function idOf(body) {
1980
+ const record = recordOf(body);
1981
+ const id = record["id"] ?? record["messageId"];
1982
+ return typeof id === "string" ? id : "unknown";
1983
+ }
1984
+ function reasonOf(body) {
1985
+ const message = recordOf(body)["message"];
1986
+ return typeof message === "string" ? message : "no reason given";
1987
+ }
1988
+ function resendMailer(options) {
1989
+ const send = options.fetch ?? ((input, init) => fetch(input, init));
1990
+ return {
1991
+ name: "resend",
1992
+ async send(message) {
1993
+ const response = await send(RESEND_URL, {
1994
+ method: "POST",
1995
+ headers: {
1996
+ authorization: `Bearer ${options.apiKey}`,
1997
+ "content-type": "application/json"
1998
+ },
1999
+ body: JSON.stringify({
2000
+ from: message.from ?? options.from,
2001
+ to: [message.to],
2002
+ subject: message.subject,
2003
+ text: message.text
2004
+ })
2005
+ });
2006
+ const body = await response.json().catch(() => void 0);
2007
+ if (!response.ok) throw new Error(`resend answered ${response.status}: ${reasonOf(body)}`);
2008
+ return { id: idOf(body) };
2009
+ }
2010
+ };
2011
+ }
2012
+ /**
2013
+ * Cloudflare Email Sending through a Worker's `send_email` binding. It exists only inside a
2014
+ * Worker: on Node there is no binding to pass, so a Node instance mails through Resend or SMTP.
2015
+ */
2016
+ function cloudflareMailer(options) {
2017
+ return {
2018
+ name: "cloudflare",
2019
+ async send(message) {
2020
+ return { id: idOf(await options.binding.send({
2021
+ from: message.from ?? options.from,
2022
+ to: message.to,
2023
+ subject: message.subject,
2024
+ text: message.text
2025
+ })) };
2026
+ }
2027
+ };
2028
+ }
2029
+ /** Prints each message to the log: for development, where nothing should leave the machine. */
2030
+ function consoleMailer(options) {
2031
+ let count = 0;
2032
+ return {
2033
+ name: "console",
2034
+ send(message) {
2035
+ count += 1;
2036
+ options.log(`mail to ${message.to}: ${message.subject}\n${message.text}`);
2037
+ return Promise.resolve({ id: `console-${count}` });
2038
+ }
2039
+ };
2040
+ }
2041
+ const HOUR_LENGTH = 13;
2042
+ const DAY_LENGTH = 10;
2043
+ const FIELD_DIMENSIONS = [
2044
+ "project",
2045
+ "source",
2046
+ "event"
2047
+ ];
2048
+ /** The UTC hour a time falls in, e.g. `2026-12-03T14`. */
2049
+ function hourOf(at) {
2050
+ return new Date(at).toISOString().slice(0, HOUR_LENGTH);
2051
+ }
2052
+ /** When an hour bucket starts, in epoch milliseconds. */
2053
+ function hourStart(hour) {
2054
+ return Date.parse(`${hour}:00:00.000Z`);
2055
+ }
2056
+ function zeroCounts() {
2057
+ return {
2058
+ events: 0,
2059
+ verificationFailures: 0,
2060
+ deliveries: 0,
2061
+ deliveryFailures: 0,
2062
+ rateLimited: 0,
2063
+ bytes: 0
2064
+ };
2065
+ }
2066
+ /** Whether a meter hour falls between `from` (its hour included) and `to`. */
2067
+ function inRange(hour, from, to) {
2068
+ const start = hourStart(hour);
2069
+ return start >= hourStart(hourOf(from)) && start < to;
2070
+ }
2071
+ /** Sums meter rows into usage rows grouped by the dimensions, sorted by their key. */
2072
+ function groupUsage(rows, by) {
2073
+ const groups = /* @__PURE__ */ new Map();
2074
+ for (const each of rows) {
2075
+ const row = {};
2076
+ if (by.includes("hour")) row["bucket"] = each.hour;
2077
+ else if (by.includes("day")) row["bucket"] = each.hour.slice(0, DAY_LENGTH);
2078
+ for (const dimension of FIELD_DIMENSIONS) if (by.includes(dimension)) row[dimension] = each[dimension];
2079
+ const key = JSON.stringify(row);
2080
+ const group = groups.get(key) ?? {
2081
+ row,
2082
+ counts: zeroCounts()
2083
+ };
2084
+ for (const counter of COUNTERS) group.counts[counter] += each.counts[counter];
2085
+ groups.set(key, group);
2086
+ }
2087
+ return [...groups.entries()].toSorted(([a], [b]) => a < b ? -1 : 1).map(([, group]) => ({
2088
+ ...group.row,
2089
+ ...group.counts
2090
+ }));
2091
+ }
2092
+ /** The full counts of a meter entry: what it does not name is zero. */
2093
+ function countsOf(entry) {
2094
+ const counts = zeroCounts();
2095
+ for (const counter of COUNTERS) counts[counter] = entry.counts[counter] ?? 0;
2096
+ return counts;
2097
+ }
2098
+ /** Whether an event passes a history query's field filters (not its id bounds or limit). */
2099
+ function matchesQuery(event, query) {
2100
+ return (query.project === void 0 || event.project === query.project) && (query.source === void 0 || event.source === query.source) && (query.event === void 0 || event.event === query.event) && (query.verified === void 0 || event.verification.ok === query.verified);
2101
+ }
2102
+ function deliverable(event) {
2103
+ return event.verification.ok && !event.held;
2104
+ }
2105
+ /** Keeps only the events `keep` keeps, with their deliveries; answers how many it dropped. */
2106
+ function drop(tenant, keep) {
2107
+ const kept = tenant.events.filter(keep);
2108
+ for (const event of tenant.events) if (!kept.includes(event)) tenant.deliveries.delete(event.id);
2109
+ const dropped = tenant.events.length - kept.length;
2110
+ tenant.events = kept;
2111
+ return dropped;
2112
+ }
2113
+ function memoryStores(options = {}) {
2114
+ const now = options.now ?? Date.now;
2115
+ const capacity = options.capacity ?? 1e4;
2116
+ const tenants = /* @__PURE__ */ new Map();
2117
+ function state(tenant) {
2118
+ const found = tenants.get(tenant);
2119
+ if (found !== void 0) return found;
2120
+ const created = {
2121
+ events: [],
2122
+ deliveries: /* @__PURE__ */ new Map(),
2123
+ meter: /* @__PURE__ */ new Map()
2124
+ };
2125
+ tenants.set(tenant, created);
2126
+ return created;
2127
+ }
2128
+ const events = {
2129
+ append(event) {
2130
+ const tenant = state(event.tenant);
2131
+ tenant.events.push(event);
2132
+ if (tenant.events.length > capacity) {
2133
+ const oldest = new Set(tenant.events.slice(0, tenant.events.length - capacity));
2134
+ drop(tenant, (each) => !oldest.has(each));
2135
+ }
2136
+ return Promise.resolve();
2137
+ },
2138
+ after(tenant, since, limit) {
2139
+ const list = state(tenant).events;
2140
+ const index = since === void 0 ? -1 : list.findIndex((each) => each.id === since);
2141
+ return Promise.resolve({
2142
+ events: list.slice(index + 1).filter(deliverable).slice(0, limit),
2143
+ found: since === void 0 || index !== -1
2144
+ });
2145
+ },
2146
+ list(tenant, query) {
2147
+ const list = state(tenant).events;
2148
+ const since = query.since === void 0 ? -1 : list.findIndex((e) => e.id === query.since);
2149
+ const before = query.before === void 0 ? -1 : list.findIndex((e) => e.id === query.before);
2150
+ return Promise.resolve(list.slice(since + 1, before === -1 ? list.length : before).filter((event) => matchesQuery(event, query)).toReversed().slice(0, query.limit));
2151
+ },
2152
+ get(tenant, id) {
2153
+ return Promise.resolve(state(tenant).events.find((event) => event.id === id));
2154
+ },
2155
+ held(tenant, limit) {
2156
+ return Promise.resolve(state(tenant).events.filter((event) => event.held).slice(0, limit));
2157
+ },
2158
+ release(tenant, id) {
2159
+ const found = state(tenant);
2160
+ found.events = found.events.map((event) => event.id === id ? {
2161
+ ...event,
2162
+ held: false
2163
+ } : event);
2164
+ return Promise.resolve();
2165
+ },
2166
+ recordDelivery(tenant, eventId, delivery) {
2167
+ const deliveries = state(tenant).deliveries;
2168
+ deliveries.set(eventId, [...deliveries.get(eventId) ?? [], delivery]);
2169
+ return Promise.resolve();
2170
+ },
2171
+ deliveries(tenant, eventId) {
2172
+ return Promise.resolve(state(tenant).deliveries.get(eventId) ?? []);
2173
+ },
2174
+ meter(entry) {
2175
+ const meter = state(entry.tenant).meter;
2176
+ const hour = hourOf(entry.at);
2177
+ const key = JSON.stringify([
2178
+ hour,
2179
+ entry.project,
2180
+ entry.source,
2181
+ entry.event
2182
+ ]);
2183
+ const counts = countsOf(entry);
2184
+ const previous = meter.get(key);
2185
+ if (previous !== void 0) for (const counter of COUNTERS) counts[counter] += previous.counts[counter];
2186
+ meter.set(key, {
2187
+ hour,
2188
+ project: entry.project,
2189
+ source: entry.source,
2190
+ event: entry.event,
2191
+ counts
2192
+ });
2193
+ return Promise.resolve();
2194
+ },
2195
+ usage(tenant, query) {
2196
+ const rows = [...state(tenant).meter.values()].filter((row) => inRange(row.hour, query.from, query.to));
2197
+ return Promise.resolve(groupUsage(rows, query.by));
2198
+ },
2199
+ prune(tenant, before) {
2200
+ return Promise.resolve(drop(state(tenant), (event) => Date.parse(event.at) >= before));
2201
+ },
2202
+ dropTenant(tenant) {
2203
+ tenants.delete(tenant);
2204
+ return Promise.resolve();
2205
+ }
2206
+ };
2207
+ const values = /* @__PURE__ */ new Map();
2208
+ const live = (entry) => entry.expiresAt === void 0 || entry.expiresAt > now();
2209
+ return {
2210
+ events,
2211
+ kv: {
2212
+ get(key) {
2213
+ const entry = values.get(key);
2214
+ return Promise.resolve(entry !== void 0 && live(entry) ? entry.value : void 0);
2215
+ },
2216
+ put(key, value, expiresAt) {
2217
+ values.set(key, expiresAt === void 0 ? { value } : {
2218
+ value,
2219
+ expiresAt
2220
+ });
2221
+ return Promise.resolve();
2222
+ },
2223
+ delete(key) {
2224
+ values.delete(key);
2225
+ return Promise.resolve();
2226
+ },
2227
+ list(prefix) {
2228
+ return Promise.resolve([...values.entries()].filter(([key, entry]) => key.startsWith(prefix) && live(entry)).toSorted(([a], [b]) => a < b ? -1 : 1).map(([key, entry]) => ({
2229
+ key,
2230
+ value: entry.value
2231
+ })));
2232
+ }
2233
+ }
2234
+ };
2235
+ }
2236
+ //#endregion
2237
+ //#region src/sql.ts
2238
+ const SCHEMA = `
2239
+ CREATE TABLE IF NOT EXISTS events (
2240
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
2241
+ tenant TEXT NOT NULL,
2242
+ id TEXT NOT NULL,
2243
+ project TEXT NOT NULL,
2244
+ source TEXT NOT NULL,
2245
+ event TEXT NOT NULL,
2246
+ verified INTEGER NOT NULL,
2247
+ held INTEGER NOT NULL,
2248
+ at_ms INTEGER NOT NULL,
2249
+ json TEXT NOT NULL,
2250
+ UNIQUE (tenant, id)
2251
+ );
2252
+ CREATE INDEX IF NOT EXISTS events_at ON events (tenant, at_ms);
2253
+ CREATE TABLE IF NOT EXISTS deliveries (
2254
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
2255
+ tenant TEXT NOT NULL,
2256
+ event_id TEXT NOT NULL,
2257
+ json TEXT NOT NULL
2258
+ );
2259
+ CREATE INDEX IF NOT EXISTS deliveries_event ON deliveries (tenant, event_id);
2260
+ CREATE TABLE IF NOT EXISTS meter (
2261
+ tenant TEXT NOT NULL,
2262
+ hour TEXT NOT NULL,
2263
+ project TEXT NOT NULL,
2264
+ source TEXT NOT NULL,
2265
+ event TEXT NOT NULL,
2266
+ events INTEGER NOT NULL,
2267
+ verificationFailures INTEGER NOT NULL,
2268
+ deliveries INTEGER NOT NULL,
2269
+ deliveryFailures INTEGER NOT NULL,
2270
+ rateLimited INTEGER NOT NULL,
2271
+ bytes INTEGER NOT NULL,
2272
+ PRIMARY KEY (tenant, hour, project, source, event)
2273
+ );
2274
+ CREATE TABLE IF NOT EXISTS kv (
2275
+ key TEXT PRIMARY KEY,
2276
+ value TEXT NOT NULL,
2277
+ expires_at INTEGER
2278
+ );
2279
+ `;
2280
+ const StoredEventSchema = BriefkastenEvent.extend({
2281
+ verification: z.object({
2282
+ ok: z.boolean(),
2283
+ method: z.string(),
2284
+ reason: z.string().nullable()
2285
+ }),
2286
+ held: z.boolean(),
2287
+ sizeBytes: z.number(),
2288
+ headers: z.record(z.string(), z.string())
2289
+ });
2290
+ const DeliverySchema = z.object({
2291
+ subscriber: z.string(),
2292
+ attempt: z.number(),
2293
+ at: z.string(),
2294
+ status: z.enum(["delivered", "failed"]),
2295
+ latencyMs: z.number().nullable(),
2296
+ error: z.string().nullable(),
2297
+ redelivery: z.boolean()
2298
+ });
2299
+ const EventRow = z.object({ json: z.string() });
2300
+ const SeqRow = z.object({ seq: z.number() });
2301
+ const KvRow = z.object({
2302
+ key: z.string(),
2303
+ value: z.string()
2304
+ });
2305
+ const MeterSchema = z.object({
2306
+ hour: z.string(),
2307
+ project: z.string(),
2308
+ source: z.string(),
2309
+ event: z.string(),
2310
+ events: z.number(),
2311
+ verificationFailures: z.number(),
2312
+ deliveries: z.number(),
2313
+ deliveryFailures: z.number(),
2314
+ rateLimited: z.number(),
2315
+ bytes: z.number()
2316
+ });
2317
+ const FIELDS = [
2318
+ "project",
2319
+ "source",
2320
+ "event"
2321
+ ];
2322
+ /** Runs synchronous database work as the port's promise: a throw becomes a rejection. */
2323
+ function attempt(work) {
2324
+ return new Promise((resolve) => {
2325
+ resolve(work());
2326
+ });
2327
+ }
2328
+ function storedEvents(rows) {
2329
+ return rows.map((row) => StoredEventSchema.parse(JSON.parse(EventRow.parse(row).json)));
2330
+ }
2331
+ const json = (event) => JSON.stringify(event);
2332
+ function sqlStores(driver, options = {}) {
2333
+ const now = options.now ?? Date.now;
2334
+ driver.script(SCHEMA);
2335
+ const all = (sql, ...values) => driver.all(sql, ...values);
2336
+ const run = (sql, ...values) => driver.run(sql, ...values);
2337
+ /** The arrival position of an event, or `undefined` when it is not kept. */
2338
+ const seqOf = (tenant, id) => {
2339
+ if (id === void 0) return;
2340
+ const row = all("SELECT seq FROM events WHERE tenant = ? AND id = ?", tenant, id)[0];
2341
+ return row === void 0 ? void 0 : SeqRow.parse(row).seq;
2342
+ };
2343
+ return {
2344
+ events: {
2345
+ append: (event) => attempt(() => {
2346
+ run(`INSERT INTO events (tenant, id, project, source, event, verified, held, at_ms, json)
2347
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, event.tenant, event.id, event.project, event.source, event.event, event.verification.ok ? 1 : 0, event.held ? 1 : 0, Date.parse(event.at), json(event));
2348
+ }),
2349
+ after: (tenant, since, limit) => attempt(() => {
2350
+ const start = seqOf(tenant, since);
2351
+ return {
2352
+ events: storedEvents(all(`SELECT json FROM events WHERE tenant = ? AND seq > ? AND verified = 1 AND held = 0
2353
+ ORDER BY seq LIMIT ?`, tenant, start ?? 0, limit)),
2354
+ found: since === void 0 || start !== void 0
2355
+ };
2356
+ }),
2357
+ list: (tenant, query) => attempt(() => {
2358
+ const conditions = [
2359
+ "tenant = ?",
2360
+ "seq > ?",
2361
+ "seq < ?"
2362
+ ];
2363
+ const values = [
2364
+ tenant,
2365
+ seqOf(tenant, query.since) ?? 0,
2366
+ seqOf(tenant, query.before) ?? Number.MAX_SAFE_INTEGER
2367
+ ];
2368
+ for (const field of FIELDS) {
2369
+ const value = query[field];
2370
+ if (value !== void 0) {
2371
+ conditions.push(`${field} = ?`);
2372
+ values.push(value);
2373
+ }
2374
+ }
2375
+ if (query.verified !== void 0) {
2376
+ conditions.push("verified = ?");
2377
+ values.push(query.verified ? 1 : 0);
2378
+ }
2379
+ return storedEvents(all(`SELECT json FROM events WHERE ${conditions.join(" AND ")} ORDER BY seq DESC LIMIT ?`, ...values, query.limit));
2380
+ }),
2381
+ get: (tenant, id) => attempt(() => storedEvents(all("SELECT json FROM events WHERE tenant = ? AND id = ?", tenant, id))[0]),
2382
+ held: (tenant, limit) => attempt(() => storedEvents(all("SELECT json FROM events WHERE tenant = ? AND held = 1 ORDER BY seq LIMIT ?", tenant, limit))),
2383
+ release: (tenant, id) => attempt(() => {
2384
+ for (const event of storedEvents(all("SELECT json FROM events WHERE tenant = ? AND id = ?", tenant, id))) run("UPDATE events SET held = 0, json = ? WHERE tenant = ? AND id = ?", json({
2385
+ ...event,
2386
+ held: false
2387
+ }), tenant, id);
2388
+ }),
2389
+ recordDelivery: (tenant, eventId, delivery) => attempt(() => {
2390
+ run("INSERT INTO deliveries (tenant, event_id, json) VALUES (?, ?, ?)", tenant, eventId, JSON.stringify(delivery));
2391
+ }),
2392
+ deliveries: (tenant, eventId) => attempt(() => all("SELECT json FROM deliveries WHERE tenant = ? AND event_id = ? ORDER BY seq", tenant, eventId).map((row) => DeliverySchema.parse(JSON.parse(EventRow.parse(row).json)))),
2393
+ meter: (entry) => attempt(() => {
2394
+ const counts = countsOf(entry);
2395
+ const updates = COUNTERS.map((counter) => `${counter} = ${counter} + excluded.${counter}`);
2396
+ run(`INSERT INTO meter (tenant, hour, project, source, event, ${COUNTERS.join(", ")})
2397
+ VALUES (?, ?, ?, ?, ?, ${COUNTERS.map(() => "?").join(", ")})
2398
+ ON CONFLICT (tenant, hour, project, source, event) DO UPDATE SET ${updates.join(", ")}`, entry.tenant, hourOf(entry.at), entry.project, entry.source, entry.event, ...COUNTERS.map((counter) => counts[counter]));
2399
+ }),
2400
+ usage: (tenant, query) => attempt(() => {
2401
+ return groupUsage(all("SELECT * FROM meter WHERE tenant = ?", tenant).map((row) => {
2402
+ const parsed = MeterSchema.parse(row);
2403
+ return {
2404
+ hour: parsed.hour,
2405
+ project: parsed.project,
2406
+ source: parsed.source,
2407
+ event: parsed.event,
2408
+ counts: parsed
2409
+ };
2410
+ }).filter((row) => inRange(row.hour, query.from, query.to)), query.by);
2411
+ }),
2412
+ prune: (tenant, before) => attempt(() => {
2413
+ run(`DELETE FROM deliveries WHERE tenant = ? AND event_id IN
2414
+ (SELECT id FROM events WHERE tenant = ? AND at_ms < ?)`, tenant, tenant, before);
2415
+ return run("DELETE FROM events WHERE tenant = ? AND at_ms < ?", tenant, before);
2416
+ }),
2417
+ dropTenant: (tenant) => attempt(() => {
2418
+ for (const table of [
2419
+ "events",
2420
+ "deliveries",
2421
+ "meter"
2422
+ ]) run(`DELETE FROM ${table} WHERE tenant = ?`, tenant);
2423
+ })
2424
+ },
2425
+ kv: {
2426
+ get: (key) => attempt(() => all("SELECT key, value FROM kv WHERE key = ? AND (expires_at IS NULL OR expires_at > ?)", key, now()).map((row) => KvRow.parse(row).value)[0]),
2427
+ put: (key, value, expiresAt) => attempt(() => {
2428
+ run("INSERT OR REPLACE INTO kv (key, value, expires_at) VALUES (?, ?, ?)", key, value, expiresAt ?? null);
2429
+ }),
2430
+ delete: (key) => attempt(() => {
2431
+ run("DELETE FROM kv WHERE key = ?", key);
2432
+ }),
2433
+ list: (prefix) => attempt(() => all(`SELECT key, value FROM kv WHERE substr(key, 1, ?) = ?
2434
+ AND (expires_at IS NULL OR expires_at > ?) ORDER BY key`, prefix.length, prefix, now()).map((row) => KvRow.parse(row)))
2435
+ }
2436
+ };
2437
+ }
2438
+ //#endregion
2439
+ export { staticVerifier as _, resendMailer as a, subscribersOf as c, RateLimiter as d, pulledConfigSource as f, signedVerifier as g, sessionVerifier as h, consoleMailer as i, tokenAllows as l, Login as m, memoryStores as n, createGateway as o, storeConfigSource as p, cloudflareMailer as r, routedTo as s, sqlStores as t, Budget as u };