@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lukas Mateffy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # @briefkasten/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The [briefkasten](https://www.npmjs.com/package/briefkasten) gateway: it receives the providers'
4
+ webhooks, verifies them, keeps the events, and streams them to subscribers over WebSockets or SSE.
5
+ It serves the management API that the CLI, the SDK and the MCP tools use. briefkasten cloud runs
6
+ the same code.
7
+
8
+ Most people run it with the CLI (`npm install -g @briefkasten/cli`, then `briefkasten server`).
9
+ This package is for running it from your own code.
10
+
11
+ ```bash
12
+ npm install @briefkasten/server briefkasten @briefkasten/adapter-github
13
+ ```
14
+
15
+ The Node runtime (`@briefkasten/server/node`, Node 22.13 or newer for `node:sqlite`) serves the
16
+ gateway of a config file, the one `briefkasten init` writes:
17
+
18
+ ```ts
19
+ import { serveInstance } from "@briefkasten/server/node";
20
+
21
+ const running = await serveInstance({
22
+ configPath: "./briefkasten.config.json",
23
+ port: 8080,
24
+ host: "127.0.0.1",
25
+ // The hooks on a public listener of their own, the management API private:
26
+ webhookPort: 8443,
27
+ webhookHost: "0.0.0.0",
28
+ });
29
+ console.log(running.hooks); // each source's hook URL
30
+ ```
31
+
32
+ The root export, `createGateway`, is the gateway as a `fetch` handler with the stores, config
33
+ sources and mailers that need no Node: run it on any runtime that speaks `Request` and
34
+ `Response`. `@briefkasten/cloudflare` runs it on Cloudflare Workers.
35
+
36
+ Docs: <https://briefkasten.fabrik.computer/docs/self-hosting>
37
+
38
+ MIT licensed.
@@ -0,0 +1,160 @@
1
+ import { a as Gateway, c as StreamOpening, i as sqlStores, l as createGateway, n as SqlStores, o as GatewayDeps, r as SqlValue, s as HookInfo, t as SqlDriver, u as StreamSession } from "./sql-dW8FI4m2.mjs";
2
+ import { Adapter, AdapterRegistry, AuthMethod, BriefkastenEvent, ConfigSource, DeviceAuthorization, EventStore, KeyValueStore, Mailer, Principal, Runtime, Settings, SignedIn, Tenant, Token, TokenVerifier, Tokens } from "briefkasten";
3
+ //#region src/state.d.ts
4
+ /**
5
+ * What the gateway runs on: the settings, the tenants, and who each static token is. Built again
6
+ * whenever the config changes, so every request sees one consistent version.
7
+ */
8
+ interface GatewayState {
9
+ readonly settings: Settings;
10
+ readonly tenants: ReadonlyMap<string, Tenant>;
11
+ /** Static tokens by their SHA-256: tenants' tokens and a `multi` instance's admins. */
12
+ readonly tokens: ReadonlyMap<string, Principal>;
13
+ }
14
+ //#endregion
15
+ //#region src/auth.d.ts
16
+ /** Static tokens: the config's tokens by hash. */
17
+ declare function staticVerifier(state: () => GatewayState): TokenVerifier;
18
+ /** Sessions from signing in. */
19
+ declare function sessionVerifier(kv: KeyValueStore): TokenVerifier;
20
+ /** Signed tokens from a control plane: `bks1.<base64url payload>.<base64url signature>`. */
21
+ declare function signedVerifier(state: () => GatewayState, now: () => number): TokenVerifier;
22
+ interface LoginDeps {
23
+ readonly kv: KeyValueStore;
24
+ readonly mailer?: Mailer;
25
+ readonly runtime: Runtime;
26
+ readonly state: () => GatewayState;
27
+ }
28
+ /** Signing in: email codes, RFC 8628 device codes, refresh and sign-out. */
29
+ declare class Login {
30
+ private readonly deps;
31
+ constructor(deps: LoginDeps);
32
+ methods(): readonly AuthMethod[];
33
+ private require;
34
+ private expiry;
35
+ /** The tenant an email owns, if any. */
36
+ private ownerOf;
37
+ /**
38
+ * Mails a code when the address owns a tenant. The answer is the same either way, so the
39
+ * endpoint does not tell who owns a tenant.
40
+ */
41
+ emailStart(email: string): Promise<{
42
+ login_id: string;
43
+ email: string;
44
+ expires_in: number;
45
+ message: string;
46
+ }>;
47
+ emailVerify(request: string, code: string): Promise<SignedIn>;
48
+ /** A new session: an access token and a refresh token, both kept hashed. */
49
+ session(tenant: string, name: string): Promise<Tokens>;
50
+ /** Trades a refresh token for a new session; the old refresh token stops working. */
51
+ refresh(token: string): Promise<Tokens>;
52
+ logout(token: string): Promise<void>;
53
+ deviceStart(): Promise<DeviceAuthorization>;
54
+ /** RFC 8628 §3.4–3.5: the session once approved, else why not yet. */
55
+ deviceToken(deviceCode: string): Promise<Tokens>;
56
+ /** A signed-in manager approves a device sign-in by the code the device shows. */
57
+ deviceApprove(principal: Principal, code: string): Promise<void>;
58
+ }
59
+ //#endregion
60
+ //#region src/config-store.d.ts
61
+ /** Tenants the instance keeps itself, changed through the management API. */
62
+ declare function storeConfigSource(options: {
63
+ readonly settings: () => Promise<Settings>;
64
+ readonly kv: KeyValueStore;
65
+ }): ConfigSource;
66
+ /**
67
+ * Tenants pulled from a control plane (`GET <url>` answers `{ tenants: [envelope, ...] }`), each
68
+ * signed. The management API cannot change them: the control plane owns them.
69
+ */
70
+ declare function pulledConfigSource(options: {
71
+ readonly settings: () => Promise<Settings>;
72
+ readonly kv: KeyValueStore;
73
+ readonly url: string;
74
+ readonly token?: string;
75
+ readonly fetch?: (request: Request) => Promise<Response>;
76
+ readonly log: (message: string) => void;
77
+ }): ConfigSource;
78
+ //#endregion
79
+ //#region src/limits.d.ts
80
+ /** Fixed one-minute windows, per key. */
81
+ declare class RateLimiter {
82
+ private readonly now;
83
+ private readonly windows;
84
+ constructor(now: () => number);
85
+ /** Takes one from the key's window; false when the window already has `perMinute`. */
86
+ take(key: string, perMinute: number | null): boolean;
87
+ }
88
+ /** Events accepted this month, per tenant: read once from the meter, then counted along. */
89
+ declare class Budget {
90
+ private readonly store;
91
+ private readonly now;
92
+ private readonly counts;
93
+ constructor(store: EventStore, now: () => number);
94
+ /** This month's count of a tenant, read from the meter when the month is new to it. */
95
+ private entry;
96
+ used(tenant: string): Promise<number>;
97
+ /** Whether one more event fits under `limit` (`null`: no limit). */
98
+ fits(tenant: string, limit: number | null): Promise<boolean>;
99
+ add(tenant: string, events: number): Promise<void>;
100
+ forget(tenant: string): void;
101
+ }
102
+ //#endregion
103
+ //#region src/mail.d.ts
104
+ /**
105
+ * The mail adapters that need no socket of their own: Resend (an HTTP API: the hosted service's
106
+ * mailer, it sends to anyone), Cloudflare Email Sending (a Worker's `send_email` binding: on the
107
+ * free Workers plan it reaches only addresses verified in the operator's own account, which is
108
+ * all a private instance needs), and the console (development: the code appears in the log).
109
+ * SMTP is in `node/smtp.ts`. Each sends the sign-in codes and nothing else.
110
+ */
111
+ type Fetch = (input: string, init: RequestInit) => Promise<Response>;
112
+ declare function resendMailer(options: {
113
+ readonly apiKey: string;
114
+ readonly from: string;
115
+ readonly fetch?: Fetch;
116
+ }): Mailer;
117
+ /** A Worker's `send_email` binding, as Cloudflare Email Sending gives it. */
118
+ interface CloudflareEmailBinding {
119
+ send(message: {
120
+ readonly from: string;
121
+ readonly to: string;
122
+ readonly subject: string;
123
+ readonly text: string;
124
+ }): Promise<unknown>;
125
+ }
126
+ /**
127
+ * Cloudflare Email Sending through a Worker's `send_email` binding. It exists only inside a
128
+ * Worker: on Node there is no binding to pass, so a Node instance mails through Resend or SMTP.
129
+ */
130
+ declare function cloudflareMailer(options: {
131
+ readonly binding: CloudflareEmailBinding;
132
+ readonly from: string;
133
+ }): Mailer;
134
+ /** Prints each message to the log: for development, where nothing should leave the machine. */
135
+ declare function consoleMailer(options: {
136
+ readonly log: (line: string) => void;
137
+ }): Mailer;
138
+ //#endregion
139
+ //#region src/memory.d.ts
140
+ interface MemoryStores {
141
+ readonly events: EventStore;
142
+ readonly kv: KeyValueStore;
143
+ }
144
+ declare function memoryStores(options?: {
145
+ readonly now?: () => number;
146
+ readonly capacity?: number;
147
+ }): MemoryStores;
148
+ //#endregion
149
+ //#region src/routing.d.ts
150
+ /** Whether the project's routes send the event to the subscriber. */
151
+ declare function routedTo(tenant: Tenant, event: BriefkastenEvent, subscriber: string): boolean;
152
+ /** Whether a token's own scope (its project, its filters) allows the event. */
153
+ declare function tokenAllows(token: {
154
+ readonly project: Token["project"];
155
+ readonly filters: readonly string[];
156
+ }, event: BriefkastenEvent): boolean;
157
+ /** The names of the subscribers an event goes to. */
158
+ declare function subscribersOf(tenant: Tenant, event: BriefkastenEvent): readonly string[];
159
+ //#endregion
160
+ export { Budget, type Gateway, type GatewayDeps, type HookInfo, Login, RateLimiter, type SqlDriver, type SqlStores, type SqlValue, type StreamOpening, type StreamSession, cloudflareMailer, consoleMailer, createGateway, memoryStores, pulledConfigSource, resendMailer, routedTo, sessionVerifier, signedVerifier, sqlStores, staticVerifier, storeConfigSource, subscribersOf, tokenAllows };
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import { _ as staticVerifier, a as resendMailer, c as subscribersOf, d as RateLimiter, f as pulledConfigSource, g as signedVerifier, h as sessionVerifier, i as consoleMailer, l as tokenAllows, m as Login, n as memoryStores, o as createGateway, p as storeConfigSource, r as cloudflareMailer, s as routedTo, t as sqlStores, u as Budget } from "./sql-Bt3YJw7M.mjs";
2
+ export { Budget, Login, RateLimiter, cloudflareMailer, consoleMailer, createGateway, memoryStores, pulledConfigSource, resendMailer, routedTo, sessionVerifier, signedVerifier, sqlStores, staticVerifier, storeConfigSource, subscribersOf, tokenAllows };
@@ -0,0 +1,211 @@
1
+ import { a as Gateway, s as HookInfo } from "./sql-dW8FI4m2.mjs";
2
+ import { Adapter, AdapterRegistry, ApiCaller, ConfigDocument, ConfigSource, EventStore, KeyValueStore, MailSettings, Mailer, Principal, SecretResolver, SecretStore, Settings } from "briefkasten";
3
+ import { IncomingMessage } from "node:http";
4
+ import { Duplex } from "node:stream";
5
+ import { DatabaseSync } from "node:sqlite";
6
+ //#region src/node/adapters.d.ts
7
+ type ModuleImporter = (specifier: string) => Promise<unknown>;
8
+ declare function nodeAdapterRegistry(options: {
9
+ readonly known?: readonly Adapter<unknown>[];
10
+ /** Where to resolve adapter packages from, in order. */
11
+ readonly from: readonly string[];
12
+ readonly importer?: ModuleImporter;
13
+ }): AdapterRegistry;
14
+ //#endregion
15
+ //#region src/node/config-file.d.ts
16
+ /**
17
+ * The config of a `single` or `personal` instance (and a `multi` instance's settings), kept in
18
+ * files: one config file, or a directory with one file per project. The management API writes a
19
+ * JSON config back (atomically: a temporary file renamed over it); a TypeScript config is a
20
+ * person's, so a write is refused with the reason, and so is a read-only file.
21
+ */
22
+ /** Where a document is kept. */
23
+ interface DocumentStore {
24
+ /** The file or directory, for messages. */
25
+ readonly where: string;
26
+ read(): Promise<{
27
+ readonly document: ConfigDocument;
28
+ readonly adapters: readonly Adapter<unknown>[];
29
+ }>;
30
+ /** Why it cannot be written, or `undefined`. */
31
+ readOnly(): Promise<string | undefined>;
32
+ write(document: ConfigDocument): Promise<void>;
33
+ }
34
+ /** Writes a file atomically: a temporary file next to it, renamed over it. */
35
+ declare function writeAtomic(path: string, text: string, mode?: number): Promise<void>;
36
+ /** One config file: `briefkasten.config.json` (written back) or `.ts`/`.mjs` (read only). */
37
+ declare function configFile(path: string): DocumentStore;
38
+ /**
39
+ * A config directory: `briefkasten.json` holds the settings, `projects/<name>.json` each
40
+ * project's sources and routes, `tokens.json` the tokens. Easy to keep in git and to diff, and a
41
+ * change rewrites only the files it touched.
42
+ */
43
+ declare function configDirectory(dir: string): DocumentStore;
44
+ /** Reads `$env` references from the environment and `$secret` ones from the secret store. */
45
+ declare function secretResolver(secrets: SecretStore, env: Readonly<Record<string, string | undefined>>): SecretResolver;
46
+ /** Where a source's secret is kept in the secret store. */
47
+ declare function secretKey(project: string, source: string): string;
48
+ interface DocumentSourceOptions {
49
+ readonly store: DocumentStore;
50
+ readonly secrets: SecretStore;
51
+ readonly env?: Readonly<Record<string, string | undefined>>;
52
+ }
53
+ /** A document's adapters, settings and (outside `multi` mode) its one tenant. */
54
+ interface DocumentConfigSource extends ConfigSource {
55
+ /** The adapter definitions a TypeScript config brings with it. */
56
+ adapters(): Promise<readonly Adapter<unknown>[]>;
57
+ settings(): Promise<Settings>;
58
+ }
59
+ declare function documentConfigSource(options: DocumentSourceOptions): DocumentConfigSource;
60
+ //#endregion
61
+ //#region src/node/instance.d.ts
62
+ /**
63
+ * The Node runtime's composition: a config path in, a gateway with its ports out. The ports
64
+ * follow the config: the store (memory or SQLite), the mail adapter, the config source (the file
65
+ * itself, or in `multi` mode the store the control plane fills), and the secret store
66
+ * (`briefkasten.secrets.json` next to the config, mode 600).
67
+ */
68
+ declare const SECRETS_FILE = "briefkasten.secrets.json";
69
+ /** Who acts through the CLI's local target: whoever can edit the config file. */
70
+ declare const LOCAL: Principal;
71
+ interface InstanceOptions {
72
+ readonly configPath: string;
73
+ readonly log?: (line: string) => void;
74
+ /** Where raw deliveries are kept, for fixtures (`BRIEFKASTEN_CAPTURE_DIR`). */
75
+ readonly captureDir?: string;
76
+ readonly env?: Readonly<Record<string, string | undefined>>;
77
+ /**
78
+ * More directories to resolve adapter packages (`@briefkasten/adapter-<id>`) from, after the
79
+ * config's: the CLI's own, which depends on every adapter.
80
+ */
81
+ readonly adapterDirs?: readonly string[];
82
+ }
83
+ interface OpenInstance {
84
+ readonly gateway: Gateway;
85
+ readonly settings: Settings;
86
+ /** Where the tenants come from, secrets read. */
87
+ readonly config: ConfigSource;
88
+ readonly close: () => Promise<void>;
89
+ }
90
+ /** The mail adapter the settings name. */
91
+ declare function mailerOf(mail: MailSettings | undefined, log: (line: string) => void): Mailer | undefined;
92
+ declare function openInstance(options: InstanceOptions): Promise<OpenInstance>;
93
+ /**
94
+ * The CLI's local target: the instance's operations, in process, with full rights, and its
95
+ * sources' secrets, which only someone who can read the config can read (`briefkasten send`).
96
+ */
97
+ interface LocalInstance {
98
+ readonly caller: ApiCaller;
99
+ /** A source's secret, as the instance verifies its deliveries with. */
100
+ secret(project: string, source: string): Promise<string | undefined>;
101
+ close(): Promise<void>;
102
+ }
103
+ /** Opens a config file as the CLI's local target. */
104
+ declare function openLocal(path: string, adapterDirs?: readonly string[]): Promise<LocalInstance>;
105
+ /** Takes a WebSocket upgrade to the stream: authorises it, then sends the session's items. */
106
+ declare function upgradeHandler(gateway: Gateway, log: (line: string) => void): (message: IncomingMessage, socket: Duplex, head: Buffer) => void;
107
+ interface ServeOptions extends InstanceOptions {
108
+ readonly port?: number;
109
+ readonly host?: string;
110
+ readonly webhookPort?: number;
111
+ readonly webhookHost?: string;
112
+ }
113
+ interface Address {
114
+ readonly port: number;
115
+ readonly host: string;
116
+ }
117
+ interface RunningInstance {
118
+ readonly main: Address;
119
+ readonly webhooks?: Address;
120
+ readonly hooks: readonly HookInfo[];
121
+ close(): Promise<void>;
122
+ }
123
+ /** Runs an instance: the private listener (every route) and, when set, the public one (hooks). */
124
+ declare function serveInstance(options: ServeOptions): Promise<RunningInstance>;
125
+ //#endregion
126
+ //#region src/node/secrets.d.ts
127
+ /** The environment's variables as secrets: `{ "$env": "NAME" }` reads one. */
128
+ declare function envSecrets(env?: Readonly<Record<string, string | undefined>>): SecretStore;
129
+ /** A JSON file `{ key: value }`, mode 600, written atomically (a temporary file, then a rename). */
130
+ declare function fileSecrets(path: string): SecretStore;
131
+ //#endregion
132
+ //#region src/node/serve.d.ts
133
+ interface RunningServer {
134
+ readonly port: number;
135
+ /** The address the listener is bound to, e.g. `::`, `0.0.0.0` or `100.64.0.1`. */
136
+ readonly host: string;
137
+ close(): Promise<void>;
138
+ }
139
+ interface ServeNodeOptions {
140
+ readonly port: number;
141
+ /** Interface to bind. Default: all interfaces, as node:http does. */
142
+ readonly hostname?: string;
143
+ /** Takes a connection that asks to upgrade (a WebSocket); without it, upgrades are refused. */
144
+ readonly upgrade?: (message: IncomingMessage, socket: Duplex, head: Buffer) => void;
145
+ }
146
+ /** A Node request as a fetch Request. */
147
+ declare function toRequest(message: IncomingMessage): Request;
148
+ /**
149
+ * Serves a fetch-style handler over node:http. Returns the bound port
150
+ * (pass 0 for an ephemeral port), the bound address, and a close function.
151
+ */
152
+ declare function serveNode(handler: (request: Request) => Promise<Response>, options: ServeNodeOptions): Promise<RunningServer>;
153
+ //#endregion
154
+ //#region src/node/smtp.d.ts
155
+ /**
156
+ * A minimal SMTP client (RFC 5321) for the sign-in codes: implicit TLS on 465, or plain then
157
+ * STARTTLS on 587, AUTH PLAIN, one recipient, a text body. Enough for a self-hosted instance that
158
+ * mails through its own provider; nothing here sends unless an instance is configured to.
159
+ */
160
+ interface SmtpOptions {
161
+ readonly host: string;
162
+ readonly port: number;
163
+ /** `true`: TLS from the first byte. `false`: plain, upgraded with STARTTLS when offered. */
164
+ readonly secure: boolean;
165
+ readonly user?: string | undefined;
166
+ readonly password?: string | undefined;
167
+ readonly from: string;
168
+ /** The name this client greets with (EHLO). */
169
+ readonly name?: string;
170
+ /** Opens the connection; TLS or plain per `secure`. */
171
+ readonly connect?: (options: SmtpEndpoint) => Promise<Duplex>;
172
+ /** Wraps a plain connection in TLS after STARTTLS. */
173
+ readonly upgrade?: (socket: Duplex, host: string) => Promise<Duplex>;
174
+ }
175
+ interface SmtpEndpoint {
176
+ readonly host: string;
177
+ readonly port: number;
178
+ readonly secure: boolean;
179
+ }
180
+ declare function smtpMailer(options: SmtpOptions): Mailer;
181
+ //#endregion
182
+ //#region src/node/sqlite.d.ts
183
+ /** The SQL stores (`../sql`) in a `node:sqlite` database file: the default event store on Node. */
184
+ interface SqliteStores {
185
+ readonly events: EventStore;
186
+ readonly kv: KeyValueStore;
187
+ close(): void;
188
+ }
189
+ declare function sqliteStores(path: string, options?: {
190
+ readonly now?: () => number;
191
+ }): SqliteStores;
192
+ //#endregion
193
+ //#region src/node/websocket.d.ts
194
+ interface WebSocketPeer {
195
+ readonly open: boolean;
196
+ send(text: string): void;
197
+ close(code?: number, reason?: string): void;
198
+ onMessage(listener: (text: string) => void): void;
199
+ onClose(listener: () => void): void;
200
+ }
201
+ /** Answers an upgrade request with a plain HTTP refusal and drops the connection. */
202
+ declare function rejectUpgrade(socket: Duplex, status: number, message: string): void;
203
+ /**
204
+ * Completes the handshake of an upgrade request and answers its frames. Throws when the request
205
+ * is not a WebSocket handshake (no key, or a version other than 13): check before calling.
206
+ */
207
+ declare function acceptWebSocket(request: IncomingMessage, socket: Duplex, head: Buffer, options?: {
208
+ readonly protocol?: string;
209
+ }): WebSocketPeer;
210
+ //#endregion
211
+ export { type DocumentConfigSource, type DocumentStore, type InstanceOptions, LOCAL, type LocalInstance, type OpenInstance, type RunningInstance, type RunningServer, SECRETS_FILE, type ServeNodeOptions, type ServeOptions, acceptWebSocket, configDirectory, configFile, documentConfigSource, envSecrets, fileSecrets, mailerOf, nodeAdapterRegistry, openInstance, openLocal, rejectUpgrade, secretKey, secretResolver, serveInstance, serveNode, smtpMailer, sqliteStores, toRequest, upgradeHandler, writeAtomic };