@briefkasten/cloudflare 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 +21 -0
- package/README.md +53 -2
- package/dist/index.d.mts +141 -0
- package/dist/index.mjs +805 -0
- package/package.json +70 -3
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,54 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @briefkasten/cloudflare
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The [briefkasten](https://www.npmjs.com/package/briefkasten) gateway on Cloudflare Workers, in
|
|
4
|
+
`multi` mode: the Worker is the front door, each tenant has its own Durable Object (its events,
|
|
5
|
+
config, meter and subscribers' hibernating WebSockets), and a directory object knows which token
|
|
6
|
+
belongs to which tenant. Every adapter is bundled.
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npm install @briefkasten/cloudflare
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Your Worker's entry hands the handler and the Durable Object classes to the runtime:
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
// worker.ts
|
|
16
|
+
import { Directory, TenantObject, createWorker } from "@briefkasten/cloudflare";
|
|
17
|
+
|
|
18
|
+
export { Directory, TenantObject };
|
|
19
|
+
export default createWorker();
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
```toml
|
|
23
|
+
# wrangler.toml
|
|
24
|
+
name = "my-briefkasten"
|
|
25
|
+
main = "worker.ts"
|
|
26
|
+
compatibility_date = "2026-11-01"
|
|
27
|
+
compatibility_flags = ["nodejs_compat"]
|
|
28
|
+
|
|
29
|
+
[vars]
|
|
30
|
+
PUBLIC_URL = "https://hooks.example.com"
|
|
31
|
+
JURISDICTION = "eu"
|
|
32
|
+
CONFIG_VERIFY_KEY_ID = "k1"
|
|
33
|
+
MAX_BODY_BYTES = "1048576"
|
|
34
|
+
|
|
35
|
+
[[durable_objects.bindings]]
|
|
36
|
+
name = "TENANTS"
|
|
37
|
+
class_name = "TenantObject"
|
|
38
|
+
|
|
39
|
+
[[durable_objects.bindings]]
|
|
40
|
+
name = "DIRECTORY"
|
|
41
|
+
class_name = "Directory"
|
|
42
|
+
|
|
43
|
+
[[migrations]]
|
|
44
|
+
tag = "v1"
|
|
45
|
+
new_sqlite_classes = ["TenantObject", "Directory"]
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Set the admin token as a secret (`wrangler secret put ADMIN_TOKEN`) and the control plane's
|
|
49
|
+
public key as `CONFIG_VERIFY_KEY`. A `HOOK_LIMITER` rate limit binding and a `USAGE` Analytics
|
|
50
|
+
Engine dataset are optional. The `Env` type lists every binding.
|
|
51
|
+
|
|
52
|
+
Docs: <https://briefkasten.fabrik.computer/docs/self-hosting>
|
|
53
|
+
|
|
54
|
+
MIT licensed.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { Adapter, AdapterRegistry } from "briefkasten";
|
|
3
|
+
//#region src/runtime.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* The parts of the Workers runtime briefkasten uses, as narrow interfaces: the bindings, a
|
|
6
|
+
* Durable Object's state, its SQLite and its hibernating WebSockets. The runtime's own objects
|
|
7
|
+
* fit them; a test gives fakes. Nothing here imports `cloudflare:workers`, so every module runs
|
|
8
|
+
* under Node too.
|
|
9
|
+
*/
|
|
10
|
+
/** A Durable Object namespace binding (`[[durable_objects.bindings]]`). */
|
|
11
|
+
interface ObjectNamespace {
|
|
12
|
+
idFromName(name: string): ObjectId;
|
|
13
|
+
get(id: ObjectId): ObjectStub;
|
|
14
|
+
/** The same namespace, its objects made and kept only in this jurisdiction. */
|
|
15
|
+
jurisdiction(name: Jurisdiction): ObjectNamespace;
|
|
16
|
+
}
|
|
17
|
+
/** A Durable Object jurisdiction: where an object runs and stores its data. */
|
|
18
|
+
type Jurisdiction = "eu" | "fedramp";
|
|
19
|
+
interface ObjectId {
|
|
20
|
+
toString(): string;
|
|
21
|
+
}
|
|
22
|
+
interface ObjectStub {
|
|
23
|
+
fetch(request: Request): Promise<Response>;
|
|
24
|
+
}
|
|
25
|
+
/** An Analytics Engine dataset binding (`[[analytics_engine_datasets]]`). */
|
|
26
|
+
interface AnalyticsDataset {
|
|
27
|
+
writeDataPoint(point: {
|
|
28
|
+
readonly indexes?: readonly string[];
|
|
29
|
+
readonly blobs?: readonly string[];
|
|
30
|
+
readonly doubles?: readonly number[];
|
|
31
|
+
}): void;
|
|
32
|
+
}
|
|
33
|
+
/** A rate limiting binding (`[[ratelimits]]`). */
|
|
34
|
+
interface RateLimitBinding {
|
|
35
|
+
limit(options: {
|
|
36
|
+
readonly key: string;
|
|
37
|
+
}): Promise<{
|
|
38
|
+
readonly success: boolean;
|
|
39
|
+
}>;
|
|
40
|
+
}
|
|
41
|
+
/** The Worker's environment: its bindings, its vars and its secrets. */
|
|
42
|
+
interface Env {
|
|
43
|
+
readonly TENANTS: ObjectNamespace;
|
|
44
|
+
readonly DIRECTORY: ObjectNamespace;
|
|
45
|
+
readonly USAGE?: AnalyticsDataset;
|
|
46
|
+
readonly HOOK_LIMITER?: RateLimitBinding;
|
|
47
|
+
/** Where providers and subscribers reach the Worker, e.g. `https://briefkasten-inbox.example`. */
|
|
48
|
+
readonly PUBLIC_URL?: string;
|
|
49
|
+
/** The admin token (a secret): the control plane's credential. */
|
|
50
|
+
readonly ADMIN_TOKEN?: string;
|
|
51
|
+
/** The control plane's Ed25519 public key (raw, base64url) and its id. */
|
|
52
|
+
readonly CONFIG_VERIFY_KEY?: string;
|
|
53
|
+
readonly CONFIG_VERIFY_KEY_ID?: string;
|
|
54
|
+
/** A second key while the control plane rotates its signing key. */
|
|
55
|
+
readonly CONFIG_VERIFY_KEY_NEXT?: string;
|
|
56
|
+
readonly CONFIG_VERIFY_KEY_NEXT_ID?: string;
|
|
57
|
+
/** The largest hook body, in bytes. */
|
|
58
|
+
readonly MAX_BODY_BYTES?: string;
|
|
59
|
+
readonly VERSION?: string;
|
|
60
|
+
/** Where the objects live: `eu`, or `none` under `wrangler dev` ({@link jurisdictionOf}). */
|
|
61
|
+
readonly JURISDICTION?: string;
|
|
62
|
+
}
|
|
63
|
+
/** A Durable Object's SQLite (`ctx.storage.sql`). */
|
|
64
|
+
interface SqlStorage {
|
|
65
|
+
exec(query: string, ...bindings: (string | number | null)[]): {
|
|
66
|
+
toArray(): unknown[];
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/** A WebSocket the object accepted with the Hibernation API. */
|
|
70
|
+
interface HibernatingSocket {
|
|
71
|
+
send(message: string): void;
|
|
72
|
+
close(code?: number, reason?: string): void;
|
|
73
|
+
serializeAttachment(value: unknown): void;
|
|
74
|
+
deserializeAttachment(): unknown;
|
|
75
|
+
}
|
|
76
|
+
/** A Durable Object's state (`ctx`), as much as the objects use. */
|
|
77
|
+
interface ObjectState {
|
|
78
|
+
readonly storage: {
|
|
79
|
+
readonly sql: SqlStorage;
|
|
80
|
+
getAlarm(): Promise<number | null>;
|
|
81
|
+
setAlarm(at: number): Promise<void>;
|
|
82
|
+
};
|
|
83
|
+
acceptWebSocket(socket: HibernatingSocket): void;
|
|
84
|
+
getWebSockets(): HibernatingSocket[];
|
|
85
|
+
setWebSocketAutoResponse(pair: unknown): void;
|
|
86
|
+
blockConcurrencyWhile<T>(work: () => Promise<T>): Promise<T>;
|
|
87
|
+
}
|
|
88
|
+
//#endregion
|
|
89
|
+
//#region src/directory.d.ts
|
|
90
|
+
/** The directory's Durable Object. */
|
|
91
|
+
declare class Directory {
|
|
92
|
+
private readonly state;
|
|
93
|
+
constructor(state: Pick<ObjectState, "storage">);
|
|
94
|
+
fetch(request: Request): Promise<Response>;
|
|
95
|
+
}
|
|
96
|
+
//#endregion
|
|
97
|
+
//#region src/objects.d.ts
|
|
98
|
+
declare class TenantObject {
|
|
99
|
+
private readonly host;
|
|
100
|
+
constructor(state: ObjectState, env: Env);
|
|
101
|
+
fetch(request: Request): Promise<Response>;
|
|
102
|
+
/** The runtime answers `ping` itself; anything else a subscriber sends is ignored. */
|
|
103
|
+
webSocketMessage(): void;
|
|
104
|
+
webSocketClose(socket: HibernatingSocket): void;
|
|
105
|
+
webSocketError(socket: HibernatingSocket): void;
|
|
106
|
+
alarm(): Promise<void>;
|
|
107
|
+
}
|
|
108
|
+
//#endregion
|
|
109
|
+
//#region src/adapters.d.ts
|
|
110
|
+
/**
|
|
111
|
+
* The source adapters a Worker carries. A Worker cannot install a package at run time, so the
|
|
112
|
+
* adapters are bundled: a source names one of these.
|
|
113
|
+
*/
|
|
114
|
+
declare const BUNDLED: readonly Adapter<unknown>[];
|
|
115
|
+
declare function bundledAdapters(adapters?: readonly Adapter<unknown>[]): AdapterRegistry;
|
|
116
|
+
//#endregion
|
|
117
|
+
//#region src/tenant.d.ts
|
|
118
|
+
/**
|
|
119
|
+
* One tenant's Durable Object: the gateway for that tenant alone, on the object's SQLite (its
|
|
120
|
+
* events for the retention window, their deliveries, the meter, the pushed config), with its
|
|
121
|
+
* subscribers on hibernating WebSockets. The Worker sends it everything that names the tenant;
|
|
122
|
+
* the tenant is a hard key, since nothing else is in the object.
|
|
123
|
+
*
|
|
124
|
+
* An object no config was ever pushed to keeps nothing: it answers 404 without writing, so a
|
|
125
|
+
* request that makes up a tenant leaves no trace.
|
|
126
|
+
*/
|
|
127
|
+
/** The header the Worker names the object's tenant in. */
|
|
128
|
+
declare const OBJECT_HEADER = "briefkasten-object";
|
|
129
|
+
/** The object that serves requests naming no tenant: a valid tenant name never starts with `_`. */
|
|
130
|
+
declare const INSTANCE = "_instance";
|
|
131
|
+
//#endregion
|
|
132
|
+
//#region src/worker.d.ts
|
|
133
|
+
interface WorkerOptions {
|
|
134
|
+
readonly now?: () => number;
|
|
135
|
+
}
|
|
136
|
+
interface WorkerHandler {
|
|
137
|
+
fetch(request: Request, env: Env): Promise<Response>;
|
|
138
|
+
}
|
|
139
|
+
declare function createWorker(options?: WorkerOptions): WorkerHandler;
|
|
140
|
+
//#endregion
|
|
141
|
+
export { BUNDLED, Directory, type Env, INSTANCE, OBJECT_HEADER, TenantObject, type WorkerHandler, type WorkerOptions, bundledAdapters, createWorker };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,805 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { API_PREFIX, BriefkastenError, COUNTERS, ConfigDocument, DEFAULT_MAX_BODY_BYTES, STREAM_PATH, TENANT_HEADER, TenantId, WS_BEARER_PREFIX, WS_CLOSE, WS_PING, WS_PONG, constantTimeEqual, encodeWs, messageOf, settingsOf, sha256Hex } from "briefkasten";
|
|
3
|
+
import { createGateway, sqlStores, storeConfigSource } from "@briefkasten/server";
|
|
4
|
+
import { adapter } from "@briefkasten/adapter-generic";
|
|
5
|
+
import { adapter as adapter$1 } from "@briefkasten/adapter-github";
|
|
6
|
+
import { adapter as adapter$2 } from "@briefkasten/adapter-linear";
|
|
7
|
+
import { adapter as adapter$3 } from "@briefkasten/adapter-nightwatch";
|
|
8
|
+
import { adapter as adapter$4 } from "@briefkasten/adapter-posthog";
|
|
9
|
+
import { adapter as adapter$5 } from "@briefkasten/adapter-sentry";
|
|
10
|
+
//#region src/runtime.ts
|
|
11
|
+
/**
|
|
12
|
+
* Where the Worker makes its objects (`JURISDICTION`): `eu` in production, so a tenant's events,
|
|
13
|
+
* its config and secrets, and the directory are stored in the EU and nowhere else. `none` only
|
|
14
|
+
* where jurisdictions do not exist: workerd under `wrangler dev` refuses them. Unset is refused, so
|
|
15
|
+
* a deploy never makes objects outside the EU by leaving it out.
|
|
16
|
+
*/
|
|
17
|
+
function jurisdictionOf(env) {
|
|
18
|
+
switch (env.JURISDICTION) {
|
|
19
|
+
case "eu":
|
|
20
|
+
case "fedramp": return env.JURISDICTION;
|
|
21
|
+
case "none": return;
|
|
22
|
+
default: throw new Error(`JURISDICTION must be eu, fedramp or none (wrangler dev), not ${env.JURISDICTION ?? "unset"}`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** The object of this name in the namespace, made and kept in the Worker's jurisdiction. */
|
|
26
|
+
function objectNamed(namespace, name, env) {
|
|
27
|
+
const jurisdiction = jurisdictionOf(env);
|
|
28
|
+
const scoped = jurisdiction === void 0 ? namespace : namespace.jurisdiction(jurisdiction);
|
|
29
|
+
return scoped.get(scoped.idFromName(name));
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region src/directory.ts
|
|
33
|
+
/**
|
|
34
|
+
* The directory: one Durable Object that knows the tenants and which tenant each token belongs
|
|
35
|
+
* to. A tenant's object tells it after every change to the tenant; the Worker asks it where a
|
|
36
|
+
* request with a tenant's token goes (a hook or a `/t/<tenant>/…` URL names the tenant itself),
|
|
37
|
+
* and which tenants a usage report spans. It holds hashes only, never a token.
|
|
38
|
+
*/
|
|
39
|
+
const DIRECTORY = "directory";
|
|
40
|
+
const ORIGIN = "https://directory.internal";
|
|
41
|
+
const HTTP_NOT_FOUND$2 = 404;
|
|
42
|
+
const Registration = z.object({
|
|
43
|
+
status: z.string(),
|
|
44
|
+
tokens: z.array(z.string())
|
|
45
|
+
});
|
|
46
|
+
const TenantRow = z.object({
|
|
47
|
+
name: z.string(),
|
|
48
|
+
status: z.string()
|
|
49
|
+
});
|
|
50
|
+
const TokenRow = z.object({ tenant: z.string() });
|
|
51
|
+
const Listing = z.object({ tenants: z.array(TenantRow) });
|
|
52
|
+
const SCHEMA = `
|
|
53
|
+
CREATE TABLE IF NOT EXISTS tenants (name TEXT PRIMARY KEY, status TEXT NOT NULL);
|
|
54
|
+
CREATE TABLE IF NOT EXISTS tokens (sha256 TEXT PRIMARY KEY, tenant TEXT NOT NULL);
|
|
55
|
+
CREATE INDEX IF NOT EXISTS tokens_tenant ON tokens (tenant);
|
|
56
|
+
`;
|
|
57
|
+
function json$2(status, value) {
|
|
58
|
+
return new Response(JSON.stringify(value), {
|
|
59
|
+
status,
|
|
60
|
+
headers: { "content-type": "application/json" }
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/** The directory's Durable Object. */
|
|
64
|
+
var Directory = class {
|
|
65
|
+
state;
|
|
66
|
+
constructor(state) {
|
|
67
|
+
this.state = state;
|
|
68
|
+
state.storage.sql.exec(SCHEMA);
|
|
69
|
+
}
|
|
70
|
+
async fetch(request) {
|
|
71
|
+
const { sql } = this.state.storage;
|
|
72
|
+
const [kind, name] = new URL(request.url).pathname.split("/").filter((part) => part !== "").map(decodeURIComponent);
|
|
73
|
+
if (kind === "tenants" && name !== void 0 && request.method === "PUT") {
|
|
74
|
+
const registration = Registration.parse(await request.json());
|
|
75
|
+
sql.exec("INSERT OR REPLACE INTO tenants (name, status) VALUES (?, ?)", name, registration.status);
|
|
76
|
+
sql.exec("DELETE FROM tokens WHERE tenant = ?", name);
|
|
77
|
+
for (const token of registration.tokens) sql.exec("INSERT OR REPLACE INTO tokens (sha256, tenant) VALUES (?, ?)", token, name);
|
|
78
|
+
return json$2(200, { ok: true });
|
|
79
|
+
}
|
|
80
|
+
if (kind === "tenants" && name !== void 0 && request.method === "DELETE") {
|
|
81
|
+
sql.exec("DELETE FROM tokens WHERE tenant = ?", name);
|
|
82
|
+
sql.exec("DELETE FROM tenants WHERE name = ?", name);
|
|
83
|
+
return json$2(200, { ok: true });
|
|
84
|
+
}
|
|
85
|
+
if (kind === "tenants" && name === void 0) return json$2(200, { tenants: sql.exec("SELECT name, status FROM tenants ORDER BY name").toArray().map((row) => TenantRow.parse(row)) });
|
|
86
|
+
if (kind === "tokens" && name !== void 0) {
|
|
87
|
+
const row = sql.exec("SELECT tenant FROM tokens WHERE sha256 = ?", name).toArray()[0];
|
|
88
|
+
return row === void 0 ? json$2(HTTP_NOT_FOUND$2, { tenant: null }) : json$2(200, TokenRow.parse(row));
|
|
89
|
+
}
|
|
90
|
+
return json$2(HTTP_NOT_FOUND$2, { error: {
|
|
91
|
+
code: "not_found",
|
|
92
|
+
message: "no such directory route"
|
|
93
|
+
} });
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
function directoryClient(env) {
|
|
97
|
+
const stub = objectNamed(env.DIRECTORY, DIRECTORY, env);
|
|
98
|
+
const call = async (method, path, body) => {
|
|
99
|
+
const response = await stub.fetch(new Request(`${ORIGIN}${path}`, {
|
|
100
|
+
method,
|
|
101
|
+
...body === void 0 ? {} : {
|
|
102
|
+
body: JSON.stringify(body),
|
|
103
|
+
headers: { "content-type": "application/json" }
|
|
104
|
+
}
|
|
105
|
+
}));
|
|
106
|
+
if (!response.ok && response.status !== HTTP_NOT_FOUND$2) throw new Error(`the directory answered ${response.status}`);
|
|
107
|
+
return response;
|
|
108
|
+
};
|
|
109
|
+
return {
|
|
110
|
+
register: async (tenant, registration) => {
|
|
111
|
+
await call("PUT", `/tenants/${encodeURIComponent(tenant)}`, registration);
|
|
112
|
+
},
|
|
113
|
+
forget: async (tenant) => {
|
|
114
|
+
await call("DELETE", `/tenants/${encodeURIComponent(tenant)}`);
|
|
115
|
+
},
|
|
116
|
+
tenants: async () => Listing.parse(await (await call("GET", "/tenants")).json()).tenants,
|
|
117
|
+
tenantOf: async (tokenSha256) => {
|
|
118
|
+
const response = await call("GET", `/tokens/${encodeURIComponent(tokenSha256)}`);
|
|
119
|
+
return response.ok ? TokenRow.parse(await response.json()).tenant : void 0;
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
//#endregion
|
|
124
|
+
//#region src/adapters.ts
|
|
125
|
+
/**
|
|
126
|
+
* The source adapters a Worker carries. A Worker cannot install a package at run time, so the
|
|
127
|
+
* adapters are bundled: a source names one of these.
|
|
128
|
+
*/
|
|
129
|
+
const BUNDLED = [
|
|
130
|
+
adapter$1,
|
|
131
|
+
adapter$2,
|
|
132
|
+
adapter$3,
|
|
133
|
+
adapter$4,
|
|
134
|
+
adapter$5,
|
|
135
|
+
adapter
|
|
136
|
+
];
|
|
137
|
+
function bundledAdapters(adapters = BUNDLED) {
|
|
138
|
+
const byId = new Map(adapters.map((each) => [each.id, each]));
|
|
139
|
+
return { resolve: (id) => Promise.resolve(byId.get(id)) };
|
|
140
|
+
}
|
|
141
|
+
//#endregion
|
|
142
|
+
//#region src/config.ts
|
|
143
|
+
/**
|
|
144
|
+
* A tenant's config on Cloudflare: the signed desired config the control plane pushes
|
|
145
|
+
* (`PUT /api/v1/tenants/:tenant/config`), verified by the gateway and kept in the tenant's
|
|
146
|
+
* object, so the object keeps routing while the control plane is away. The control plane owns
|
|
147
|
+
* it: the management API's writes to projects, sources, routes and tokens are refused here.
|
|
148
|
+
*/
|
|
149
|
+
const READ_ONLY = "this instance's tenants come from its control plane: change them there";
|
|
150
|
+
function pushedConfigSource(options) {
|
|
151
|
+
return {
|
|
152
|
+
...storeConfigSource(options),
|
|
153
|
+
readOnly: () => Promise.resolve(READ_ONLY),
|
|
154
|
+
apply: () => Promise.reject(new BriefkastenError("read_only", READ_ONLY))
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
//#endregion
|
|
158
|
+
//#region src/meter.ts
|
|
159
|
+
/**
|
|
160
|
+
* Metering on Cloudflare: every count goes to the object's SQLite (the meter the usage API reads)
|
|
161
|
+
* and, when the Worker has an Analytics Engine dataset bound, to it as well, one data point per
|
|
162
|
+
* entry: indexed by tenant, blobs `project, source, event`, doubles in the order of `COUNTERS`.
|
|
163
|
+
*/
|
|
164
|
+
function analyticsMeter(store, dataset) {
|
|
165
|
+
if (dataset === void 0) return store;
|
|
166
|
+
return {
|
|
167
|
+
...store,
|
|
168
|
+
meter: async (entry) => {
|
|
169
|
+
await store.meter(entry);
|
|
170
|
+
dataset.writeDataPoint({
|
|
171
|
+
indexes: [entry.tenant],
|
|
172
|
+
blobs: [
|
|
173
|
+
entry.project,
|
|
174
|
+
entry.source,
|
|
175
|
+
entry.event
|
|
176
|
+
],
|
|
177
|
+
doubles: COUNTERS.map((counter) => entry.counts[counter] ?? 0)
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
//#endregion
|
|
183
|
+
//#region src/settings.ts
|
|
184
|
+
/**
|
|
185
|
+
* The instance settings of the Cloudflare runtime: a `multi` instance whose tenants a control
|
|
186
|
+
* plane pushes, configured by the Worker's vars and secrets. The secrets port is the Worker's
|
|
187
|
+
* environment: a `{ $env }` reference reads a var or a secret; nothing writes one.
|
|
188
|
+
*/
|
|
189
|
+
const DEFAULT_KEY_ID = "k1";
|
|
190
|
+
const ADMIN = "admin";
|
|
191
|
+
/** Reads `{ $env: NAME }` from the Worker's environment. */
|
|
192
|
+
function envSecrets(env) {
|
|
193
|
+
return (value, where) => {
|
|
194
|
+
if (typeof value === "string") return Promise.resolve(value);
|
|
195
|
+
const name = "$env" in value ? value.$env : void 0;
|
|
196
|
+
const found = name === void 0 ? void 0 : Reflect.get(env, name);
|
|
197
|
+
if (typeof found !== "string" || found === "") return Promise.reject(new BriefkastenError("unavailable", `${where}: set it as a Worker secret (wrangler secret put)`));
|
|
198
|
+
return Promise.resolve(found);
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
/** The control plane's verification keys by id: the current one and, while rotating, the next. */
|
|
202
|
+
function verifyKeys(env) {
|
|
203
|
+
const keys = {};
|
|
204
|
+
if (env.CONFIG_VERIFY_KEY !== void 0 && env.CONFIG_VERIFY_KEY !== "") keys[env.CONFIG_VERIFY_KEY_ID ?? DEFAULT_KEY_ID] = env.CONFIG_VERIFY_KEY;
|
|
205
|
+
if (env.CONFIG_VERIFY_KEY_NEXT !== void 0 && env.CONFIG_VERIFY_KEY_NEXT !== "") keys[env.CONFIG_VERIFY_KEY_NEXT_ID ?? `${DEFAULT_KEY_ID}-next`] = env.CONFIG_VERIFY_KEY_NEXT;
|
|
206
|
+
return keys;
|
|
207
|
+
}
|
|
208
|
+
/** The largest hook body the Worker takes. */
|
|
209
|
+
function maxBodyBytes(env) {
|
|
210
|
+
const parsed = Number(env.MAX_BODY_BYTES);
|
|
211
|
+
return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_MAX_BODY_BYTES;
|
|
212
|
+
}
|
|
213
|
+
function settingsOfEnv(env) {
|
|
214
|
+
const keys = verifyKeys(env);
|
|
215
|
+
const document = ConfigDocument.parse({
|
|
216
|
+
mode: "multi",
|
|
217
|
+
server: env.PUBLIC_URL === void 0 ? {} : { publicUrl: env.PUBLIC_URL },
|
|
218
|
+
maxBodyBytes: maxBodyBytes(env),
|
|
219
|
+
...Object.keys(keys).length === 0 ? {} : { controlPlane: { keys } },
|
|
220
|
+
...env.ADMIN_TOKEN === void 0 || env.ADMIN_TOKEN === "" ? {} : { tokens: { [ADMIN]: {
|
|
221
|
+
scope: "admin",
|
|
222
|
+
token: { $env: "ADMIN_TOKEN" }
|
|
223
|
+
} } }
|
|
224
|
+
});
|
|
225
|
+
return settingsOf(document, envSecrets(env));
|
|
226
|
+
}
|
|
227
|
+
//#endregion
|
|
228
|
+
//#region src/sockets.ts
|
|
229
|
+
/**
|
|
230
|
+
* The event stream over hibernating WebSockets. The object accepts a subscriber's socket with
|
|
231
|
+
* the Hibernation API, so an idle connection costs nothing: the runtime keeps the socket and
|
|
232
|
+
* answers its `ping` while the object sleeps. The gateway's session (catch-up after `since`,
|
|
233
|
+
* then the live events) lives in memory and is lost when the object hibernates, so each socket
|
|
234
|
+
* carries what reopens it (its request and the last event it got) as its attachment; a woken
|
|
235
|
+
* object reopens every socket's session from there before it handles anything else, and misses
|
|
236
|
+
* nothing still kept.
|
|
237
|
+
*
|
|
238
|
+
* The attachment holds the subscriber's token: the runtime keeps it with the socket, never in
|
|
239
|
+
* storage, and a reopened session checks the token again, so a revoked token is cut off.
|
|
240
|
+
*/
|
|
241
|
+
/** A refusal while the socket is open: 4000 plus the HTTP status (4401, 4403, 4404). */
|
|
242
|
+
const CLOSE_REFUSED = 4e3;
|
|
243
|
+
/** Close reasons are at most 123 bytes. */
|
|
244
|
+
const REASON_BYTES = 123;
|
|
245
|
+
const BEARER = "Bearer ";
|
|
246
|
+
const Attachment = z.object({
|
|
247
|
+
url: z.string(),
|
|
248
|
+
token: z.string(),
|
|
249
|
+
last: z.string().optional()
|
|
250
|
+
});
|
|
251
|
+
/** The bearer token of a stream request: the header, or a `bearer.<token>` subprotocol. */
|
|
252
|
+
function bearerOf(request) {
|
|
253
|
+
const header = request.headers.get("authorization");
|
|
254
|
+
if (header?.startsWith(BEARER) === true) return header.slice(7).trim();
|
|
255
|
+
return (request.headers.get("sec-websocket-protocol") ?? "").split(",").map((each) => each.trim()).find((each) => each.startsWith(WS_BEARER_PREFIX))?.slice(WS_BEARER_PREFIX.length);
|
|
256
|
+
}
|
|
257
|
+
/** The request that reopens a socket's session after the last event it got. */
|
|
258
|
+
function reopening(attachment) {
|
|
259
|
+
return new Request(attachment.url, { headers: {
|
|
260
|
+
authorization: `${BEARER}${attachment.token}`,
|
|
261
|
+
...attachment.last === void 0 ? {} : { "last-event-id": attachment.last }
|
|
262
|
+
} });
|
|
263
|
+
}
|
|
264
|
+
function closeReason(status, text) {
|
|
265
|
+
const bytes = new TextEncoder().encode(`${status} ${text}`);
|
|
266
|
+
return new TextDecoder().decode(bytes.subarray(0, REASON_BYTES)).replace(/�$/, "");
|
|
267
|
+
}
|
|
268
|
+
/** Why the gateway refused a stream, for a close frame: the error code if it says one. */
|
|
269
|
+
async function refusalOf(response) {
|
|
270
|
+
const text = await response.text();
|
|
271
|
+
try {
|
|
272
|
+
const body = JSON.parse(text);
|
|
273
|
+
const error = typeof body === "object" && body !== null ? Reflect.get(body, "error") : void 0;
|
|
274
|
+
const code = typeof error === "object" && error !== null ? Reflect.get(error, "code") : error;
|
|
275
|
+
return typeof code === "string" ? code : text;
|
|
276
|
+
} catch {
|
|
277
|
+
return text;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
var Sockets = class {
|
|
281
|
+
deps;
|
|
282
|
+
sessions = /* @__PURE__ */ new Map();
|
|
283
|
+
constructor(deps) {
|
|
284
|
+
this.deps = deps;
|
|
285
|
+
}
|
|
286
|
+
/** Answers a WebSocket upgrade of the stream: a refusal, or the client's end of a new socket. */
|
|
287
|
+
async open(request) {
|
|
288
|
+
const opening = await this.deps.gateway.openStream(request);
|
|
289
|
+
if (opening.kind === "refused") return opening.response;
|
|
290
|
+
const { client, server } = this.deps.factory.pair();
|
|
291
|
+
this.deps.accept(server);
|
|
292
|
+
const since = new URL(request.url).searchParams.get("since") ?? request.headers.get("last-event-id");
|
|
293
|
+
server.serializeAttachment({
|
|
294
|
+
url: request.url,
|
|
295
|
+
token: bearerOf(request) ?? "",
|
|
296
|
+
...since === null || since === "" ? {} : { last: since }
|
|
297
|
+
});
|
|
298
|
+
this.pump(server, opening.session);
|
|
299
|
+
return this.deps.factory.upgraded(client, opening.protocol);
|
|
300
|
+
}
|
|
301
|
+
/** Reopens the session of every socket the object kept while it slept. */
|
|
302
|
+
async restore() {
|
|
303
|
+
for (const socket of this.deps.accepted()) {
|
|
304
|
+
const attachment = Attachment.safeParse(socket.deserializeAttachment());
|
|
305
|
+
if (!attachment.success) {
|
|
306
|
+
socket.close(4400, "the socket lost its session");
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
const opening = await this.deps.gateway.openStream(reopening(attachment.data));
|
|
310
|
+
if (opening.kind === "refused") {
|
|
311
|
+
const { status } = opening.response;
|
|
312
|
+
socket.close(CLOSE_REFUSED + status, closeReason(status, await refusalOf(opening.response)));
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
this.pump(socket, opening.session);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
/** The socket closed (or failed): its session ends. */
|
|
319
|
+
closed(socket) {
|
|
320
|
+
this.sessions.get(socket)?.close();
|
|
321
|
+
this.sessions.delete(socket);
|
|
322
|
+
}
|
|
323
|
+
size() {
|
|
324
|
+
return this.sessions.size;
|
|
325
|
+
}
|
|
326
|
+
pump(socket, session) {
|
|
327
|
+
this.sessions.set(socket, session);
|
|
328
|
+
const send = async () => {
|
|
329
|
+
for await (const item of session.items) {
|
|
330
|
+
socket.send(encodeWs(item));
|
|
331
|
+
this.remember(socket, item);
|
|
332
|
+
}
|
|
333
|
+
const ended = session.ended();
|
|
334
|
+
if (ended !== void 0) {
|
|
335
|
+
this.sessions.delete(socket);
|
|
336
|
+
socket.close(WS_CLOSE[ended], `tenant ${ended}`);
|
|
337
|
+
}
|
|
338
|
+
};
|
|
339
|
+
send().catch((error) => {
|
|
340
|
+
this.deps.log(`a stream socket failed: ${messageOf(error)}`);
|
|
341
|
+
this.closed(socket);
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
remember(socket, item) {
|
|
345
|
+
if (item.kind !== "event") return;
|
|
346
|
+
const attachment = Attachment.safeParse(socket.deserializeAttachment());
|
|
347
|
+
if (attachment.success) socket.serializeAttachment({
|
|
348
|
+
...attachment.data,
|
|
349
|
+
last: item.event.id
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
};
|
|
353
|
+
//#endregion
|
|
354
|
+
//#region src/sql.ts
|
|
355
|
+
/**
|
|
356
|
+
* A Durable Object's SQLite as the driver of briefkasten's SQL stores: the same events, meter and
|
|
357
|
+
* key-value tables the Node runtime keeps in `node:sqlite`, private to one tenant's object.
|
|
358
|
+
*/
|
|
359
|
+
const Changes = z.object({ changes: z.number() });
|
|
360
|
+
function objectSqlDriver(sql) {
|
|
361
|
+
return {
|
|
362
|
+
script: (query) => {
|
|
363
|
+
sql.exec(query);
|
|
364
|
+
},
|
|
365
|
+
all: (query, ...values) => sql.exec(query, ...values).toArray(),
|
|
366
|
+
run: (query, ...values) => {
|
|
367
|
+
sql.exec(query, ...values);
|
|
368
|
+
return Changes.parse(sql.exec("SELECT changes() AS changes").toArray()[0]).changes;
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
/** Whether the object has kept anything yet: an unknown tenant's object stays empty. */
|
|
373
|
+
function hasTables(sql) {
|
|
374
|
+
return sql.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'kv'").toArray().length > 0;
|
|
375
|
+
}
|
|
376
|
+
//#endregion
|
|
377
|
+
//#region src/tenant.ts
|
|
378
|
+
/**
|
|
379
|
+
* One tenant's Durable Object: the gateway for that tenant alone, on the object's SQLite (its
|
|
380
|
+
* events for the retention window, their deliveries, the meter, the pushed config), with its
|
|
381
|
+
* subscribers on hibernating WebSockets. The Worker sends it everything that names the tenant;
|
|
382
|
+
* the tenant is a hard key, since nothing else is in the object.
|
|
383
|
+
*
|
|
384
|
+
* An object no config was ever pushed to keeps nothing: it answers 404 without writing, so a
|
|
385
|
+
* request that makes up a tenant leaves no trace.
|
|
386
|
+
*/
|
|
387
|
+
/** The header the Worker names the object's tenant in. */
|
|
388
|
+
const OBJECT_HEADER = "briefkasten-object";
|
|
389
|
+
/** The object that serves requests naming no tenant: a valid tenant name never starts with `_`. */
|
|
390
|
+
const INSTANCE = "_instance";
|
|
391
|
+
const PRUNE_MS = 36e5;
|
|
392
|
+
const DAY_MS = 864e5;
|
|
393
|
+
const HTTP_NOT_FOUND$1 = 404;
|
|
394
|
+
const TENANTS_PATH$1 = `${API_PREFIX}/tenants`;
|
|
395
|
+
function json$1(status, value) {
|
|
396
|
+
return new Response(JSON.stringify(value), {
|
|
397
|
+
status,
|
|
398
|
+
headers: { "content-type": "application/json" }
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
function pathOf(request) {
|
|
402
|
+
return new URL(request.url).pathname.replace(/\/+$/, "");
|
|
403
|
+
}
|
|
404
|
+
/** Whether the request may bring a tenant into being: its first config, or an admin's create. */
|
|
405
|
+
function creates(request) {
|
|
406
|
+
const path = pathOf(request);
|
|
407
|
+
return request.method === "PUT" && /^\/api\/v1\/tenants\/[^/]+\/config$/.test(path) || request.method === "POST" && path === TENANTS_PATH$1;
|
|
408
|
+
}
|
|
409
|
+
function isStream(request) {
|
|
410
|
+
const path = pathOf(request);
|
|
411
|
+
return path === STREAM_PATH || /^\/t\/[^/]+\/stream$/.test(path);
|
|
412
|
+
}
|
|
413
|
+
function isUpgrade(request) {
|
|
414
|
+
return request.headers.get("upgrade")?.toLowerCase() === "websocket";
|
|
415
|
+
}
|
|
416
|
+
/** The SHA-256 of every token the tenant has: where the directory sends a token's requests. */
|
|
417
|
+
function tokensOf(tenant) {
|
|
418
|
+
return Object.values(tenant.tokens).map((token) => token.tokenSha256);
|
|
419
|
+
}
|
|
420
|
+
var TenantHost = class {
|
|
421
|
+
deps;
|
|
422
|
+
opened;
|
|
423
|
+
alarmSet = false;
|
|
424
|
+
store;
|
|
425
|
+
directory;
|
|
426
|
+
now;
|
|
427
|
+
log;
|
|
428
|
+
constructor(deps) {
|
|
429
|
+
this.deps = deps;
|
|
430
|
+
this.directory = directoryClient(deps.env);
|
|
431
|
+
this.now = deps.now ?? Date.now;
|
|
432
|
+
this.log = deps.log ?? ((message) => console.warn(message));
|
|
433
|
+
this.store = lazyStores(deps.state, this.now);
|
|
434
|
+
deps.state.setWebSocketAutoResponse(deps.factory.autoResponse(WS_PING, WS_PONG));
|
|
435
|
+
}
|
|
436
|
+
/** Opens the gateway when the object keeps a tenant, and reopens its sockets' sessions. */
|
|
437
|
+
async wake() {
|
|
438
|
+
if (hasTables(this.deps.state.storage.sql)) await (await this.open()).sockets.restore();
|
|
439
|
+
}
|
|
440
|
+
async fetch(request) {
|
|
441
|
+
const opens = creates(request) || request.headers.get("briefkasten-object") === "_instance";
|
|
442
|
+
if (this.opened === void 0 && !opens && !hasTables(this.deps.state.storage.sql)) return json$1(HTTP_NOT_FOUND$1, { error: {
|
|
443
|
+
code: "not_found",
|
|
444
|
+
message: "no such tenant"
|
|
445
|
+
} });
|
|
446
|
+
const opened = await this.open();
|
|
447
|
+
if (isStream(request) && isUpgrade(request)) return opened.sockets.open(request);
|
|
448
|
+
const response = await opened.gateway.fetch(request);
|
|
449
|
+
const path = pathOf(request);
|
|
450
|
+
if (response.ok && request.method === "POST" && !path.startsWith(API_PREFIX)) await this.scheduleAlarm();
|
|
451
|
+
if (response.ok && request.method !== "GET" && path.startsWith(TENANTS_PATH$1)) await this.changed(opened, request.headers.get("briefkasten-object") ?? "");
|
|
452
|
+
return response;
|
|
453
|
+
}
|
|
454
|
+
/** The runtime closed a socket, or it failed. */
|
|
455
|
+
closed(socket) {
|
|
456
|
+
this.opened?.sockets.closed(socket);
|
|
457
|
+
}
|
|
458
|
+
/** Drops the events older than the tenant's retention, and comes back in an hour. */
|
|
459
|
+
async alarm() {
|
|
460
|
+
this.alarmSet = false;
|
|
461
|
+
const tenant = this.opened === void 0 ? void 0 : (await this.opened.config.load()).tenants[0];
|
|
462
|
+
if (tenant === void 0) return;
|
|
463
|
+
const dropped = await this.store.events.prune(tenant.name, this.now() - tenant.limits.retentionDays * DAY_MS);
|
|
464
|
+
if (dropped > 0) this.log(`${tenant.name}: dropped ${dropped} event(s) past retention`);
|
|
465
|
+
await this.scheduleAlarm();
|
|
466
|
+
}
|
|
467
|
+
async open() {
|
|
468
|
+
if (this.opened !== void 0) return this.opened;
|
|
469
|
+
const { env, state, factory } = this.deps;
|
|
470
|
+
const { events, kv } = this.store;
|
|
471
|
+
const settings = await settingsOfEnv(env);
|
|
472
|
+
const config = pushedConfigSource({
|
|
473
|
+
settings: () => Promise.resolve(settings),
|
|
474
|
+
kv
|
|
475
|
+
});
|
|
476
|
+
const gateway = await createGateway({
|
|
477
|
+
config,
|
|
478
|
+
store: analyticsMeter(events, env.USAGE),
|
|
479
|
+
kv,
|
|
480
|
+
adapters: bundledAdapters(),
|
|
481
|
+
log: this.log,
|
|
482
|
+
runtime: {
|
|
483
|
+
now: this.now,
|
|
484
|
+
random: (size) => crypto.getRandomValues(new Uint8Array(size))
|
|
485
|
+
},
|
|
486
|
+
...env.VERSION === void 0 ? {} : { version: env.VERSION }
|
|
487
|
+
});
|
|
488
|
+
const sockets = new Sockets({
|
|
489
|
+
gateway,
|
|
490
|
+
factory,
|
|
491
|
+
accept: (socket) => {
|
|
492
|
+
state.acceptWebSocket(socket);
|
|
493
|
+
},
|
|
494
|
+
accepted: () => state.getWebSockets(),
|
|
495
|
+
log: this.log
|
|
496
|
+
});
|
|
497
|
+
this.opened = {
|
|
498
|
+
gateway,
|
|
499
|
+
config,
|
|
500
|
+
sockets
|
|
501
|
+
};
|
|
502
|
+
return this.opened;
|
|
503
|
+
}
|
|
504
|
+
async scheduleAlarm() {
|
|
505
|
+
if (this.alarmSet) return;
|
|
506
|
+
const { storage } = this.deps.state;
|
|
507
|
+
if (await storage.getAlarm() === null) await storage.setAlarm(this.now() + PRUNE_MS);
|
|
508
|
+
this.alarmSet = true;
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* After an admin's change: tells the directory. The gateway itself ends the streams of a
|
|
512
|
+
* suspended or deleted tenant, and their sockets close with its reason (`Sockets`).
|
|
513
|
+
*/
|
|
514
|
+
async changed(opened, name) {
|
|
515
|
+
const [tenant] = (await opened.config.load()).tenants;
|
|
516
|
+
try {
|
|
517
|
+
if (tenant === void 0) await this.directory.forget(name);
|
|
518
|
+
else await this.directory.register(tenant.name, {
|
|
519
|
+
status: tenant.status,
|
|
520
|
+
tokens: tokensOf(tenant)
|
|
521
|
+
});
|
|
522
|
+
} catch (error) {
|
|
523
|
+
this.log(`${name}: the directory refused the change: ${messageOf(error)}`);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
};
|
|
527
|
+
/**
|
|
528
|
+
* The object's SQL stores, made on first use: an object that never opens (a tenant nobody
|
|
529
|
+
* pushed) never creates its tables.
|
|
530
|
+
*/
|
|
531
|
+
function lazyStores(state, now) {
|
|
532
|
+
let made;
|
|
533
|
+
const stores = () => {
|
|
534
|
+
made ??= sqlStores(objectSqlDriver(state.storage.sql), { now });
|
|
535
|
+
return made;
|
|
536
|
+
};
|
|
537
|
+
return {
|
|
538
|
+
get events() {
|
|
539
|
+
return stores().events;
|
|
540
|
+
},
|
|
541
|
+
get kv() {
|
|
542
|
+
return stores().kv;
|
|
543
|
+
}
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
//#endregion
|
|
547
|
+
//#region src/workers.ts
|
|
548
|
+
/**
|
|
549
|
+
* The socket factory over the Workers runtime's globals: `WebSocketPair`, a `Response` with a
|
|
550
|
+
* `webSocket`, and `WebSocketRequestResponsePair` for the ping the runtime answers itself.
|
|
551
|
+
*/
|
|
552
|
+
const SWITCHING_PROTOCOLS = 101;
|
|
553
|
+
function isConstructor(value) {
|
|
554
|
+
return typeof value === "function";
|
|
555
|
+
}
|
|
556
|
+
function global(name) {
|
|
557
|
+
const value = Reflect.get(globalThis, name);
|
|
558
|
+
if (!isConstructor(value)) throw new Error(`${name} is missing: this runs on the Workers runtime only`);
|
|
559
|
+
return value;
|
|
560
|
+
}
|
|
561
|
+
function isSocket(value) {
|
|
562
|
+
return typeof value === "object" && value !== null && typeof Reflect.get(value, "send") === "function" && typeof Reflect.get(value, "serializeAttachment") === "function";
|
|
563
|
+
}
|
|
564
|
+
const workersSockets = {
|
|
565
|
+
pair() {
|
|
566
|
+
const pair = new (global("WebSocketPair"))();
|
|
567
|
+
const client = Reflect.get(pair, 0);
|
|
568
|
+
const server = Reflect.get(pair, 1);
|
|
569
|
+
if (!isSocket(server)) throw new Error("WebSocketPair gave no server socket");
|
|
570
|
+
return {
|
|
571
|
+
client,
|
|
572
|
+
server
|
|
573
|
+
};
|
|
574
|
+
},
|
|
575
|
+
upgraded(client, protocol) {
|
|
576
|
+
return new Response(null, {
|
|
577
|
+
status: SWITCHING_PROTOCOLS,
|
|
578
|
+
webSocket: client,
|
|
579
|
+
headers: protocol === void 0 ? {} : { "sec-websocket-protocol": protocol }
|
|
580
|
+
});
|
|
581
|
+
},
|
|
582
|
+
autoResponse(request, response) {
|
|
583
|
+
return new (global("WebSocketRequestResponsePair"))(request, response);
|
|
584
|
+
}
|
|
585
|
+
};
|
|
586
|
+
//#endregion
|
|
587
|
+
//#region src/objects.ts
|
|
588
|
+
/**
|
|
589
|
+
* The Durable Object classes the Worker exports (`wrangler.toml` binds them): one per tenant, and
|
|
590
|
+
* the directory. Each is a thin shell over a class that runs without the Workers runtime.
|
|
591
|
+
*/
|
|
592
|
+
const CLOSE_NORMAL = 1e3;
|
|
593
|
+
var TenantObject = class {
|
|
594
|
+
host;
|
|
595
|
+
constructor(state, env) {
|
|
596
|
+
this.host = new TenantHost({
|
|
597
|
+
state,
|
|
598
|
+
env,
|
|
599
|
+
factory: workersSockets
|
|
600
|
+
});
|
|
601
|
+
state.blockConcurrencyWhile(() => this.host.wake());
|
|
602
|
+
}
|
|
603
|
+
fetch(request) {
|
|
604
|
+
return this.host.fetch(request);
|
|
605
|
+
}
|
|
606
|
+
/** The runtime answers `ping` itself; anything else a subscriber sends is ignored. */
|
|
607
|
+
webSocketMessage() {}
|
|
608
|
+
webSocketClose(socket) {
|
|
609
|
+
this.host.closed(socket);
|
|
610
|
+
try {
|
|
611
|
+
socket.close(CLOSE_NORMAL, "closed");
|
|
612
|
+
} catch {}
|
|
613
|
+
}
|
|
614
|
+
webSocketError(socket) {
|
|
615
|
+
this.host.closed(socket);
|
|
616
|
+
}
|
|
617
|
+
alarm() {
|
|
618
|
+
return this.host.alarm();
|
|
619
|
+
}
|
|
620
|
+
};
|
|
621
|
+
//#endregion
|
|
622
|
+
//#region src/worker.ts
|
|
623
|
+
/**
|
|
624
|
+
* The Worker: the front door of a `multi` instance. It answers `/health` itself and sends every
|
|
625
|
+
* other request to the Durable Object of the tenant it names, where the gateway (the same `fetch`
|
|
626
|
+
* handler as on Node) serves it:
|
|
627
|
+
*
|
|
628
|
+
* POST /t/<tenant>/hooks/<project>/<source> a provider's delivery (size and rate checked here first)
|
|
629
|
+
* GET /t/<tenant>/stream the event stream (SSE, or a WebSocket upgrade)
|
|
630
|
+
* * /api/v1/tenants/<tenant>[/config] an admin's change to one tenant, or its pushed config
|
|
631
|
+
* * /api/v1/… with `Briefkasten-Tenant` an admin's call on a tenant's endpoints (the only way:
|
|
632
|
+
* there are no `/tenants/<tenant>/…` copies of them)
|
|
633
|
+
* * /api/v1/… with a tenant's token that token's tenant (the directory knows whose it is)
|
|
634
|
+
*
|
|
635
|
+
* and fans out the calls that span tenants: `GET /api/v1/tenants` and `GET /api/v1/tenants/usage`.
|
|
636
|
+
* What names no tenant (sign-in methods, the adapters) goes to one object without a tenant.
|
|
637
|
+
*/
|
|
638
|
+
const DIRECTORY_CACHE_MS = 6e4;
|
|
639
|
+
const HTTP_OK = 200;
|
|
640
|
+
const HTTP_UNAUTHORIZED = 401;
|
|
641
|
+
const HTTP_NOT_FOUND = 404;
|
|
642
|
+
const HTTP_TOO_LARGE = 413;
|
|
643
|
+
const HTTP_TOO_MANY = 429;
|
|
644
|
+
const HTTP_BAD_GATEWAY = 502;
|
|
645
|
+
const TENANTS_PATH = `${API_PREFIX}/tenants`;
|
|
646
|
+
const USAGE_PATH = `${TENANTS_PATH}/usage`;
|
|
647
|
+
function json(status, value, headers = {}) {
|
|
648
|
+
return new Response(JSON.stringify(value), {
|
|
649
|
+
status,
|
|
650
|
+
headers: {
|
|
651
|
+
"content-type": "application/json",
|
|
652
|
+
...headers
|
|
653
|
+
}
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
function failure(status, code, message, headers = {}) {
|
|
657
|
+
return json(status, { error: {
|
|
658
|
+
code,
|
|
659
|
+
message
|
|
660
|
+
} }, headers);
|
|
661
|
+
}
|
|
662
|
+
function tenantName(text) {
|
|
663
|
+
const decoded = text === void 0 ? void 0 : decodeURIComponent(text);
|
|
664
|
+
return TenantId.safeParse(decoded).success ? decoded : void 0;
|
|
665
|
+
}
|
|
666
|
+
var TooLarge = class extends Error {};
|
|
667
|
+
/** The body, read up to `max` bytes; a longer one is refused without reading the rest. */
|
|
668
|
+
async function readLimited(request, max) {
|
|
669
|
+
if (request.body === null) return;
|
|
670
|
+
if (Number(request.headers.get("content-length") ?? "0") > max) throw new TooLarge();
|
|
671
|
+
const reader = request.body.getReader();
|
|
672
|
+
const chunks = [];
|
|
673
|
+
let size = 0;
|
|
674
|
+
for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
|
|
675
|
+
size += chunk.value.byteLength;
|
|
676
|
+
if (size > max) {
|
|
677
|
+
await reader.cancel();
|
|
678
|
+
throw new TooLarge();
|
|
679
|
+
}
|
|
680
|
+
chunks.push(chunk.value);
|
|
681
|
+
}
|
|
682
|
+
const body = new Uint8Array(size);
|
|
683
|
+
let offset = 0;
|
|
684
|
+
for (const chunk of chunks) {
|
|
685
|
+
body.set(chunk, offset);
|
|
686
|
+
offset += chunk.byteLength;
|
|
687
|
+
}
|
|
688
|
+
return body.buffer;
|
|
689
|
+
}
|
|
690
|
+
const Frame = z.object({
|
|
691
|
+
from: z.string(),
|
|
692
|
+
to: z.string(),
|
|
693
|
+
by: z.array(z.string()),
|
|
694
|
+
rows: z.array(z.unknown())
|
|
695
|
+
});
|
|
696
|
+
const TenantList = z.object({ tenants: z.array(z.unknown()) });
|
|
697
|
+
async function isAdmin(request, env) {
|
|
698
|
+
const token = bearerOf(request);
|
|
699
|
+
if (token === void 0 || env.ADMIN_TOKEN === void 0 || env.ADMIN_TOKEN === "") return false;
|
|
700
|
+
return constantTimeEqual(await sha256Hex(token), await sha256Hex(env.ADMIN_TOKEN));
|
|
701
|
+
}
|
|
702
|
+
/** Sends a request to a tenant's object, its body already read. */
|
|
703
|
+
function forward(env, tenant, request, body) {
|
|
704
|
+
const url = new URL(request.url);
|
|
705
|
+
const headers = new Headers(request.headers);
|
|
706
|
+
headers.set(OBJECT_HEADER, tenant);
|
|
707
|
+
return objectNamed(env.TENANTS, tenant, env).fetch(new Request(url, {
|
|
708
|
+
method: request.method,
|
|
709
|
+
headers,
|
|
710
|
+
...body === void 0 ? {} : { body }
|
|
711
|
+
}));
|
|
712
|
+
}
|
|
713
|
+
function createWorker(options = {}) {
|
|
714
|
+
const now = options.now ?? Date.now;
|
|
715
|
+
/** Which tenant a token's hash belongs to, for a minute: the directory is one object for all. */
|
|
716
|
+
const cache = /* @__PURE__ */ new Map();
|
|
717
|
+
async function tenantOfToken(directory, token) {
|
|
718
|
+
const hash = await sha256Hex(token);
|
|
719
|
+
const known = cache.get(hash);
|
|
720
|
+
if (known !== void 0 && known.until > now()) return known.tenant;
|
|
721
|
+
const tenant = await directory.tenantOf(hash);
|
|
722
|
+
cache.set(hash, {
|
|
723
|
+
tenant,
|
|
724
|
+
until: now() + DIRECTORY_CACHE_MS
|
|
725
|
+
});
|
|
726
|
+
return tenant;
|
|
727
|
+
}
|
|
728
|
+
async function hook(env, request, tenant) {
|
|
729
|
+
if (request.method !== "POST") return failure(HTTP_NOT_FOUND, "not_found", "hooks take POST");
|
|
730
|
+
const max = maxBodyBytes(env);
|
|
731
|
+
let body;
|
|
732
|
+
try {
|
|
733
|
+
body = await readLimited(request, max);
|
|
734
|
+
} catch (error) {
|
|
735
|
+
if (error instanceof TooLarge) return failure(HTTP_TOO_LARGE, "payload_too_large", `the body is larger than ${max} bytes`);
|
|
736
|
+
throw error;
|
|
737
|
+
}
|
|
738
|
+
if (!((await env.HOOK_LIMITER?.limit({ key: `tenant:${tenant}` }))?.success ?? true)) return failure(HTTP_TOO_MANY, "rate_limited", "too many deliveries for this tenant: try again in a minute", { "retry-after": "60" });
|
|
739
|
+
return forward(env, tenant, request, body);
|
|
740
|
+
}
|
|
741
|
+
/** A call that spans tenants: asked of each tenant's object, the answers merged. */
|
|
742
|
+
async function fanOut(env, request, tenants, merge) {
|
|
743
|
+
if (tenants.length === 0) return forward(env, INSTANCE, request, void 0);
|
|
744
|
+
const answers = [];
|
|
745
|
+
for (const tenant of tenants) {
|
|
746
|
+
const url = new URL(request.url);
|
|
747
|
+
if (url.pathname.replace(/\/+$/, "") === USAGE_PATH) url.searchParams.set("tenant", tenant);
|
|
748
|
+
const response = await forward(env, tenant, new Request(url, request), void 0);
|
|
749
|
+
if (response.status === HTTP_NOT_FOUND) continue;
|
|
750
|
+
if (!response.ok) return failure(HTTP_BAD_GATEWAY, "upstream", `tenant ${tenant} answered ${response.status}`);
|
|
751
|
+
answers.push(await response.json());
|
|
752
|
+
}
|
|
753
|
+
return json(HTTP_OK, merge(answers));
|
|
754
|
+
}
|
|
755
|
+
async function spanning(env, request, path) {
|
|
756
|
+
if (!await isAdmin(request, env)) return failure(HTTP_UNAUTHORIZED, "unauthorized", "this needs an admin token");
|
|
757
|
+
const directory = directoryClient(env);
|
|
758
|
+
const named = tenantName(new URL(request.url).searchParams.get("tenant") ?? void 0);
|
|
759
|
+
const tenants = named === void 0 ? (await directory.tenants()).map((each) => each.name) : [named];
|
|
760
|
+
if (path === USAGE_PATH) return fanOut(env, request, tenants, (answers) => {
|
|
761
|
+
const frames = answers.map((answer) => Frame.parse(answer));
|
|
762
|
+
return {
|
|
763
|
+
...frames[0],
|
|
764
|
+
rows: frames.flatMap((frame) => frame.rows)
|
|
765
|
+
};
|
|
766
|
+
});
|
|
767
|
+
return fanOut(env, request, tenants, (answers) => ({ tenants: answers.flatMap((answer) => TenantList.parse(answer).tenants) }));
|
|
768
|
+
}
|
|
769
|
+
async function route(request, env) {
|
|
770
|
+
const path = new URL(request.url).pathname.replace(/\/+$/, "") || "/";
|
|
771
|
+
if (request.method === "GET" && path === "/health") return json(HTTP_OK, {
|
|
772
|
+
ok: true,
|
|
773
|
+
...env.VERSION === void 0 ? {} : { version: env.VERSION }
|
|
774
|
+
});
|
|
775
|
+
const addressed = /^\/t\/([^/]+)\/(hooks(?:\/.*)?|stream)$/.exec(path);
|
|
776
|
+
if (addressed !== null) {
|
|
777
|
+
const tenant = tenantName(addressed[1]);
|
|
778
|
+
if (tenant === void 0) return failure(HTTP_NOT_FOUND, "not_found", "no such tenant");
|
|
779
|
+
return addressed[2] === "stream" ? forward(env, tenant, request, void 0) : hook(env, request, tenant);
|
|
780
|
+
}
|
|
781
|
+
if (request.method === "GET" && (path === TENANTS_PATH || path === USAGE_PATH)) return spanning(env, request, path);
|
|
782
|
+
const body = request.method === "GET" || request.method === "HEAD" ? void 0 : await request.arrayBuffer();
|
|
783
|
+
if (request.method === "POST" && path === TENANTS_PATH) return forward(env, createdName(body) ?? "_instance", request, body);
|
|
784
|
+
const scoped = /^\/api\/v1\/tenants\/([^/]+)(?:\/config)?$/.exec(path);
|
|
785
|
+
const named = scoped === null ? request.headers.get(TENANT_HEADER) ?? void 0 : scoped[1];
|
|
786
|
+
if (named !== void 0) {
|
|
787
|
+
const tenant = tenantName(named);
|
|
788
|
+
return tenant === void 0 ? failure(HTTP_NOT_FOUND, "not_found", "no such tenant") : forward(env, tenant, request, body);
|
|
789
|
+
}
|
|
790
|
+
const token = path.startsWith(`${API_PREFIX}/`) ? bearerOf(request) : void 0;
|
|
791
|
+
return forward(env, (token === void 0 ? void 0 : await tenantOfToken(directoryClient(env), token)) ?? "_instance", request, body);
|
|
792
|
+
}
|
|
793
|
+
return { fetch: (request, env) => route(request, env) };
|
|
794
|
+
}
|
|
795
|
+
/** The name of the tenant a create (`POST /api/v1/tenants`) asks for, if its body says one. */
|
|
796
|
+
function createdName(body) {
|
|
797
|
+
try {
|
|
798
|
+
const parsed = z.object({ name: z.string() }).safeParse(JSON.parse(new TextDecoder().decode(body)));
|
|
799
|
+
return parsed.success ? tenantName(parsed.data.name) : void 0;
|
|
800
|
+
} catch {
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
//#endregion
|
|
805
|
+
export { BUNDLED, Directory, INSTANCE, OBJECT_HEADER, TenantObject, bundledAdapters, createWorker };
|
package/package.json
CHANGED
|
@@ -1,6 +1,73 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@briefkasten/cloudflare",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "briefkasten on Cloudflare: the gateway as a Worker, one Durable Object per tenant, hibernating WebSockets",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"briefkasten",
|
|
7
|
+
"cloudflare",
|
|
8
|
+
"durable-objects",
|
|
9
|
+
"gateway",
|
|
10
|
+
"typescript",
|
|
11
|
+
"webhooks",
|
|
12
|
+
"workers"
|
|
13
|
+
],
|
|
14
|
+
"homepage": "https://briefkasten.fabrik.computer/docs",
|
|
15
|
+
"bugs": {
|
|
16
|
+
"url": "https://github.com/mateffy/fabrik/issues"
|
|
17
|
+
},
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"author": "Lukas Mateffy",
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/mateffy/fabrik.git",
|
|
23
|
+
"directory": "packages/briefkasten-cloudflare"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"dist",
|
|
27
|
+
"README.md",
|
|
28
|
+
"LICENSE"
|
|
29
|
+
],
|
|
30
|
+
"type": "module",
|
|
31
|
+
"sideEffects": false,
|
|
32
|
+
"main": "./dist/index.mjs",
|
|
33
|
+
"types": "./dist/index.d.mts",
|
|
34
|
+
"exports": {
|
|
35
|
+
".": {
|
|
36
|
+
"types": "./dist/index.d.mts",
|
|
37
|
+
"import": "./dist/index.mjs",
|
|
38
|
+
"default": "./dist/index.mjs"
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public"
|
|
43
|
+
},
|
|
44
|
+
"dependencies": {
|
|
45
|
+
"zod": "^4.4.3",
|
|
46
|
+
"@briefkasten/adapter-generic": "0.1.0",
|
|
47
|
+
"@briefkasten/adapter-github": "0.1.0",
|
|
48
|
+
"@briefkasten/adapter-nightwatch": "0.1.0",
|
|
49
|
+
"@briefkasten/adapter-linear": "0.1.0",
|
|
50
|
+
"@briefkasten/adapter-posthog": "0.1.0",
|
|
51
|
+
"@briefkasten/server": "0.1.0",
|
|
52
|
+
"briefkasten": "0.1.0",
|
|
53
|
+
"@briefkasten/adapter-sentry": "0.1.0"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@types/node": "^22.0.0",
|
|
57
|
+
"@vitest/coverage-v8": "4.1.11",
|
|
58
|
+
"tsdown": "^0.22.3",
|
|
59
|
+
"typescript": "^5.8.0",
|
|
60
|
+
"vitest": "^4.0.0",
|
|
61
|
+
"wrangler": "4.170.0"
|
|
62
|
+
},
|
|
63
|
+
"engines": {
|
|
64
|
+
"node": ">=22"
|
|
65
|
+
},
|
|
66
|
+
"scripts": {
|
|
67
|
+
"build": "tsdown",
|
|
68
|
+
"typecheck": "tsc --noEmit",
|
|
69
|
+
"test": "vitest run",
|
|
70
|
+
"test:workers": "vitest run --config vitest.workers.config.ts",
|
|
71
|
+
"dev": "wrangler dev --env dev"
|
|
72
|
+
}
|
|
6
73
|
}
|