@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 +21 -0
- package/README.md +37 -2
- package/dist/index.d.mts +160 -0
- package/dist/index.mjs +2 -0
- package/dist/node.d.mts +211 -0
- package/dist/node.mjs +935 -0
- package/dist/sql-Bt3YJw7M.mjs +2439 -0
- package/dist/sql-dW8FI4m2.d.mts +102 -0
- package/package.json +65 -3
package/dist/node.mjs
ADDED
|
@@ -0,0 +1,935 @@
|
|
|
1
|
+
import { a as resendMailer, f as pulledConfigSource, i as consoleMailer, n as memoryStores, o as createGateway, p as storeConfigSource, t as sqlStores } from "./sql-Bt3YJw7M.mjs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { BriefkastenError, ConfigError, WS_CLOSE, WS_PING, WS_PONG, applyMutation, configPath, encodeWs, fileTenantOf, loadConfigFile, messageOf, parseDocument, recordOf, settingsOf, shapeOf, withShape } from "briefkasten";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { basename, dirname, isAbsolute, join } from "node:path";
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
7
|
+
import { constants } from "node:fs";
|
|
8
|
+
import { access, chmod, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
9
|
+
import { createServer } from "node:http";
|
|
10
|
+
import { Readable } from "node:stream";
|
|
11
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
12
|
+
import { connect } from "node:net";
|
|
13
|
+
import { connect as connect$1 } from "node:tls";
|
|
14
|
+
import { DatabaseSync } from "node:sqlite";
|
|
15
|
+
//#region src/node/adapters.ts
|
|
16
|
+
/**
|
|
17
|
+
* Finds a source adapter by id on Node: the definitions a TypeScript config brought, else the
|
|
18
|
+
* installed package `@briefkasten/adapter-<id>`, resolved from the config's directory first (where
|
|
19
|
+
* an installer links the packages) and then from briefkasten's own. The package exports its
|
|
20
|
+
* definition as `adapter`.
|
|
21
|
+
*/
|
|
22
|
+
function isAdapter(value) {
|
|
23
|
+
const record = recordOf(value);
|
|
24
|
+
return typeof record["id"] === "string" && typeof record["create"] === "function" && typeof record["optionsSchema"] === "object" && typeof record["events"] === "object";
|
|
25
|
+
}
|
|
26
|
+
function resolveFrom(directories, name) {
|
|
27
|
+
for (const directory of directories) try {
|
|
28
|
+
return createRequire(join(directory, "noop.js")).resolve(name);
|
|
29
|
+
} catch {}
|
|
30
|
+
}
|
|
31
|
+
function nodeAdapterRegistry(options) {
|
|
32
|
+
const load = options.importer ?? ((specifier) => import(specifier));
|
|
33
|
+
const cache = new Map((options.known ?? []).map((adapter) => [adapter.id, adapter]));
|
|
34
|
+
return { async resolve(id) {
|
|
35
|
+
if (cache.has(id)) return cache.get(id);
|
|
36
|
+
const path = resolveFrom(options.from, `@briefkasten/adapter-${id}`);
|
|
37
|
+
const loaded = path === void 0 ? void 0 : recordOf(await load(pathToFileURL(path).href))["adapter"];
|
|
38
|
+
const adapter = isAdapter(loaded) && loaded.id === id ? loaded : void 0;
|
|
39
|
+
cache.set(id, adapter);
|
|
40
|
+
return adapter;
|
|
41
|
+
} };
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
//#region src/node/config-file.ts
|
|
45
|
+
/** Writes a file atomically: a temporary file next to it, renamed over it. */
|
|
46
|
+
async function writeAtomic(path, text, mode) {
|
|
47
|
+
const temporary = join(dirname(path), `.${basename(path)}.${process.pid}.tmp`);
|
|
48
|
+
await writeFile(temporary, text, mode === void 0 ? {} : { mode });
|
|
49
|
+
await rename(temporary, path);
|
|
50
|
+
}
|
|
51
|
+
async function writable$1(path) {
|
|
52
|
+
try {
|
|
53
|
+
await access(path, constants.W_OK);
|
|
54
|
+
return true;
|
|
55
|
+
} catch {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function json(document) {
|
|
60
|
+
return `${JSON.stringify(document, void 0, 2)}\n`;
|
|
61
|
+
}
|
|
62
|
+
/** One config file: `briefkasten.config.json` (written back) or `.ts`/`.mjs` (read only). */
|
|
63
|
+
function configFile(path) {
|
|
64
|
+
const module = !path.endsWith(".json");
|
|
65
|
+
return {
|
|
66
|
+
where: path,
|
|
67
|
+
async read() {
|
|
68
|
+
const loaded = await loadConfigFile(path);
|
|
69
|
+
return {
|
|
70
|
+
document: loaded.document,
|
|
71
|
+
adapters: loaded.adapters
|
|
72
|
+
};
|
|
73
|
+
},
|
|
74
|
+
async readOnly() {
|
|
75
|
+
if (module) return `${path} is a TypeScript config, which only a person edits: change it there (or keep the instance in a briefkasten.config.json)`;
|
|
76
|
+
return await writable$1(path) && await writable$1(dirname(path)) ? void 0 : `${path} is read-only`;
|
|
77
|
+
},
|
|
78
|
+
write: (document) => writeAtomic(path, json(document))
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
const SETTINGS_FILE = "briefkasten.json";
|
|
82
|
+
const PROJECTS_DIR = "projects";
|
|
83
|
+
const TOKENS_FILE = "tokens.json";
|
|
84
|
+
async function readJson(path) {
|
|
85
|
+
try {
|
|
86
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
87
|
+
} catch (error) {
|
|
88
|
+
throw new ConfigError(`${path}: ${messageOf(error)}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
async function exists(path) {
|
|
92
|
+
return await stat(path).catch(() => void 0) !== void 0;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* A config directory: `briefkasten.json` holds the settings, `projects/<name>.json` each
|
|
96
|
+
* project's sources and routes, `tokens.json` the tokens. Easy to keep in git and to diff, and a
|
|
97
|
+
* change rewrites only the files it touched.
|
|
98
|
+
*/
|
|
99
|
+
function configDirectory(dir) {
|
|
100
|
+
const settingsPath = join(dir, SETTINGS_FILE);
|
|
101
|
+
const projectsDir = join(dir, PROJECTS_DIR);
|
|
102
|
+
const tokensPath = join(dir, TOKENS_FILE);
|
|
103
|
+
return {
|
|
104
|
+
where: dir,
|
|
105
|
+
async read() {
|
|
106
|
+
const settings = await readJson(settingsPath);
|
|
107
|
+
const projects = {};
|
|
108
|
+
const names = await exists(projectsDir) ? await readdir(projectsDir) : [];
|
|
109
|
+
for (const file of names.filter((name) => name.endsWith(".json")).toSorted()) projects[file.slice(0, -5)] = await readJson(join(projectsDir, file));
|
|
110
|
+
const tokens = await exists(tokensPath) ? { tokens: await readJson(tokensPath) } : {};
|
|
111
|
+
return {
|
|
112
|
+
document: parseDocument({
|
|
113
|
+
...typeof settings === "object" && settings !== null ? settings : {},
|
|
114
|
+
projects,
|
|
115
|
+
...tokens
|
|
116
|
+
}, dir),
|
|
117
|
+
adapters: []
|
|
118
|
+
};
|
|
119
|
+
},
|
|
120
|
+
async readOnly() {
|
|
121
|
+
return await writable$1(dir) ? void 0 : `${dir} is read-only`;
|
|
122
|
+
},
|
|
123
|
+
async write(document) {
|
|
124
|
+
const { projects = {}, tokens, ...settings } = document;
|
|
125
|
+
await writeAtomic(settingsPath, json(settings));
|
|
126
|
+
await mkdir(projectsDir, { recursive: true });
|
|
127
|
+
const kept = new Set(Object.keys(projects).map((name) => `${name}.json`));
|
|
128
|
+
for (const [name, project] of Object.entries(projects)) await writeAtomic(join(projectsDir, `${name}.json`), `${JSON.stringify(project, void 0, 2)}\n`);
|
|
129
|
+
for (const file of await readdir(projectsDir)) if (file.endsWith(".json") && !kept.has(file)) await rm(join(projectsDir, file));
|
|
130
|
+
if (tokens === void 0) await rm(tokensPath, { force: true });
|
|
131
|
+
else await writeAtomic(tokensPath, `${JSON.stringify(tokens, void 0, 2)}\n`);
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/** Reads `$env` references from the environment and `$secret` ones from the secret store. */
|
|
136
|
+
function secretResolver(secrets, env) {
|
|
137
|
+
return async (value, where) => {
|
|
138
|
+
if (typeof value === "string") return value;
|
|
139
|
+
if ("$env" in value) {
|
|
140
|
+
const found = env[value.$env];
|
|
141
|
+
if (found === void 0 || found === "") throw new ConfigError(`${where}: the environment variable ${value.$env} is not set`);
|
|
142
|
+
return found;
|
|
143
|
+
}
|
|
144
|
+
const found = await secrets.get(value.$secret);
|
|
145
|
+
if (found === void 0) throw new ConfigError(`${where}: no secret ${value.$secret} in the secret store`);
|
|
146
|
+
return found;
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
/** Where a source's secret is kept in the secret store. */
|
|
150
|
+
function secretKey(project, source) {
|
|
151
|
+
return `${project}/${source}`;
|
|
152
|
+
}
|
|
153
|
+
function documentConfigSource(options) {
|
|
154
|
+
const { store, secrets } = options;
|
|
155
|
+
const resolve = secretResolver(secrets, options.env ?? process.env);
|
|
156
|
+
async function load() {
|
|
157
|
+
const { document } = await store.read();
|
|
158
|
+
const settings = await settingsOf(document, resolve);
|
|
159
|
+
return {
|
|
160
|
+
settings,
|
|
161
|
+
tenants: settings.mode === "multi" ? [] : [await fileTenantOf(document, settings, resolve)]
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
async function apply(_tenant, mutation) {
|
|
165
|
+
const reason = await store.readOnly();
|
|
166
|
+
if (reason !== void 0) throw new BriefkastenError("read_only", reason);
|
|
167
|
+
const { document } = await store.read();
|
|
168
|
+
if ((mutation.kind === "source.create" || mutation.kind === "source.update") && mutation.secret !== void 0) await secrets.put(secretKey(mutation.project, mutation.source), mutation.secret);
|
|
169
|
+
const shape = applyMutation(shapeOf(document), mutation, {
|
|
170
|
+
secret: (_value, project, source) => ({ $secret: secretKey(project, source) }),
|
|
171
|
+
token: (token) => ({ ...token })
|
|
172
|
+
});
|
|
173
|
+
await store.write(withShape(document, shape));
|
|
174
|
+
if (mutation.kind === "source.delete") await secrets.delete(secretKey(mutation.project, mutation.source));
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
load,
|
|
178
|
+
readOnly: () => store.readOnly(),
|
|
179
|
+
apply,
|
|
180
|
+
adapters: async () => (await store.read()).adapters,
|
|
181
|
+
settings: async () => (await load()).settings
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
//#endregion
|
|
185
|
+
//#region src/node/secrets.ts
|
|
186
|
+
/**
|
|
187
|
+
* Where secrets are kept on Node: the environment (read-only), or a JSON file only its owner
|
|
188
|
+
* can read, which the management API writes when it creates a source or rotates its secret.
|
|
189
|
+
*/
|
|
190
|
+
const FILE_MODE = 384;
|
|
191
|
+
/** The environment cannot be written: a put or a delete is refused. */
|
|
192
|
+
function refuse() {
|
|
193
|
+
return Promise.reject(new BriefkastenError("read_only", "secrets come from the environment here, and the environment cannot be written: give a secrets file (secrets: { file }) to keep new ones"));
|
|
194
|
+
}
|
|
195
|
+
/** The environment's variables as secrets: `{ "$env": "NAME" }` reads one. */
|
|
196
|
+
function envSecrets(env = process.env) {
|
|
197
|
+
return {
|
|
198
|
+
get: (key) => {
|
|
199
|
+
const value = env[key];
|
|
200
|
+
return Promise.resolve(value === void 0 || value === "" ? void 0 : value);
|
|
201
|
+
},
|
|
202
|
+
put: refuse,
|
|
203
|
+
delete: refuse
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
const SecretsFile = z.record(z.string(), z.string());
|
|
207
|
+
function missing(error) {
|
|
208
|
+
return recordOf(error)["code"] === "ENOENT";
|
|
209
|
+
}
|
|
210
|
+
async function writable(path) {
|
|
211
|
+
try {
|
|
212
|
+
await access(path, constants.W_OK);
|
|
213
|
+
return true;
|
|
214
|
+
} catch {
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
/** A JSON file `{ key: value }`, mode 600, written atomically (a temporary file, then a rename). */
|
|
219
|
+
function fileSecrets(path) {
|
|
220
|
+
async function read() {
|
|
221
|
+
let text;
|
|
222
|
+
try {
|
|
223
|
+
text = await readFile(path, "utf8");
|
|
224
|
+
} catch (error) {
|
|
225
|
+
if (missing(error)) return {};
|
|
226
|
+
throw error;
|
|
227
|
+
}
|
|
228
|
+
return SecretsFile.parse(JSON.parse(text));
|
|
229
|
+
}
|
|
230
|
+
async function write(values) {
|
|
231
|
+
const dir = dirname(path);
|
|
232
|
+
if (!await writable(await access(path).then(() => true, () => false) ? path : dir)) throw new BriefkastenError("read_only", `the secrets file ${path} (or its directory) is not writable: make it writable by the gateway's user`);
|
|
233
|
+
const temporary = join(dir, `.${basename(path)}.${process.pid}.tmp`);
|
|
234
|
+
await writeFile(temporary, `${JSON.stringify(values, void 0, 2)}\n`, { mode: FILE_MODE });
|
|
235
|
+
await chmod(temporary, FILE_MODE);
|
|
236
|
+
await rename(temporary, path);
|
|
237
|
+
}
|
|
238
|
+
return {
|
|
239
|
+
get: async (key) => (await read())[key],
|
|
240
|
+
put: async (key, value) => {
|
|
241
|
+
await write({
|
|
242
|
+
...await read(),
|
|
243
|
+
[key]: value
|
|
244
|
+
});
|
|
245
|
+
},
|
|
246
|
+
delete: async (key) => {
|
|
247
|
+
const values = await read();
|
|
248
|
+
if (key in values) await write(Object.fromEntries(Object.entries(values).filter(([each]) => each !== key)));
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
//#endregion
|
|
253
|
+
//#region src/node/serve.ts
|
|
254
|
+
const TcpAddress = z.object({
|
|
255
|
+
port: z.number(),
|
|
256
|
+
address: z.string()
|
|
257
|
+
});
|
|
258
|
+
const BODILESS_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
|
|
259
|
+
const HTTP_INTERNAL_ERROR = 500;
|
|
260
|
+
/** A Node request as a fetch Request. */
|
|
261
|
+
function toRequest(message) {
|
|
262
|
+
const headers = new Headers();
|
|
263
|
+
for (const [name, value] of Object.entries(message.headers)) if (typeof value === "string") headers.set(name, value);
|
|
264
|
+
else if (Array.isArray(value)) headers.set(name, value.join(", "));
|
|
265
|
+
const method = message.method ?? "GET";
|
|
266
|
+
const init = {
|
|
267
|
+
method,
|
|
268
|
+
headers,
|
|
269
|
+
duplex: "half"
|
|
270
|
+
};
|
|
271
|
+
if (!BODILESS_METHODS.has(method)) init.body = Readable.toWeb(message);
|
|
272
|
+
return new Request(`http://localhost${message.url ?? "/"}`, init);
|
|
273
|
+
}
|
|
274
|
+
async function writeResponse(response, message) {
|
|
275
|
+
const headers = {};
|
|
276
|
+
response.headers.forEach((value, name) => {
|
|
277
|
+
headers[name] = value;
|
|
278
|
+
});
|
|
279
|
+
message.writeHead(response.status, headers);
|
|
280
|
+
if (response.body === null) {
|
|
281
|
+
message.end();
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
message.flushHeaders();
|
|
285
|
+
const reader = response.body.getReader();
|
|
286
|
+
try {
|
|
287
|
+
while (!message.destroyed) {
|
|
288
|
+
const { done, value } = await reader.read();
|
|
289
|
+
if (done) break;
|
|
290
|
+
message.write(value);
|
|
291
|
+
}
|
|
292
|
+
} catch {} finally {
|
|
293
|
+
message.end();
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Serves a fetch-style handler over node:http. Returns the bound port
|
|
298
|
+
* (pass 0 for an ephemeral port), the bound address, and a close function.
|
|
299
|
+
*/
|
|
300
|
+
async function serveNode(handler, options) {
|
|
301
|
+
const server = createServer((message, response) => {
|
|
302
|
+
handler(toRequest(message)).then((result) => writeResponse(result, response), (error) => {
|
|
303
|
+
response.writeHead(HTTP_INTERNAL_ERROR);
|
|
304
|
+
response.end(messageOf(error));
|
|
305
|
+
});
|
|
306
|
+
});
|
|
307
|
+
server.on("upgrade", (message, socket, head) => {
|
|
308
|
+
if (options.upgrade === void 0) {
|
|
309
|
+
socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n");
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
options.upgrade(message, socket, head);
|
|
313
|
+
});
|
|
314
|
+
await new Promise((resolve, reject) => {
|
|
315
|
+
server.once("error", reject);
|
|
316
|
+
const listening = () => {
|
|
317
|
+
server.off("error", reject);
|
|
318
|
+
resolve();
|
|
319
|
+
};
|
|
320
|
+
if (options.hostname === void 0) server.listen(options.port, listening);
|
|
321
|
+
else server.listen(options.port, options.hostname, listening);
|
|
322
|
+
});
|
|
323
|
+
const bound = TcpAddress.parse(server.address());
|
|
324
|
+
return {
|
|
325
|
+
port: bound.port,
|
|
326
|
+
host: bound.address,
|
|
327
|
+
close: async () => {
|
|
328
|
+
await new Promise((resolve, reject) => {
|
|
329
|
+
server.closeAllConnections();
|
|
330
|
+
server.close((error) => {
|
|
331
|
+
if (error === void 0) {
|
|
332
|
+
resolve();
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
reject(error);
|
|
336
|
+
});
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
//#endregion
|
|
342
|
+
//#region src/node/smtp.ts
|
|
343
|
+
function opened(socket, event) {
|
|
344
|
+
return new Promise((resolve, reject) => {
|
|
345
|
+
socket.once(event, () => {
|
|
346
|
+
socket.off("error", reject);
|
|
347
|
+
resolve(socket);
|
|
348
|
+
});
|
|
349
|
+
socket.once("error", reject);
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
/** The default connection: TLS or a plain socket. */
|
|
353
|
+
function connectSmtp(endpoint) {
|
|
354
|
+
return endpoint.secure ? opened(connect$1({
|
|
355
|
+
host: endpoint.host,
|
|
356
|
+
port: endpoint.port,
|
|
357
|
+
servername: endpoint.host
|
|
358
|
+
}), "secureConnect") : opened(connect({
|
|
359
|
+
host: endpoint.host,
|
|
360
|
+
port: endpoint.port
|
|
361
|
+
}), "connect");
|
|
362
|
+
}
|
|
363
|
+
/** The default STARTTLS upgrade. */
|
|
364
|
+
function upgradeSmtp(socket, host) {
|
|
365
|
+
return opened(connect$1({
|
|
366
|
+
socket,
|
|
367
|
+
servername: host
|
|
368
|
+
}), "secureConnect");
|
|
369
|
+
}
|
|
370
|
+
const REPLY_END = /^(\d{3}) /;
|
|
371
|
+
/** Reads SMTP replies (one or several lines each) from a socket. */
|
|
372
|
+
var Replies = class {
|
|
373
|
+
socket;
|
|
374
|
+
buffer = "";
|
|
375
|
+
lines = [];
|
|
376
|
+
pending;
|
|
377
|
+
failure;
|
|
378
|
+
ready = [];
|
|
379
|
+
constructor(socket) {
|
|
380
|
+
this.socket = socket;
|
|
381
|
+
socket.on("data", this.data);
|
|
382
|
+
socket.on("error", this.fail);
|
|
383
|
+
socket.on("close", this.closed);
|
|
384
|
+
}
|
|
385
|
+
data = (chunk) => {
|
|
386
|
+
this.buffer += chunk.toString("utf8");
|
|
387
|
+
let end = this.buffer.indexOf("\r\n");
|
|
388
|
+
while (end !== -1) {
|
|
389
|
+
const line = this.buffer.slice(0, end);
|
|
390
|
+
this.buffer = this.buffer.slice(end + 2);
|
|
391
|
+
this.lines.push(line);
|
|
392
|
+
const match = REPLY_END.exec(line);
|
|
393
|
+
if (match !== null) {
|
|
394
|
+
this.ready.push({
|
|
395
|
+
code: Number(match[1]),
|
|
396
|
+
lines: this.lines
|
|
397
|
+
});
|
|
398
|
+
this.lines = [];
|
|
399
|
+
}
|
|
400
|
+
end = this.buffer.indexOf("\r\n");
|
|
401
|
+
}
|
|
402
|
+
this.deliver();
|
|
403
|
+
};
|
|
404
|
+
fail = (error) => {
|
|
405
|
+
this.failure ??= error;
|
|
406
|
+
this.deliver();
|
|
407
|
+
};
|
|
408
|
+
closed = () => {
|
|
409
|
+
this.fail(/* @__PURE__ */ new Error("smtp: the server closed the connection"));
|
|
410
|
+
};
|
|
411
|
+
deliver() {
|
|
412
|
+
const pending = this.pending;
|
|
413
|
+
if (pending === void 0) return;
|
|
414
|
+
const next = this.ready.shift();
|
|
415
|
+
if (next !== void 0) pending.resolve(next);
|
|
416
|
+
else if (this.failure !== void 0) pending.reject(this.failure);
|
|
417
|
+
else return;
|
|
418
|
+
this.pending = void 0;
|
|
419
|
+
}
|
|
420
|
+
next() {
|
|
421
|
+
return new Promise((resolve, reject) => {
|
|
422
|
+
this.pending = {
|
|
423
|
+
resolve,
|
|
424
|
+
reject
|
|
425
|
+
};
|
|
426
|
+
this.deliver();
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
detach() {
|
|
430
|
+
this.socket.off("data", this.data);
|
|
431
|
+
this.socket.off("error", this.fail);
|
|
432
|
+
this.socket.off("close", this.closed);
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
/** The bare address of `Name <address>`. */
|
|
436
|
+
function addressOf(mailbox) {
|
|
437
|
+
return /<([^>]+)>/.exec(mailbox)?.[1] ?? mailbox.trim();
|
|
438
|
+
}
|
|
439
|
+
function header(value) {
|
|
440
|
+
return /^[\x20-\x7e]*$/.test(value) ? value : `=?UTF-8?B?${Buffer.from(value, "utf8").toString("base64")}?=`;
|
|
441
|
+
}
|
|
442
|
+
/** The message as DATA carries it: headers, a blank line, the dot-stuffed body. */
|
|
443
|
+
function renderMessage(input) {
|
|
444
|
+
const body = input.text.replaceAll("\r\n", "\n").split("\n").map((line) => line.startsWith(".") ? `.${line}` : line).join("\r\n");
|
|
445
|
+
return [
|
|
446
|
+
`From: ${header(input.from)}`,
|
|
447
|
+
`To: ${input.to}`,
|
|
448
|
+
`Subject: ${header(input.subject)}`,
|
|
449
|
+
`Date: ${input.date.toUTCString()}`,
|
|
450
|
+
`Message-ID: <${input.id}>`,
|
|
451
|
+
"MIME-Version: 1.0",
|
|
452
|
+
"Content-Type: text/plain; charset=utf-8",
|
|
453
|
+
"Content-Transfer-Encoding: 8bit",
|
|
454
|
+
"",
|
|
455
|
+
body
|
|
456
|
+
].join("\r\n");
|
|
457
|
+
}
|
|
458
|
+
function smtpMailer(options) {
|
|
459
|
+
const connect = options.connect ?? connectSmtp;
|
|
460
|
+
const upgrade = options.upgrade ?? upgradeSmtp;
|
|
461
|
+
const name = options.name ?? "briefkasten";
|
|
462
|
+
return {
|
|
463
|
+
name: "smtp",
|
|
464
|
+
async send(message) {
|
|
465
|
+
let socket = await connect(options);
|
|
466
|
+
let replies = new Replies(socket);
|
|
467
|
+
const expect = async (codes, what) => {
|
|
468
|
+
const reply = await replies.next();
|
|
469
|
+
if (!codes.includes(reply.code)) throw new Error(`smtp: ${what} refused: ${reply.lines.join(" ")}`);
|
|
470
|
+
return reply;
|
|
471
|
+
};
|
|
472
|
+
const command = (line, codes, what) => {
|
|
473
|
+
socket.write(`${line}\r\n`);
|
|
474
|
+
return expect(codes, what);
|
|
475
|
+
};
|
|
476
|
+
try {
|
|
477
|
+
await expect([220], "greeting");
|
|
478
|
+
const hello = await command(`EHLO ${name}`, [250], "EHLO");
|
|
479
|
+
if (!options.secure && hello.lines.some((line) => /^250[ -]STARTTLS/i.test(line))) {
|
|
480
|
+
await command("STARTTLS", [220], "STARTTLS");
|
|
481
|
+
replies.detach();
|
|
482
|
+
socket = await upgrade(socket, options.host);
|
|
483
|
+
replies = new Replies(socket);
|
|
484
|
+
await command(`EHLO ${name}`, [250], "EHLO");
|
|
485
|
+
}
|
|
486
|
+
if (options.user !== void 0) await command(`AUTH PLAIN ${Buffer.from(`\0${options.user}\0${options.password ?? ""}`, "utf8").toString("base64")}`, [235], "AUTH");
|
|
487
|
+
const from = message.from ?? options.from;
|
|
488
|
+
const id = `${randomUUID()}@${addressOf(from).split("@")[1] ?? name}`;
|
|
489
|
+
await command(`MAIL FROM:<${addressOf(from)}>`, [250], "MAIL FROM");
|
|
490
|
+
await command(`RCPT TO:<${addressOf(message.to)}>`, [250, 251], "RCPT TO");
|
|
491
|
+
await command("DATA", [354], "DATA");
|
|
492
|
+
await command(`${renderMessage({
|
|
493
|
+
...message,
|
|
494
|
+
from,
|
|
495
|
+
id,
|
|
496
|
+
date: /* @__PURE__ */ new Date()
|
|
497
|
+
})}\r\n.`, [250], "the message");
|
|
498
|
+
await command("QUIT", [221], "QUIT");
|
|
499
|
+
return { id };
|
|
500
|
+
} finally {
|
|
501
|
+
replies.detach();
|
|
502
|
+
socket.destroy();
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
//#endregion
|
|
508
|
+
//#region src/node/sqlite.ts
|
|
509
|
+
/** A `node:sqlite` database as the SQL stores' driver. */
|
|
510
|
+
function nodeSqlDriver(db) {
|
|
511
|
+
return {
|
|
512
|
+
script: (sql) => {
|
|
513
|
+
db.exec(sql);
|
|
514
|
+
},
|
|
515
|
+
all: (sql, ...values) => db.prepare(sql).all(...values),
|
|
516
|
+
run: (sql, ...values) => Number(db.prepare(sql).run(...values).changes)
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
function sqliteStores(path, options = {}) {
|
|
520
|
+
const db = new DatabaseSync(path);
|
|
521
|
+
db.exec("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL;");
|
|
522
|
+
return {
|
|
523
|
+
...sqlStores(nodeSqlDriver(db), options),
|
|
524
|
+
close: () => {
|
|
525
|
+
db.close();
|
|
526
|
+
}
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
//#endregion
|
|
530
|
+
//#region src/node/websocket.ts
|
|
531
|
+
/**
|
|
532
|
+
* The server side of a WebSocket (RFC 6455) on a Node `upgrade` event, as much as the event
|
|
533
|
+
* stream needs: text messages out, text messages in (the `ping` keep-alive), the control frames,
|
|
534
|
+
* and the close handshake. Binary messages are ignored; a frame or message over 1 MiB closes
|
|
535
|
+
* the connection (1009).
|
|
536
|
+
*/
|
|
537
|
+
const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
538
|
+
const OP_CONTINUATION = 0;
|
|
539
|
+
const OP_TEXT = 1;
|
|
540
|
+
const OP_BINARY = 2;
|
|
541
|
+
const OP_CLOSE = 8;
|
|
542
|
+
const OP_PING = 9;
|
|
543
|
+
const OP_PONG = 10;
|
|
544
|
+
const FIN = 128;
|
|
545
|
+
const MASKED = 128;
|
|
546
|
+
const LENGTH_16 = 126;
|
|
547
|
+
const LENGTH_64 = 127;
|
|
548
|
+
const MASK_BYTES = 4;
|
|
549
|
+
const CLOSE_NORMAL = 1e3;
|
|
550
|
+
const CLOSE_PROTOCOL_ERROR = 1002;
|
|
551
|
+
const CLOSE_TOO_BIG = 1009;
|
|
552
|
+
/** The `Sec-WebSocket-Accept` value for a client's key. */
|
|
553
|
+
function acceptKey(key) {
|
|
554
|
+
return createHash("sha1").update(`${key}${GUID}`).digest("base64");
|
|
555
|
+
}
|
|
556
|
+
/** Answers an upgrade request with a plain HTTP refusal and drops the connection. */
|
|
557
|
+
function rejectUpgrade(socket, status, message) {
|
|
558
|
+
const body = JSON.stringify({ error: {
|
|
559
|
+
code: status === 401 ? "unauthorized" : "bad_request",
|
|
560
|
+
message
|
|
561
|
+
} });
|
|
562
|
+
const reason = status === 401 ? "Unauthorized" : "Refused";
|
|
563
|
+
socket.end(`HTTP/1.1 ${status} ${reason}\r\ncontent-type: application/json\r\ncontent-length: ${Buffer.byteLength(body)}\r\nconnection: close\r\n\r\n${body}`);
|
|
564
|
+
}
|
|
565
|
+
/** One unmasked frame, as a server sends it. */
|
|
566
|
+
function encodeFrame(opcode, payload) {
|
|
567
|
+
const length = payload.length;
|
|
568
|
+
let head;
|
|
569
|
+
if (length < LENGTH_16) head = Buffer.from([FIN | opcode, length]);
|
|
570
|
+
else if (length < 65536) {
|
|
571
|
+
head = Buffer.alloc(4);
|
|
572
|
+
head.writeUInt8(FIN | opcode, 0);
|
|
573
|
+
head.writeUInt8(LENGTH_16, 1);
|
|
574
|
+
head.writeUInt16BE(length, 2);
|
|
575
|
+
} else {
|
|
576
|
+
head = Buffer.alloc(10);
|
|
577
|
+
head.writeUInt8(FIN | opcode, 0);
|
|
578
|
+
head.writeUInt8(LENGTH_64, 1);
|
|
579
|
+
head.writeBigUInt64BE(BigInt(length), 2);
|
|
580
|
+
}
|
|
581
|
+
return Buffer.concat([head, payload]);
|
|
582
|
+
}
|
|
583
|
+
function closePayload(code, reason) {
|
|
584
|
+
const payload = Buffer.alloc(2 + Buffer.byteLength(reason));
|
|
585
|
+
payload.writeUInt16BE(code, 0);
|
|
586
|
+
payload.write(reason, 2);
|
|
587
|
+
return payload;
|
|
588
|
+
}
|
|
589
|
+
/** Reads one client frame from the front of a buffer. */
|
|
590
|
+
function decodeFrame(buffer) {
|
|
591
|
+
if (buffer.length < 2) return "incomplete";
|
|
592
|
+
const first = buffer.readUInt8(0);
|
|
593
|
+
const second = buffer.readUInt8(1);
|
|
594
|
+
if ((second & MASKED) === 0) return { error: CLOSE_PROTOCOL_ERROR };
|
|
595
|
+
let length = second & 127;
|
|
596
|
+
let offset = 2;
|
|
597
|
+
if (length === LENGTH_16) {
|
|
598
|
+
if (buffer.length < 4) return "incomplete";
|
|
599
|
+
length = buffer.readUInt16BE(2);
|
|
600
|
+
offset = 4;
|
|
601
|
+
} else if (length === LENGTH_64) {
|
|
602
|
+
if (buffer.length < 10) return "incomplete";
|
|
603
|
+
const big = buffer.readBigUInt64BE(2);
|
|
604
|
+
if (big > BigInt(1048576)) return { error: CLOSE_TOO_BIG };
|
|
605
|
+
length = Number(big);
|
|
606
|
+
offset = 10;
|
|
607
|
+
}
|
|
608
|
+
if (buffer.length < offset + MASK_BYTES + length) return "incomplete";
|
|
609
|
+
const mask = buffer.subarray(offset, offset + MASK_BYTES);
|
|
610
|
+
const payload = Buffer.from(buffer.subarray(offset + MASK_BYTES, offset + MASK_BYTES + length));
|
|
611
|
+
for (let index = 0; index < payload.length; index++) payload.writeUInt8(payload.readUInt8(index) ^ mask.readUInt8(index % MASK_BYTES), index);
|
|
612
|
+
return {
|
|
613
|
+
fin: (first & FIN) !== 0,
|
|
614
|
+
opcode: first & 15,
|
|
615
|
+
payload,
|
|
616
|
+
size: offset + MASK_BYTES + length
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Completes the handshake of an upgrade request and answers its frames. Throws when the request
|
|
621
|
+
* is not a WebSocket handshake (no key, or a version other than 13): check before calling.
|
|
622
|
+
*/
|
|
623
|
+
function acceptWebSocket(request, socket, head, options = {}) {
|
|
624
|
+
const key = request.headers["sec-websocket-key"];
|
|
625
|
+
if (typeof key !== "string" || request.headers["sec-websocket-version"] !== "13") throw new Error("not a WebSocket handshake (Sec-WebSocket-Key, version 13)");
|
|
626
|
+
const protocol = options.protocol === void 0 ? "" : `Sec-WebSocket-Protocol: ${options.protocol}\r\n`;
|
|
627
|
+
socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${acceptKey(key)}\r\n${protocol}\r\n`);
|
|
628
|
+
const messages = [];
|
|
629
|
+
const closes = [];
|
|
630
|
+
let open = true;
|
|
631
|
+
let buffer = Buffer.from(head);
|
|
632
|
+
let fragments = [];
|
|
633
|
+
let fragmentType;
|
|
634
|
+
let fragmentBytes = 0;
|
|
635
|
+
const write = (opcode, payload) => {
|
|
636
|
+
socket.write(encodeFrame(opcode, payload));
|
|
637
|
+
};
|
|
638
|
+
const close = (code = CLOSE_NORMAL, reason = "") => {
|
|
639
|
+
if (!open) return;
|
|
640
|
+
open = false;
|
|
641
|
+
write(OP_CLOSE, closePayload(code, reason));
|
|
642
|
+
socket.end();
|
|
643
|
+
};
|
|
644
|
+
const message = (opcode, payload) => {
|
|
645
|
+
if (opcode === OP_TEXT) {
|
|
646
|
+
const text = payload.toString("utf8");
|
|
647
|
+
for (const listener of messages) listener(text);
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
const handle = (frame) => {
|
|
651
|
+
switch (frame.opcode) {
|
|
652
|
+
case OP_TEXT:
|
|
653
|
+
case OP_BINARY:
|
|
654
|
+
case OP_CONTINUATION:
|
|
655
|
+
if (frame.opcode !== OP_CONTINUATION === (fragmentType !== void 0)) {
|
|
656
|
+
close(CLOSE_PROTOCOL_ERROR, "unexpected frame");
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
659
|
+
fragmentType ??= frame.opcode;
|
|
660
|
+
fragments.push(frame.payload);
|
|
661
|
+
fragmentBytes += frame.payload.length;
|
|
662
|
+
if (fragmentBytes > 1048576) {
|
|
663
|
+
close(CLOSE_TOO_BIG, "message too big");
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
if (frame.fin) {
|
|
667
|
+
message(fragmentType, Buffer.concat(fragments));
|
|
668
|
+
fragments = [];
|
|
669
|
+
fragmentType = void 0;
|
|
670
|
+
fragmentBytes = 0;
|
|
671
|
+
}
|
|
672
|
+
return;
|
|
673
|
+
case OP_PING:
|
|
674
|
+
write(OP_PONG, frame.payload);
|
|
675
|
+
return;
|
|
676
|
+
case OP_PONG: return;
|
|
677
|
+
case OP_CLOSE: {
|
|
678
|
+
const code = frame.payload.length >= 2 ? frame.payload.readUInt16BE(0) : CLOSE_NORMAL;
|
|
679
|
+
close(code);
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
default: close(CLOSE_PROTOCOL_ERROR, "unknown opcode");
|
|
683
|
+
}
|
|
684
|
+
};
|
|
685
|
+
const data = (chunk) => {
|
|
686
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
687
|
+
for (;;) {
|
|
688
|
+
if (!open) return;
|
|
689
|
+
const parsed = decodeFrame(buffer);
|
|
690
|
+
if (parsed === "incomplete") return;
|
|
691
|
+
if ("error" in parsed) {
|
|
692
|
+
close(parsed.error, parsed.error === 1009 ? "frame too big" : "unmasked frame");
|
|
693
|
+
return;
|
|
694
|
+
}
|
|
695
|
+
buffer = buffer.subarray(parsed.size);
|
|
696
|
+
handle(parsed);
|
|
697
|
+
}
|
|
698
|
+
};
|
|
699
|
+
socket.on("data", data);
|
|
700
|
+
socket.on("error", () => {
|
|
701
|
+
socket.destroy();
|
|
702
|
+
});
|
|
703
|
+
socket.once("end", () => {
|
|
704
|
+
socket.destroy();
|
|
705
|
+
});
|
|
706
|
+
socket.once("close", () => {
|
|
707
|
+
open = false;
|
|
708
|
+
for (const listener of closes) listener();
|
|
709
|
+
});
|
|
710
|
+
if (head.length > 0) queueMicrotask(() => data(Buffer.alloc(0)));
|
|
711
|
+
return {
|
|
712
|
+
get open() {
|
|
713
|
+
return open;
|
|
714
|
+
},
|
|
715
|
+
send(text) {
|
|
716
|
+
if (open) write(OP_TEXT, Buffer.from(text, "utf8"));
|
|
717
|
+
},
|
|
718
|
+
close,
|
|
719
|
+
onMessage(listener) {
|
|
720
|
+
messages.push(listener);
|
|
721
|
+
},
|
|
722
|
+
onClose(listener) {
|
|
723
|
+
closes.push(listener);
|
|
724
|
+
}
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
//#endregion
|
|
728
|
+
//#region src/node/instance.ts
|
|
729
|
+
/**
|
|
730
|
+
* The Node runtime's composition: a config path in, a gateway with its ports out. The ports
|
|
731
|
+
* follow the config: the store (memory or SQLite), the mail adapter, the config source (the file
|
|
732
|
+
* itself, or in `multi` mode the store the control plane fills), and the secret store
|
|
733
|
+
* (`briefkasten.secrets.json` next to the config, mode 600).
|
|
734
|
+
*/
|
|
735
|
+
const SECRETS_FILE = "briefkasten.secrets.json";
|
|
736
|
+
/** Who acts through the CLI's local target: whoever can edit the config file. */
|
|
737
|
+
const LOCAL = {
|
|
738
|
+
kind: "admin",
|
|
739
|
+
name: "local"
|
|
740
|
+
};
|
|
741
|
+
/** The mail adapter the settings name. */
|
|
742
|
+
function mailerOf(mail, log) {
|
|
743
|
+
switch (mail?.kind) {
|
|
744
|
+
case void 0: return;
|
|
745
|
+
case "console": return consoleMailer({ log });
|
|
746
|
+
case "resend": return resendMailer({
|
|
747
|
+
apiKey: mail.apiKey,
|
|
748
|
+
from: mail.from
|
|
749
|
+
});
|
|
750
|
+
case "smtp": return smtpMailer(mail);
|
|
751
|
+
}
|
|
752
|
+
throw new ConfigError("mail kind cloudflare needs the Cloudflare runtime's send_email binding");
|
|
753
|
+
}
|
|
754
|
+
function storesOf(settings, base) {
|
|
755
|
+
if (settings.store.kind === "memory") {
|
|
756
|
+
const { events, kv } = memoryStores();
|
|
757
|
+
return {
|
|
758
|
+
store: events,
|
|
759
|
+
kv,
|
|
760
|
+
close: () => void 0
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
const stores = sqliteStores(isAbsolute(settings.store.path) ? settings.store.path : join(base, settings.store.path));
|
|
764
|
+
return {
|
|
765
|
+
store: stores.events,
|
|
766
|
+
kv: stores.kv,
|
|
767
|
+
close: () => {
|
|
768
|
+
stores.close();
|
|
769
|
+
}
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
async function captureTo(dir, source, body, headers) {
|
|
773
|
+
const stamp = (/* @__PURE__ */ new Date()).toISOString().replaceAll(":", "-");
|
|
774
|
+
const delivery = (headers.get("linear-delivery") ?? headers.get("x-github-delivery") ?? "unknown").slice(0, 64);
|
|
775
|
+
await mkdir(dir, { recursive: true });
|
|
776
|
+
await writeFile(join(dir, `${source}-${stamp}-${delivery}.json`), body, { mode: 384 });
|
|
777
|
+
}
|
|
778
|
+
async function openInstance(options) {
|
|
779
|
+
const log = options.log ?? ((line) => void process.stderr.write(`${line}\n`));
|
|
780
|
+
const env = options.env ?? process.env;
|
|
781
|
+
const path = configPath(options.configPath);
|
|
782
|
+
const directory = (await stat(path).catch(() => void 0))?.isDirectory() === true;
|
|
783
|
+
const base = directory ? path : dirname(path);
|
|
784
|
+
const secrets = fileSecrets(join(base, SECRETS_FILE));
|
|
785
|
+
const file = documentConfigSource({
|
|
786
|
+
store: directory ? configDirectory(path) : configFile(path),
|
|
787
|
+
secrets,
|
|
788
|
+
env
|
|
789
|
+
});
|
|
790
|
+
const settings = await file.settings();
|
|
791
|
+
const stores = storesOf(settings, base);
|
|
792
|
+
const plane = settings.controlPlane;
|
|
793
|
+
let config = file;
|
|
794
|
+
if (settings.mode === "multi") config = plane?.url === void 0 ? storeConfigSource({
|
|
795
|
+
settings: () => file.settings(),
|
|
796
|
+
kv: stores.kv
|
|
797
|
+
}) : pulledConfigSource({
|
|
798
|
+
settings: () => file.settings(),
|
|
799
|
+
kv: stores.kv,
|
|
800
|
+
url: plane.url,
|
|
801
|
+
...plane.token === void 0 ? {} : { token: plane.token },
|
|
802
|
+
log
|
|
803
|
+
});
|
|
804
|
+
const mailer = mailerOf(settings.mail, log);
|
|
805
|
+
const captureDir = options.captureDir ?? env["BRIEFKASTEN_CAPTURE_DIR"];
|
|
806
|
+
const gateway = await createGateway({
|
|
807
|
+
config,
|
|
808
|
+
store: stores.store,
|
|
809
|
+
kv: stores.kv,
|
|
810
|
+
adapters: nodeAdapterRegistry({
|
|
811
|
+
known: await file.adapters(),
|
|
812
|
+
from: [
|
|
813
|
+
base,
|
|
814
|
+
...options.adapterDirs ?? [],
|
|
815
|
+
import.meta.dirname
|
|
816
|
+
]
|
|
817
|
+
}),
|
|
818
|
+
...mailer === void 0 ? {} : { mailer },
|
|
819
|
+
log,
|
|
820
|
+
...captureDir === void 0 || captureDir === "" ? {} : { capture: (source, body, headers) => captureTo(captureDir, source, body, headers) }
|
|
821
|
+
});
|
|
822
|
+
return {
|
|
823
|
+
gateway,
|
|
824
|
+
settings,
|
|
825
|
+
config,
|
|
826
|
+
close: async () => {
|
|
827
|
+
await gateway.close();
|
|
828
|
+
stores.close();
|
|
829
|
+
}
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
/** Opens a config file as the CLI's local target. */
|
|
833
|
+
async function openLocal(path, adapterDirs = []) {
|
|
834
|
+
const instance = await openInstance({
|
|
835
|
+
configPath: path,
|
|
836
|
+
log: () => void 0,
|
|
837
|
+
adapterDirs
|
|
838
|
+
});
|
|
839
|
+
return {
|
|
840
|
+
caller: { call: (id, input) => instance.gateway.call(id, input, LOCAL) },
|
|
841
|
+
secret: async (project, source) => {
|
|
842
|
+
const [tenant] = (await instance.config.load()).tenants;
|
|
843
|
+
return tenant?.projects[project]?.sources[source]?.secret;
|
|
844
|
+
},
|
|
845
|
+
close: () => instance.close()
|
|
846
|
+
};
|
|
847
|
+
}
|
|
848
|
+
/** Takes a WebSocket upgrade to the stream: authorises it, then sends the session's items. */
|
|
849
|
+
function upgradeHandler(gateway, log) {
|
|
850
|
+
return (message, socket, head) => {
|
|
851
|
+
stream(gateway, log, message, socket, head);
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
/** One upgraded connection: its session's items as WebSocket messages, until either side ends. */
|
|
855
|
+
async function stream(gateway, log, message, socket, head) {
|
|
856
|
+
const opening = await gateway.openStream(toRequest(message));
|
|
857
|
+
if (opening.kind === "refused") {
|
|
858
|
+
rejectUpgrade(socket, opening.response.status, await opening.response.text());
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
const { session } = opening;
|
|
862
|
+
let peer;
|
|
863
|
+
try {
|
|
864
|
+
peer = acceptWebSocket(message, socket, head, opening.protocol === void 0 ? {} : { protocol: opening.protocol });
|
|
865
|
+
} catch (error) {
|
|
866
|
+
session.close();
|
|
867
|
+
rejectUpgrade(socket, 400, messageOf(error));
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
peer.onMessage((text) => {
|
|
871
|
+
if (text === WS_PING) peer.send(WS_PONG);
|
|
872
|
+
});
|
|
873
|
+
peer.onClose(() => {
|
|
874
|
+
session.close();
|
|
875
|
+
});
|
|
876
|
+
try {
|
|
877
|
+
for await (const item of session.items) peer.send(encodeWs(item));
|
|
878
|
+
} catch (error) {
|
|
879
|
+
log(`a WebSocket stream ended: ${messageOf(error)}`);
|
|
880
|
+
} finally {
|
|
881
|
+
session.close();
|
|
882
|
+
const ended = session.ended();
|
|
883
|
+
if (ended === void 0) peer.close();
|
|
884
|
+
else peer.close(WS_CLOSE[ended], `tenant ${ended}`);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
/** Runs an instance: the private listener (every route) and, when set, the public one (hooks). */
|
|
888
|
+
async function serveInstance(options) {
|
|
889
|
+
const log = options.log ?? ((line) => void process.stderr.write(`${line}\n`));
|
|
890
|
+
const instance = await openInstance({
|
|
891
|
+
...options,
|
|
892
|
+
log
|
|
893
|
+
});
|
|
894
|
+
const { gateway, settings } = instance;
|
|
895
|
+
await gateway.start();
|
|
896
|
+
const host = options.host ?? settings.server.host;
|
|
897
|
+
const main = await serveNode(gateway.fetch, {
|
|
898
|
+
port: options.port ?? settings.server.port,
|
|
899
|
+
...host === void 0 ? {} : { hostname: host },
|
|
900
|
+
upgrade: upgradeHandler(gateway, log)
|
|
901
|
+
});
|
|
902
|
+
const webhookPort = options.webhookPort ?? settings.server.webhooks?.port;
|
|
903
|
+
const webhookHost = options.webhookHost ?? settings.server.webhooks?.host;
|
|
904
|
+
let webhooks;
|
|
905
|
+
if (webhookPort !== void 0) try {
|
|
906
|
+
webhooks = await serveNode(gateway.publicFetch, {
|
|
907
|
+
port: webhookPort,
|
|
908
|
+
...webhookHost === void 0 ? {} : { hostname: webhookHost },
|
|
909
|
+
...settings.mode === "multi" ? { upgrade: upgradeHandler(gateway, log) } : {}
|
|
910
|
+
});
|
|
911
|
+
} catch (error) {
|
|
912
|
+
await main.close();
|
|
913
|
+
await instance.close();
|
|
914
|
+
throw error;
|
|
915
|
+
}
|
|
916
|
+
const opened = webhooks;
|
|
917
|
+
return {
|
|
918
|
+
main: {
|
|
919
|
+
port: main.port,
|
|
920
|
+
host: main.host
|
|
921
|
+
},
|
|
922
|
+
...opened === void 0 ? {} : { webhooks: {
|
|
923
|
+
port: opened.port,
|
|
924
|
+
host: opened.host
|
|
925
|
+
} },
|
|
926
|
+
hooks: gateway.hooks(),
|
|
927
|
+
close: async () => {
|
|
928
|
+
await opened?.close();
|
|
929
|
+
await main.close();
|
|
930
|
+
await instance.close();
|
|
931
|
+
}
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
//#endregion
|
|
935
|
+
export { LOCAL, SECRETS_FILE, acceptWebSocket, configDirectory, configFile, documentConfigSource, envSecrets, fileSecrets, mailerOf, nodeAdapterRegistry, openInstance, openLocal, rejectUpgrade, secretKey, secretResolver, serveInstance, serveNode, smtpMailer, sqliteStores, toRequest, upgradeHandler, writeAtomic };
|