@brickkit/core 0.14.0 → 0.16.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/client.d.ts +8 -3
- package/dist/chunks/client.js +54 -22
- package/dist/chunks/client.js.map +1 -1
- package/dist/chunks/server.d.ts +33 -14
- package/dist/chunks/server.js +2829 -651
- package/dist/chunks/server.js.map +1 -1
- package/dist/chunks/types.d.ts +1171 -298
- package/dist/client.d.ts +1 -1
- package/dist/client.js +1 -1
- package/dist/index.d.ts +233 -14
- package/dist/index.js +255 -252
- package/dist/index.js.map +1 -1
- package/dist/pg.d.ts +2 -3
- package/dist/pg.js +1 -1
- package/dist/tanstack-query.d.ts +1 -2
- package/dist/testing.d.ts +1 -2
- package/dist/testing.js +1 -1
- package/dist/workflow.d.ts +2 -3
- package/package.json +11 -11
package/dist/chunks/server.js
CHANGED
|
@@ -1,18 +1,21 @@
|
|
|
1
|
-
import { A as
|
|
1
|
+
import { A as STANDARD_ERRORS, B as signSeq, C as actionMeta, D as SOCKET_MAX_BYTES, E as SOCKET_CONTROL, F as isSocketEnvelope, G as ActionExecutionError, H as ATTR, I as isSocketRoom, K as DuplicateNameError, L as isSocketSeq, M as compareSocketSeq, N as encodeFrame, O as SOCKET_PROTOCOL, P as isControlEvent, R as replayFrame, S as kebabCase, T as SOCKET_CLOSE, U as GLOBAL_SYMBOL, V as splitSeq, W as SPAN, _ as ownerPath, b as routeKey, c as DEFAULT_PREFIX, d as checkSegments, f as getActionRoute, g as joinRoute, h as isReadLike, j as byteLength, k as SOCKET_TOKEN_PROTOCOL, l as actionMethod, m as inputSource, q as ValidationError, s as serializeSocketSchema, u as actionOwners, v as pathParamNames, w as SOCKET_BUFFER_BYTES, x as toOpenApiPath, y as pluginRoutePath, z as replayHeadroom } from "./client.js";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
|
+
import { format, formatWithOptions, inspect } from "node:util";
|
|
3
5
|
import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
|
|
4
|
-
import {
|
|
6
|
+
import { Kind, Type as Type$1, TypeRegistry } from "@sinclair/typebox";
|
|
5
7
|
import { TypeCompiler } from "@sinclair/typebox/compiler";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
9
|
+
import { isIPv4, isIPv6 } from "node:net";
|
|
10
|
+
import { lstat, mkdir, readFile, realpath, rm } from "node:fs/promises";
|
|
11
|
+
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
8
12
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
13
|
+
import { Value } from "@sinclair/typebox/value";
|
|
14
|
+
import { bigserial, index, integer, jsonb, pgTable, text, timestamp } from "drizzle-orm/pg-core";
|
|
15
|
+
import { index as index$1, integer as integer$1, sqliteTable, text as text$1 } from "drizzle-orm/sqlite-core";
|
|
9
16
|
import { and, asc, eq, inArray, isNull, lt, lte, or, sql } from "drizzle-orm";
|
|
10
|
-
import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
|
11
|
-
import { bigserial, index as index$1, integer as integer$1, jsonb, pgTable, text as text$1, timestamp } from "drizzle-orm/pg-core";
|
|
12
17
|
import { existsSync, readFileSync } from "node:fs";
|
|
13
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
14
18
|
import { Elysia } from "elysia";
|
|
15
|
-
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
16
19
|
import { websocket } from "elysia/websocket";
|
|
17
20
|
// src/plugin-types.ts
|
|
18
21
|
/** Where a plugin route mounts: under the app prefix, its service, or its resource. */
|
|
@@ -28,6 +31,419 @@ const PLUGIN_KIND = Symbol.for("brickkit.plugin.kind");
|
|
|
28
31
|
* once its install succeeds; a failed install drops it.
|
|
29
32
|
*/
|
|
30
33
|
const PLUGIN_COMMIT = Symbol.for("brickkit.plugin.commit");
|
|
34
|
+
// src/sensitive.ts
|
|
35
|
+
const SENSITIVE = Symbol.for("brickkit.sensitive");
|
|
36
|
+
/** The schema, unchanged in type and validation, marked sensitive. */
|
|
37
|
+
function Sensitive(schema) {
|
|
38
|
+
return {
|
|
39
|
+
...schema,
|
|
40
|
+
[SENSITIVE]: true
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
const isSensitive = (schema) => schema?.[SENSITIVE] === true;
|
|
44
|
+
const analyses = /* @__PURE__ */ new WeakMap();
|
|
45
|
+
function analyze(schema) {
|
|
46
|
+
if (!schema || typeof schema !== "object") return {
|
|
47
|
+
paths: [],
|
|
48
|
+
publics: []
|
|
49
|
+
};
|
|
50
|
+
let analysis = analyses.get(schema);
|
|
51
|
+
if (!analysis) {
|
|
52
|
+
const walk = {
|
|
53
|
+
paths: [],
|
|
54
|
+
publics: [],
|
|
55
|
+
markedIds: /* @__PURE__ */ new Set(),
|
|
56
|
+
loops: /* @__PURE__ */ new Map()
|
|
57
|
+
};
|
|
58
|
+
collect(schema, [], false, [], walk);
|
|
59
|
+
analysis = {
|
|
60
|
+
paths: walk.paths,
|
|
61
|
+
publics: walk.publics,
|
|
62
|
+
hidden: walk.hidden
|
|
63
|
+
};
|
|
64
|
+
if (walk.paths.length || walk.hidden) analysis.ref = walk.external ?? [...walk.markedIds].map((id) => walk.loops.get(id)).find(Boolean);
|
|
65
|
+
analyses.set(schema, analysis);
|
|
66
|
+
}
|
|
67
|
+
return analysis;
|
|
68
|
+
}
|
|
69
|
+
function sensitivePaths(schema) {
|
|
70
|
+
return analyze(schema).paths;
|
|
71
|
+
}
|
|
72
|
+
const holdsMark = (node, seen = /* @__PURE__ */ new Set()) => {
|
|
73
|
+
if (!node || typeof node !== "object" || seen.has(node)) return false;
|
|
74
|
+
seen.add(node);
|
|
75
|
+
return isSensitive(node) || Object.values(node).some((child) => holdsMark(child, seen));
|
|
76
|
+
};
|
|
77
|
+
function collect(schema, segments, optional, ids, walk) {
|
|
78
|
+
if (!schema || typeof schema !== "object") return;
|
|
79
|
+
if (isSensitive(schema)) {
|
|
80
|
+
walk.paths.push({
|
|
81
|
+
segments,
|
|
82
|
+
optional
|
|
83
|
+
});
|
|
84
|
+
for (const id of ids) walk.markedIds.add(id);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (typeof schema.$ref === "string") {
|
|
88
|
+
if (!ids.includes(schema.$ref)) walk.external ??= pointer(segments);
|
|
89
|
+
else if (!walk.loops.has(schema.$ref)) walk.loops.set(schema.$ref, pointer(segments));
|
|
90
|
+
}
|
|
91
|
+
if (typeof schema.$id === "string") ids = [...ids, schema.$id];
|
|
92
|
+
const list = schema.type === "array" && !Array.isArray(schema.items);
|
|
93
|
+
for (const key of Object.keys(schema)) if (!WALKED.has(key) || key === "items" && !list && !Array.isArray(schema.items)) {
|
|
94
|
+
if (holdsMark(schema[key])) walk.hidden ??= pointer([...segments, key]);
|
|
95
|
+
}
|
|
96
|
+
const branchesSharingOnePath = [
|
|
97
|
+
...schema.anyOf ?? [],
|
|
98
|
+
...schema.allOf ?? [],
|
|
99
|
+
...schema.oneOf ?? []
|
|
100
|
+
];
|
|
101
|
+
for (const branch of branchesSharingOnePath) collect(branch, segments, optional, ids, walk);
|
|
102
|
+
const declared = Object.keys(schema.properties ?? {});
|
|
103
|
+
const required = new Set(schema.required ?? []);
|
|
104
|
+
const removable = !(schema.minProperties > declared.filter((key) => required.has(key) && !isSensitive(schema.properties[key])).length);
|
|
105
|
+
for (const key of declared) {
|
|
106
|
+
const child = schema.properties[key];
|
|
107
|
+
if (!isSensitive(child)) walk.publics.push({
|
|
108
|
+
segments: [...segments, key],
|
|
109
|
+
required: required.has(key)
|
|
110
|
+
});
|
|
111
|
+
collect(child, [...segments, key], removable && !required.has(key), ids, walk);
|
|
112
|
+
}
|
|
113
|
+
for (const child of Object.values(schema.patternProperties ?? {})) collect(child, [...segments, null], removable, ids, walk);
|
|
114
|
+
if (schema.additionalProperties && typeof schema.additionalProperties === "object") collect(schema.additionalProperties, [...segments, declared.length ? { except: declared } : null], removable, ids, walk);
|
|
115
|
+
const before = walk.paths.length;
|
|
116
|
+
const items = Array.isArray(schema.items) ? schema.items.map((child, index) => [child, String(index)]) : list ? [[schema.items, null]] : [];
|
|
117
|
+
for (const [child, segment] of items) {
|
|
118
|
+
if (!isSensitive(child)) walk.publics.push({
|
|
119
|
+
segments: [...segments, segment],
|
|
120
|
+
required: true
|
|
121
|
+
});
|
|
122
|
+
collect(child, [...segments, segment], false, ids, walk);
|
|
123
|
+
}
|
|
124
|
+
if (schema.uniqueItems) for (const path of walk.paths.slice(before)) path.optional = false;
|
|
125
|
+
}
|
|
126
|
+
const WALKED = /* @__PURE__ */ new Set([
|
|
127
|
+
"anyOf",
|
|
128
|
+
"allOf",
|
|
129
|
+
"oneOf",
|
|
130
|
+
"properties",
|
|
131
|
+
"patternProperties",
|
|
132
|
+
"additionalProperties",
|
|
133
|
+
"items"
|
|
134
|
+
]);
|
|
135
|
+
const admits = (segment, key) => segment === null || (typeof segment === "string" ? segment === key : !segment.except.includes(key));
|
|
136
|
+
const overlap = (a, b) => typeof a === "string" ? admits(b, a) : typeof b === "string" ? admits(a, b) : true;
|
|
137
|
+
const marksKey = (schema, key) => sensitivePaths(schema).some(({ segments: [first] }) => first === void 0 || admits(first, key));
|
|
138
|
+
/** Whether any part of a schema is marked sensitive. */
|
|
139
|
+
function hasSensitive(schema) {
|
|
140
|
+
const { paths, hidden } = analyze(schema);
|
|
141
|
+
return paths.length > 0 || hidden !== void 0;
|
|
142
|
+
}
|
|
143
|
+
function writeOnly(schema) {
|
|
144
|
+
if (!hasSensitive(schema)) return schema;
|
|
145
|
+
const visit = (node) => {
|
|
146
|
+
if (Array.isArray(node)) return node.map(visit);
|
|
147
|
+
if (!node || typeof node !== "object") return node;
|
|
148
|
+
const copy = { ...node };
|
|
149
|
+
for (const key of Object.keys(copy)) copy[key] = visit(copy[key]);
|
|
150
|
+
if (isSensitive(node)) copy.writeOnly = true;
|
|
151
|
+
return copy;
|
|
152
|
+
};
|
|
153
|
+
return visit(schema);
|
|
154
|
+
}
|
|
155
|
+
const pointer = (segments) => segments.map((key) => `/${typeof key === "string" ? key : "*"}`).join("") || "/";
|
|
156
|
+
function sensitivePointer(schema) {
|
|
157
|
+
const { paths, hidden } = analyze(schema);
|
|
158
|
+
return paths[0] ? pointer(paths[0].segments) : hidden;
|
|
159
|
+
}
|
|
160
|
+
const escape = (key) => key.replaceAll("~", "~0").replaceAll("/", "~1");
|
|
161
|
+
const keysAt = (value, segment) => segment === null ? Object.keys(value) : typeof segment === "object" ? Object.keys(value).filter((key) => !segment.except.includes(key)) : Object.hasOwn(value, segment) ? [segment] : [];
|
|
162
|
+
function* found(value, segments, index = 0, at = "") {
|
|
163
|
+
if (value === null || typeof value !== "object") return;
|
|
164
|
+
for (const key of keysAt(value, segments[index])) {
|
|
165
|
+
const field = `${at}/${escape(key)}`;
|
|
166
|
+
if (index === segments.length - 1) yield [
|
|
167
|
+
value,
|
|
168
|
+
key,
|
|
169
|
+
field
|
|
170
|
+
];
|
|
171
|
+
else yield* found(value[key], segments, index + 1, field);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function omit(value, segments, hidden, index = 0, at = "") {
|
|
175
|
+
if (value === null || typeof value !== "object") return value;
|
|
176
|
+
let copy;
|
|
177
|
+
for (const key of keysAt(value, segments[index])) {
|
|
178
|
+
const field = `${at}/${escape(key)}`;
|
|
179
|
+
if (index === segments.length - 1) {
|
|
180
|
+
if (!hidden.has(field)) continue;
|
|
181
|
+
copy ??= Array.isArray(value) ? [...value] : { ...value };
|
|
182
|
+
delete copy[key];
|
|
183
|
+
} else {
|
|
184
|
+
const next = omit(value[key], segments, hidden, index + 1, field);
|
|
185
|
+
if (next === value[key]) continue;
|
|
186
|
+
copy ??= Array.isArray(value) ? [...value] : { ...value };
|
|
187
|
+
copy[key] = next;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return copy ?? value;
|
|
191
|
+
}
|
|
192
|
+
function sensitivity(config, service) {
|
|
193
|
+
const input = analyze(config.input);
|
|
194
|
+
const output = analyze(config.output);
|
|
195
|
+
const inputs = input.paths;
|
|
196
|
+
const outputs = output.paths;
|
|
197
|
+
if (!hasSensitive(config.input) && !hasSensitive(config.output)) return void 0;
|
|
198
|
+
const owner = service ? `Service '${service}' action '${config.name}'` : `Action '${config.name}'`;
|
|
199
|
+
for (const [kind, { ref, hidden }] of [["input", input], ["output", output]]) {
|
|
200
|
+
if (ref !== void 0) throw new Error(`${owner}: the ${kind} schema marks a field t.Sensitive and has a $ref at '${ref}' (t.Recursive, t.Module or t.Ref), which sensitive fields do not follow; move the secret out of the recursive or referenced schema`);
|
|
201
|
+
if (hidden !== void 0) throw new Error(`${owner}: the ${kind} schema marks a field t.Sensitive under '${hidden}', which sensitive fields do not follow; mark it in properties, items, records or union branches`);
|
|
202
|
+
}
|
|
203
|
+
const { reveal = false } = config;
|
|
204
|
+
if (reveal !== true) for (const path of outputs) {
|
|
205
|
+
const at = pointer(path.segments);
|
|
206
|
+
if (!path.optional) throw new Error(`${owner}: sensitive output field '${at}' is removed unless \`reveal\` allows it, so the schema must let it be absent: make it t.Optional in every union or intersect branch, not an array item, a record value or a property under minProperties, nor inside a uniqueItems array (or set \`reveal: true\`)`);
|
|
207
|
+
const exact = JSON.stringify(path.segments);
|
|
208
|
+
const hit = output.publics.find(({ segments, required }) => segments.length === path.segments.length && segments.every((segment, index) => overlap(segment, path.segments[index])) && (required || JSON.stringify(segments) !== exact));
|
|
209
|
+
if (hit) throw new Error(`${owner}: sensitive output field '${at}' is removed unless \`reveal\` allows it, and that path also matches the unmarked field '${pointer(hit.segments)}', which would be removed with it; give the secret a name of its own (or set \`reveal: true\`)`);
|
|
210
|
+
}
|
|
211
|
+
const values = (value, paths) => {
|
|
212
|
+
const all = [];
|
|
213
|
+
for (const { segments } of paths) if (!segments.length) all.push(value);
|
|
214
|
+
else for (const [parent, key] of found(value, segments)) all.push(parent[key]);
|
|
215
|
+
return all;
|
|
216
|
+
};
|
|
217
|
+
return {
|
|
218
|
+
input(input) {
|
|
219
|
+
for (const value of values(input, inputs)) redact(value);
|
|
220
|
+
},
|
|
221
|
+
async output(output, input, ctx) {
|
|
222
|
+
for (const value of values(output, outputs)) redact(value);
|
|
223
|
+
if (reveal === true) return output;
|
|
224
|
+
let result = output;
|
|
225
|
+
for (const { segments } of outputs) {
|
|
226
|
+
const hidden = /* @__PURE__ */ new Set();
|
|
227
|
+
for (const [, , field] of found(output, segments)) if (typeof reveal !== "function" || await reveal({
|
|
228
|
+
field,
|
|
229
|
+
input,
|
|
230
|
+
ctx
|
|
231
|
+
}) !== true) hidden.add(field);
|
|
232
|
+
if (hidden.size) result = omit(result, segments, hidden);
|
|
233
|
+
}
|
|
234
|
+
return result;
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
const MIN_REDACTED_LENGTH = 8;
|
|
239
|
+
const MIN_REDACTED_DIGITS = 4;
|
|
240
|
+
const MAX_REDACTED_VALUES = 1e4;
|
|
241
|
+
const MAX_WALKED_ENTRIES = 100;
|
|
242
|
+
const REDACTED = "[REDACTED]";
|
|
243
|
+
const WITHHELD = "[REDACTED: too many sensitive values in this call]";
|
|
244
|
+
const redactions = globalThis[Symbol.for("brickkit.redactions")] ??= new AsyncLocalStorage();
|
|
245
|
+
let warned$1 = false;
|
|
246
|
+
function add(set, value) {
|
|
247
|
+
if (set.values.has(value)) return;
|
|
248
|
+
if (set.count >= MAX_REDACTED_VALUES) {
|
|
249
|
+
if (!warned$1) console.warn(`[brick] A call's redaction set reached ${MAX_REDACTED_VALUES} values, so its log lines are now withheld. A timer or task started inside a call with t.Sensitive fields joins that call's set; bound an input's sensitive records and arrays with maxProperties or maxItems.`);
|
|
250
|
+
warned$1 = true;
|
|
251
|
+
set.full = true;
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
set.count++;
|
|
255
|
+
set.values.add(value);
|
|
256
|
+
set.values.add(JSON.stringify(value).slice(1, -1));
|
|
257
|
+
set.sorted = void 0;
|
|
258
|
+
}
|
|
259
|
+
const longNumber = (value) => String(value).replace(/\D/g, "").length >= MIN_REDACTED_DIGITS;
|
|
260
|
+
/**
|
|
261
|
+
* Keep a secret out of what Brick logs and traces for the rest of the running
|
|
262
|
+
* call: the logger, the span recorder and error responses replace it with
|
|
263
|
+
* `[REDACTED]`. Call it as soon as `execute` loads a secret, before it can be
|
|
264
|
+
* logged. It takes each string and number in the value, as a `t.Sensitive`
|
|
265
|
+
* field's value is taken: booleans, and numbers under 4 digits, are left out.
|
|
266
|
+
* Outside a call with `t.Sensitive` fields it does nothing.
|
|
267
|
+
*/
|
|
268
|
+
function redact(value) {
|
|
269
|
+
const set = redactions.getStore();
|
|
270
|
+
if (set) register(set, value, /* @__PURE__ */ new Set());
|
|
271
|
+
}
|
|
272
|
+
function register(set, value, seen) {
|
|
273
|
+
if (typeof value === "string") {
|
|
274
|
+
if (value) add(set, value);
|
|
275
|
+
} else if (typeof value === "number" || typeof value === "bigint") {
|
|
276
|
+
if (longNumber(value)) add(set, String(value));
|
|
277
|
+
} else if (value && typeof value === "object" && !seen.has(value)) {
|
|
278
|
+
seen.add(value);
|
|
279
|
+
for (const child of Object.values(value)) register(set, child, seen);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
function redacting() {
|
|
283
|
+
const set = redactions.getStore();
|
|
284
|
+
return !!set && (set.full || set.values.size > 0);
|
|
285
|
+
}
|
|
286
|
+
function redactText(text) {
|
|
287
|
+
const set = redactions.getStore();
|
|
288
|
+
if (!set || typeof text !== "string") return text;
|
|
289
|
+
if (set.full) return WITHHELD;
|
|
290
|
+
set.sorted ??= [...set.values].filter((value) => value.length >= MIN_REDACTED_LENGTH).sort((a, b) => b.length - a.length);
|
|
291
|
+
let redacted = text;
|
|
292
|
+
for (const value of set.sorted) if (redacted.includes(value)) redacted = redacted.split(value).join(REDACTED);
|
|
293
|
+
return redacted;
|
|
294
|
+
}
|
|
295
|
+
function redactLeaf(set, value) {
|
|
296
|
+
if (typeof value === "string") return set.values.has(value) ? REDACTED : redactText(value);
|
|
297
|
+
if (typeof value === "number" || typeof value === "bigint") return longNumber(value) && set.values.has(String(value)) ? REDACTED : value;
|
|
298
|
+
return value;
|
|
299
|
+
}
|
|
300
|
+
const LEAF_DEPTH = 5;
|
|
301
|
+
function publicFieldsCopy(original, props) {
|
|
302
|
+
const copy = Object.create(Object.getPrototypeOf(original));
|
|
303
|
+
for (const [key, next] of props) Object.defineProperty(copy, key, {
|
|
304
|
+
value: next,
|
|
305
|
+
enumerable: true,
|
|
306
|
+
writable: true,
|
|
307
|
+
configurable: true
|
|
308
|
+
});
|
|
309
|
+
return copy;
|
|
310
|
+
}
|
|
311
|
+
function redactValues(value) {
|
|
312
|
+
const set = redactions.getStore();
|
|
313
|
+
if (!set || !set.full && !set.values.size) return value;
|
|
314
|
+
const walking = /* @__PURE__ */ new Set();
|
|
315
|
+
const done = /* @__PURE__ */ new Map();
|
|
316
|
+
const visit = (value, depth) => {
|
|
317
|
+
if (typeof value === "function") return Object.keys(value).length ? "[Function]" : value;
|
|
318
|
+
if (!value || typeof value !== "object") return redactLeaf(set, value);
|
|
319
|
+
if (value instanceof Date) return value;
|
|
320
|
+
if (walking.has(value)) return "[Circular]";
|
|
321
|
+
if (done.has(value)) return done.get(value);
|
|
322
|
+
if (depth > LEAF_DEPTH) return "[Object]";
|
|
323
|
+
walking.add(value);
|
|
324
|
+
let copy;
|
|
325
|
+
try {
|
|
326
|
+
copy = inside(value, depth);
|
|
327
|
+
} catch {
|
|
328
|
+
copy = "[Unreadable]";
|
|
329
|
+
}
|
|
330
|
+
walking.delete(value);
|
|
331
|
+
done.set(value, copy);
|
|
332
|
+
return copy;
|
|
333
|
+
};
|
|
334
|
+
const entries = (value, size, depth) => {
|
|
335
|
+
const items = [];
|
|
336
|
+
for (const item of value) {
|
|
337
|
+
if (items.length === MAX_WALKED_ENTRIES) break;
|
|
338
|
+
items.push(item);
|
|
339
|
+
}
|
|
340
|
+
const next = items.map((item) => visit(item, value instanceof Map ? depth : depth + 1));
|
|
341
|
+
const more = size - items.length;
|
|
342
|
+
return {
|
|
343
|
+
next,
|
|
344
|
+
more,
|
|
345
|
+
changed: more > 0 || next.some((item, i) => item !== items[i])
|
|
346
|
+
};
|
|
347
|
+
};
|
|
348
|
+
const inside = (value, depth) => {
|
|
349
|
+
if (Array.isArray(value)) {
|
|
350
|
+
const { next, more, changed } = entries(value, value.length, depth);
|
|
351
|
+
if (more) next.push(`... ${more} more items not shown`);
|
|
352
|
+
return changed || Object.keys(value).length !== value.length ? next : value;
|
|
353
|
+
}
|
|
354
|
+
if (value instanceof Map || value instanceof Set) {
|
|
355
|
+
const { next, more, changed } = entries(value, value.size, depth);
|
|
356
|
+
if (!changed) return value;
|
|
357
|
+
if (value instanceof Set) {
|
|
358
|
+
if (more) next.push(`... ${more} more items not shown`);
|
|
359
|
+
return new Set(next);
|
|
360
|
+
}
|
|
361
|
+
const map = new Map(next);
|
|
362
|
+
if (more) map.set("...", `${more} more entries not shown`);
|
|
363
|
+
return map;
|
|
364
|
+
}
|
|
365
|
+
if (value instanceof Error) {
|
|
366
|
+
let text = redactText(String(value.stack || `${value.name}: ${value.message}`));
|
|
367
|
+
if (Object.keys(value).length) text += ` ${inspect(visit({ ...value }, depth + 1), { depth: 2 })}`;
|
|
368
|
+
if (value.cause !== void 0) {
|
|
369
|
+
const cause = visit(value.cause, depth + 1);
|
|
370
|
+
text += `\n [cause]: ${typeof cause === "string" ? cause : inspect(cause, { depth: 2 })}`;
|
|
371
|
+
}
|
|
372
|
+
return text;
|
|
373
|
+
}
|
|
374
|
+
const tag = Object.prototype.toString.call(value);
|
|
375
|
+
if (tag !== "[object Object]") return `[${tag.slice(8, -1)}]`;
|
|
376
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
377
|
+
let changed = false;
|
|
378
|
+
const props = [];
|
|
379
|
+
for (const key of Reflect.ownKeys(descriptors)) {
|
|
380
|
+
const descriptor = descriptors[key];
|
|
381
|
+
if (!descriptor.enumerable) continue;
|
|
382
|
+
const name = typeof key === "string" ? redactLeaf(set, key) : key;
|
|
383
|
+
const next = "value" in descriptor ? visit(descriptor.value, depth + 1) : "[Getter]";
|
|
384
|
+
if (name !== key || next !== descriptor.value) changed = true;
|
|
385
|
+
props.push([name, next]);
|
|
386
|
+
}
|
|
387
|
+
return changed ? publicFieldsCopy(value, props) : value;
|
|
388
|
+
};
|
|
389
|
+
return visit(value, 0);
|
|
390
|
+
}
|
|
391
|
+
function redactDetails(details) {
|
|
392
|
+
const set = redactions.getStore();
|
|
393
|
+
if (!set || details === void 0 || !set.full && !set.values.size) return details;
|
|
394
|
+
if (set.full) return WITHHELD;
|
|
395
|
+
try {
|
|
396
|
+
const text = JSON.stringify(details);
|
|
397
|
+
if (text === void 0) return details;
|
|
398
|
+
const copy = JSON.parse(text, (_key, value) => value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).map(([key, child]) => [redactLeaf(set, key), child])) : redactLeaf(set, value));
|
|
399
|
+
return JSON.stringify(copy) === text ? details : copy;
|
|
400
|
+
} catch {
|
|
401
|
+
return REDACTED;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
const outsideRedaction = (fn) => redactions.exit(fn);
|
|
405
|
+
/** Set a property of an error, unless it is read-only (a `DOMException`, a frozen error). */
|
|
406
|
+
function assign(target, key, value) {
|
|
407
|
+
try {
|
|
408
|
+
target[key] = value;
|
|
409
|
+
} catch {}
|
|
410
|
+
}
|
|
411
|
+
const ESCAPED_ERROR_FIELDS = /* @__PURE__ */ new Set([
|
|
412
|
+
"message",
|
|
413
|
+
"stack",
|
|
414
|
+
"cause",
|
|
415
|
+
"details"
|
|
416
|
+
]);
|
|
417
|
+
const MAX_CAUSE_DEPTH = 8;
|
|
418
|
+
/** `err`, redacted in place along its cause chain, for whoever logs it outside the call. */
|
|
419
|
+
function redactEscaped(err) {
|
|
420
|
+
if (!(err instanceof Error)) return redactValues(err);
|
|
421
|
+
let e = err;
|
|
422
|
+
for (let n = 0; n < MAX_CAUSE_DEPTH; n++) {
|
|
423
|
+
assign(e, "message", redactText(e.message));
|
|
424
|
+
if (e.stack) assign(e, "stack", redactText(e.stack));
|
|
425
|
+
if ("details" in e) assign(e, "details", redactDetails(e.details));
|
|
426
|
+
for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(e))) if (descriptor.enumerable && "value" in descriptor && !ESCAPED_ERROR_FIELDS.has(key)) assign(e, key, redactValues(descriptor.value));
|
|
427
|
+
if (!(e.cause instanceof Error)) {
|
|
428
|
+
if (e.cause !== void 0) assign(e, "cause", redactValues(e.cause));
|
|
429
|
+
break;
|
|
430
|
+
}
|
|
431
|
+
e = e.cause;
|
|
432
|
+
}
|
|
433
|
+
return err;
|
|
434
|
+
}
|
|
435
|
+
async function withRedaction(fn) {
|
|
436
|
+
if (redactions.getStore()) return fn();
|
|
437
|
+
const set = {
|
|
438
|
+
values: /* @__PURE__ */ new Set(),
|
|
439
|
+
count: 0
|
|
440
|
+
};
|
|
441
|
+
try {
|
|
442
|
+
return await redactions.run(set, fn);
|
|
443
|
+
} catch (err) {
|
|
444
|
+
throw redactions.run(set, () => redactEscaped(err));
|
|
445
|
+
}
|
|
446
|
+
}
|
|
31
447
|
// src/telemetry.ts
|
|
32
448
|
const INSTRUMENTATION_SCOPE = "@brickkit/core";
|
|
33
449
|
const MAX_TEXT_LENGTH = 500;
|
|
@@ -130,6 +546,13 @@ function recordFailure(error, failure) {
|
|
|
130
546
|
});
|
|
131
547
|
if (failure.status >= 500) recordThrown(span, error);
|
|
132
548
|
}
|
|
549
|
+
function recordWebhook(name, eventId, outcome) {
|
|
550
|
+
trace.getActiveSpan()?.setAttributes({
|
|
551
|
+
[ATTR.webhook]: name,
|
|
552
|
+
...eventId === void 0 ? {} : { [ATTR.webhookEventId]: eventId },
|
|
553
|
+
[ATTR.webhookOutcome]: outcome
|
|
554
|
+
});
|
|
555
|
+
}
|
|
133
556
|
/**
|
|
134
557
|
* Record SQL statements as client spans for the database behind a service.
|
|
135
558
|
* Drizzle's logger has no timing, so the hook sits on the driver: each
|
|
@@ -247,10 +670,17 @@ function settle(fn, done) {
|
|
|
247
670
|
return result;
|
|
248
671
|
}
|
|
249
672
|
function recordThrown(span, error) {
|
|
250
|
-
|
|
673
|
+
if (!(error instanceof Error)) span.recordException(redactText(String(error)));
|
|
674
|
+
else if (!redacting()) span.recordException(error);
|
|
675
|
+
else span.recordException({
|
|
676
|
+
code: error.code,
|
|
677
|
+
name: error.name,
|
|
678
|
+
message: redactText(error.message),
|
|
679
|
+
stack: error.stack && redactText(error.stack)
|
|
680
|
+
});
|
|
251
681
|
span.setStatus({
|
|
252
682
|
code: SpanStatusCode.ERROR,
|
|
253
|
-
message: truncate(messageOf(error))
|
|
683
|
+
message: truncate(redactText(messageOf(error)))
|
|
254
684
|
});
|
|
255
685
|
}
|
|
256
686
|
function responseStatus(value) {
|
|
@@ -287,10 +717,15 @@ function normalizeActionError(err, { logger, requestId }) {
|
|
|
287
717
|
* `details` or `errors` when there are any.
|
|
288
718
|
*/
|
|
289
719
|
function toErrorResponse(err, context) {
|
|
290
|
-
const envelope = buildErrorEnvelope(err, context);
|
|
720
|
+
const envelope = redactAnsweredEnvelope(buildErrorEnvelope(err, context));
|
|
291
721
|
recordFailure(err, envelope);
|
|
292
722
|
return envelope;
|
|
293
723
|
}
|
|
724
|
+
function redactAnsweredEnvelope(envelope) {
|
|
725
|
+
envelope.message = redactText(envelope.message);
|
|
726
|
+
if (envelope.details !== void 0) envelope.details = redactDetails(envelope.details);
|
|
727
|
+
return envelope;
|
|
728
|
+
}
|
|
294
729
|
function buildErrorEnvelope(err, context) {
|
|
295
730
|
const failure = normalizeActionError(err, context);
|
|
296
731
|
if (failure.status >= 500 && (err instanceof ActionExecutionError || err instanceof ValidationError)) context.logger.error("Server action error", { requestId: context.requestId }, err);
|
|
@@ -307,6 +742,69 @@ function buildErrorEnvelope(err, context) {
|
|
|
307
742
|
};
|
|
308
743
|
}
|
|
309
744
|
// src/typebox.ts
|
|
745
|
+
/**
|
|
746
|
+
* Any JSON value: null, boolean, number, string, or an array or object of
|
|
747
|
+
* JSON values.
|
|
748
|
+
*/
|
|
749
|
+
function Json(options) {
|
|
750
|
+
return Type$1.Recursive((This) => Type$1.Union([
|
|
751
|
+
Type$1.Null(),
|
|
752
|
+
Type$1.Boolean(),
|
|
753
|
+
Type$1.Number(),
|
|
754
|
+
Type$1.String(),
|
|
755
|
+
Type$1.Array(This),
|
|
756
|
+
Type$1.Record(Type$1.String(), This)
|
|
757
|
+
]), options);
|
|
758
|
+
}
|
|
759
|
+
function accepts(accept, type) {
|
|
760
|
+
if (!accept) return true;
|
|
761
|
+
const given = type.split(";")[0].trim().toLowerCase();
|
|
762
|
+
return accept.some((pattern) => {
|
|
763
|
+
const wanted = pattern.toLowerCase();
|
|
764
|
+
if (wanted === "*/*") return true;
|
|
765
|
+
return wanted.endsWith("/*") ? given.startsWith(wanted.slice(0, -1)) && given.length > wanted.length - 1 : given === wanted;
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
TypeRegistry.Set("File", (schema, value) => value instanceof Blob && !(value.size > (schema.maxSize ?? 1e400)) && accepts(schema.accept, value.type));
|
|
769
|
+
/** A file from a `multipart/form-data` body: a `File` (a `Blob`), at most `maxSize` bytes, of a type in `accept`. */
|
|
770
|
+
function File(options = {}) {
|
|
771
|
+
return Type$1.Unsafe({
|
|
772
|
+
[Kind]: "File",
|
|
773
|
+
type: "string",
|
|
774
|
+
format: "binary",
|
|
775
|
+
...options
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
/** Several files under one form field. */
|
|
779
|
+
function Files(options = {}) {
|
|
780
|
+
const { minItems, maxItems, ...file } = options;
|
|
781
|
+
return Type$1.Array(File(file), {
|
|
782
|
+
minItems,
|
|
783
|
+
maxItems
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
/** TypeBox's `Type` plus Brick's `Json`, `File`, `Files` and `Sensitive`. */
|
|
787
|
+
const Type = Object.assign({}, Type$1, {
|
|
788
|
+
Json,
|
|
789
|
+
File,
|
|
790
|
+
Files,
|
|
791
|
+
Sensitive
|
|
792
|
+
});
|
|
793
|
+
function fileFields(schema) {
|
|
794
|
+
const fields = [];
|
|
795
|
+
const properties = schema?.properties;
|
|
796
|
+
for (const [key, prop] of Object.entries(properties ?? {})) {
|
|
797
|
+
const file = prop[Kind] === "File" ? prop : prop.items;
|
|
798
|
+
if (file?.[Kind] !== "File") continue;
|
|
799
|
+
const count = file === prop ? 1 : prop.maxItems;
|
|
800
|
+
const maxBytes = file.maxSize === void 0 || count === void 0 ? void 0 : file.maxSize * count;
|
|
801
|
+
fields.push({
|
|
802
|
+
key,
|
|
803
|
+
maxBytes
|
|
804
|
+
});
|
|
805
|
+
}
|
|
806
|
+
return fields;
|
|
807
|
+
}
|
|
310
808
|
const compilerCache = /* @__PURE__ */ new WeakMap();
|
|
311
809
|
/**
|
|
312
810
|
* The compiled validator for a TypeBox schema. Compiling is slow and checking
|
|
@@ -330,7 +828,8 @@ function getCompiledCheck(schema) {
|
|
|
330
828
|
* @param schema - A TypeBox schema, or `undefined` to accept anything.
|
|
331
829
|
* @param value - The value to check.
|
|
332
830
|
* @returns `{ success: true, data }`, or `{ success: false, errors }` with a
|
|
333
|
-
* `path`, `message
|
|
831
|
+
* `path`, `message` and `type` for each problem. The offending value is
|
|
832
|
+
* left out so a rejected secret is never echoed or logged.
|
|
334
833
|
*/
|
|
335
834
|
function validateWithSchema(schema, value) {
|
|
336
835
|
if (!schema) return {
|
|
@@ -346,7 +845,6 @@ function validateWithSchema(schema, value) {
|
|
|
346
845
|
for (const error of check.Errors(value)) errors.push({
|
|
347
846
|
path: error.path,
|
|
348
847
|
message: error.message,
|
|
349
|
-
value: error.value,
|
|
350
848
|
type: error.type
|
|
351
849
|
});
|
|
352
850
|
return {
|
|
@@ -379,120 +877,1823 @@ const ANSI = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)
|
|
|
379
877
|
function stripAnsi(text) {
|
|
380
878
|
return text.includes("\x1B") ? text.replace(ANSI, "") : text;
|
|
381
879
|
}
|
|
880
|
+
const REDACTED_COPY_NOT_PRINTABLE = "[Unreadable]";
|
|
881
|
+
function formatRedacted(print, args) {
|
|
882
|
+
let printed;
|
|
883
|
+
try {
|
|
884
|
+
printed = print(...redactValues(args));
|
|
885
|
+
} catch {
|
|
886
|
+
printed = REDACTED_COPY_NOT_PRINTABLE;
|
|
887
|
+
}
|
|
888
|
+
return redactText(printed);
|
|
889
|
+
}
|
|
890
|
+
/**
|
|
891
|
+
* What `console.log` would print, without terminal colors, with objects cut off
|
|
892
|
+
* at a sensible size.
|
|
893
|
+
*/
|
|
894
|
+
function render(args) {
|
|
895
|
+
const text = formatRedacted((...values) => stripAnsi(formatWithOptions({
|
|
896
|
+
depth: 3,
|
|
897
|
+
breakLength: 120,
|
|
898
|
+
maxArrayLength: 50,
|
|
899
|
+
maxStringLength: 1e3
|
|
900
|
+
}, ...values)), args);
|
|
901
|
+
return text.length > MAX_MESSAGE_LENGTH ? `${text.slice(0, MAX_MESSAGE_LENGTH)}…` : text;
|
|
902
|
+
}
|
|
903
|
+
function record(span, level, args) {
|
|
904
|
+
const count = (logged.get(span) ?? 0) + 1;
|
|
905
|
+
logged.set(span, count);
|
|
906
|
+
if (count > MAX_LOGS_PER_SPAN) {
|
|
907
|
+
span.setAttribute(ATTR.logsDropped, count - MAX_LOGS_PER_SPAN);
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
span.addEvent(SPAN.logEvent, {
|
|
911
|
+
[ATTR.logLevel]: level,
|
|
912
|
+
[ATTR.logMessage]: render(args)
|
|
913
|
+
});
|
|
914
|
+
}
|
|
915
|
+
/**
|
|
916
|
+
* Record a line on the running span, if a recording one is running. Returns
|
|
917
|
+
* whether it did, so the caller prints only when it did not.
|
|
918
|
+
*/
|
|
919
|
+
function recordActive(level, args) {
|
|
920
|
+
const span = trace.getActiveSpan();
|
|
921
|
+
if (!span?.isRecording()) return false;
|
|
922
|
+
record(span, level, args);
|
|
923
|
+
return true;
|
|
924
|
+
}
|
|
925
|
+
globalThis[Symbol.for(GLOBAL_SYMBOL.logsRecord)] = recordActive;
|
|
926
|
+
/**
|
|
927
|
+
* A logger for actions, tools, and endpoints. While a dashboard is on, a line
|
|
928
|
+
* logged while a request is being traced becomes an event on the span that is
|
|
929
|
+
* running, which the dashboard shows with that request (and in its Logs tab);
|
|
930
|
+
* it is not printed. Everywhere else, and for lines logged outside a request,
|
|
931
|
+
* it prints to the console, prefixed by `prefix`: one for all levels, or one
|
|
932
|
+
* per level.
|
|
933
|
+
*
|
|
934
|
+
* Capturing costs one context lookup and a span event per line, and nothing
|
|
935
|
+
* is serialized for the dashboard until the span ends, so it is cheaper than
|
|
936
|
+
* a console write. Lines are cut at 4,000 characters and a span keeps 100.
|
|
937
|
+
*/
|
|
938
|
+
function createLogger(prefix) {
|
|
939
|
+
const level = (name, print) => (...args) => {
|
|
940
|
+
if (globalThis[CAPTURE] === true && recordActive(name, args)) return;
|
|
941
|
+
if (redacting()) args = [formatRedacted(format, args)];
|
|
942
|
+
print(typeof prefix === "string" ? prefix : prefix[name], ...args);
|
|
943
|
+
};
|
|
944
|
+
return {
|
|
945
|
+
info: level("info", (...args) => console.log(...args)),
|
|
946
|
+
warn: level("warn", (...args) => console.warn(...args)),
|
|
947
|
+
error: level("error", (...args) => console.error(...args)),
|
|
948
|
+
debug: level("debug", (...args) => console.debug(...args))
|
|
949
|
+
};
|
|
950
|
+
}
|
|
951
|
+
/** The prefixes of loggers a caller did not supply. */
|
|
952
|
+
const DEFAULT_LOG_PREFIXES = {
|
|
953
|
+
info: "[INFO]",
|
|
954
|
+
warn: "[WARN]",
|
|
955
|
+
error: "[ERROR]",
|
|
956
|
+
debug: "[DEBUG]"
|
|
957
|
+
};
|
|
958
|
+
// src/dashboard-identity.ts
|
|
959
|
+
/** The header the dashboard's `/app/*` proxy signs the identity into. */
|
|
960
|
+
const DASHBOARD_IDENTITY_HEADER = "x-brick-dashboard";
|
|
961
|
+
/** How `brick dev` hands the signing key to the app's process. */
|
|
962
|
+
const DASHBOARD_KEY_ENV = "BRICK_DASHBOARD_KEY";
|
|
963
|
+
const SIGNATURE_TTL_MS = 6e4;
|
|
964
|
+
const KEY = Symbol.for(GLOBAL_SYMBOL.dashboardKey);
|
|
965
|
+
const global = globalThis;
|
|
966
|
+
function hideKeyFromChildProcesses() {
|
|
967
|
+
const handedOver = process.env[DASHBOARD_KEY_ENV];
|
|
968
|
+
if (!handedOver) return;
|
|
969
|
+
global[KEY] = handedOver;
|
|
970
|
+
delete process.env[DASHBOARD_KEY_ENV];
|
|
971
|
+
}
|
|
972
|
+
hideKeyFromChildProcesses();
|
|
973
|
+
/**
|
|
974
|
+
* The key the dashboard signs identities with: random per process, or the one
|
|
975
|
+
* `brick dev` or the Vite plugin handed the app.
|
|
976
|
+
*/
|
|
977
|
+
function dashboardKey() {
|
|
978
|
+
return global[KEY] ??= randomBytes(32).toString("base64url");
|
|
979
|
+
}
|
|
980
|
+
const arrivedAt = /* @__PURE__ */ new WeakMap();
|
|
981
|
+
/** Note when `request` arrived, before its body is read. */
|
|
982
|
+
function markDashboardArrival(request) {
|
|
983
|
+
arrivedAt.set(request, Date.now());
|
|
984
|
+
}
|
|
985
|
+
const mac$1 = (payload) => createHmac("sha256", dashboardKey()).update(payload).digest();
|
|
986
|
+
/** The header value for an identity: `<base64url(json)>.<hmac>`. */
|
|
987
|
+
function signDashboardIdentity(identity, now = Date.now()) {
|
|
988
|
+
const payload = Buffer.from(JSON.stringify({
|
|
989
|
+
user: identity.user,
|
|
990
|
+
exp: now + SIGNATURE_TTL_MS
|
|
991
|
+
})).toString("base64url");
|
|
992
|
+
return `${payload}.${mac$1(payload).toString("base64url")}`;
|
|
993
|
+
}
|
|
994
|
+
function dashboardIdentity(request) {
|
|
995
|
+
const header = request?.headers.get(DASHBOARD_IDENTITY_HEADER);
|
|
996
|
+
if (!header) return void 0;
|
|
997
|
+
const dot = header.indexOf(".");
|
|
998
|
+
if (dot < 0) return void 0;
|
|
999
|
+
const payload = header.slice(0, dot);
|
|
1000
|
+
const given = Buffer.from(header.slice(dot + 1), "base64url");
|
|
1001
|
+
const expected = mac$1(payload);
|
|
1002
|
+
if (given.length !== expected.length || !timingSafeEqual(given, expected)) return void 0;
|
|
1003
|
+
try {
|
|
1004
|
+
const { user, exp } = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
1005
|
+
const now = (request && arrivedAt.get(request)) ?? Date.now();
|
|
1006
|
+
if (typeof exp !== "number" || exp < now) return void 0;
|
|
1007
|
+
return user === void 0 ? {} : { user };
|
|
1008
|
+
} catch {
|
|
1009
|
+
return;
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
/**
|
|
1013
|
+
* The dashboard user a request came from, for an endpoint: the person
|
|
1014
|
+
* `dashboard.auth.authorize` let in, when the request arrived through the
|
|
1015
|
+
* dashboard's `/app/*` proxy. Undefined for any other request, and for one the
|
|
1016
|
+
* dashboard let in by token. Actions read it as `ctx.dashboard?.user`.
|
|
1017
|
+
*/
|
|
1018
|
+
function dashboardUser(request) {
|
|
1019
|
+
return dashboardIdentity(request)?.user;
|
|
1020
|
+
}
|
|
1021
|
+
// src/identity.ts
|
|
1022
|
+
const IDENTITY = Symbol.for("brickkit.identity");
|
|
1023
|
+
function attachIdentity(ctx, service, deps) {
|
|
1024
|
+
const hook = service.options.identity;
|
|
1025
|
+
if (typeof hook !== "function") return;
|
|
1026
|
+
let identity;
|
|
1027
|
+
ctx[IDENTITY] = () => identity ??= Promise.resolve().then(() => {
|
|
1028
|
+
const { [IDENTITY]: _own, ...withoutIdentity } = ctx;
|
|
1029
|
+
return hook({
|
|
1030
|
+
...withoutIdentity,
|
|
1031
|
+
deps
|
|
1032
|
+
});
|
|
1033
|
+
}).then((value) => checked(service.name, value));
|
|
1034
|
+
}
|
|
1035
|
+
function checked(service, value) {
|
|
1036
|
+
if (value === null || value === void 0) return null;
|
|
1037
|
+
const { id, label, tenant } = value;
|
|
1038
|
+
if (typeof id !== "string" || !id || label !== void 0 && typeof label !== "string" || tenant !== void 0 && typeof tenant !== "string") throw new Error(`Service "${service}": identity must return { id: string, label?: string, tenant?: string } with a non-empty id, null or undefined`);
|
|
1039
|
+
return {
|
|
1040
|
+
id,
|
|
1041
|
+
...label !== void 0 && { label },
|
|
1042
|
+
...tenant !== void 0 && { tenant }
|
|
1043
|
+
};
|
|
1044
|
+
}
|
|
1045
|
+
function identityOf(ctx) {
|
|
1046
|
+
const resolve = ctx[IDENTITY];
|
|
1047
|
+
return typeof resolve === "function" ? resolve() : Promise.resolve(null);
|
|
1048
|
+
}
|
|
1049
|
+
function hasIdentity(service) {
|
|
1050
|
+
return typeof service.options.identity === "function";
|
|
1051
|
+
}
|
|
1052
|
+
// src/service-port.ts
|
|
1053
|
+
/** The port of a service: every `Service` is a `ServicePort`. */
|
|
1054
|
+
function portOf(service) {
|
|
1055
|
+
return service;
|
|
1056
|
+
}
|
|
1057
|
+
// src/deps.ts
|
|
1058
|
+
/** Where a listener a plugin added keeps the plugin's deps, for its handler and workflow steps; global so a second core copy finds it. */
|
|
1059
|
+
const PLUGIN_DEPS = Symbol.for("brickkit.plugin.deps");
|
|
1060
|
+
function sharedAcrossCoreCopies(key, create) {
|
|
1061
|
+
const store = globalThis;
|
|
1062
|
+
return store[Symbol.for(key)] ??= create();
|
|
1063
|
+
}
|
|
1064
|
+
const depsBuiltByBrick = sharedAcrossCoreCopies("brickkit.deps.built", () => /* @__PURE__ */ new WeakSet());
|
|
1065
|
+
function freezeAsBuiltDeps(deps) {
|
|
1066
|
+
depsBuiltByBrick.add(Object.freeze(deps));
|
|
1067
|
+
return deps;
|
|
1068
|
+
}
|
|
1069
|
+
function depsOverride(callCtx) {
|
|
1070
|
+
const deps = callCtx?.deps;
|
|
1071
|
+
return deps && typeof deps === "object" && !depsBuiltByBrick.has(deps) ? deps : void 0;
|
|
1072
|
+
}
|
|
1073
|
+
const running = new AsyncLocalStorage();
|
|
1074
|
+
/** Run `fn` with the deps of one app, so `useDeps()` inside it finds them. */
|
|
1075
|
+
function runWithDeps(deps, fn) {
|
|
1076
|
+
return running.run(deps, fn);
|
|
1077
|
+
}
|
|
1078
|
+
function useDeps(service) {
|
|
1079
|
+
if (service) return portOf(service).deps;
|
|
1080
|
+
const deps = running.getStore();
|
|
1081
|
+
if (!deps) throw new Error("useDeps() was called outside a Brick app: call it from a listener, a schedule or a workflow step (actions read ctx.deps), or pass the service: useDeps(service).");
|
|
1082
|
+
return deps;
|
|
1083
|
+
}
|
|
1084
|
+
function makeAmbiguous(deps, name, firstService, otherService) {
|
|
1085
|
+
Object.defineProperty(deps, name, {
|
|
1086
|
+
enumerable: false,
|
|
1087
|
+
get() {
|
|
1088
|
+
throw new Error(`useDeps().${name} is ambiguous: services "${firstService}" and "${otherService}" both declare dep "${name}" with different values. Call useDeps(service) with the service you mean.`);
|
|
1089
|
+
}
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
function appDeps(services) {
|
|
1093
|
+
const deps = {};
|
|
1094
|
+
const owner = /* @__PURE__ */ new Map();
|
|
1095
|
+
for (const service of services) for (const [name, value] of Object.entries(portOf(service).deps)) {
|
|
1096
|
+
const seen = Object.getOwnPropertyDescriptor(deps, name);
|
|
1097
|
+
const first = owner.get(name);
|
|
1098
|
+
if (!seen) {
|
|
1099
|
+
owner.set(name, service.name);
|
|
1100
|
+
deps[name] = value;
|
|
1101
|
+
} else if ("value" in seen && seen.value !== value) makeAmbiguous(deps, name, first, service.name);
|
|
1102
|
+
}
|
|
1103
|
+
return freezeAsBuiltDeps(deps);
|
|
1104
|
+
}
|
|
1105
|
+
// src/definition-site.ts
|
|
1106
|
+
const brickRoot = fileURLToPath(new URL("..", import.meta.url));
|
|
1107
|
+
/**
|
|
1108
|
+
* The first `file:line` outside Brick on the current stack: where a name is
|
|
1109
|
+
* being defined. Best-effort: `undefined` when there is no stack.
|
|
1110
|
+
*/
|
|
1111
|
+
function definitionSite() {
|
|
1112
|
+
const limit = Error.stackTraceLimit;
|
|
1113
|
+
Error.stackTraceLimit = 50;
|
|
1114
|
+
const stack = (/* @__PURE__ */ new Error()).stack;
|
|
1115
|
+
Error.stackTraceLimit = limit;
|
|
1116
|
+
for (const line of stack?.split("\n").slice(1) ?? []) {
|
|
1117
|
+
const match = /(?:\(|at )(?:file:\/\/)?([^\s()?]+)(?:\?[^\s():]*)?:(\d+):\d+\)?$/.exec(line);
|
|
1118
|
+
if (!match) continue;
|
|
1119
|
+
const [, file, row] = match;
|
|
1120
|
+
if (file.startsWith(`${brickRoot}src/`) || file.startsWith(`${brickRoot}dist/`)) continue;
|
|
1121
|
+
return `${file}:${row}`;
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
/**
|
|
1125
|
+
* Records where `name` is defined. The same file defining it again (a dev
|
|
1126
|
+
* reload) replaces the old definition.
|
|
1127
|
+
*
|
|
1128
|
+
* @throws When a different file already defined `name`.
|
|
1129
|
+
*/
|
|
1130
|
+
function claimName(sites, label, name, site) {
|
|
1131
|
+
const file = (at) => at?.replace(/:\d+$/, "");
|
|
1132
|
+
if (sites.has(name) && file(sites.get(name)) !== file(site)) throw new DuplicateNameError(`Brick: duplicate ${label}\n ${sites.get(name) ?? "unknown"}\n ${site ?? "unknown"}`);
|
|
1133
|
+
sites.set(name, site);
|
|
1134
|
+
}
|
|
1135
|
+
// src/secrets.ts
|
|
1136
|
+
/**
|
|
1137
|
+
* Type-safe secrets & environment variables.
|
|
1138
|
+
*
|
|
1139
|
+
* Declare each secret once at module scope instead of scattering untyped
|
|
1140
|
+
* `process.env.FOO` reads:
|
|
1141
|
+
*
|
|
1142
|
+
* const port = defineSecret("PORT").default("3333").transform(Number).require();
|
|
1143
|
+
* const baseUrl = defineSecret("BASE_URL").url().require();
|
|
1144
|
+
* const key = defineSecret("STRIPE_KEY").validate((v) =>
|
|
1145
|
+
* v.startsWith("sk_") || "must start with sk_"
|
|
1146
|
+
* ).require();
|
|
1147
|
+
*
|
|
1148
|
+
* Values resolve from the environment (Bun populates `process.env` from
|
|
1149
|
+
* `.env` locally; in prod the same env source applies — a future
|
|
1150
|
+
* `SecretSource` such as AWS can slot in without touching call sites).
|
|
1151
|
+
*
|
|
1152
|
+
* Resolution order per secret: test/session override → source (`process.env`
|
|
1153
|
+
* by default) → declared `default`. `resolveSecrets()` validates every
|
|
1154
|
+
* registered secret at boot and throws listing all missing required ones.
|
|
1155
|
+
*/
|
|
1156
|
+
/** Default source: `process.env` (Bun loads `.env` into it automatically). */
|
|
1157
|
+
const envSource = { get: (name) => process.env[name] };
|
|
1158
|
+
const registry = /* @__PURE__ */ new Map();
|
|
1159
|
+
const overrides = /* @__PURE__ */ new Map();
|
|
1160
|
+
/** Where each secret was first declared. */
|
|
1161
|
+
const sites = /* @__PURE__ */ new Map();
|
|
1162
|
+
var SecretRef = class {
|
|
1163
|
+
name;
|
|
1164
|
+
options;
|
|
1165
|
+
transformFn;
|
|
1166
|
+
validators = [];
|
|
1167
|
+
constructor(name, options = {}) {
|
|
1168
|
+
this.name = name;
|
|
1169
|
+
this.options = options;
|
|
1170
|
+
}
|
|
1171
|
+
/** True when a default was declared (i.e. the secret is optional). */
|
|
1172
|
+
get hasDefault() {
|
|
1173
|
+
return this.options.default !== void 0;
|
|
1174
|
+
}
|
|
1175
|
+
/** Fallback used when the source has no value. Makes the secret optional. */
|
|
1176
|
+
default(value) {
|
|
1177
|
+
this.options.default = value;
|
|
1178
|
+
return this;
|
|
1179
|
+
}
|
|
1180
|
+
/**
|
|
1181
|
+
* Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
|
|
1182
|
+
* Runs before validators; a throwing transform fails resolution.
|
|
1183
|
+
*/
|
|
1184
|
+
transform(fn) {
|
|
1185
|
+
this.transformFn = fn;
|
|
1186
|
+
return this;
|
|
1187
|
+
}
|
|
1188
|
+
/** Run a custom check on the (transformed) value at every resolution. */
|
|
1189
|
+
validate(fn) {
|
|
1190
|
+
this.validators.push(fn);
|
|
1191
|
+
return this;
|
|
1192
|
+
}
|
|
1193
|
+
/** Shorthand validator: value must parse as a URL. String refs only. */
|
|
1194
|
+
url() {
|
|
1195
|
+
this.validators.push((v) => {
|
|
1196
|
+
try {
|
|
1197
|
+
new URL(v);
|
|
1198
|
+
} catch {
|
|
1199
|
+
return "must be a valid URL";
|
|
1200
|
+
}
|
|
1201
|
+
});
|
|
1202
|
+
return this;
|
|
1203
|
+
}
|
|
1204
|
+
resolveRaw(source) {
|
|
1205
|
+
return overrides.get(this.name) ?? source.get(this.name) ?? this.options.default;
|
|
1206
|
+
}
|
|
1207
|
+
coerce(raw) {
|
|
1208
|
+
let value;
|
|
1209
|
+
if (this.transformFn) try {
|
|
1210
|
+
value = this.transformFn(raw);
|
|
1211
|
+
} catch (err) {
|
|
1212
|
+
throw new Error(`Invalid value for secret "${this.name}": transform failed (${err instanceof Error ? err.message : String(err)})`);
|
|
1213
|
+
}
|
|
1214
|
+
else value = raw;
|
|
1215
|
+
for (const fn of this.validators) {
|
|
1216
|
+
let result;
|
|
1217
|
+
try {
|
|
1218
|
+
result = fn(value);
|
|
1219
|
+
} catch (err) {
|
|
1220
|
+
throw new Error(`Invalid value for secret "${this.name}": ${err instanceof Error ? err.message : String(err)}`);
|
|
1221
|
+
}
|
|
1222
|
+
if (result === false) throw new Error(`Invalid value for secret "${this.name}": validation failed`);
|
|
1223
|
+
if (typeof result === "string") throw new Error(`Invalid value for secret "${this.name}": ${result}`);
|
|
1224
|
+
}
|
|
1225
|
+
return value;
|
|
1226
|
+
}
|
|
1227
|
+
/** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
|
|
1228
|
+
value(source = envSource) {
|
|
1229
|
+
const raw = this.resolveRaw(source);
|
|
1230
|
+
if (raw === void 0) return void 0;
|
|
1231
|
+
return this.coerce(raw);
|
|
1232
|
+
}
|
|
1233
|
+
/** Resolved value, or throws naming the missing/invalid secret. */
|
|
1234
|
+
require(source = envSource) {
|
|
1235
|
+
const raw = this.resolveRaw(source);
|
|
1236
|
+
if (raw === void 0) throw new Error(`Missing required secret "${this.name}": set it in .env (local) or the environment (prod)`);
|
|
1237
|
+
return this.coerce(raw);
|
|
1238
|
+
}
|
|
1239
|
+
/** True when a value would resolve (override, source, or default). */
|
|
1240
|
+
isSet(source = envSource) {
|
|
1241
|
+
return this.resolveRaw(source) !== void 0;
|
|
1242
|
+
}
|
|
1243
|
+
};
|
|
1244
|
+
/**
|
|
1245
|
+
* Declare a secret. Calling it again for the name returns the same ref. From
|
|
1246
|
+
* the same line (a module evaluated again) it starts the declaration over, so
|
|
1247
|
+
* its builder calls replace the earlier ones instead of adding to them.
|
|
1248
|
+
*/
|
|
1249
|
+
function defineSecret(name, options = {}) {
|
|
1250
|
+
const site = definitionSite();
|
|
1251
|
+
const existing = registry.get(name);
|
|
1252
|
+
if (existing) {
|
|
1253
|
+
if (site !== void 0 && sites.get(name) === site) {
|
|
1254
|
+
existing.options = options;
|
|
1255
|
+
existing["validators"] = [];
|
|
1256
|
+
existing["transformFn"] = void 0;
|
|
1257
|
+
}
|
|
1258
|
+
return existing;
|
|
1259
|
+
}
|
|
1260
|
+
sites.set(name, site);
|
|
1261
|
+
const ref = new SecretRef(name, options);
|
|
1262
|
+
registry.set(name, ref);
|
|
1263
|
+
return ref;
|
|
1264
|
+
}
|
|
1265
|
+
/**
|
|
1266
|
+
* Validate every registered secret at boot. Throws a single error listing
|
|
1267
|
+
* all missing required secrets. Returns the resolved values.
|
|
1268
|
+
*/
|
|
1269
|
+
function resolveSecrets(opts = {}) {
|
|
1270
|
+
const source = opts.source ?? envSource;
|
|
1271
|
+
const missing = [];
|
|
1272
|
+
const resolved = {};
|
|
1273
|
+
for (const ref of registry.values()) {
|
|
1274
|
+
const v = ref.value(source);
|
|
1275
|
+
if (v === void 0) missing.push(ref.name);
|
|
1276
|
+
else resolved[ref.name] = v;
|
|
1277
|
+
}
|
|
1278
|
+
if (missing.length > 0) throw new Error(`Missing required secrets: ${missing.join(", ")}. Set them in .env (local) or the environment (prod)`);
|
|
1279
|
+
return resolved;
|
|
1280
|
+
}
|
|
1281
|
+
/** Metadata for introspection (values never exposed — future dashboard use). */
|
|
1282
|
+
function listSecrets(opts = {}) {
|
|
1283
|
+
const source = opts.source ?? envSource;
|
|
1284
|
+
return [...registry.values()].map((ref) => ({
|
|
1285
|
+
hasDefault: ref.hasDefault,
|
|
1286
|
+
isSet: ref.isSet(source),
|
|
1287
|
+
name: ref.name
|
|
1288
|
+
}));
|
|
1289
|
+
}
|
|
1290
|
+
/** Test/session override for one secret (`undefined` clears the override). */
|
|
1291
|
+
function overrideSecret(name, value) {
|
|
1292
|
+
if (value === void 0) overrides.delete(name);
|
|
1293
|
+
else overrides.set(name, value);
|
|
1294
|
+
}
|
|
1295
|
+
/** Clear registry and overrides. Test-only. */
|
|
1296
|
+
function resetSecrets() {
|
|
1297
|
+
registry.clear();
|
|
1298
|
+
overrides.clear();
|
|
1299
|
+
sites.clear();
|
|
1300
|
+
}
|
|
1301
|
+
// src/file-storage.ts
|
|
1302
|
+
const DEFAULT_EXPIRY_MS = 3e5;
|
|
1303
|
+
/** The longest a link may last: S3 refuses a presigned URL valid for longer. */
|
|
1304
|
+
const MAX_EXPIRY_MS = 6048e5;
|
|
1305
|
+
const S3_READ_IDLE_TIMEOUT_MS = 3e4;
|
|
1306
|
+
const LOCAL_FILES_ROUTE = "/_brick/files";
|
|
1307
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
1308
|
+
const drivers = globalThis[Symbol.for("brickkit.storage.files")] ??= /* @__PURE__ */ new WeakMap();
|
|
1309
|
+
const sha256 = (value) => createHash("sha256").update(value).digest("hex");
|
|
1310
|
+
function tenantKey(tenant, local = false) {
|
|
1311
|
+
if (typeof tenant !== "string" || !tenant || tenant === "." || tenant === ".." || !tenant.isWellFormed()) throw new Error(`File storage: the tenant must be a non-empty, well-formed string other than "." and "..", got ${JSON.stringify(tenant)}`);
|
|
1312
|
+
return local ? sha256(tenant) : encodeURIComponent(tenant);
|
|
1313
|
+
}
|
|
1314
|
+
function attachment(download) {
|
|
1315
|
+
if (!download) return "attachment";
|
|
1316
|
+
return `attachment; filename="${download.replace(/[^\x20-\x7e]|["\\]/g, "_")}"; filename*=UTF-8''${encodeURIComponent(download)}`;
|
|
1317
|
+
}
|
|
1318
|
+
function scoped(driver, tenant) {
|
|
1319
|
+
const folder = async () => `${driver.prefix}${tenantKey(await tenant(), !!driver.local)}/`;
|
|
1320
|
+
const keyOf = async (id) => {
|
|
1321
|
+
const at = await folder();
|
|
1322
|
+
return typeof id === "string" && UUID.test(id) ? at + id : void 0;
|
|
1323
|
+
};
|
|
1324
|
+
return Object.freeze({
|
|
1325
|
+
put: async (file, options) => {
|
|
1326
|
+
if (!(file instanceof Blob)) throw new TypeError("File storage: put needs a Blob or a File");
|
|
1327
|
+
const at = await folder();
|
|
1328
|
+
const id = crypto.randomUUID();
|
|
1329
|
+
const given = (options?.contentType || file.type).toLowerCase();
|
|
1330
|
+
const contentType = new Blob([], { type: given }).type || "application/octet-stream";
|
|
1331
|
+
await driver.write(at + id, file, contentType);
|
|
1332
|
+
return {
|
|
1333
|
+
id,
|
|
1334
|
+
size: file.size,
|
|
1335
|
+
contentType
|
|
1336
|
+
};
|
|
1337
|
+
},
|
|
1338
|
+
url: async (id, options = {}) => {
|
|
1339
|
+
const key = await keyOf(id);
|
|
1340
|
+
if (!key) throw new Error(`File storage: ${JSON.stringify(id)} is not a file id`);
|
|
1341
|
+
const expiresInMs = options.expiresInMs ?? DEFAULT_EXPIRY_MS;
|
|
1342
|
+
if (!Number.isSafeInteger(expiresInMs) || expiresInMs <= 0) throw new Error(`File storage: expiresInMs must be a positive integer, got ${expiresInMs}`);
|
|
1343
|
+
if (expiresInMs > MAX_EXPIRY_MS) throw new Error(`File storage: expiresInMs must be at most 7 days (${MAX_EXPIRY_MS}), got ${expiresInMs}`);
|
|
1344
|
+
return driver.sign(key, expiresInMs, attachment(options.download));
|
|
1345
|
+
},
|
|
1346
|
+
get: async (id) => {
|
|
1347
|
+
const key = await keyOf(id);
|
|
1348
|
+
return key ? driver.read(key) : void 0;
|
|
1349
|
+
},
|
|
1350
|
+
delete: async (id) => {
|
|
1351
|
+
const key = await keyOf(id);
|
|
1352
|
+
if (key) await driver.remove(key);
|
|
1353
|
+
}
|
|
1354
|
+
});
|
|
1355
|
+
}
|
|
1356
|
+
function fileStorage(driver) {
|
|
1357
|
+
const outside = () => Promise.reject(/* @__PURE__ */ new Error("File storage: there is no caller here to take the tenant from. In an action read ctx.deps.<name>; elsewhere name the tenant: files.in(tenantId)"));
|
|
1358
|
+
const handle = Object.freeze({
|
|
1359
|
+
kind: "file",
|
|
1360
|
+
in: (tenant) => {
|
|
1361
|
+
tenantKey(tenant);
|
|
1362
|
+
return scoped(driver, async () => tenant);
|
|
1363
|
+
},
|
|
1364
|
+
put: outside,
|
|
1365
|
+
url: outside,
|
|
1366
|
+
get: outside,
|
|
1367
|
+
delete: outside
|
|
1368
|
+
});
|
|
1369
|
+
drivers.set(handle, driver);
|
|
1370
|
+
return handle;
|
|
1371
|
+
}
|
|
1372
|
+
const fileNames = /* @__PURE__ */ new WeakMap();
|
|
1373
|
+
const views = /* @__PURE__ */ new WeakMap();
|
|
1374
|
+
function hasFilesView(ctx, deps) {
|
|
1375
|
+
const view = views.get(ctx.deps);
|
|
1376
|
+
return view?.deps === deps && view.ctx === ctx;
|
|
1377
|
+
}
|
|
1378
|
+
function scopeFiles(deps, ctx) {
|
|
1379
|
+
let names = fileNames.get(deps);
|
|
1380
|
+
if (!names) fileNames.set(deps, names = Object.keys(deps).filter((name) => drivers.has(deps[name])));
|
|
1381
|
+
if (!names.length) return deps;
|
|
1382
|
+
const tenant = async () => {
|
|
1383
|
+
const identity = await identityOf(ctx);
|
|
1384
|
+
if (!identity?.tenant) throw new Error("File storage: this call has no tenant. The service's identity hook must return { id, tenant } for callers that use files; outside a request use files.in(tenantId)");
|
|
1385
|
+
return identity.tenant;
|
|
1386
|
+
};
|
|
1387
|
+
const copy = { ...deps };
|
|
1388
|
+
for (const name of names) {
|
|
1389
|
+
const handle = deps[name];
|
|
1390
|
+
copy[name] = Object.freeze({
|
|
1391
|
+
kind: "file",
|
|
1392
|
+
...scoped(drivers.get(handle), tenant)
|
|
1393
|
+
});
|
|
1394
|
+
}
|
|
1395
|
+
const view = freezeAsBuiltDeps(copy);
|
|
1396
|
+
views.set(view, {
|
|
1397
|
+
deps,
|
|
1398
|
+
ctx
|
|
1399
|
+
});
|
|
1400
|
+
return view;
|
|
1401
|
+
}
|
|
1402
|
+
function checkFileStorages(service, deps) {
|
|
1403
|
+
if (hasIdentity(service)) return;
|
|
1404
|
+
for (const values of deps) {
|
|
1405
|
+
const name = Object.keys(values).find((key) => drivers.has(values[key]));
|
|
1406
|
+
if (name) throw new Error(`Service "${service.name}" has file storage "${name}" in its deps or a plugin's but no identity hook. Files are kept per tenant: add identity: (ctx) => ({ id, tenant }) to the service.`);
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
const warned = /* @__PURE__ */ new WeakSet();
|
|
1410
|
+
function localFileDirs(deps) {
|
|
1411
|
+
const dirs = /* @__PURE__ */ new Set();
|
|
1412
|
+
for (const values of deps) for (const value of Object.values(values)) {
|
|
1413
|
+
const driver = drivers.get(value);
|
|
1414
|
+
driver?.check?.();
|
|
1415
|
+
if (!driver?.local) continue;
|
|
1416
|
+
dirs.add(driver.local);
|
|
1417
|
+
if (process.env.NODE_ENV === "production" && !warned.has(driver)) {
|
|
1418
|
+
warned.add(driver);
|
|
1419
|
+
console.warn(`[Brick-TS] A file storage stores files in the local directory ${driver.local} while NODE_ENV is production. Set local only for development and tests.`);
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
return dirs;
|
|
1423
|
+
}
|
|
1424
|
+
/**
|
|
1425
|
+
* File storage in S3 or an S3-compatible store (R2, MinIO), through Bun's
|
|
1426
|
+
* built-in client. Nothing connects or reads credentials until the first call.
|
|
1427
|
+
* With `local`, files are written under that directory instead.
|
|
1428
|
+
*
|
|
1429
|
+
* @param options - `bucket`, `prefix`, `local`, and the credentials and
|
|
1430
|
+
* `endpoint` Bun's client takes, each a string or a `SecretRef`; left out,
|
|
1431
|
+
* Bun's `S3_*` and `AWS_*` environment variables apply.
|
|
1432
|
+
*/
|
|
1433
|
+
function s3(options = {}) {
|
|
1434
|
+
const prefix = options.prefix ?? "";
|
|
1435
|
+
if (prefix.startsWith("/") || prefix.split("/").some((part) => part === "." || part === "..")) throw new Error(`s3(): prefix must not start with "/" or hold "." or ".." segments, got ${JSON.stringify(prefix)}`);
|
|
1436
|
+
if (options.local !== void 0) return localDriver(resolve(options.local), prefix);
|
|
1437
|
+
let client;
|
|
1438
|
+
const bucket = () => options.bucket || process.env.S3_BUCKET || process.env.AWS_BUCKET;
|
|
1439
|
+
const check = () => {
|
|
1440
|
+
if (!bucket()) throw new Error("s3(): no bucket. Pass bucket, set S3_BUCKET or AWS_BUCKET, or set local for a directory.");
|
|
1441
|
+
};
|
|
1442
|
+
const open = () => {
|
|
1443
|
+
if (client) return client;
|
|
1444
|
+
check();
|
|
1445
|
+
const settings = { bucket: bucket() };
|
|
1446
|
+
for (const name of [
|
|
1447
|
+
"accessKeyId",
|
|
1448
|
+
"secretAccessKey",
|
|
1449
|
+
"sessionToken",
|
|
1450
|
+
"region",
|
|
1451
|
+
"endpoint"
|
|
1452
|
+
]) {
|
|
1453
|
+
const value = options[name];
|
|
1454
|
+
if (value !== void 0) settings[name] = value instanceof SecretRef ? value.require() : value;
|
|
1455
|
+
}
|
|
1456
|
+
return client = new Bun.S3Client(settings);
|
|
1457
|
+
};
|
|
1458
|
+
const presign = (key, expiresInMs, contentDisposition) => open().presign(key, {
|
|
1459
|
+
method: "GET",
|
|
1460
|
+
expiresIn: Math.ceil(expiresInMs / 1e3),
|
|
1461
|
+
...contentDisposition && { contentDisposition }
|
|
1462
|
+
});
|
|
1463
|
+
const rethrowWithoutUrl = async (operation, run) => {
|
|
1464
|
+
try {
|
|
1465
|
+
return await run();
|
|
1466
|
+
} catch (error) {
|
|
1467
|
+
const code = error.code;
|
|
1468
|
+
throw new Error(`File storage: S3 failed ${operation} a file${typeof code === "string" ? ` (${code})` : ""}`);
|
|
1469
|
+
}
|
|
1470
|
+
};
|
|
1471
|
+
return {
|
|
1472
|
+
kind: "file",
|
|
1473
|
+
prefix,
|
|
1474
|
+
check,
|
|
1475
|
+
write: async (key, file, contentType) => {
|
|
1476
|
+
const client = open();
|
|
1477
|
+
await rethrowWithoutUrl("writing", () => client.write(key, file, { type: contentType }));
|
|
1478
|
+
},
|
|
1479
|
+
read: async (key) => {
|
|
1480
|
+
const url = presign(key, 6e4);
|
|
1481
|
+
const stalled = new AbortController();
|
|
1482
|
+
let idle;
|
|
1483
|
+
const stillMoving = () => {
|
|
1484
|
+
clearTimeout(idle);
|
|
1485
|
+
idle = setTimeout(() => stalled.abort(), S3_READ_IDLE_TIMEOUT_MS);
|
|
1486
|
+
};
|
|
1487
|
+
stillMoving();
|
|
1488
|
+
try {
|
|
1489
|
+
const response = await rethrowWithoutUrl("reading", () => fetch(url, { signal: stalled.signal }));
|
|
1490
|
+
if (response.status === 404) return void 0;
|
|
1491
|
+
if (!response.ok) throw new Error(`File storage: S3 answered ${response.status} reading a file`);
|
|
1492
|
+
return await rethrowWithoutUrl("reading", async () => {
|
|
1493
|
+
const chunks = [];
|
|
1494
|
+
for await (const chunk of response.body ?? []) {
|
|
1495
|
+
stillMoving();
|
|
1496
|
+
chunks.push(chunk);
|
|
1497
|
+
}
|
|
1498
|
+
return new Blob(chunks, { type: response.headers.get("content-type") ?? "" });
|
|
1499
|
+
});
|
|
1500
|
+
} finally {
|
|
1501
|
+
clearTimeout(idle);
|
|
1502
|
+
}
|
|
1503
|
+
},
|
|
1504
|
+
remove: async (key) => {
|
|
1505
|
+
const client = open();
|
|
1506
|
+
await rethrowWithoutUrl("deleting", () => client.delete(key));
|
|
1507
|
+
},
|
|
1508
|
+
sign: async (key, expiresInMs, contentDisposition) => presign(key, expiresInMs, contentDisposition)
|
|
1509
|
+
};
|
|
1510
|
+
}
|
|
1511
|
+
const perProcessLinkKey = globalThis[Symbol.for("brickkit.storage.files.linkKey")] ??= randomBytes(32);
|
|
1512
|
+
const mac = (payload) => createHmac("sha256", perProcessLinkKey).update(payload).digest();
|
|
1513
|
+
function signFileLink(claims) {
|
|
1514
|
+
const payload = Buffer.from(JSON.stringify(claims)).toString("base64url");
|
|
1515
|
+
return `${payload}.${mac(payload).toString("base64url")}`;
|
|
1516
|
+
}
|
|
1517
|
+
function verifyFileLink(token) {
|
|
1518
|
+
const dot = token?.indexOf(".") ?? -1;
|
|
1519
|
+
if (!token || dot < 0) return void 0;
|
|
1520
|
+
const payload = token.slice(0, dot);
|
|
1521
|
+
const given = Buffer.from(token.slice(dot + 1), "base64url");
|
|
1522
|
+
const expected = mac(payload);
|
|
1523
|
+
if (given.length !== expected.length || !timingSafeEqual(given, expected)) return void 0;
|
|
1524
|
+
try {
|
|
1525
|
+
const claims = JSON.parse(Buffer.from(payload, "base64url").toString());
|
|
1526
|
+
return typeof claims.expiresAt === "number" && claims.expiresAt > Date.now() ? claims : void 0;
|
|
1527
|
+
} catch {
|
|
1528
|
+
return;
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
async function localPath(dir, key) {
|
|
1532
|
+
const folder = relative(dir, dirname(join(dir, key)));
|
|
1533
|
+
if (folder.split(sep).includes("..")) return void 0;
|
|
1534
|
+
try {
|
|
1535
|
+
const [root, real] = await Promise.all([realpath(dir), realpath(join(dir, folder))]);
|
|
1536
|
+
return real === join(root, folder) ? join(real, basename(key)) : void 0;
|
|
1537
|
+
} catch (error) {
|
|
1538
|
+
if (["ENOENT", "ENOTDIR"].includes(error.code)) return void 0;
|
|
1539
|
+
throw error;
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
const isFile = (path) => lstat(path).then((stat) => stat.isFile(), (error) => {
|
|
1543
|
+
if (["ENOENT", "ENOTDIR"].includes(error.code)) return false;
|
|
1544
|
+
throw error;
|
|
1545
|
+
});
|
|
1546
|
+
async function readLocal(dir, key) {
|
|
1547
|
+
const path = await localPath(dir, key);
|
|
1548
|
+
if (!path || !await isFile(path) || !await isFile(`${path}.type`)) return void 0;
|
|
1549
|
+
const type = await readFile(`${path}.type`, "utf8");
|
|
1550
|
+
return new Blob([await readFile(path)], { type });
|
|
1551
|
+
}
|
|
1552
|
+
const outsideDir = () => /* @__PURE__ */ new Error("File storage: the file's folder is not inside the local directory; refusing to follow a symlink");
|
|
1553
|
+
function localDriver(dir, prefix) {
|
|
1554
|
+
return {
|
|
1555
|
+
kind: "file",
|
|
1556
|
+
prefix,
|
|
1557
|
+
local: dir,
|
|
1558
|
+
write: async (key, file, contentType) => {
|
|
1559
|
+
await mkdir(dirname(join(dir, key)), { recursive: true });
|
|
1560
|
+
const path = await localPath(dir, key);
|
|
1561
|
+
if (!path) throw outsideDir();
|
|
1562
|
+
await Bun.write(`${path}.type`, contentType);
|
|
1563
|
+
await Bun.write(path, file);
|
|
1564
|
+
},
|
|
1565
|
+
read: (key) => readLocal(dir, key),
|
|
1566
|
+
remove: async (key) => {
|
|
1567
|
+
const path = await localPath(dir, key);
|
|
1568
|
+
if (!path) return;
|
|
1569
|
+
await rm(path, { force: true });
|
|
1570
|
+
await rm(`${path}.type`, { force: true });
|
|
1571
|
+
},
|
|
1572
|
+
sign: async (key, expiresInMs, contentDisposition) => `${LOCAL_FILES_ROUTE}?token=${signFileLink({
|
|
1573
|
+
dirDigest: sha256(dir),
|
|
1574
|
+
key,
|
|
1575
|
+
expiresAt: Date.now() + expiresInMs,
|
|
1576
|
+
disposition: contentDisposition
|
|
1577
|
+
})}`
|
|
1578
|
+
};
|
|
1579
|
+
}
|
|
1580
|
+
function localFilesRoute(dirs) {
|
|
1581
|
+
const byDigest = new Map([...dirs].map((dir) => [sha256(dir), dir]));
|
|
1582
|
+
return async ({ request }) => {
|
|
1583
|
+
const claims = verifyFileLink(new URL(request.url).searchParams.get("token"));
|
|
1584
|
+
const dir = claims && byDigest.get(claims.dirDigest);
|
|
1585
|
+
if (!claims || !dir) return new Response("Invalid or expired link", { status: 403 });
|
|
1586
|
+
const file = await readLocal(dir, claims.key);
|
|
1587
|
+
if (!file) return new Response("Not found", { status: 404 });
|
|
1588
|
+
return new Response(file, { headers: {
|
|
1589
|
+
"content-type": file.type,
|
|
1590
|
+
"content-disposition": claims.disposition,
|
|
1591
|
+
"x-content-type-options": "nosniff",
|
|
1592
|
+
"cache-control": "private, no-store"
|
|
1593
|
+
} });
|
|
1594
|
+
};
|
|
1595
|
+
}
|
|
1596
|
+
// src/socket-redis.ts
|
|
1597
|
+
/** Exponential backoff from 500 ms to 30 s, with jitter so processes don't reconnect in step. */
|
|
1598
|
+
function reconnectDelay(failures) {
|
|
1599
|
+
const ceiling = Math.min(3e4, 500 * 2 ** failures);
|
|
1600
|
+
return ceiling / 2 + Math.random() * (ceiling / 2);
|
|
1601
|
+
}
|
|
1602
|
+
/** How long a call waits for Redis to connect before going on without it. */
|
|
1603
|
+
const REDIS_WAIT_MS = 1e3;
|
|
1604
|
+
/** One Redis connection that reconnects by itself and reports each fresh connection. */
|
|
1605
|
+
function connection(url, connected) {
|
|
1606
|
+
let redis;
|
|
1607
|
+
let timer;
|
|
1608
|
+
let closed = false;
|
|
1609
|
+
let failures = 0;
|
|
1610
|
+
let failure;
|
|
1611
|
+
const waiters = [];
|
|
1612
|
+
const lost = (client) => {
|
|
1613
|
+
if (redis !== client) return;
|
|
1614
|
+
redis = void 0;
|
|
1615
|
+
if (closed || timer) return;
|
|
1616
|
+
timer = setTimeout(() => {
|
|
1617
|
+
timer = void 0;
|
|
1618
|
+
start();
|
|
1619
|
+
}, reconnectDelay(failures++));
|
|
1620
|
+
timer.unref();
|
|
1621
|
+
};
|
|
1622
|
+
const start = () => {
|
|
1623
|
+
if (closed || redis || timer) return;
|
|
1624
|
+
const client = new Bun.RedisClient(url, {
|
|
1625
|
+
autoReconnect: false,
|
|
1626
|
+
enableOfflineQueue: false
|
|
1627
|
+
});
|
|
1628
|
+
redis = client;
|
|
1629
|
+
client.onclose = () => lost(client);
|
|
1630
|
+
client.connect().then(() => {
|
|
1631
|
+
if (redis !== client) return;
|
|
1632
|
+
failures = 0;
|
|
1633
|
+
failure = void 0;
|
|
1634
|
+
connected(client);
|
|
1635
|
+
for (const wake of waiters.splice(0)) wake();
|
|
1636
|
+
}, (error) => {
|
|
1637
|
+
failure = error;
|
|
1638
|
+
lost(client);
|
|
1639
|
+
});
|
|
1640
|
+
};
|
|
1641
|
+
return {
|
|
1642
|
+
get() {
|
|
1643
|
+
start();
|
|
1644
|
+
return redis?.connected ? redis : void 0;
|
|
1645
|
+
},
|
|
1646
|
+
failure: () => failure,
|
|
1647
|
+
/** Resolves after the next connection is made and announced, or after `ms`. */
|
|
1648
|
+
opened(ms) {
|
|
1649
|
+
if (redis?.connected) return Promise.resolve();
|
|
1650
|
+
start();
|
|
1651
|
+
return new Promise((resolve) => {
|
|
1652
|
+
const timeout = setTimeout(resolve, ms);
|
|
1653
|
+
waiters.push(() => {
|
|
1654
|
+
clearTimeout(timeout);
|
|
1655
|
+
resolve();
|
|
1656
|
+
});
|
|
1657
|
+
});
|
|
1658
|
+
},
|
|
1659
|
+
close() {
|
|
1660
|
+
closed = true;
|
|
1661
|
+
clearTimeout(timer);
|
|
1662
|
+
for (const wake of waiters.splice(0)) wake();
|
|
1663
|
+
const client = redis;
|
|
1664
|
+
redis = void 0;
|
|
1665
|
+
client?.close();
|
|
1666
|
+
}
|
|
1667
|
+
};
|
|
1668
|
+
}
|
|
1669
|
+
/**
|
|
1670
|
+
* Fans socket emits and kicks out across processes through Redis pub/sub, one
|
|
1671
|
+
* channel per room topic. An emit is a PUBLISH only: every process, the emitting
|
|
1672
|
+
* one included, delivers it once to its own connections. Uses Bun's built-in
|
|
1673
|
+
* Redis client and two connections, one to publish and one to subscribe.
|
|
1674
|
+
*/
|
|
1675
|
+
function redisBroker(options = {}) {
|
|
1676
|
+
const limit = options.queue ?? 1e3;
|
|
1677
|
+
if (!Number.isInteger(limit) || limit < 0) throw new Error("redisBroker queue must be a nonnegative integer");
|
|
1678
|
+
const channel = (topic) => `brick:socket:${topic}`;
|
|
1679
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
1680
|
+
const pending = /* @__PURE__ */ new Map();
|
|
1681
|
+
const stream = (topic) => `brick:socket:stream:${topic}`;
|
|
1682
|
+
const warned = /* @__PURE__ */ new Set();
|
|
1683
|
+
const warn = (what) => (error) => {
|
|
1684
|
+
if (warned.has(what)) return;
|
|
1685
|
+
warned.add(what);
|
|
1686
|
+
console.warn(`[Brick-TS] Redis socket broker: ${what} failed; later failures of it are not logged.`, error);
|
|
1687
|
+
};
|
|
1688
|
+
const queue = [];
|
|
1689
|
+
const send = (work) => {
|
|
1690
|
+
const redis = publisher.get();
|
|
1691
|
+
if (redis) return work(redis);
|
|
1692
|
+
queue.push(work);
|
|
1693
|
+
if (queue.length > limit) queue.shift();
|
|
1694
|
+
};
|
|
1695
|
+
const receive = (payload, name) => {
|
|
1696
|
+
let message;
|
|
1697
|
+
try {
|
|
1698
|
+
message = JSON.parse(payload);
|
|
1699
|
+
} catch {
|
|
1700
|
+
return;
|
|
1701
|
+
}
|
|
1702
|
+
for (const deliver of listeners.get(name) ?? []) deliver(message);
|
|
1703
|
+
};
|
|
1704
|
+
const subscribe = (redis, name) => {
|
|
1705
|
+
const done = redis.subscribe(name, receive).catch(warn("SUBSCRIBE"));
|
|
1706
|
+
pending.set(name, done);
|
|
1707
|
+
done.then(() => {
|
|
1708
|
+
if (pending.get(name) === done) pending.delete(name);
|
|
1709
|
+
});
|
|
1710
|
+
};
|
|
1711
|
+
const publisher = connection(options.url, (redis) => {
|
|
1712
|
+
for (const work of queue.splice(0)) work(redis);
|
|
1713
|
+
});
|
|
1714
|
+
const subscriber = connection(options.url, (redis) => {
|
|
1715
|
+
for (const name of listeners.keys()) subscribe(redis, name);
|
|
1716
|
+
});
|
|
1717
|
+
return {
|
|
1718
|
+
publish(message, replay) {
|
|
1719
|
+
const name = channel(message.topic);
|
|
1720
|
+
if (message.type !== "emit" || !replay) return send((redis) => void redis.publish(name, JSON.stringify(message)).catch(warn("PUBLISH")));
|
|
1721
|
+
const key = stream(message.topic);
|
|
1722
|
+
send((redis) => {
|
|
1723
|
+
redis.send("XADD", [
|
|
1724
|
+
key,
|
|
1725
|
+
"MAXLEN",
|
|
1726
|
+
"~",
|
|
1727
|
+
String(replay.keep),
|
|
1728
|
+
"*",
|
|
1729
|
+
"m",
|
|
1730
|
+
message.frame
|
|
1731
|
+
]).then((seq) => {
|
|
1732
|
+
redis.send("PEXPIRE", [key, String(replay.maxAgeMs)]).catch(warn("PEXPIRE"));
|
|
1733
|
+
return redis.publish(name, JSON.stringify({
|
|
1734
|
+
...message,
|
|
1735
|
+
seq
|
|
1736
|
+
}));
|
|
1737
|
+
}).catch(warn("XADD/PUBLISH"));
|
|
1738
|
+
});
|
|
1739
|
+
},
|
|
1740
|
+
async head() {
|
|
1741
|
+
try {
|
|
1742
|
+
await publisher.opened(REDIS_WAIT_MS);
|
|
1743
|
+
const [seconds, micros] = await publisher.get().send("TIME", []);
|
|
1744
|
+
return `${Number(seconds) * 1e3 + Math.floor(Number(micros) / 1e3) - 1}-0`;
|
|
1745
|
+
} catch {
|
|
1746
|
+
return `${Date.now() - 1}-0`;
|
|
1747
|
+
}
|
|
1748
|
+
},
|
|
1749
|
+
async history(topic, since, replay) {
|
|
1750
|
+
let raw;
|
|
1751
|
+
try {
|
|
1752
|
+
await publisher.opened(REDIS_WAIT_MS);
|
|
1753
|
+
raw = await publisher.get().send("XRANGE", [
|
|
1754
|
+
stream(topic),
|
|
1755
|
+
"-",
|
|
1756
|
+
"+"
|
|
1757
|
+
]);
|
|
1758
|
+
} catch {
|
|
1759
|
+
return;
|
|
1760
|
+
}
|
|
1761
|
+
const ms = (seq) => Number(seq.split("-")[0]);
|
|
1762
|
+
const after = raw.filter(([id]) => compareSocketSeq(id, since) > 0);
|
|
1763
|
+
if (after.length === raw.length && (raw.length >= replay.keep || (raw[0] ? ms(raw[0][0]) : Date.now()) - ms(since) >= replay.maxAgeMs)) return void 0;
|
|
1764
|
+
return after.map(([seq, fields]) => ({
|
|
1765
|
+
type: "emit",
|
|
1766
|
+
topic,
|
|
1767
|
+
frame: fields[fields.indexOf("m") + 1],
|
|
1768
|
+
seq
|
|
1769
|
+
}));
|
|
1770
|
+
},
|
|
1771
|
+
subscribe(topic, deliver) {
|
|
1772
|
+
const name = channel(topic);
|
|
1773
|
+
let local = listeners.get(name);
|
|
1774
|
+
if (!local) {
|
|
1775
|
+
local = /* @__PURE__ */ new Set();
|
|
1776
|
+
listeners.set(name, local);
|
|
1777
|
+
const redis = subscriber.get();
|
|
1778
|
+
if (redis) subscribe(redis, name);
|
|
1779
|
+
}
|
|
1780
|
+
local.add(deliver);
|
|
1781
|
+
return () => {
|
|
1782
|
+
local.delete(deliver);
|
|
1783
|
+
if (local.size || listeners.get(name) !== local) return;
|
|
1784
|
+
listeners.delete(name);
|
|
1785
|
+
pending.delete(name);
|
|
1786
|
+
subscriber.get()?.unsubscribe(name).catch(warn("UNSUBSCRIBE"));
|
|
1787
|
+
};
|
|
1788
|
+
},
|
|
1789
|
+
async ready(topic) {
|
|
1790
|
+
const name = channel(topic);
|
|
1791
|
+
if (!pending.has(name)) await subscriber.opened(REDIS_WAIT_MS);
|
|
1792
|
+
await pending.get(name);
|
|
1793
|
+
},
|
|
1794
|
+
close() {
|
|
1795
|
+
publisher.close();
|
|
1796
|
+
subscriber.close();
|
|
1797
|
+
}
|
|
1798
|
+
};
|
|
1799
|
+
}
|
|
1800
|
+
// src/storage.ts
|
|
1801
|
+
/** A storage could not be reached, or did not answer in time. Thrown by every call while it is down. A write that rejects with it may still have been applied. */
|
|
1802
|
+
var StorageUnavailableError = class StorageUnavailableError extends Error {
|
|
1803
|
+
name = "StorageUnavailableError";
|
|
1804
|
+
static [Symbol.hasInstance](value) {
|
|
1805
|
+
if (this !== StorageUnavailableError) return Function.prototype[Symbol.hasInstance].call(this, value);
|
|
1806
|
+
return value instanceof Error && value.name === "StorageUnavailableError";
|
|
1807
|
+
}
|
|
1808
|
+
};
|
|
1809
|
+
const APP_PREFIX = "app:";
|
|
1810
|
+
const BRICK_PREFIX = "brick:storage:";
|
|
1811
|
+
/** The framework side of each storage handle; global so a second core copy finds it. */
|
|
1812
|
+
const frameworkSides = globalThis[Symbol.for("brickkit.storage")] ??= /* @__PURE__ */ new WeakMap();
|
|
1813
|
+
const users = globalThis[Symbol.for("brickkit.storage.users")] ??= /* @__PURE__ */ new WeakMap();
|
|
1814
|
+
function notACounter(key) {
|
|
1815
|
+
return /* @__PURE__ */ new Error(`Storage: "${key}" does not hold a counter`);
|
|
1816
|
+
}
|
|
1817
|
+
function counterOverflow(key) {
|
|
1818
|
+
return /* @__PURE__ */ new Error(`Storage: incrementing "${key}" would overflow`);
|
|
1819
|
+
}
|
|
1820
|
+
function ttl(ttlMs, required) {
|
|
1821
|
+
if (ttlMs === void 0 && !required) return;
|
|
1822
|
+
if (!Number.isSafeInteger(ttlMs) || ttlMs <= 0) throw new Error(`Storage ttlMs must be a positive integer, got ${ttlMs}`);
|
|
1823
|
+
}
|
|
1824
|
+
function storageKey(feature, parts) {
|
|
1825
|
+
return `${feature}:${JSON.stringify(parts.map((part) => typeof part === "string" && part.length > 128 ? { sha256: createHash("sha256").update(part).digest("hex") } : part))}`;
|
|
1826
|
+
}
|
|
1827
|
+
function side(driver, prefix) {
|
|
1828
|
+
return Object.freeze({
|
|
1829
|
+
kind: "key-value",
|
|
1830
|
+
get: async (key) => driver.get(prefix + key),
|
|
1831
|
+
put: async (key, value, ttlMs) => {
|
|
1832
|
+
ttl(ttlMs, false);
|
|
1833
|
+
return driver.put(prefix + key, value, ttlMs);
|
|
1834
|
+
},
|
|
1835
|
+
putIfAbsent: async (key, value, ttlMs) => {
|
|
1836
|
+
ttl(ttlMs, true);
|
|
1837
|
+
return driver.putIfAbsent(prefix + key, value, ttlMs);
|
|
1838
|
+
},
|
|
1839
|
+
increment: async (key, ttlMs) => {
|
|
1840
|
+
ttl(ttlMs, true);
|
|
1841
|
+
return driver.increment(prefix + key, ttlMs);
|
|
1842
|
+
},
|
|
1843
|
+
delete: async (key) => driver.delete(prefix + key),
|
|
1844
|
+
close: async () => driver.close()
|
|
1845
|
+
});
|
|
1846
|
+
}
|
|
1847
|
+
/**
|
|
1848
|
+
* Declare a storage. The driver decides its kind: `redis()` and `memory()` make
|
|
1849
|
+
* key-value storage, `s3()` file storage kept per tenant. Pass it to a service
|
|
1850
|
+
* as a dep, and read it as `ctx.deps.<name>`. Nothing connects until the first call.
|
|
1851
|
+
*
|
|
1852
|
+
* @param options - `driver`: `redis({ url })`, or `memory()` for tests and local
|
|
1853
|
+
* development; `s3({ bucket, prefix, local })` for files.
|
|
1854
|
+
* @returns The handle. Key-value: `get`, `put`, `putIfAbsent`, `increment`,
|
|
1855
|
+
* `delete` and `close`. File: `put`, `url`, `get`, `delete` in the caller's
|
|
1856
|
+
* tenant, and `in(tenant)` outside a request.
|
|
1857
|
+
* @example
|
|
1858
|
+
* export const cache = defineStorage({ driver: redis({ url: process.env.REDIS_URL }) });
|
|
1859
|
+
* export const auth = defineService("auth", { deps: { cache } });
|
|
1860
|
+
* // in an action
|
|
1861
|
+
* await ctx.deps.cache.put(`otp:${input.email}`, code, 5 * 60_000);
|
|
1862
|
+
*/
|
|
1863
|
+
function defineStorage(options) {
|
|
1864
|
+
const driver = options?.driver;
|
|
1865
|
+
if (driver?.kind === "file") return fileStorage(driver);
|
|
1866
|
+
if (driver?.kind !== "key-value") throw new Error("defineStorage needs a driver, such as redis(), memory() or s3()");
|
|
1867
|
+
const handle = side(driver, APP_PREFIX);
|
|
1868
|
+
frameworkSides.set(handle, Object.freeze({
|
|
1869
|
+
...side(driver, BRICK_PREFIX),
|
|
1870
|
+
compareAndDelete: async (key, expected) => driver.compareAndDelete(BRICK_PREFIX + key, expected)
|
|
1871
|
+
}));
|
|
1872
|
+
return handle;
|
|
1873
|
+
}
|
|
1874
|
+
function serviceStorage(service, deps = portOf(service).deps) {
|
|
1875
|
+
const found = Object.entries(deps).filter(([, value], index, all) => frameworkSides.has(value) && all.findIndex(([, other]) => other === value) === index);
|
|
1876
|
+
if (found.length > 1) throw new Error(`Service "${service.name}" has two key-value storages in its deps, "${found[0][0]}" and "${found[1][0]}"; Brick needs one for its own keys. Keep one of them on this service.`);
|
|
1877
|
+
return found[0] && frameworkSides.get(found[0][1]);
|
|
1878
|
+
}
|
|
1879
|
+
function useStorages(deps) {
|
|
1880
|
+
const handles = new Set(deps.flatMap((values) => Object.values(values).filter((value) => frameworkSides.has(value))));
|
|
1881
|
+
for (const handle of handles) users.set(handle, (users.get(handle) ?? 0) + 1);
|
|
1882
|
+
let released = false;
|
|
1883
|
+
return async () => {
|
|
1884
|
+
if (released) return;
|
|
1885
|
+
released = true;
|
|
1886
|
+
const unused = [...handles].filter((handle) => {
|
|
1887
|
+
const left = users.get(handle) - 1;
|
|
1888
|
+
users.set(handle, left);
|
|
1889
|
+
return left === 0;
|
|
1890
|
+
});
|
|
1891
|
+
await Promise.all(unused.map((handle) => handle.close()));
|
|
1892
|
+
};
|
|
1893
|
+
}
|
|
1894
|
+
const NOT_A_COUNTER = "BRICK_NOT_A_COUNTER";
|
|
1895
|
+
const INCREMENT = `local n = redis.pcall('INCR', KEYS[1])
|
|
1896
|
+
if type(n) == 'table' and n.err then
|
|
1897
|
+
if string.find(n.err, '^WRONGTYPE') or string.find(n.err, 'not an integer') then return redis.error_reply('${NOT_A_COUNTER}') end
|
|
1898
|
+
return n
|
|
1899
|
+
end
|
|
1900
|
+
local t = redis.call('PTTL', KEYS[1])
|
|
1901
|
+
if t < 0 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) t = tonumber(ARGV[1]) end
|
|
1902
|
+
return {n, t}`;
|
|
1903
|
+
const PUT_IF_ABSENT = `if redis.call('SET', KEYS[1], ARGV[1], 'NX', 'PX', ARGV[2]) then return {1, ARGV[1]} end
|
|
1904
|
+
return {0, redis.call('GET', KEYS[1])}`;
|
|
1905
|
+
const COMPARE_AND_DELETE = `if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
|
|
1906
|
+
return 0`;
|
|
1907
|
+
const TIMED_OUT = Symbol("timed out");
|
|
1908
|
+
const UNAVAILABLE_REPLY = /^(LOADING|READONLY|OOM|BUSY|MASTERDOWN|CLUSTERDOWN|NOREPLICAS|MISCONF|TRYAGAIN)\b/;
|
|
1909
|
+
/**
|
|
1910
|
+
* Key-value storage in Redis, through Bun's built-in client. Connects on first
|
|
1911
|
+
* use and reconnects by itself. While Redis is unreachable, calls reject with
|
|
1912
|
+
* `StorageUnavailableError`: the first after about a second, the rest at once.
|
|
1913
|
+
* A command Redis doesn't answer within a second rejects the same way, and the
|
|
1914
|
+
* connection is dropped so the next call opens a fresh one.
|
|
1915
|
+
*
|
|
1916
|
+
* @param options - `url`: defaults to `REDIS_URL`, then `redis://localhost:6379`.
|
|
1917
|
+
* `prefix`: put in front of every key, to share one Redis database between apps.
|
|
1918
|
+
*/
|
|
1919
|
+
function redis(options = {}) {
|
|
1920
|
+
const prefix = options.prefix ?? "";
|
|
1921
|
+
let conn;
|
|
1922
|
+
let down = false;
|
|
1923
|
+
const send = async (command, args) => {
|
|
1924
|
+
const current = conn ??= connection(options.url, () => {
|
|
1925
|
+
down = false;
|
|
1926
|
+
});
|
|
1927
|
+
if (!down) await current.opened(REDIS_WAIT_MS);
|
|
1928
|
+
const closedMeanwhile = () => conn !== current;
|
|
1929
|
+
const client = current.get();
|
|
1930
|
+
if (!client) {
|
|
1931
|
+
if (!closedMeanwhile()) down = true;
|
|
1932
|
+
throw new StorageUnavailableError("Storage: Redis is unreachable", { cause: current.failure() });
|
|
1933
|
+
}
|
|
1934
|
+
let timer;
|
|
1935
|
+
try {
|
|
1936
|
+
return await Promise.race([client.send(command, args), new Promise((_, reject) => {
|
|
1937
|
+
timer = setTimeout(reject, REDIS_WAIT_MS, TIMED_OUT);
|
|
1938
|
+
})]);
|
|
1939
|
+
} catch (error) {
|
|
1940
|
+
if (error === TIMED_OUT) {
|
|
1941
|
+
if (!closedMeanwhile()) {
|
|
1942
|
+
conn = void 0;
|
|
1943
|
+
down = false;
|
|
1944
|
+
}
|
|
1945
|
+
current.close();
|
|
1946
|
+
throw new StorageUnavailableError(`Storage: Redis did not answer within ${REDIS_WAIT_MS} ms`);
|
|
1947
|
+
}
|
|
1948
|
+
if (client.connected) {
|
|
1949
|
+
if (UNAVAILABLE_REPLY.test(String(error?.message))) throw new StorageUnavailableError(`Storage: Redis cannot serve the command right now (${error.message})`, { cause: error });
|
|
1950
|
+
throw error;
|
|
1951
|
+
}
|
|
1952
|
+
throw new StorageUnavailableError("Storage: the Redis connection was lost", { cause: error });
|
|
1953
|
+
} finally {
|
|
1954
|
+
clearTimeout(timer);
|
|
1955
|
+
}
|
|
1956
|
+
};
|
|
1957
|
+
return {
|
|
1958
|
+
kind: "key-value",
|
|
1959
|
+
get: (key) => send("GET", [prefix + key]),
|
|
1960
|
+
put: async (key, value, ttlMs) => {
|
|
1961
|
+
const args = [prefix + key, value];
|
|
1962
|
+
await send("SET", ttlMs === void 0 ? args : [
|
|
1963
|
+
...args,
|
|
1964
|
+
"PX",
|
|
1965
|
+
String(ttlMs)
|
|
1966
|
+
]);
|
|
1967
|
+
},
|
|
1968
|
+
putIfAbsent: async (key, value, ttlMs) => {
|
|
1969
|
+
const [stored, now] = await send("EVAL", [
|
|
1970
|
+
PUT_IF_ABSENT,
|
|
1971
|
+
"1",
|
|
1972
|
+
prefix + key,
|
|
1973
|
+
value,
|
|
1974
|
+
String(ttlMs)
|
|
1975
|
+
]);
|
|
1976
|
+
return {
|
|
1977
|
+
stored: stored === 1,
|
|
1978
|
+
value: now
|
|
1979
|
+
};
|
|
1980
|
+
},
|
|
1981
|
+
increment: async (key, ttlMs) => {
|
|
1982
|
+
const [count, expiresInMs] = await send("EVAL", [
|
|
1983
|
+
INCREMENT,
|
|
1984
|
+
"1",
|
|
1985
|
+
prefix + key,
|
|
1986
|
+
String(ttlMs)
|
|
1987
|
+
]).catch((error) => {
|
|
1988
|
+
throw String(error?.message).includes(NOT_A_COUNTER) ? notACounter(key) : error;
|
|
1989
|
+
});
|
|
1990
|
+
return {
|
|
1991
|
+
count: Number(count),
|
|
1992
|
+
expiresInMs: Math.max(1, Number(expiresInMs))
|
|
1993
|
+
};
|
|
1994
|
+
},
|
|
1995
|
+
delete: async (key) => {
|
|
1996
|
+
await send("DEL", [prefix + key]);
|
|
1997
|
+
},
|
|
1998
|
+
compareAndDelete: async (key, expected) => await send("EVAL", [
|
|
1999
|
+
COMPARE_AND_DELETE,
|
|
2000
|
+
"1",
|
|
2001
|
+
prefix + key,
|
|
2002
|
+
expected
|
|
2003
|
+
]) === 1,
|
|
2004
|
+
close: async () => {
|
|
2005
|
+
conn?.close();
|
|
2006
|
+
conn = void 0;
|
|
2007
|
+
down = false;
|
|
2008
|
+
}
|
|
2009
|
+
};
|
|
2010
|
+
}
|
|
2011
|
+
/**
|
|
2012
|
+
* Key-value storage in this process's memory, for tests and local development.
|
|
2013
|
+
* Lost on restart and not shared between processes.
|
|
2014
|
+
*/
|
|
2015
|
+
function memory() {
|
|
2016
|
+
const entries = /* @__PURE__ */ new Map();
|
|
2017
|
+
const readEvictingExpired = (key) => {
|
|
2018
|
+
const entry = entries.get(key);
|
|
2019
|
+
if (entry?.expiresAt !== void 0 && entry.expiresAt <= Date.now()) {
|
|
2020
|
+
entries.delete(key);
|
|
2021
|
+
return;
|
|
2022
|
+
}
|
|
2023
|
+
return entry;
|
|
2024
|
+
};
|
|
2025
|
+
const expiry = (ttlMs) => ttlMs === void 0 ? void 0 : Date.now() + ttlMs;
|
|
2026
|
+
return {
|
|
2027
|
+
kind: "key-value",
|
|
2028
|
+
get: async (key) => readEvictingExpired(key)?.value ?? null,
|
|
2029
|
+
put: async (key, value, ttlMs) => {
|
|
2030
|
+
entries.set(key, {
|
|
2031
|
+
value,
|
|
2032
|
+
expiresAt: expiry(ttlMs)
|
|
2033
|
+
});
|
|
2034
|
+
},
|
|
2035
|
+
putIfAbsent: async (key, value, ttlMs) => {
|
|
2036
|
+
const entry = readEvictingExpired(key);
|
|
2037
|
+
if (entry) return {
|
|
2038
|
+
stored: false,
|
|
2039
|
+
value: entry.value
|
|
2040
|
+
};
|
|
2041
|
+
entries.set(key, {
|
|
2042
|
+
value,
|
|
2043
|
+
expiresAt: expiry(ttlMs)
|
|
2044
|
+
});
|
|
2045
|
+
return {
|
|
2046
|
+
stored: true,
|
|
2047
|
+
value
|
|
2048
|
+
};
|
|
2049
|
+
},
|
|
2050
|
+
increment: async (key, ttlMs) => {
|
|
2051
|
+
const entry = readEvictingExpired(key) ?? { value: "0" };
|
|
2052
|
+
const count = Number(entry.value) + 1;
|
|
2053
|
+
if (!/^(0|-?[1-9][0-9]*)$/.test(entry.value)) throw notACounter(key);
|
|
2054
|
+
if (!Number.isSafeInteger(count)) throw counterOverflow(key);
|
|
2055
|
+
const expiresAt = entry.expiresAt ?? Date.now() + ttlMs;
|
|
2056
|
+
entries.set(key, {
|
|
2057
|
+
value: String(count),
|
|
2058
|
+
expiresAt
|
|
2059
|
+
});
|
|
2060
|
+
return {
|
|
2061
|
+
count,
|
|
2062
|
+
expiresInMs: Math.max(1, expiresAt - Date.now())
|
|
2063
|
+
};
|
|
2064
|
+
},
|
|
2065
|
+
delete: async (key) => {
|
|
2066
|
+
entries.delete(key);
|
|
2067
|
+
},
|
|
2068
|
+
compareAndDelete: async (key, expected) => readEvictingExpired(key)?.value === expected && entries.delete(key),
|
|
2069
|
+
close: async () => {}
|
|
2070
|
+
};
|
|
2071
|
+
}
|
|
2072
|
+
// src/rate-limit.ts
|
|
2073
|
+
const SOURCE = Symbol.for("brickkit.addressSource");
|
|
2074
|
+
const CLIENT_REQUEST = Symbol.for("brickkit.clientRequest");
|
|
2075
|
+
function markAddressSource(request, source) {
|
|
2076
|
+
request[SOURCE] = source;
|
|
2077
|
+
}
|
|
2078
|
+
function withClientIp(request, clientIp) {
|
|
2079
|
+
const app = request[SOURCE];
|
|
2080
|
+
markAddressSource(request, {
|
|
2081
|
+
clientIp,
|
|
2082
|
+
server: app?.server ?? noServer
|
|
2083
|
+
});
|
|
2084
|
+
}
|
|
2085
|
+
const noServer = () => void 0;
|
|
2086
|
+
function clientRequestOf(ctx) {
|
|
2087
|
+
const request = ctx[CLIENT_REQUEST] ?? ctx.request;
|
|
2088
|
+
return request?.[SOURCE] ? request : void 0;
|
|
2089
|
+
}
|
|
2090
|
+
function carryClientRequest(envelope, from) {
|
|
2091
|
+
const request = clientRequestOf(from);
|
|
2092
|
+
if (request) envelope[CLIENT_REQUEST] = request;
|
|
2093
|
+
}
|
|
2094
|
+
/**
|
|
2095
|
+
* The client address of a call as rate limits count it, or `undefined` when it
|
|
2096
|
+
* has none: in-process without a request, or `app.handle` without `clientIp`.
|
|
2097
|
+
* An IPv4-mapped or NAT64 IPv6 address counts as its IPv4 address, any other
|
|
2098
|
+
* IPv6 address by its /64, and every spelling of one address the same. For a
|
|
2099
|
+
* custom `per` that combines it with another key.
|
|
2100
|
+
*
|
|
2101
|
+
* @throws When `clientIp` returns anything but a non-empty string or `undefined`.
|
|
2102
|
+
*/
|
|
2103
|
+
function clientAddress(ctx) {
|
|
2104
|
+
const request = clientRequestOf(ctx);
|
|
2105
|
+
if (!request) return void 0;
|
|
2106
|
+
const source = request[SOURCE];
|
|
2107
|
+
const peer = source.server()?.requestIP(request)?.address ?? void 0;
|
|
2108
|
+
const ip = source.clientIp ? source.clientIp({
|
|
2109
|
+
request,
|
|
2110
|
+
peer
|
|
2111
|
+
}) : peer;
|
|
2112
|
+
if (ip !== void 0 && (typeof ip !== "string" || ip === "")) throw new Error(`clientIp must return a non-empty string, or undefined when there is no address; it returned ${ip === "" ? "an empty string" : ip instanceof Promise ? "a promise (it must not be async)" : String(ip)}`);
|
|
2113
|
+
return ip === void 0 ? void 0 : addressKey(ip);
|
|
2114
|
+
}
|
|
2115
|
+
function addressKey(address) {
|
|
2116
|
+
const ip = address.trim().toLowerCase().replace(/%.*$/, "");
|
|
2117
|
+
if (isIPv4(ip)) return ip;
|
|
2118
|
+
if (!isIPv6(ip)) return address;
|
|
2119
|
+
const [head = "", tail] = ip.split("::");
|
|
2120
|
+
const split = (part) => part ? part.split(":") : [];
|
|
2121
|
+
const left = split(head);
|
|
2122
|
+
const right = split(tail);
|
|
2123
|
+
const groups = (part) => part.flatMap((group) => {
|
|
2124
|
+
if (!group.includes(".")) return [parseInt(group, 16)];
|
|
2125
|
+
const [a, b, c, d] = group.split(".").map(Number);
|
|
2126
|
+
return [a << 8 | b, c << 8 | d];
|
|
2127
|
+
});
|
|
2128
|
+
const l = groups(left);
|
|
2129
|
+
const r = groups(right);
|
|
2130
|
+
const all = [
|
|
2131
|
+
...l,
|
|
2132
|
+
...Array(8 - l.length - r.length).fill(0),
|
|
2133
|
+
...r
|
|
2134
|
+
];
|
|
2135
|
+
const head6 = all.slice(0, 6).join(":");
|
|
2136
|
+
if (head6 === "0:0:0:0:0:65535" || head6 === "100:65435:0:0:0:0") return [
|
|
2137
|
+
all[6] >> 8,
|
|
2138
|
+
all[6] & 255,
|
|
2139
|
+
all[7] >> 8,
|
|
2140
|
+
all[7] & 255
|
|
2141
|
+
].join(".");
|
|
2142
|
+
return `${all.slice(0, 4).map((g) => g.toString(16)).join(":")}::/64`;
|
|
2143
|
+
}
|
|
2144
|
+
function rateLimitsOf(config) {
|
|
2145
|
+
const { rateLimit } = config;
|
|
2146
|
+
if (rateLimit === void 0) return void 0;
|
|
2147
|
+
const limits = Array.isArray(rateLimit) ? rateLimit : [rateLimit];
|
|
2148
|
+
if (!limits.length) throw new Error(`Action '${config.name}': rateLimit is an empty list, which limits nothing. Give it at least one limit, or remove it.`);
|
|
2149
|
+
for (const { per, max, windowMs } of limits) if (!(per === "actor" || per === "ip" || typeof per === "function") || !Number.isSafeInteger(max) || max < 1 || !Number.isSafeInteger(windowMs) || windowMs < 1) throw new Error(`Action '${config.name}': each rateLimit needs per ("actor", "ip" or a function) and max and windowMs as positive integers`);
|
|
2150
|
+
return limits;
|
|
2151
|
+
}
|
|
2152
|
+
function checkRateLimits(service, action, deps) {
|
|
2153
|
+
const limits = rateLimitsOf(action.config);
|
|
2154
|
+
if (!limits) return;
|
|
2155
|
+
if (!storageOf(service, deps)) throw noStorage(service, action.name);
|
|
2156
|
+
if (limits.some((limit) => limit.per === "actor") && !hasIdentity(service)) throw new Error(`Service "${service.name}": action '${action.name}' limits per "actor", but the service declares no identity. Add identity: (ctx) => ctx.user && { id: ctx.user.id } to defineService("${service.name}", { ... }).`);
|
|
2157
|
+
}
|
|
2158
|
+
function storageOf(service, deps) {
|
|
2159
|
+
return serviceStorage(service, deps) ?? serviceStorage(service);
|
|
2160
|
+
}
|
|
2161
|
+
function noStorage(service, action) {
|
|
2162
|
+
return /* @__PURE__ */ new Error(`Service "${service.name}": action '${action}' declares rateLimit, but the service has no key-value storage to count in. Add one: defineService("${service.name}", { deps: { cache: defineStorage({ driver: redis() }) } }).`);
|
|
2163
|
+
}
|
|
2164
|
+
const QUIET_MS = 1e4;
|
|
2165
|
+
const PROBE_MS = 1e3;
|
|
2166
|
+
const SWEEP_MS = 1e3;
|
|
2167
|
+
const fallbacks = /* @__PURE__ */ new WeakMap();
|
|
2168
|
+
function countInMemory(fallback, key, windowMs, now) {
|
|
2169
|
+
if (now >= fallback.sweepAt) sweep(fallback, now);
|
|
2170
|
+
let entry = fallback.counters.get(key);
|
|
2171
|
+
if (!entry || entry.expiresAt <= now) fallback.counters.set(key, entry = {
|
|
2172
|
+
count: 0,
|
|
2173
|
+
expiresAt: now + windowMs
|
|
2174
|
+
});
|
|
2175
|
+
entry.count++;
|
|
2176
|
+
return {
|
|
2177
|
+
count: entry.count,
|
|
2178
|
+
expiresInMs: Math.max(1, entry.expiresAt - now)
|
|
2179
|
+
};
|
|
2180
|
+
}
|
|
2181
|
+
function sweep(fallback, now) {
|
|
2182
|
+
for (const [key, entry] of fallback.counters) if (entry.expiresAt <= now) fallback.counters.delete(key);
|
|
2183
|
+
fallback.sweepAt = now + SWEEP_MS;
|
|
2184
|
+
}
|
|
2185
|
+
const isTimeToProbe = (fallback, now) => now >= fallback.probeAt;
|
|
2186
|
+
const hasBeenHealthyLongEnough = (fallback, now) => fallback.healthySince !== void 0 && now - fallback.healthySince >= QUIET_MS;
|
|
2187
|
+
function enterFallback(fallback, now, cause) {
|
|
2188
|
+
Object.assign(fallback, {
|
|
2189
|
+
active: true,
|
|
2190
|
+
probeAt: now + PROBE_MS,
|
|
2191
|
+
healthySince: void 0
|
|
2192
|
+
});
|
|
2193
|
+
console.warn(`[Brick-TS] Rate limits: storage is unavailable (${cause.message}); counting in this process's memory until it is back.`);
|
|
2194
|
+
}
|
|
2195
|
+
function leaveFallback(fallback) {
|
|
2196
|
+
fallback.active = false;
|
|
2197
|
+
console.warn("[Brick-TS] Rate limits: storage is back; counting there again.");
|
|
2198
|
+
}
|
|
2199
|
+
function probe(storage, fallback, key, windowMs) {
|
|
2200
|
+
const answered = () => {
|
|
2201
|
+
const now = Date.now();
|
|
2202
|
+
fallback.healthySince ??= now;
|
|
2203
|
+
if (fallback.active && hasBeenHealthyLongEnough(fallback, now)) leaveFallback(fallback);
|
|
2204
|
+
};
|
|
2205
|
+
storage.increment(key, windowMs).then(answered, (error) => {
|
|
2206
|
+
if (error instanceof StorageUnavailableError) fallback.healthySince = void 0;
|
|
2207
|
+
else answered();
|
|
2208
|
+
});
|
|
2209
|
+
}
|
|
2210
|
+
async function increment(storage, key, windowMs) {
|
|
2211
|
+
let fallback = fallbacks.get(storage);
|
|
2212
|
+
if (fallback) {
|
|
2213
|
+
const now = Date.now();
|
|
2214
|
+
if (fallback.active) {
|
|
2215
|
+
if (isTimeToProbe(fallback, now)) {
|
|
2216
|
+
fallback.probeAt = now + PROBE_MS;
|
|
2217
|
+
probe(storage, fallback, key, windowMs);
|
|
2218
|
+
}
|
|
2219
|
+
return countInMemory(fallback, key, windowMs, now);
|
|
2220
|
+
}
|
|
2221
|
+
if (now >= fallback.sweepAt) {
|
|
2222
|
+
sweep(fallback, now);
|
|
2223
|
+
if (!fallback.counters.size) fallbacks.delete(storage);
|
|
2224
|
+
}
|
|
2225
|
+
}
|
|
2226
|
+
try {
|
|
2227
|
+
return await storage.increment(key, windowMs);
|
|
2228
|
+
} catch (error) {
|
|
2229
|
+
if (!(error instanceof StorageUnavailableError)) throw error;
|
|
2230
|
+
const now = Date.now();
|
|
2231
|
+
fallback = fallbacks.get(storage);
|
|
2232
|
+
if (!fallback) fallbacks.set(storage, fallback = {
|
|
2233
|
+
active: false,
|
|
2234
|
+
counters: /* @__PURE__ */ new Map(),
|
|
2235
|
+
probeAt: 0,
|
|
2236
|
+
sweepAt: now + SWEEP_MS
|
|
2237
|
+
});
|
|
2238
|
+
if (!fallback.active) enterFallback(fallback, now, error);
|
|
2239
|
+
return countInMemory(fallback, key, windowMs, now);
|
|
2240
|
+
}
|
|
2241
|
+
}
|
|
2242
|
+
async function keyOf(limit, input, ctx) {
|
|
2243
|
+
if (typeof limit.per === "function") {
|
|
2244
|
+
const key = limit.per({
|
|
2245
|
+
input,
|
|
2246
|
+
ctx
|
|
2247
|
+
});
|
|
2248
|
+
if (typeof key?.then === "function") {
|
|
2249
|
+
Promise.resolve(key).catch(() => {});
|
|
2250
|
+
throw new Error("rateLimit per must return a string, null or undefined; it returned a promise (it must not be async)");
|
|
2251
|
+
}
|
|
2252
|
+
return key == null ? void 0 : ["key", String(key)];
|
|
2253
|
+
}
|
|
2254
|
+
if (limit.per === "actor") {
|
|
2255
|
+
const identity = await identityOf(ctx);
|
|
2256
|
+
if (identity) return ["actor", identity.id];
|
|
2257
|
+
}
|
|
2258
|
+
const ip = clientAddress(ctx);
|
|
2259
|
+
return ip === void 0 ? void 0 : ["ip", ip];
|
|
2260
|
+
}
|
|
2261
|
+
async function enforceRateLimits(service, kind, action, limits, input, ctx) {
|
|
2262
|
+
if (!service) throw new Error(`Action '${action}' declares rateLimit, but it is not registered on a service`);
|
|
2263
|
+
const storage = storageOf(service, ctx.deps);
|
|
2264
|
+
if (!storage) throw noStorage(service, action);
|
|
2265
|
+
for (const [index, limit] of limits.entries()) {
|
|
2266
|
+
const key = await keyOf(limit, input, ctx);
|
|
2267
|
+
if (!key) continue;
|
|
2268
|
+
const { count, expiresInMs } = await increment(storage, storageKey("rate-limit", [
|
|
2269
|
+
service.name,
|
|
2270
|
+
kind,
|
|
2271
|
+
action,
|
|
2272
|
+
index,
|
|
2273
|
+
...key
|
|
2274
|
+
]), limit.windowMs);
|
|
2275
|
+
if (count > limit.max) {
|
|
2276
|
+
const retryAfterSeconds = Math.max(1, Math.ceil(expiresInMs / 1e3));
|
|
2277
|
+
throw new ActionExecutionError("RATE_LIMITED", `Too many calls to '${action}'; retry in ${retryAfterSeconds} s`, 429, { retryAfterSeconds });
|
|
2278
|
+
}
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
// src/context.ts
|
|
2282
|
+
const DEFAULT_REQUEST = new Request("http://localhost");
|
|
2283
|
+
const EMPTY = Object.freeze({});
|
|
2284
|
+
const defaultLogger = createLogger(DEFAULT_LOG_PREFIXES);
|
|
2285
|
+
/** Random, so ids never repeat across restarts or processes. */
|
|
2286
|
+
const newId = (kind) => `${kind}_${crypto.randomUUID()}`;
|
|
2287
|
+
/**
|
|
2288
|
+
* The trace and request ids of an HTTP request: the caller's `x-trace-id` and
|
|
2289
|
+
* `x-request-id` headers, else fresh ones. Both are echoed on the response.
|
|
2290
|
+
*/
|
|
2291
|
+
function requestIds(headers, set) {
|
|
2292
|
+
const traceId = headers?.["x-trace-id"] || newId("tr");
|
|
2293
|
+
const requestId = headers?.["x-request-id"] || newId("req");
|
|
2294
|
+
if (set?.headers) {
|
|
2295
|
+
set.headers["x-trace-id"] = traceId;
|
|
2296
|
+
set.headers["x-request-id"] = requestId;
|
|
2297
|
+
}
|
|
2298
|
+
return {
|
|
2299
|
+
traceId,
|
|
2300
|
+
requestId
|
|
2301
|
+
};
|
|
2302
|
+
}
|
|
2303
|
+
/**
|
|
2304
|
+
* The framework fields of an action context: what the caller gave, the rest
|
|
2305
|
+
* defaulted. A missing trace or request id gets a fresh `tr_`/`req_` one.
|
|
2306
|
+
*/
|
|
2307
|
+
function baseContext(fields) {
|
|
2308
|
+
return {
|
|
2309
|
+
request: fields.request ?? DEFAULT_REQUEST,
|
|
2310
|
+
db: fields.db,
|
|
2311
|
+
logger: fields.logger ?? defaultLogger,
|
|
2312
|
+
traceId: fields.traceId ?? newId("tr"),
|
|
2313
|
+
requestId: fields.requestId ?? newId("req"),
|
|
2314
|
+
services: fields.services ?? EMPTY,
|
|
2315
|
+
metadata: fields.metadata ?? EMPTY,
|
|
2316
|
+
deps: fields.deps ?? EMPTY,
|
|
2317
|
+
dashboard: fields.dashboard ?? dashboardIdentity(fields.request)
|
|
2318
|
+
};
|
|
2319
|
+
}
|
|
2320
|
+
function pickContextEnvelope(context) {
|
|
2321
|
+
if (!context) return {};
|
|
2322
|
+
const envelope = {};
|
|
2323
|
+
if (context.caller !== void 0) envelope.caller = context.caller;
|
|
2324
|
+
if (context.user !== void 0) envelope.user = context.user;
|
|
2325
|
+
if (context.traceId !== void 0) envelope.traceId = context.traceId;
|
|
2326
|
+
if (context.requestId !== void 0) envelope.requestId = context.requestId;
|
|
2327
|
+
if (context.tenantId !== void 0) envelope.tenantId = context.tenantId;
|
|
2328
|
+
if (context.dashboard !== void 0) envelope.dashboard = context.dashboard;
|
|
2329
|
+
carryClientRequest(envelope, context);
|
|
2330
|
+
return envelope;
|
|
2331
|
+
}
|
|
2332
|
+
const RESOLVED = Symbol("resolved");
|
|
2333
|
+
const OWN_DEPS = Symbol("ownDeps");
|
|
2334
|
+
function markResolved(ctx, service, ownDeps) {
|
|
2335
|
+
const marked = ctx;
|
|
2336
|
+
marked[RESOLVED] = service;
|
|
2337
|
+
marked[OWN_DEPS] = ownDeps;
|
|
2338
|
+
attachIdentity(marked, service, ownDeps);
|
|
2339
|
+
}
|
|
2340
|
+
function resolvedDeps(ctx, service) {
|
|
2341
|
+
const marked = ctx;
|
|
2342
|
+
return marked?.[RESOLVED] === service ? marked[OWN_DEPS] : void 0;
|
|
2343
|
+
}
|
|
2344
|
+
function serviceOf(ctx) {
|
|
2345
|
+
return ctx[RESOLVED];
|
|
2346
|
+
}
|
|
2347
|
+
// src/webhook.ts
|
|
2348
|
+
const DEFAULT_MAX_BODY_BYTES = 1048576;
|
|
2349
|
+
function webhookOf(action) {
|
|
2350
|
+
return action ? actionMeta(action).webhook : void 0;
|
|
2351
|
+
}
|
|
2352
|
+
/** Whether an action was declared with `service.webhook`. */
|
|
2353
|
+
function isWebhook(action) {
|
|
2354
|
+
return webhookOf(action) !== void 0;
|
|
2355
|
+
}
|
|
2356
|
+
function defineWebhookMeta(service, config) {
|
|
2357
|
+
const where = `Service "${service}": webhook '${config?.name}'`;
|
|
2358
|
+
if (typeof config?.verify !== "function") throw new Error(`${where} needs verify: a verifier such as hmacSignature({ secret, header }), standardWebhooks({ secret }) or twilioSignature({ authToken, url }), or your own (request) => boolean. A webhook cannot run without one.`);
|
|
2359
|
+
if (!config.input || typeof config.input !== "object") throw new Error(`${where} needs input: the schema of the payload, such as t.Object({ ... }).`);
|
|
2360
|
+
if (config.method !== void 0 && !["POST", "GET"].includes(config.method)) throw new Error(`${where}: method must be "POST" or "GET".`);
|
|
2361
|
+
if (config.method === "GET" && config.verify.signsBody) throw new Error(`${where}: method "GET" has no body, and this verifier signs the body, so it would accept one signature for every query. Use twilioSignature (it signs the URL) or a verifier of your own, or method "POST".`);
|
|
2362
|
+
for (const option of ["authorize", "output"]) if (config[option] !== void 0) throw new Error(`${where}: ${option} is not an option of a webhook, and would be ignored. verify is the check.`);
|
|
2363
|
+
const { maxBodyBytes = DEFAULT_MAX_BODY_BYTES, replay } = config;
|
|
2364
|
+
if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1) throw new Error(`${where}: maxBodyBytes must be a positive integer.`);
|
|
2365
|
+
const ttlMs = replay === false ? void 0 : replay?.ttlMs ?? 6048e5;
|
|
2366
|
+
if (ttlMs !== void 0 && (!Number.isSafeInteger(ttlMs) || ttlMs < 1)) throw new Error(`${where}: replay.ttlMs must be a positive integer.`);
|
|
2367
|
+
return {
|
|
2368
|
+
verify: config.verify,
|
|
2369
|
+
eventId: config.eventId,
|
|
2370
|
+
replay: ttlMs === void 0 ? false : { ttlMs },
|
|
2371
|
+
maxBodyBytes
|
|
2372
|
+
};
|
|
2373
|
+
}
|
|
2374
|
+
function checkWebhook(service, action, deps) {
|
|
2375
|
+
const webhook = webhookOf(action);
|
|
2376
|
+
if (!webhook) return;
|
|
2377
|
+
checkRateLimits(service, action, deps);
|
|
2378
|
+
if (webhook.replay === false) return;
|
|
2379
|
+
const where = `Service "${service.name}": webhook '${action.name}'`;
|
|
2380
|
+
if (!webhook.eventId && !webhook.verify.suppliesEventId) throw new Error(`${where} has no event id to tell deliveries apart by, so a delivery sent twice would run twice. Add eventId: ({ input }) => input.id, reading an id from a field of the signed payload (an id from a header the signature does not cover only removes accidental duplicates: anyone who captured a delivery can resend it with another id), use a verifier that supplies one (standardWebhooks), or set replay: false to run every delivery.`);
|
|
2381
|
+
if (!serviceStorage(service)) throw new Error(`${where} remembers the events it has handled, but the service has no key-value storage. Add one: defineService("${service.name}", { deps: { cache: defineStorage({ driver: redis() }) } }), or set replay: false.`);
|
|
2382
|
+
}
|
|
2383
|
+
// src/events/transaction.ts
|
|
2384
|
+
const sqliteQueues = /* @__PURE__ */ new WeakMap();
|
|
2385
|
+
const active = new AsyncLocalStorage();
|
|
2386
|
+
function joined(db) {
|
|
2387
|
+
const open = active.getStore();
|
|
2388
|
+
return open?.open && open.handles.has(db) ? open : void 0;
|
|
2389
|
+
}
|
|
2390
|
+
function isSqliteDatabase(db) {
|
|
2391
|
+
return typeof db?.$client?.prepare === "function" && typeof db?.$client?.run === "function";
|
|
2392
|
+
}
|
|
2393
|
+
function rollbackQuietly(db, statement = "ROLLBACK") {
|
|
2394
|
+
try {
|
|
2395
|
+
db.$client.run(statement);
|
|
2396
|
+
} catch {
|
|
2397
|
+
return;
|
|
2398
|
+
}
|
|
2399
|
+
}
|
|
2400
|
+
async function nested(db, open, fn) {
|
|
2401
|
+
const commits = open.commits.length;
|
|
2402
|
+
try {
|
|
2403
|
+
if (!isSqliteDatabase(db)) return await db.transaction((tx) => {
|
|
2404
|
+
open.handles.add(tx);
|
|
2405
|
+
return fn(tx);
|
|
2406
|
+
});
|
|
2407
|
+
const name = `brick_${++open.savepoints}`;
|
|
2408
|
+
db.$client.run(`SAVEPOINT ${name}`);
|
|
2409
|
+
try {
|
|
2410
|
+
const result = await fn(db);
|
|
2411
|
+
db.$client.run(`RELEASE ${name}`);
|
|
2412
|
+
return result;
|
|
2413
|
+
} catch (error) {
|
|
2414
|
+
rollbackQuietly(db, `ROLLBACK TO ${name}`);
|
|
2415
|
+
rollbackQuietly(db, `RELEASE ${name}`);
|
|
2416
|
+
throw error;
|
|
2417
|
+
}
|
|
2418
|
+
} catch (error) {
|
|
2419
|
+
open.commits.length = commits;
|
|
2420
|
+
throw error;
|
|
2421
|
+
}
|
|
2422
|
+
}
|
|
2423
|
+
/**
|
|
2424
|
+
* Run `fn` in a database transaction: everything it writes through the `tx` it is
|
|
2425
|
+
* given is committed together when it returns, or undone if it throws.
|
|
2426
|
+
*
|
|
2427
|
+
* Postgres uses a real transaction on one connection. SQLite has one connection
|
|
2428
|
+
* and a synchronous driver, which Drizzle's own `transaction` cannot use with an
|
|
2429
|
+
* async callback (it would commit before the callback finished). So transactions
|
|
2430
|
+
* on one SQLite database take turns, each between `BEGIN IMMEDIATE` and `COMMIT`.
|
|
2431
|
+
* A write made elsewhere in the process during that time, outside this helper,
|
|
2432
|
+
* would join the transaction; use Postgres where that matters.
|
|
2433
|
+
*
|
|
2434
|
+
* A call made inside `fn` with the `tx` it was given (on SQLite, the database
|
|
2435
|
+
* itself) joins the open transaction as a savepoint instead of waiting for it: a
|
|
2436
|
+
* nested failure undoes only the nested work, and the outer transaction decides
|
|
2437
|
+
* the commit. Nested calls must run one at a time.
|
|
2438
|
+
*
|
|
2439
|
+
* @param db - A Drizzle database, from `service.getDb()`.
|
|
2440
|
+
* @param fn - Receives the transaction handle to run queries on.
|
|
2441
|
+
* @returns What `fn` returned.
|
|
2442
|
+
* @throws What `fn` threw, after rolling back.
|
|
2443
|
+
*/
|
|
2444
|
+
async function runInTransaction(db, fn) {
|
|
2445
|
+
const outer = joined(db);
|
|
2446
|
+
if (outer) return nested(db, outer, fn);
|
|
2447
|
+
const open = {
|
|
2448
|
+
handles: /* @__PURE__ */ new Set(),
|
|
2449
|
+
commits: [],
|
|
2450
|
+
open: true,
|
|
2451
|
+
savepoints: 0
|
|
2452
|
+
};
|
|
2453
|
+
let result;
|
|
2454
|
+
try {
|
|
2455
|
+
result = await active.run(open, () => begin(db, open, fn));
|
|
2456
|
+
} finally {
|
|
2457
|
+
open.open = false;
|
|
2458
|
+
}
|
|
2459
|
+
for (const commit of open.commits) await commit();
|
|
2460
|
+
return result;
|
|
2461
|
+
}
|
|
2462
|
+
async function begin(db, open, fn) {
|
|
2463
|
+
if (!isSqliteDatabase(db)) return db.transaction((tx) => {
|
|
2464
|
+
open.handles.add(tx);
|
|
2465
|
+
return fn(tx);
|
|
2466
|
+
});
|
|
2467
|
+
open.handles.add(db);
|
|
2468
|
+
const previous = sqliteQueues.get(db) ?? Promise.resolve();
|
|
2469
|
+
let release;
|
|
2470
|
+
const turn = new Promise((resolve) => {
|
|
2471
|
+
release = resolve;
|
|
2472
|
+
});
|
|
2473
|
+
sqliteQueues.set(db, previous.then(() => turn));
|
|
2474
|
+
await previous;
|
|
2475
|
+
try {
|
|
2476
|
+
db.$client.run("BEGIN IMMEDIATE");
|
|
2477
|
+
try {
|
|
2478
|
+
const result = await fn(db);
|
|
2479
|
+
db.$client.run("COMMIT");
|
|
2480
|
+
return result;
|
|
2481
|
+
} catch (error) {
|
|
2482
|
+
rollbackQuietly(db);
|
|
2483
|
+
throw error;
|
|
2484
|
+
}
|
|
2485
|
+
} finally {
|
|
2486
|
+
release();
|
|
2487
|
+
}
|
|
2488
|
+
}
|
|
2489
|
+
/** Whether `db` belongs to a transaction opened by `runInTransaction` that is still open. */
|
|
2490
|
+
function inTransaction(db) {
|
|
2491
|
+
return joined(db) !== void 0;
|
|
2492
|
+
}
|
|
382
2493
|
/**
|
|
383
|
-
*
|
|
384
|
-
*
|
|
2494
|
+
* Run `fn` once the transaction that `db` belongs to has committed, or now when
|
|
2495
|
+
* `db` is not in one opened by `runInTransaction`. It never runs when that
|
|
2496
|
+
* transaction, or the savepoint it was queued in, rolls back. An error it throws
|
|
2497
|
+
* reaches the caller of the outermost `runInTransaction`, after the commit.
|
|
2498
|
+
*
|
|
2499
|
+
* @param db - The handle the work ran on: a `tx`, or a database.
|
|
2500
|
+
* @param fn - The side effect, such as clearing a cache.
|
|
385
2501
|
*/
|
|
386
|
-
function
|
|
387
|
-
const
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
maxArrayLength: 50,
|
|
391
|
-
maxStringLength: 1e3
|
|
392
|
-
}, ...args));
|
|
393
|
-
return text.length > MAX_MESSAGE_LENGTH ? `${text.slice(0, MAX_MESSAGE_LENGTH)}…` : text;
|
|
2502
|
+
async function onTransactionCommit(db, fn) {
|
|
2503
|
+
const open = joined(db);
|
|
2504
|
+
if (open) open.commits.push(fn);
|
|
2505
|
+
else await fn();
|
|
394
2506
|
}
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
2507
|
+
// src/audit.ts
|
|
2508
|
+
const AUDIT = Symbol.for("brick.audit");
|
|
2509
|
+
function sqliteAudit(name) {
|
|
2510
|
+
return sqliteTable(name, {
|
|
2511
|
+
seq: integer$1("seq").primaryKey({ autoIncrement: true }),
|
|
2512
|
+
id: text$1("id").notNull().unique(),
|
|
2513
|
+
at: integer$1("at", { mode: "timestamp_ms" }).notNull(),
|
|
2514
|
+
service: text$1("service").notNull(),
|
|
2515
|
+
action: text$1("action").notNull(),
|
|
2516
|
+
resource: text$1("resource"),
|
|
2517
|
+
recordId: text$1("record_id"),
|
|
2518
|
+
actorId: text$1("actor_id"),
|
|
2519
|
+
actorLabel: text$1("actor_label"),
|
|
2520
|
+
tenant: text$1("tenant"),
|
|
2521
|
+
traceId: text$1("trace_id"),
|
|
2522
|
+
requestId: text$1("request_id"),
|
|
2523
|
+
meta: text$1("meta", { mode: "json" })
|
|
405
2524
|
});
|
|
406
2525
|
}
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
2526
|
+
function postgresAudit(name) {
|
|
2527
|
+
return pgTable(name, {
|
|
2528
|
+
seq: bigserial("seq", { mode: "number" }).primaryKey(),
|
|
2529
|
+
id: text("id").notNull().unique(),
|
|
2530
|
+
at: timestamp("at", { withTimezone: true }).notNull(),
|
|
2531
|
+
service: text("service").notNull(),
|
|
2532
|
+
action: text("action").notNull(),
|
|
2533
|
+
resource: text("resource"),
|
|
2534
|
+
recordId: text("record_id"),
|
|
2535
|
+
actorId: text("actor_id"),
|
|
2536
|
+
actorLabel: text("actor_label"),
|
|
2537
|
+
tenant: text("tenant"),
|
|
2538
|
+
traceId: text("trace_id"),
|
|
2539
|
+
requestId: text("request_id"),
|
|
2540
|
+
meta: jsonb("meta")
|
|
2541
|
+
});
|
|
416
2542
|
}
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
const
|
|
432
|
-
|
|
433
|
-
|
|
2543
|
+
function auditTable(engine, options = {}) {
|
|
2544
|
+
const name = options.name ?? "brick_audit";
|
|
2545
|
+
const table = engine === "sqlite" ? sqliteAudit(name) : postgresAudit(name);
|
|
2546
|
+
Object.defineProperty(table, AUDIT, { value: { engine } });
|
|
2547
|
+
return table;
|
|
2548
|
+
}
|
|
2549
|
+
/** Whether a value is an audit table made by `auditTable`. */
|
|
2550
|
+
function isAuditTable(value) {
|
|
2551
|
+
return typeof value === "object" && value !== null && AUDIT in value;
|
|
2552
|
+
}
|
|
2553
|
+
function auditStage(service, action) {
|
|
2554
|
+
const table = service.getAuditTable();
|
|
2555
|
+
const config = action.config;
|
|
2556
|
+
if (!table || config.audit === false) return void 0;
|
|
2557
|
+
const { audit: mode, resourceAction } = actionMeta(action);
|
|
2558
|
+
if (mode === "none" || !mode && actionMethod(action) === "GET") return void 0;
|
|
2559
|
+
return {
|
|
2560
|
+
service,
|
|
2561
|
+
table,
|
|
2562
|
+
action: action.name,
|
|
2563
|
+
recordsInOwnTransaction: mode === "inline",
|
|
2564
|
+
resource: config.audit?.resource ?? resourceAction?.resource,
|
|
2565
|
+
record: config.audit?.record ?? (resourceAction?.record ? ({ input }) => input.id : void 0)
|
|
434
2566
|
};
|
|
2567
|
+
}
|
|
2568
|
+
const calls = sharedAcrossCoreCopies("brickkit.audit.calls", () => new AsyncLocalStorage());
|
|
2569
|
+
function runUnaudited(run) {
|
|
2570
|
+
return calls.getStore() ? calls.exit(run) : run();
|
|
2571
|
+
}
|
|
2572
|
+
function recordIdText(id) {
|
|
2573
|
+
if (id === void 0 || id === null) return null;
|
|
2574
|
+
if (typeof id === "string") return id;
|
|
2575
|
+
if (typeof id === "number" || typeof id === "bigint") return String(id);
|
|
2576
|
+
return JSON.stringify(id) ?? null;
|
|
2577
|
+
}
|
|
2578
|
+
async function auditRow(ctx, target, entry) {
|
|
2579
|
+
const who = await identityOf(ctx);
|
|
435
2580
|
return {
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
2581
|
+
id: crypto.randomUUID(),
|
|
2582
|
+
at: /* @__PURE__ */ new Date(),
|
|
2583
|
+
service: target.service.name,
|
|
2584
|
+
action: entry.action,
|
|
2585
|
+
resource: entry.resource ?? null,
|
|
2586
|
+
recordId: recordIdText(entry.recordId),
|
|
2587
|
+
actorId: who?.id ?? null,
|
|
2588
|
+
actorLabel: who?.label ?? null,
|
|
2589
|
+
tenant: who?.tenant ?? null,
|
|
2590
|
+
traceId: ctx.traceId ?? null,
|
|
2591
|
+
requestId: ctx.requestId ?? null,
|
|
2592
|
+
meta: entry.meta ?? null
|
|
440
2593
|
};
|
|
441
2594
|
}
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
2595
|
+
function insertOutsideOtherRequestsTransactions(db, fn) {
|
|
2596
|
+
return isSqliteDatabase(db) && !inTransaction(db) ? runInTransaction(db, fn) : fn(db);
|
|
2597
|
+
}
|
|
2598
|
+
async function writeAudit(handle, ctx, target, entry) {
|
|
2599
|
+
await handle.insert(target.table).values(await auditRow(ctx, target, entry));
|
|
2600
|
+
}
|
|
2601
|
+
function resolveActorBeforeAction(ctx) {
|
|
2602
|
+
return identityOf(ctx);
|
|
2603
|
+
}
|
|
2604
|
+
function buildRow(audit, ctx) {
|
|
2605
|
+
return auditRow(ctx, audit, {
|
|
2606
|
+
action: audit.action,
|
|
2607
|
+
resource: audit.resource
|
|
2608
|
+
});
|
|
2609
|
+
}
|
|
2610
|
+
function setRecordIdOf(row, audit, input, result) {
|
|
2611
|
+
row.recordId = recordIdText(audit.record?.({
|
|
2612
|
+
input,
|
|
2613
|
+
result
|
|
2614
|
+
}));
|
|
2615
|
+
}
|
|
2616
|
+
async function runAudited(audit, input, ctx, run) {
|
|
2617
|
+
await resolveActorBeforeAction(ctx);
|
|
2618
|
+
const call = {
|
|
2619
|
+
audit,
|
|
2620
|
+
written: false
|
|
2621
|
+
};
|
|
2622
|
+
const result = await calls.run(call, run);
|
|
2623
|
+
if (!audit.recordsInOwnTransaction && !call.written) {
|
|
2624
|
+
let row;
|
|
2625
|
+
try {
|
|
2626
|
+
row = await buildRow(audit, ctx);
|
|
2627
|
+
setRecordIdOf(row, audit, input, result);
|
|
2628
|
+
await insertOutsideOtherRequestsTransactions(ctx.db, (tx) => tx.insert(audit.table).values(row));
|
|
2629
|
+
} catch (error) {
|
|
2630
|
+
ctx.logger?.error?.(`audit: '${audit.action}' ran but its audit row was not written`, row, error);
|
|
2631
|
+
}
|
|
465
2632
|
}
|
|
2633
|
+
return result;
|
|
2634
|
+
}
|
|
2635
|
+
function entryOf(audit, input, result) {
|
|
466
2636
|
return {
|
|
467
|
-
|
|
468
|
-
|
|
2637
|
+
action: audit.action,
|
|
2638
|
+
resource: audit.resource,
|
|
2639
|
+
recordId: audit.record?.({
|
|
2640
|
+
input,
|
|
2641
|
+
result
|
|
2642
|
+
})
|
|
469
2643
|
};
|
|
470
2644
|
}
|
|
2645
|
+
function inlineAudit() {
|
|
2646
|
+
const audit = calls.getStore()?.audit;
|
|
2647
|
+
return audit?.recordsInOwnTransaction ? audit : void 0;
|
|
2648
|
+
}
|
|
2649
|
+
function recordInline(audit, tx, ctx, entry) {
|
|
2650
|
+
return writeAudit(tx, ctx, audit, entry);
|
|
2651
|
+
}
|
|
2652
|
+
function commitsWithBrickTransaction(tx, ctx) {
|
|
2653
|
+
return tx === ctx.db || inTransaction(tx);
|
|
2654
|
+
}
|
|
471
2655
|
/**
|
|
472
|
-
*
|
|
473
|
-
*
|
|
2656
|
+
* Record a change of your own from an action: for what Brick cannot see, or to
|
|
2657
|
+
* add `meta`. By default the row is inserted at once. Pass the `tx` of a
|
|
2658
|
+
* transaction you have open to commit it with your writes instead; once `tx`
|
|
2659
|
+
* commits it is the record of this call, and Brick does not add the automatic row.
|
|
2660
|
+
*
|
|
2661
|
+
* Brick copies no input or output into the log: `meta` holds what you pass.
|
|
2662
|
+
*
|
|
2663
|
+
* @param ctx - The action context: it names the service and the actor.
|
|
2664
|
+
* @param entry - `action` defaults to the running action's name, and is needed
|
|
2665
|
+
* in an action that is not itself recorded (a `GET`, `audit: false`).
|
|
2666
|
+
* `resource` and `recordId` say which record; `meta` is JSON of your choosing.
|
|
2667
|
+
* @param options - `tx`: an open transaction on the service's database.
|
|
2668
|
+
* @throws When `ctx` is not from an action of a service whose database holds an
|
|
2669
|
+
* audit table (a listener, a schedule or a workflow step has no such context),
|
|
2670
|
+
* or when `action` is missing.
|
|
2671
|
+
* @example
|
|
2672
|
+
* await runInTransaction(ctx.db, async (tx) => {
|
|
2673
|
+
* await tx.update(orders).set({ status: "refunded" }).where(eq(orders.id, input.orderId));
|
|
2674
|
+
* await recordAudit(ctx, { resource: "order", recordId: input.orderId, meta: { reason: input.reason } }, { tx });
|
|
2675
|
+
* });
|
|
474
2676
|
*/
|
|
475
|
-
function
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
2677
|
+
async function recordAudit(ctx, entry, options = {}) {
|
|
2678
|
+
const service = serviceOf(ctx);
|
|
2679
|
+
const table = service && portOf(service).getAuditTable();
|
|
2680
|
+
if (!service || !table) throw new Error("recordAudit needs the ctx of an action of a service whose database holds an audit table");
|
|
2681
|
+
const call = calls.getStore();
|
|
2682
|
+
const action = entry.action ?? call?.audit.action;
|
|
2683
|
+
if (!action) throw new Error("recordAudit needs an action: it defaults to the running action only when that action is recorded");
|
|
2684
|
+
const target = {
|
|
2685
|
+
service: portOf(service),
|
|
2686
|
+
table
|
|
485
2687
|
};
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
if (
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
return envelope;
|
|
2688
|
+
const named = {
|
|
2689
|
+
...entry,
|
|
2690
|
+
action
|
|
2691
|
+
};
|
|
2692
|
+
if (options.tx === void 0) await insertOutsideOtherRequestsTransactions(ctx.db, (tx) => writeAudit(tx, ctx, target, named));
|
|
2693
|
+
else {
|
|
2694
|
+
await writeAudit(options.tx, ctx, target, named);
|
|
2695
|
+
if (call && commitsWithBrickTransaction(options.tx, ctx)) await onTransactionCommit(options.tx, () => call.written = true);
|
|
2696
|
+
}
|
|
496
2697
|
}
|
|
497
2698
|
// src/compiler/runtime.ts
|
|
498
2699
|
function isNonEmpty(value) {
|
|
@@ -508,28 +2709,60 @@ function mergeInput(first, second, third) {
|
|
|
508
2709
|
if (c && !a && !b) return third;
|
|
509
2710
|
if (a || b || c) return Object.assign({}, first, second, third);
|
|
510
2711
|
}
|
|
511
|
-
function
|
|
2712
|
+
function coerceScalar(value, type) {
|
|
2713
|
+
if (typeof value !== "string") return value;
|
|
512
2714
|
if (type === "number") {
|
|
513
2715
|
const number = Number(value);
|
|
514
2716
|
return Number.isNaN(number) ? value : number;
|
|
515
2717
|
}
|
|
516
|
-
if (type === "
|
|
517
|
-
|
|
518
|
-
|
|
2718
|
+
if (type === "boolean") {
|
|
2719
|
+
if (value === "true" || value === "1") return true;
|
|
2720
|
+
if (value === "false" || value === "0") return false;
|
|
2721
|
+
}
|
|
2722
|
+
if (type === "json") try {
|
|
2723
|
+
return JSON.parse(value);
|
|
2724
|
+
} catch {
|
|
2725
|
+
return value;
|
|
519
2726
|
}
|
|
520
|
-
if (value === "true" || value === "1") return true;
|
|
521
|
-
if (value === "false" || value === "0") return false;
|
|
522
2727
|
return value;
|
|
523
2728
|
}
|
|
2729
|
+
function coerceQueryValue(value, { key, type, items }, request) {
|
|
2730
|
+
if (type !== "array") return coerceScalar(value, type);
|
|
2731
|
+
const values = request ? new URL(request.url).searchParams.getAll(key) : [];
|
|
2732
|
+
return (values.length ? values : Array.isArray(value) ? value : [value]).map((item) => coerceScalar(item, items));
|
|
2733
|
+
}
|
|
2734
|
+
const BODY_TOO_LARGE = Symbol("brick.bodyTooLarge");
|
|
2735
|
+
function bodyLimitParser(limit) {
|
|
2736
|
+
return ({ request }) => Number(request.headers.get("content-length")) > limit ? BODY_TOO_LARGE : void 0;
|
|
2737
|
+
}
|
|
2738
|
+
function rawBodyParser(limit) {
|
|
2739
|
+
return async ({ request }) => {
|
|
2740
|
+
if (Number(request.headers.get("content-length")) > limit) return BODY_TOO_LARGE;
|
|
2741
|
+
const chunks = [];
|
|
2742
|
+
let size = 0;
|
|
2743
|
+
if (request.body) for await (const chunk of request.body) {
|
|
2744
|
+
size += chunk.byteLength;
|
|
2745
|
+
if (size > limit) return BODY_TOO_LARGE;
|
|
2746
|
+
chunks.push(chunk);
|
|
2747
|
+
}
|
|
2748
|
+
return new Uint8Array(Buffer.concat(chunks));
|
|
2749
|
+
};
|
|
2750
|
+
}
|
|
524
2751
|
/** The action's input from the path, query and body, coerced by its schema. */
|
|
525
2752
|
function readInput(route, { params, body, query, request }) {
|
|
2753
|
+
if (body === BODY_TOO_LARGE) throw new ActionExecutionError("PAYLOAD_TOO_LARGE", `Request body exceeds ${route.bodyLimit} bytes`, 413);
|
|
526
2754
|
if (!route.input) return void 0;
|
|
527
2755
|
let coercedQuery = query;
|
|
528
2756
|
let coercedParams = params;
|
|
2757
|
+
let coercedBody = body;
|
|
529
2758
|
if (route.coercions.length) {
|
|
530
2759
|
if (query) {
|
|
531
2760
|
coercedQuery = { ...query };
|
|
532
|
-
for (const
|
|
2761
|
+
for (const coercion of route.coercions) if (query[coercion.key] !== void 0) coercedQuery[coercion.key] = coerceQueryValue(query[coercion.key], coercion, request);
|
|
2762
|
+
}
|
|
2763
|
+
if (body && request?.headers.get("content-type")?.startsWith("multipart/form-data")) {
|
|
2764
|
+
coercedBody = { ...body };
|
|
2765
|
+
for (const coercion of route.coercions) if (body[coercion.key] !== void 0) coercedBody[coercion.key] = coerceQueryValue(body[coercion.key], coercion, void 0);
|
|
533
2766
|
}
|
|
534
2767
|
for (const { key, type } of route.coercions) {
|
|
535
2768
|
if (type !== "number" || typeof params?.[key] !== "string") continue;
|
|
@@ -539,7 +2772,7 @@ function readInput(route, { params, body, query, request }) {
|
|
|
539
2772
|
coercedParams[key] = value;
|
|
540
2773
|
}
|
|
541
2774
|
}
|
|
542
|
-
const input = route.readLike ? mergeInput(coercedQuery, coercedParams,
|
|
2775
|
+
const input = route.readLike ? mergeInput(coercedQuery, coercedParams, coercedBody) : mergeInput(coercedParams, coercedBody, coercedQuery);
|
|
543
2776
|
return input === void 0 && route.inputSchema?.type === "object" ? {} : input;
|
|
544
2777
|
}
|
|
545
2778
|
const MAX_INPUT_DEPTH = 128;
|
|
@@ -568,10 +2801,9 @@ function invalid(action, stage, errors) {
|
|
|
568
2801
|
}
|
|
569
2802
|
function validate(check, value, action, stage) {
|
|
570
2803
|
if (check.Check(value)) return;
|
|
571
|
-
throw invalid(action, stage, Array.from(check.Errors(value)
|
|
572
|
-
path
|
|
573
|
-
message
|
|
574
|
-
value: err.value
|
|
2804
|
+
throw invalid(action, stage, Array.from(check.Errors(value), ({ path, message }) => ({
|
|
2805
|
+
path,
|
|
2806
|
+
message
|
|
575
2807
|
})));
|
|
576
2808
|
}
|
|
577
2809
|
function validateInput(check, input, action, checkInput) {
|
|
@@ -595,25 +2827,35 @@ async function authorizeCall(authorize, ctx, input, action) {
|
|
|
595
2827
|
user: ctx.user
|
|
596
2828
|
})) deny(action, ctx.user);
|
|
597
2829
|
}
|
|
598
|
-
/** The stage order of every call, over HTTP and in-process: check input → authorize → execute → check output. */
|
|
2830
|
+
/** The stage order of every call, over HTTP and in-process: check input → rate limit → authorize → execute → check output. */
|
|
599
2831
|
async function runStages(stages, input, ctx) {
|
|
2832
|
+
if (stages.dashboardOnly && !ctx.dashboard) throw new ActionExecutionError("UNAUTHORIZED", `Action '${stages.name}' is only for the dashboard`, 401);
|
|
600
2833
|
stages.checkInput(input);
|
|
2834
|
+
stages.sensitive?.input(input);
|
|
2835
|
+
if (stages.rateLimit) await stages.rateLimit(input, ctx);
|
|
601
2836
|
await authorizeCall(stages.authorize, ctx, input, stages.name);
|
|
602
|
-
|
|
2837
|
+
const output = stages.audit ? await runAudited(stages.audit, input, ctx, async () => stages.checkOutput(await stages.execute({
|
|
603
2838
|
input,
|
|
604
2839
|
ctx,
|
|
605
2840
|
error: stages.errorBuilder
|
|
606
|
-
}))
|
|
2841
|
+
}))) : stages.checkOutput(await runUnaudited(() => stages.execute({
|
|
2842
|
+
input,
|
|
2843
|
+
ctx,
|
|
2844
|
+
error: stages.errorBuilder
|
|
2845
|
+
})));
|
|
2846
|
+
return stages.sensitive ? stages.sensitive.output(output, input, ctx) : output;
|
|
607
2847
|
}
|
|
608
2848
|
function mapError(err, set, options) {
|
|
609
2849
|
const response = toErrorResponse(err, options);
|
|
610
2850
|
set.status = response.status;
|
|
2851
|
+
const retry = response.details?.retryAfterSeconds;
|
|
2852
|
+
if (response.status === 429 && Number.isFinite(retry)) set.headers["retry-after"] = String(BigInt(Math.max(1, Math.ceil(retry))));
|
|
611
2853
|
return response;
|
|
612
2854
|
}
|
|
613
2855
|
const isThenable = (value) => value != null && typeof value.then === "function";
|
|
614
2856
|
/** The context of one HTTP request, with the trace and request id headers set. */
|
|
615
2857
|
function requestContext(plan, { headers, request, set }) {
|
|
616
|
-
|
|
2858
|
+
const ctx = baseContext({
|
|
617
2859
|
...requestIds(headers, set),
|
|
618
2860
|
request: request instanceof Request ? request : void 0,
|
|
619
2861
|
db: plan.cachedDb ?? plan.service.getDb(),
|
|
@@ -621,42 +2863,238 @@ function requestContext(plan, { headers, request, set }) {
|
|
|
621
2863
|
metadata: { headers },
|
|
622
2864
|
deps: plan.contextHook ? plan.service.deps : plan.deps ?? plan.service.deps
|
|
623
2865
|
});
|
|
2866
|
+
if (!plan.contextHook) resolveServiceDeps(ctx, plan);
|
|
2867
|
+
return ctx;
|
|
2868
|
+
}
|
|
2869
|
+
const HANDLED = "handled";
|
|
2870
|
+
const IN_FLIGHT_CLAIM_MS = 3e5;
|
|
2871
|
+
const eventIdFrom = (value) => Number.isSafeInteger(value) ? String(value) : typeof value === "string" && value ? value : void 0;
|
|
2872
|
+
const refuse = (code, message, status) => new ActionExecutionError(code, message, status);
|
|
2873
|
+
function fieldsOf(params) {
|
|
2874
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
2875
|
+
for (const [name, value] of params) grouped.set(name, [...grouped.get(name) ?? [], value]);
|
|
2876
|
+
return Object.fromEntries([...grouped].map(([name, values]) => [name, values.length > 1 ? values : values[0]]));
|
|
2877
|
+
}
|
|
2878
|
+
function webhookInput(route, request, rawBody) {
|
|
2879
|
+
const text = new TextDecoder().decode(rawBody);
|
|
2880
|
+
const form = route.method === "GET" ? new URL(request.url).searchParams : /^application\/x-www-form-urlencoded/i.test(request.headers.get("content-type") ?? "") ? new URLSearchParams(text) : void 0;
|
|
2881
|
+
if (form) return readInput(route, { query: fieldsOf(form) });
|
|
2882
|
+
if (!text) return void 0;
|
|
2883
|
+
try {
|
|
2884
|
+
return JSON.parse(text);
|
|
2885
|
+
} catch {
|
|
2886
|
+
throw invalid(route.action, "input", [{
|
|
2887
|
+
path: "",
|
|
2888
|
+
message: "Body is not valid JSON"
|
|
2889
|
+
}]);
|
|
2890
|
+
}
|
|
2891
|
+
}
|
|
2892
|
+
function bindWebhook(plan) {
|
|
2893
|
+
const { execute } = plan;
|
|
2894
|
+
const name = plan.route.action;
|
|
2895
|
+
const webhook = webhookOf(plan.action);
|
|
2896
|
+
const limits = rateLimitsOf(plan.action.config);
|
|
2897
|
+
const audit = auditStage(plan.service, plan.action);
|
|
2898
|
+
const storage = webhook.replay ? serviceStorage(plan.service) : void 0;
|
|
2899
|
+
if (webhook.replay && !storage) throw new Error(`Webhook '${name}' remembers the events it has handled, but its service has no key-value storage`);
|
|
2900
|
+
const brickWebhook = async (context) => {
|
|
2901
|
+
const delivery = {
|
|
2902
|
+
plan,
|
|
2903
|
+
webhook,
|
|
2904
|
+
storage,
|
|
2905
|
+
limits,
|
|
2906
|
+
request: context.request,
|
|
2907
|
+
ctx: requestContext(plan, context),
|
|
2908
|
+
outcome: "failed"
|
|
2909
|
+
};
|
|
2910
|
+
try {
|
|
2911
|
+
rejectOversizedBody(delivery, context.body);
|
|
2912
|
+
const rawBody = rawBodyOf(context.body);
|
|
2913
|
+
await verifyDelivery(delivery, rawBody);
|
|
2914
|
+
const input = parseAndCheckInput(delivery, rawBody);
|
|
2915
|
+
plan.sensitive?.input(input);
|
|
2916
|
+
await resolveEventId(delivery, input);
|
|
2917
|
+
if (await claimEvent(delivery) === ALREADY_HANDLED) return { duplicate: true };
|
|
2918
|
+
let result;
|
|
2919
|
+
try {
|
|
2920
|
+
await resolveContext(delivery);
|
|
2921
|
+
await enforceWebhookRateLimits(delivery, input);
|
|
2922
|
+
const run = () => execute({
|
|
2923
|
+
input,
|
|
2924
|
+
ctx: delivery.ctx,
|
|
2925
|
+
error: plan.errorBuilder,
|
|
2926
|
+
eventId: delivery.eventId
|
|
2927
|
+
});
|
|
2928
|
+
result = audit ? await runAudited(audit, input, delivery.ctx, async () => run()) : await runUnaudited(run);
|
|
2929
|
+
if (plan.sensitive && !(result instanceof Response)) result = await plan.sensitive.output(result, input, delivery.ctx);
|
|
2930
|
+
} catch (error) {
|
|
2931
|
+
await releaseClaim(delivery);
|
|
2932
|
+
throw error;
|
|
2933
|
+
}
|
|
2934
|
+
await settleClaim(delivery, result);
|
|
2935
|
+
return result === void 0 ? { ok: true } : result;
|
|
2936
|
+
} catch (err) {
|
|
2937
|
+
return mapError(err, context.set, delivery.ctx);
|
|
2938
|
+
} finally {
|
|
2939
|
+
recordWebhook(name, delivery.eventId, delivery.outcome);
|
|
2940
|
+
}
|
|
2941
|
+
};
|
|
2942
|
+
return plan.sensitive ? (context) => withRedaction(() => brickWebhook(context)) : brickWebhook;
|
|
2943
|
+
}
|
|
2944
|
+
const ALREADY_HANDLED = Symbol("alreadyHandled");
|
|
2945
|
+
function rejectOversizedBody(delivery, body) {
|
|
2946
|
+
if (body !== BODY_TOO_LARGE) return;
|
|
2947
|
+
delivery.outcome = "too_large";
|
|
2948
|
+
throw refuse("PAYLOAD_TOO_LARGE", `Request body exceeds ${delivery.webhook.maxBodyBytes} bytes`, 413);
|
|
2949
|
+
}
|
|
2950
|
+
const rawBodyOf = (body) => body instanceof Uint8Array ? body : /* @__PURE__ */ new Uint8Array();
|
|
2951
|
+
function logVerifierThrowWithoutItsMessage({ plan, ctx }, error) {
|
|
2952
|
+
plan.logger.warn("A webhook verifier threw, so its delivery was refused", {
|
|
2953
|
+
service: plan.service.name,
|
|
2954
|
+
webhook: plan.route.action,
|
|
2955
|
+
error: error instanceof Error ? error.constructor.name : typeof error,
|
|
2956
|
+
requestId: ctx.requestId
|
|
2957
|
+
});
|
|
2958
|
+
}
|
|
2959
|
+
async function verifyDelivery(delivery, rawBody) {
|
|
2960
|
+
const { webhook, request } = delivery;
|
|
2961
|
+
let verdict;
|
|
2962
|
+
try {
|
|
2963
|
+
verdict = await webhook.verify({
|
|
2964
|
+
rawBody,
|
|
2965
|
+
headers: request.headers,
|
|
2966
|
+
url: request.url,
|
|
2967
|
+
method: request.method
|
|
2968
|
+
});
|
|
2969
|
+
} catch (error) {
|
|
2970
|
+
logVerifierThrowWithoutItsMessage(delivery, error);
|
|
2971
|
+
verdict = false;
|
|
2972
|
+
}
|
|
2973
|
+
const given = eventIdFrom(verdict?.eventId);
|
|
2974
|
+
if (verdict !== true && !given) {
|
|
2975
|
+
delivery.outcome = "refused";
|
|
2976
|
+
throw refuse("UNAUTHORIZED", "Webhook verification failed", 401);
|
|
2977
|
+
}
|
|
2978
|
+
delivery.eventId = verdict === true ? void 0 : given;
|
|
2979
|
+
}
|
|
2980
|
+
function parseAndCheckInput(delivery, rawBody) {
|
|
2981
|
+
const { plan, request } = delivery;
|
|
2982
|
+
const { route, inputChecker, checkInput } = plan;
|
|
2983
|
+
delivery.outcome = "invalid";
|
|
2984
|
+
let input = webhookInput(route, request, rawBody);
|
|
2985
|
+
if (inputChecker) validateInput(inputChecker, input, route.action, checkInput);
|
|
2986
|
+
input = Value.Clean(plan.action.config.input, input);
|
|
2987
|
+
delivery.outcome = "failed";
|
|
2988
|
+
return input;
|
|
2989
|
+
}
|
|
2990
|
+
async function resolveEventId(delivery, input) {
|
|
2991
|
+
const { webhook, request } = delivery;
|
|
2992
|
+
delivery.eventId ??= eventIdFrom(await webhook.eventId?.({
|
|
2993
|
+
input,
|
|
2994
|
+
headers: request.headers,
|
|
2995
|
+
url: request.url,
|
|
2996
|
+
method: request.method
|
|
2997
|
+
}));
|
|
2998
|
+
}
|
|
2999
|
+
async function claimEvent(delivery) {
|
|
3000
|
+
const { plan, storage, eventId } = delivery;
|
|
3001
|
+
if (!storage) return;
|
|
3002
|
+
if (!eventId) {
|
|
3003
|
+
delivery.outcome = "no_event_id";
|
|
3004
|
+
throw refuse("BAD_REQUEST", "The delivery has no event id", 400);
|
|
3005
|
+
}
|
|
3006
|
+
const claim = delivery.claim = {
|
|
3007
|
+
key: storageKey("webhook", [
|
|
3008
|
+
plan.service.name,
|
|
3009
|
+
plan.route.action,
|
|
3010
|
+
eventId
|
|
3011
|
+
]),
|
|
3012
|
+
mine: `pending:${crypto.randomUUID()}`
|
|
3013
|
+
};
|
|
3014
|
+
try {
|
|
3015
|
+
const claimed = await storage.putIfAbsent(claim.key, claim.mine, IN_FLIGHT_CLAIM_MS);
|
|
3016
|
+
if (claimed.stored) return;
|
|
3017
|
+
if (claimed.value === HANDLED) {
|
|
3018
|
+
delivery.outcome = "duplicate";
|
|
3019
|
+
return ALREADY_HANDLED;
|
|
3020
|
+
}
|
|
3021
|
+
delivery.outcome = "in_flight";
|
|
3022
|
+
throw refuse("CONFLICT", "Another delivery of this event is being handled; retry later", 409);
|
|
3023
|
+
} catch (error) {
|
|
3024
|
+
if (!(error instanceof StorageUnavailableError)) throw error;
|
|
3025
|
+
releaseClaim(delivery);
|
|
3026
|
+
delivery.outcome = "unavailable";
|
|
3027
|
+
throw new ActionExecutionError("SERVICE_UNAVAILABLE", "Webhook storage is unavailable; retry later", 503, void 0, { cause: error });
|
|
3028
|
+
}
|
|
3029
|
+
}
|
|
3030
|
+
async function resolveContext({ plan, ctx }) {
|
|
3031
|
+
if (!plan.contextHook) return;
|
|
3032
|
+
const extra = await plan.contextHook(ctx);
|
|
3033
|
+
if (extra) Object.assign(ctx, extra);
|
|
3034
|
+
resolveServiceDeps(ctx, plan);
|
|
3035
|
+
}
|
|
3036
|
+
async function enforceWebhookRateLimits({ plan, limits, ctx }, input) {
|
|
3037
|
+
if (limits) await enforceRateLimits(plan.service, "action", plan.route.action, limits, input, ctx);
|
|
3038
|
+
}
|
|
3039
|
+
async function releaseClaim({ storage, claim }) {
|
|
3040
|
+
await storage?.compareAndDelete(claim.key, claim.mine).catch(() => {});
|
|
3041
|
+
}
|
|
3042
|
+
async function settleClaim(delivery, result) {
|
|
3043
|
+
const { plan, webhook, storage, claim, ctx } = delivery;
|
|
3044
|
+
const failed = result instanceof Response && result.status >= 400;
|
|
3045
|
+
if (storage && failed) await releaseClaim(delivery);
|
|
3046
|
+
else if (storage && webhook.replay) await storage.put(claim.key, HANDLED, webhook.replay.ttlMs).catch((error) => plan.logger.warn("Webhook handled, but its id was not recorded; a retry may run it again", { requestId: ctx.requestId }, error));
|
|
3047
|
+
delivery.outcome = failed ? "failed" : "processed";
|
|
3048
|
+
}
|
|
3049
|
+
function resolveServiceDeps(ctx, plan) {
|
|
3050
|
+
markResolved(ctx, plan.service, plan.service.deps);
|
|
3051
|
+
ctx.deps = scopeFiles(plan.deps ?? plan.service.deps, ctx);
|
|
624
3052
|
}
|
|
625
3053
|
/** The HTTP handler of one route: the pipeline's stages, synchronous when no stage needs to wait. */
|
|
626
3054
|
function bindRoute(plan) {
|
|
3055
|
+
if (plan.route.kind === "webhook") return bindWebhook(plan);
|
|
627
3056
|
const { route, execute, contextHook, authorize, inputChecker, outputChecker, checkInput, errorBuilder } = plan;
|
|
628
3057
|
const name = route.action;
|
|
3058
|
+
const limits = rateLimitsOf(plan.action.config);
|
|
3059
|
+
const audit = auditStage(plan.service, plan.action);
|
|
629
3060
|
const stages = {
|
|
630
3061
|
name,
|
|
3062
|
+
dashboardOnly: plan.action.config.dashboard === true,
|
|
631
3063
|
checkInput: (input) => {
|
|
632
3064
|
if (inputChecker) validateInput(inputChecker, input, name, checkInput);
|
|
633
3065
|
},
|
|
3066
|
+
rateLimit: limits && ((input, ctx) => enforceRateLimits(plan.service, plan.action.kind === "tool" ? "tool" : "action", name, limits, input, ctx)),
|
|
634
3067
|
authorize,
|
|
3068
|
+
audit,
|
|
635
3069
|
execute,
|
|
636
3070
|
errorBuilder,
|
|
637
3071
|
checkOutput: (result) => {
|
|
638
3072
|
if (outputChecker) validate(outputChecker, result, name, "output");
|
|
639
3073
|
return result;
|
|
640
|
-
}
|
|
3074
|
+
},
|
|
3075
|
+
sensitive: plan.sensitive
|
|
641
3076
|
};
|
|
642
|
-
if (contextHook || authorize
|
|
643
|
-
const
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
3077
|
+
if (contextHook || authorize || stages.dashboardOnly || limits || audit || stages.sensitive) {
|
|
3078
|
+
const brickAction = async (context) => {
|
|
3079
|
+
const ctx = requestContext(plan, context);
|
|
3080
|
+
try {
|
|
3081
|
+
const input = readInput(route, context);
|
|
3082
|
+
if (contextHook) {
|
|
3083
|
+
const extra = await contextHook(ctx);
|
|
3084
|
+
if (extra) Object.assign(ctx, extra);
|
|
3085
|
+
resolveServiceDeps(ctx, plan);
|
|
3086
|
+
}
|
|
3087
|
+
return await runStages(stages, input, ctx);
|
|
3088
|
+
} catch (err) {
|
|
3089
|
+
return mapError(err, context.set, ctx);
|
|
650
3090
|
}
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
}
|
|
655
|
-
};
|
|
3091
|
+
};
|
|
3092
|
+
return stages.sensitive ? (context) => withRedaction(() => brickAction(context)) : brickAction;
|
|
3093
|
+
}
|
|
656
3094
|
return function brickAction(context) {
|
|
657
|
-
const input = readInput(route, context);
|
|
658
3095
|
const ctx = requestContext(plan, context);
|
|
659
3096
|
try {
|
|
3097
|
+
const input = readInput(route, context);
|
|
660
3098
|
stages.checkInput(input);
|
|
661
3099
|
const result = execute({
|
|
662
3100
|
input,
|
|
@@ -677,7 +3115,7 @@ const compilerRuntime = Object.freeze({ bindRoute });
|
|
|
677
3115
|
* The `error` helpers an action receives: one function per error code that
|
|
678
3116
|
* throws an `ActionExecutionError` with that code and status. The standard HTTP
|
|
679
3117
|
* codes (`BAD_REQUEST`, `UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`,
|
|
680
|
-
* `INTERNAL_SERVER_ERROR`) are always there; the action's own `errors` add to
|
|
3118
|
+
* `RATE_LIMITED`, `INTERNAL_SERVER_ERROR`) are always there; the action's own `errors` add to
|
|
681
3119
|
* them or replace one.
|
|
682
3120
|
*
|
|
683
3121
|
* @param errorsDef - The action's `errors`: for each code, its `message` and
|
|
@@ -724,13 +3162,16 @@ function defineAction(config) {
|
|
|
724
3162
|
ctx
|
|
725
3163
|
});
|
|
726
3164
|
};
|
|
3165
|
+
const limits = rateLimitsOf(config);
|
|
727
3166
|
const stages = {
|
|
728
3167
|
name: config.name,
|
|
3168
|
+
dashboardOnly: config.dashboard === true,
|
|
729
3169
|
checkInput: (input) => {
|
|
730
3170
|
if (!config.input) return;
|
|
731
3171
|
const checked = actionFn.validateInput(input);
|
|
732
3172
|
if (!checked.success) throw invalid(config.name, "input", checked.errors);
|
|
733
3173
|
},
|
|
3174
|
+
rateLimit: limits && ((input, ctx) => enforceRateLimits(actionMeta(actionFn).service, actionFn.kind === "tool" ? "tool" : "action", config.name, limits, input, ctx)),
|
|
734
3175
|
authorize: config.authorize,
|
|
735
3176
|
execute: config.execute,
|
|
736
3177
|
errorBuilder: errorHelpers,
|
|
@@ -739,22 +3180,43 @@ function defineAction(config) {
|
|
|
739
3180
|
const checked = actionFn.validateOutput(result);
|
|
740
3181
|
if (!checked.success) throw invalid(config.name, "output", checked.errors);
|
|
741
3182
|
return result;
|
|
742
|
-
}
|
|
3183
|
+
},
|
|
3184
|
+
sensitive: sensitivity(config)
|
|
743
3185
|
};
|
|
744
|
-
|
|
3186
|
+
const auditStageOf = memoizedPerAuditTable(actionFn);
|
|
3187
|
+
const run = async (params) => {
|
|
745
3188
|
const meta = actionMeta(actionFn);
|
|
746
3189
|
const ctx = meta.service ? await meta.service.resolveContext(params?.ctx, meta.deps?.values) : {
|
|
747
3190
|
...baseContext(params?.ctx ?? {}),
|
|
748
3191
|
...params?.ctx
|
|
749
3192
|
};
|
|
750
3193
|
try {
|
|
751
|
-
|
|
3194
|
+
const audit = auditStageOf(meta.service);
|
|
3195
|
+
return await runStages(audit ? {
|
|
3196
|
+
...stages,
|
|
3197
|
+
audit
|
|
3198
|
+
} : stages, params?.input, ctx);
|
|
752
3199
|
} catch (err) {
|
|
753
3200
|
throw normalizeActionError(err, ctx);
|
|
754
3201
|
}
|
|
755
3202
|
};
|
|
3203
|
+
actionFn.execute = stages.sensitive ? (params) => withRedaction(() => run(params)) : run;
|
|
756
3204
|
return actionFn;
|
|
757
3205
|
}
|
|
3206
|
+
function memoizedPerAuditTable(action) {
|
|
3207
|
+
let memo;
|
|
3208
|
+
return (service) => {
|
|
3209
|
+
const table = service?.getAuditTable();
|
|
3210
|
+
if (memo && table === memo.table && service === memo.service) return memo.stage;
|
|
3211
|
+
const stage = service && auditStage(service, action);
|
|
3212
|
+
memo = {
|
|
3213
|
+
service,
|
|
3214
|
+
table,
|
|
3215
|
+
stage
|
|
3216
|
+
};
|
|
3217
|
+
return stage;
|
|
3218
|
+
};
|
|
3219
|
+
}
|
|
758
3220
|
// src/http.ts
|
|
759
3221
|
/** The HTTP methods an action, endpoint or plugin route can use. */
|
|
760
3222
|
const HTTP_METHODS = [
|
|
@@ -764,11 +3226,6 @@ const HTTP_METHODS = [
|
|
|
764
3226
|
"PATCH",
|
|
765
3227
|
"DELETE"
|
|
766
3228
|
];
|
|
767
|
-
// src/service-port.ts
|
|
768
|
-
/** The port of a service: every `Service` is a `ServicePort`. */
|
|
769
|
-
function portOf(service) {
|
|
770
|
-
return service;
|
|
771
|
-
}
|
|
772
3229
|
// src/plugin.ts
|
|
773
3230
|
/**
|
|
774
3231
|
* Define a plugin that installs onto a service with `service.use(plugin)`. Its
|
|
@@ -975,6 +3432,10 @@ function installPlugin(service, resource, descriptor) {
|
|
|
975
3432
|
const name = `${resource ? `${resource.name}.` : ""}${config.name}`;
|
|
976
3433
|
if (service.getAction(name)) throw new DuplicateNameError(`Duplicate plugin action '${name}' (from plugin '${descriptor.name}')`);
|
|
977
3434
|
const { scope: _scope, runtimeOutput, checkInput, ...actionConfig } = config;
|
|
3435
|
+
sensitivity({
|
|
3436
|
+
...actionConfig,
|
|
3437
|
+
name
|
|
3438
|
+
}, service.name);
|
|
978
3439
|
const action = defineAction({
|
|
979
3440
|
...actionConfig,
|
|
980
3441
|
name
|
|
@@ -1057,67 +3518,17 @@ function hasPlugin(service, host, name) {
|
|
|
1057
3518
|
return states.get(service)?.hosts.get(host)?.get(name)?.status === "installed";
|
|
1058
3519
|
}
|
|
1059
3520
|
/** Every descriptor installed on the service or its resources, in install order per host. */
|
|
1060
|
-
function installedPlugins(service) {
|
|
1061
|
-
return [...states.get(service)?.hosts.values() ?? []].flatMap((installations) => [...installations.values()].filter((item) => item.status === "installed").map((item) => item.descriptor));
|
|
1062
|
-
}
|
|
1063
|
-
// src/deps.ts
|
|
1064
|
-
/**
|
|
1065
|
-
* Declare a dependency a service needs, without creating it. The app provides
|
|
1066
|
-
* the value with `brick({ deps })`, and the service's code reads it as
|
|
1067
|
-
* `ctx.deps.<name>` (or `useDeps()` in listeners and workflow steps).
|
|
1068
|
-
*
|
|
1069
|
-
* @returns A slot typed as `T`. It holds nothing at runtime.
|
|
1070
|
-
* @example
|
|
1071
|
-
* import { defineService, port } from "@brickkit/core";
|
|
1072
|
-
*
|
|
1073
|
-
* export const orders = defineService("orders", {
|
|
1074
|
-
* database,
|
|
1075
|
-
* deps: { carrier: port<Carrier>() },
|
|
1076
|
-
* });
|
|
1077
|
-
*
|
|
1078
|
-
* // app.ts
|
|
1079
|
-
* export default brick({ services: [orders], deps: { carrier: createCarrier() } });
|
|
1080
|
-
*/
|
|
1081
|
-
function port() {
|
|
1082
|
-
return Object.freeze({});
|
|
1083
|
-
}
|
|
1084
|
-
/** Where a listener a plugin added keeps the plugin's deps, for its handler and workflow steps; global so a second core copy finds it. */
|
|
1085
|
-
const PLUGIN_DEPS = Symbol.for("brickkit.plugin.deps");
|
|
1086
|
-
const running = new AsyncLocalStorage();
|
|
1087
|
-
/** Run `fn` with the deps of one app, so `useDeps()` inside it finds them. */
|
|
1088
|
-
function runWithDeps(deps, fn) {
|
|
1089
|
-
return running.run(deps, fn);
|
|
1090
|
-
}
|
|
1091
|
-
function useDeps() {
|
|
1092
|
-
const deps = running.getStore();
|
|
1093
|
-
if (!deps) throw new Error("useDeps() was called outside a Brick app: call it from a listener or a workflow step (actions read ctx.deps).");
|
|
1094
|
-
return deps;
|
|
1095
|
-
}
|
|
1096
|
-
/**
|
|
1097
|
-
* Check `brick({ deps })` against what the services declare, and give each
|
|
1098
|
-
* service the values of its own ports.
|
|
1099
|
-
*
|
|
1100
|
-
* @throws When a service declares a dep the app does not provide, or the app
|
|
1101
|
-
* provides one that no service declares.
|
|
1102
|
-
*/
|
|
1103
|
-
function bindDeps(services, provided = {}) {
|
|
1104
|
-
const declared = /* @__PURE__ */ new Set();
|
|
1105
|
-
for (const service of services) {
|
|
1106
|
-
const own = {};
|
|
1107
|
-
for (const name of Object.keys(service.options.deps ?? {})) {
|
|
1108
|
-
if (!Object.hasOwn(provided, name) || provided[name] === void 0) throw new Error(`Brick: service "${service.name}" declares dep "${name}", but brick({ deps }) does not provide it`);
|
|
1109
|
-
declared.add(name);
|
|
1110
|
-
own[name] = provided[name];
|
|
1111
|
-
}
|
|
1112
|
-
portOf(service).setDeps(Object.freeze(own));
|
|
1113
|
-
}
|
|
1114
|
-
for (const name of Object.keys(provided)) if (!declared.has(name)) throw new Error(`Brick: brick({ deps }) provides "${name}", but no service declares it (services: ${services.map((service) => service.name).join(", ") || "none"})`);
|
|
3521
|
+
function installedPlugins(service) {
|
|
3522
|
+
return [...states.get(service)?.hosts.values() ?? []].flatMap((installations) => [...installations.values()].filter((item) => item.status === "installed").map((item) => item.descriptor));
|
|
1115
3523
|
}
|
|
1116
3524
|
// src/plugin-app.ts
|
|
1117
3525
|
const INTERNALS = Symbol.for("brickkit.plugin.internals");
|
|
1118
3526
|
function isPluginInstance(value) {
|
|
1119
3527
|
return typeof value === "object" && value !== null && INTERNALS in value;
|
|
1120
3528
|
}
|
|
3529
|
+
function pluginDepsOf(value) {
|
|
3530
|
+
return internalsOf(value)?.deps ?? {};
|
|
3531
|
+
}
|
|
1121
3532
|
function internalsOf(value) {
|
|
1122
3533
|
return isPluginInstance(value) ? value[INTERNALS] ?? void 0 : void 0;
|
|
1123
3534
|
}
|
|
@@ -1195,7 +3606,8 @@ function setupAppPlugins(installedOnServices, appPlugins) {
|
|
|
1195
3606
|
lifecycles,
|
|
1196
3607
|
middleware,
|
|
1197
3608
|
listeners,
|
|
1198
|
-
plugins: listed
|
|
3609
|
+
plugins: listed,
|
|
3610
|
+
deps: ordered.map((plugin) => internalsOf(plugin).deps)
|
|
1199
3611
|
};
|
|
1200
3612
|
}
|
|
1201
3613
|
/**
|
|
@@ -1237,37 +3649,14 @@ function pluginLifecycle(lifecycles) {
|
|
|
1237
3649
|
}
|
|
1238
3650
|
};
|
|
1239
3651
|
}
|
|
1240
|
-
// src/definition-site.ts
|
|
1241
|
-
const brickRoot = fileURLToPath(new URL("..", import.meta.url));
|
|
1242
|
-
/**
|
|
1243
|
-
* The first `file:line` outside Brick on the current stack: where a name is
|
|
1244
|
-
* being defined. Best-effort: `undefined` when there is no stack.
|
|
1245
|
-
*/
|
|
1246
|
-
function definitionSite() {
|
|
1247
|
-
const limit = Error.stackTraceLimit;
|
|
1248
|
-
Error.stackTraceLimit = 50;
|
|
1249
|
-
const stack = (/* @__PURE__ */ new Error()).stack;
|
|
1250
|
-
Error.stackTraceLimit = limit;
|
|
1251
|
-
for (const line of stack?.split("\n").slice(1) ?? []) {
|
|
1252
|
-
const match = /(?:\(|at )(?:file:\/\/)?([^\s()?]+)(?:\?[^\s():]*)?:(\d+):\d+\)?$/.exec(line);
|
|
1253
|
-
if (!match) continue;
|
|
1254
|
-
const [, file, row] = match;
|
|
1255
|
-
if (file.startsWith(`${brickRoot}src/`) || file.startsWith(`${brickRoot}dist/`)) continue;
|
|
1256
|
-
return `${file}:${row}`;
|
|
1257
|
-
}
|
|
1258
|
-
}
|
|
1259
|
-
/**
|
|
1260
|
-
* Records where `name` is defined. The same file defining it again (a dev
|
|
1261
|
-
* reload) replaces the old definition.
|
|
1262
|
-
*
|
|
1263
|
-
* @throws When a different file already defined `name`.
|
|
1264
|
-
*/
|
|
1265
|
-
function claimName(sites, label, name, site) {
|
|
1266
|
-
const file = (at) => at?.replace(/:\d+$/, "");
|
|
1267
|
-
if (sites.has(name) && file(sites.get(name)) !== file(site)) throw new DuplicateNameError(`Brick: duplicate ${label}\n ${sites.get(name) ?? "unknown"}\n ${site ?? "unknown"}`);
|
|
1268
|
-
sites.set(name, site);
|
|
1269
|
-
}
|
|
1270
3652
|
// src/compiler/ir.ts
|
|
3653
|
+
const FORM_FIELDS_AND_FRAMING_BYTES = 1048576;
|
|
3654
|
+
function coercionOf(schema) {
|
|
3655
|
+
if (schema?.type === "number" || schema?.type === "integer") return "number";
|
|
3656
|
+
if (schema?.type === "boolean") return "boolean";
|
|
3657
|
+
if (schema?.type === "array") return "array";
|
|
3658
|
+
if (schema?.type === "object") return "json";
|
|
3659
|
+
}
|
|
1271
3660
|
function freezeIR(value) {
|
|
1272
3661
|
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
1273
3662
|
for (const child of Object.values(value)) freezeIR(child);
|
|
@@ -1300,6 +3689,7 @@ function analyzeDeclaredApplication(services, prefix = DEFAULT_PREFIX) {
|
|
|
1300
3689
|
const key = routeKey(method, path);
|
|
1301
3690
|
const previous = registered.get(key);
|
|
1302
3691
|
if (previous) {
|
|
3692
|
+
if (route.kind === "webhook" || previous.webhook) throw new DuplicateNameError(`Brick compiler: '${service.name}.${action.name}' and '${previous.name}' both claim '${method} ${path}', and a webhook cannot share its route`);
|
|
1303
3693
|
if (route.plugin || previous.plugin) throw new DuplicateNameError(`Brick compiler: duplicate plugin route '${method} ${path}'`);
|
|
1304
3694
|
diagnostics.push(`${key}: '${service.name}.${action.name}' shadowed by '${previous.name}' (earlier service, then lower action name, wins)`);
|
|
1305
3695
|
return;
|
|
@@ -1307,7 +3697,8 @@ function analyzeDeclaredApplication(services, prefix = DEFAULT_PREFIX) {
|
|
|
1307
3697
|
if (typeof action.config.execute !== "function") throw new Error(`Brick compiler: '${service.name}.${action.name}' has no execute handler`);
|
|
1308
3698
|
registered.set(key, {
|
|
1309
3699
|
name: `${service.name}.${action.name}`,
|
|
1310
|
-
plugin: Boolean(route.plugin)
|
|
3700
|
+
plugin: Boolean(route.plugin),
|
|
3701
|
+
webhook: route.kind === "webhook"
|
|
1311
3702
|
});
|
|
1312
3703
|
routes.push(route);
|
|
1313
3704
|
bindings.push({
|
|
@@ -1355,26 +3746,31 @@ function analyzeDeclaredApplication(services, prefix = DEFAULT_PREFIX) {
|
|
|
1355
3746
|
const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
1356
3747
|
/** What the compiler records about one action route. */
|
|
1357
3748
|
function describeRoute(service, action, method, path) {
|
|
3749
|
+
for (const name of pathParamNames(path)) if (marksKey(action.config.input, name)) throw new Error(`Service '${service.name}' action '${action.name}': sensitive input field '/${name}' is a path parameter of '${method} ${path}', and request logs and traces record the path; take it in the request body instead`);
|
|
1358
3750
|
const coercions = [];
|
|
1359
|
-
for (const [key, prop] of Object.entries(action.config.input?.properties ?? {}))
|
|
1360
|
-
|
|
1361
|
-
type
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
3751
|
+
for (const [key, prop] of Object.entries(action.config.input?.properties ?? {})) {
|
|
3752
|
+
const type = coercionOf(prop);
|
|
3753
|
+
if (!type) continue;
|
|
3754
|
+
const items = type === "array" ? coercionOf(prop.items) : void 0;
|
|
3755
|
+
coercions.push(items && items !== "array" ? {
|
|
3756
|
+
key,
|
|
3757
|
+
type,
|
|
3758
|
+
items
|
|
3759
|
+
} : {
|
|
3760
|
+
key,
|
|
3761
|
+
type
|
|
3762
|
+
});
|
|
3763
|
+
}
|
|
1371
3764
|
const plugin = actionMeta(action).route?.plugin;
|
|
3765
|
+
const files = fileFields(action.config.input);
|
|
3766
|
+
const webhook = webhookOf(action);
|
|
3767
|
+
const bodyLimit = webhook ? webhook.maxBodyBytes : files.length && files.every((field) => field.maxBytes !== void 0) ? files.reduce((sum, field) => sum + (field.maxBytes ?? 0), 0) + FORM_FIELDS_AND_FRAMING_BYTES : void 0;
|
|
1372
3768
|
return {
|
|
1373
3769
|
method,
|
|
1374
3770
|
path,
|
|
1375
3771
|
service: service.name,
|
|
1376
3772
|
action: action.name,
|
|
1377
|
-
kind: "action",
|
|
3773
|
+
kind: webhook ? "webhook" : "action",
|
|
1378
3774
|
...plugin ? { plugin } : {},
|
|
1379
3775
|
input: Boolean(action.config.input),
|
|
1380
3776
|
output: Boolean(action.config.output),
|
|
@@ -1383,6 +3779,7 @@ function describeRoute(service, action, method, path) {
|
|
|
1383
3779
|
readLike: isReadLike(method, action.name),
|
|
1384
3780
|
inputSource: inputSource(method),
|
|
1385
3781
|
coercions,
|
|
3782
|
+
...bodyLimit === void 0 ? {} : { bodyLimit },
|
|
1386
3783
|
inputSchema: schemaSnapshot(action.config.input),
|
|
1387
3784
|
outputSchema: schemaSnapshot(action.config.output)
|
|
1388
3785
|
};
|
|
@@ -1405,6 +3802,7 @@ function planRoute(route, service, action) {
|
|
|
1405
3802
|
logger: createLogger(`[${service.name}:${action.name}]`),
|
|
1406
3803
|
cachedDb: service.getDb(),
|
|
1407
3804
|
checkInput: meta.checkInput,
|
|
3805
|
+
sensitive: sensitivity(action.config, service.name),
|
|
1408
3806
|
deps: meta.deps?.values
|
|
1409
3807
|
};
|
|
1410
3808
|
}
|
|
@@ -1460,6 +3858,8 @@ function eventRefs(service, catalog) {
|
|
|
1460
3858
|
for (const [key, schema] of Object.entries(catalog ?? {})) {
|
|
1461
3859
|
if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(key)) throw new Error(`Event "${key}" in service "${service}" must be a plain name such as shipped or itemAdded`);
|
|
1462
3860
|
if (!schema || typeof schema !== "object") throw new Error(`Event "${service}.${key}" needs a payload schema, such as t.Object({ ... })`);
|
|
3861
|
+
const at = sensitivePointer(schema);
|
|
3862
|
+
if (at) throw new Error(`Event "${service}.${key}" payload marks '${at}' t.Sensitive, which event payloads do not support yet; carry an id and load the secret in the listener`);
|
|
1463
3863
|
refs[key] = Object.freeze({
|
|
1464
3864
|
name: `${service}.${key}`,
|
|
1465
3865
|
service,
|
|
@@ -1941,6 +4341,15 @@ function getActionAccess(action) {
|
|
|
1941
4341
|
policy
|
|
1942
4342
|
};
|
|
1943
4343
|
}
|
|
4344
|
+
/**
|
|
4345
|
+
* Say how the audit log records an action a plugin owns: `"inline"` when the
|
|
4346
|
+
* plugin writes in its own transaction and records the write there with a
|
|
4347
|
+
* host hook, `"none"` when it never writes. Without this, an action that is not
|
|
4348
|
+
* a `GET` is recorded after it runs, as a plain action is.
|
|
4349
|
+
*/
|
|
4350
|
+
function setActionAudit(action, mode) {
|
|
4351
|
+
actionMeta(action).audit = mode;
|
|
4352
|
+
}
|
|
1944
4353
|
// src/openapi.ts
|
|
1945
4354
|
/** The OpenAPI document's defaults, shared by `brick()` and `generateOpenApiSpec`. */
|
|
1946
4355
|
const OPENAPI_DEFAULTS = Object.freeze({
|
|
@@ -2033,6 +4442,7 @@ function generateOpenApiSpec(options = {}) {
|
|
|
2033
4442
|
const { plugin, resource } = actionOwners(action);
|
|
2034
4443
|
const group = resource ? `${service.name} · ${resource}` : service.name;
|
|
2035
4444
|
if (resource) tags.set(group, `Routes of resource '${resource}' in service '${service.name}'`);
|
|
4445
|
+
const webhook = webhookOf(action);
|
|
2036
4446
|
const hasAuth = getActionAccess(action).hasAuthorize;
|
|
2037
4447
|
if (hasAuth) hasAnyAuthorizedAction = true;
|
|
2038
4448
|
const responses = {};
|
|
@@ -2068,6 +4478,32 @@ function generateOpenApiSpec(options = {}) {
|
|
|
2068
4478
|
addError("UNAUTHORIZED", 401, "Authentication required");
|
|
2069
4479
|
addError("FORBIDDEN", 403, "Access denied");
|
|
2070
4480
|
}
|
|
4481
|
+
if (webhook) {
|
|
4482
|
+
addError("UNAUTHORIZED", 401, "Webhook verification failed");
|
|
4483
|
+
addError("PAYLOAD_TOO_LARGE", 413, `Body over ${webhook.maxBodyBytes} bytes`);
|
|
4484
|
+
if (webhook.replay) {
|
|
4485
|
+
addError("CONFLICT", 409, "Another delivery of this event is being handled; retry later");
|
|
4486
|
+
addError("SERVICE_UNAVAILABLE", 503, "Webhook storage is unavailable; retry later");
|
|
4487
|
+
}
|
|
4488
|
+
}
|
|
4489
|
+
if (action.config.dashboard === true) addError("UNAUTHORIZED", 401, "Only for the dashboard");
|
|
4490
|
+
if (rateLimitsOf(action.config)) {
|
|
4491
|
+
addError("RATE_LIMITED", 429, "Too many calls; retry after Retry-After seconds", {
|
|
4492
|
+
type: "object",
|
|
4493
|
+
properties: { retryAfterSeconds: {
|
|
4494
|
+
type: "integer",
|
|
4495
|
+
minimum: 1
|
|
4496
|
+
} },
|
|
4497
|
+
required: ["retryAfterSeconds"]
|
|
4498
|
+
});
|
|
4499
|
+
responses["429"].headers = { "Retry-After": {
|
|
4500
|
+
description: "Seconds until the window resets",
|
|
4501
|
+
schema: {
|
|
4502
|
+
type: "integer",
|
|
4503
|
+
minimum: 1
|
|
4504
|
+
}
|
|
4505
|
+
} };
|
|
4506
|
+
}
|
|
2071
4507
|
if (action.config.errors) for (const [code, errorDef] of Object.entries(action.config.errors)) {
|
|
2072
4508
|
const def = errorDef;
|
|
2073
4509
|
addError(code, def.status || 400, def.message || code, def.details);
|
|
@@ -2079,11 +4515,12 @@ function generateOpenApiSpec(options = {}) {
|
|
|
2079
4515
|
summary: `${service.name}.${action.name}`,
|
|
2080
4516
|
description: action.config.description ?? `Execute action '${action.name}' on service '${service.name}'`,
|
|
2081
4517
|
tags: [.../* @__PURE__ */ new Set([group, ...action.config.tags ?? []])],
|
|
4518
|
+
...webhook ? { "x-brick-webhook": true } : {},
|
|
2082
4519
|
...plugin ? { "x-brick-plugin": plugin } : {},
|
|
2083
4520
|
...resource ? { "x-brick-resource": resource } : {},
|
|
2084
4521
|
responses
|
|
2085
4522
|
};
|
|
2086
|
-
const inputSchema = action.config.input;
|
|
4523
|
+
const inputSchema = writeOnly(action.config.input);
|
|
2087
4524
|
const properties = inputSchema?.properties ?? {};
|
|
2088
4525
|
const parameters = [...new Set(pathParams)].map((key) => ({
|
|
2089
4526
|
name: key,
|
|
@@ -2100,243 +4537,82 @@ function generateOpenApiSpec(options = {}) {
|
|
|
2100
4537
|
schema
|
|
2101
4538
|
});
|
|
2102
4539
|
}
|
|
2103
|
-
else if (inputSchema)
|
|
2104
|
-
|
|
2105
|
-
content: { "application/json": { schema: pathParams.length && inputSchema.properties ? {
|
|
4540
|
+
else if (inputSchema) {
|
|
4541
|
+
const bodySchema = pathParams.length && inputSchema.properties ? {
|
|
2106
4542
|
...inputSchema,
|
|
2107
4543
|
properties: Object.fromEntries(Object.entries(properties).filter(([key]) => !pathParams.includes(key))),
|
|
2108
|
-
required: (inputSchema.required ?? []).filter((key) => !pathParams.includes(key))
|
|
2109
|
-
} : inputSchema
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
},
|
|
2123
|
-
paths,
|
|
2124
|
-
tags: Array.from(tags, ([name, description]) => ({
|
|
2125
|
-
name,
|
|
2126
|
-
description
|
|
2127
|
-
}))
|
|
2128
|
-
};
|
|
2129
|
-
spec.components = { schemas: { ErrorEnvelope: {
|
|
2130
|
-
type: "object",
|
|
2131
|
-
required: [
|
|
2132
|
-
"name",
|
|
2133
|
-
"code",
|
|
2134
|
-
"message",
|
|
2135
|
-
"status",
|
|
2136
|
-
"requestId"
|
|
2137
|
-
],
|
|
2138
|
-
properties: {
|
|
2139
|
-
name: { type: "string" },
|
|
2140
|
-
code: { type: "string" },
|
|
2141
|
-
message: { type: "string" },
|
|
2142
|
-
status: { type: "integer" },
|
|
2143
|
-
requestId: { type: "string" },
|
|
2144
|
-
details: {},
|
|
2145
|
-
errors: {
|
|
2146
|
-
type: "array",
|
|
2147
|
-
items: {
|
|
2148
|
-
type: "object",
|
|
2149
|
-
required: ["path", "message"],
|
|
2150
|
-
properties: {
|
|
2151
|
-
path: { type: "string" },
|
|
2152
|
-
message: { type: "string" },
|
|
2153
|
-
value: {}
|
|
2154
|
-
}
|
|
2155
|
-
}
|
|
2156
|
-
}
|
|
2157
|
-
}
|
|
2158
|
-
} } };
|
|
2159
|
-
if (hasAnyAuthorizedAction) Object.assign(spec.components, { securitySchemes: { bearerAuth: {
|
|
2160
|
-
type: "http",
|
|
2161
|
-
scheme: "bearer",
|
|
2162
|
-
bearerFormat: "JWT",
|
|
2163
|
-
description: "Enter your Bearer authentication token"
|
|
2164
|
-
} } });
|
|
2165
|
-
const events = Object.fromEntries(services.flatMap((service) => Object.values(service.events ?? {}).map((ref) => [ref.name, {
|
|
2166
|
-
service: service.name,
|
|
2167
|
-
payload: ref.schema,
|
|
2168
|
-
...ref.plugin ? { "x-brick-plugin": ref.plugin } : {}
|
|
2169
|
-
}])));
|
|
2170
|
-
if (Object.keys(events).length) spec["x-brick-events"] = events;
|
|
2171
|
-
const document = JSON.parse(JSON.stringify(spec));
|
|
2172
|
-
hoistAnchoredSchemas(document);
|
|
2173
|
-
return document;
|
|
2174
|
-
}
|
|
2175
|
-
// src/secrets.ts
|
|
2176
|
-
/**
|
|
2177
|
-
* Type-safe secrets & environment variables.
|
|
2178
|
-
*
|
|
2179
|
-
* Declare each secret once at module scope instead of scattering untyped
|
|
2180
|
-
* `process.env.FOO` reads:
|
|
2181
|
-
*
|
|
2182
|
-
* const port = defineSecret("PORT").default("3333").transform(Number).require();
|
|
2183
|
-
* const baseUrl = defineSecret("BASE_URL").url().require();
|
|
2184
|
-
* const key = defineSecret("STRIPE_KEY").validate((v) =>
|
|
2185
|
-
* v.startsWith("sk_") || "must start with sk_"
|
|
2186
|
-
* ).require();
|
|
2187
|
-
*
|
|
2188
|
-
* Values resolve from the environment (Bun populates `process.env` from
|
|
2189
|
-
* `.env` locally; in prod the same env source applies — a future
|
|
2190
|
-
* `SecretSource` such as AWS can slot in without touching call sites).
|
|
2191
|
-
*
|
|
2192
|
-
* Resolution order per secret: test/session override → source (`process.env`
|
|
2193
|
-
* by default) → declared `default`. `resolveSecrets()` validates every
|
|
2194
|
-
* registered secret at boot and throws listing all missing required ones.
|
|
2195
|
-
*/
|
|
2196
|
-
/** Default source: `process.env` (Bun loads `.env` into it automatically). */
|
|
2197
|
-
const envSource = { get: (name) => process.env[name] };
|
|
2198
|
-
const registry = /* @__PURE__ */ new Map();
|
|
2199
|
-
const overrides = /* @__PURE__ */ new Map();
|
|
2200
|
-
/** Where each secret was first declared. */
|
|
2201
|
-
const sites = /* @__PURE__ */ new Map();
|
|
2202
|
-
var SecretRef = class {
|
|
2203
|
-
name;
|
|
2204
|
-
options;
|
|
2205
|
-
transformFn;
|
|
2206
|
-
validators = [];
|
|
2207
|
-
constructor(name, options = {}) {
|
|
2208
|
-
this.name = name;
|
|
2209
|
-
this.options = options;
|
|
2210
|
-
}
|
|
2211
|
-
/** True when a default was declared (i.e. the secret is optional). */
|
|
2212
|
-
get hasDefault() {
|
|
2213
|
-
return this.options.default !== void 0;
|
|
2214
|
-
}
|
|
2215
|
-
/** Fallback used when the source has no value. Makes the secret optional. */
|
|
2216
|
-
default(value) {
|
|
2217
|
-
this.options.default = value;
|
|
2218
|
-
return this;
|
|
2219
|
-
}
|
|
2220
|
-
/**
|
|
2221
|
-
* Convert the raw string (e.g. `Number`, `JSON.parse`, `v === "true"`).
|
|
2222
|
-
* Runs before validators; a throwing transform fails resolution.
|
|
2223
|
-
*/
|
|
2224
|
-
transform(fn) {
|
|
2225
|
-
this.transformFn = fn;
|
|
2226
|
-
return this;
|
|
2227
|
-
}
|
|
2228
|
-
/** Run a custom check on the (transformed) value at every resolution. */
|
|
2229
|
-
validate(fn) {
|
|
2230
|
-
this.validators.push(fn);
|
|
2231
|
-
return this;
|
|
2232
|
-
}
|
|
2233
|
-
/** Shorthand validator: value must parse as a URL. String refs only. */
|
|
2234
|
-
url() {
|
|
2235
|
-
this.validators.push((v) => {
|
|
2236
|
-
try {
|
|
2237
|
-
new URL(v);
|
|
2238
|
-
} catch {
|
|
2239
|
-
return "must be a valid URL";
|
|
2240
|
-
}
|
|
2241
|
-
});
|
|
2242
|
-
return this;
|
|
2243
|
-
}
|
|
2244
|
-
resolveRaw(source) {
|
|
2245
|
-
return overrides.get(this.name) ?? source.get(this.name) ?? this.options.default;
|
|
2246
|
-
}
|
|
2247
|
-
coerce(raw) {
|
|
2248
|
-
let value;
|
|
2249
|
-
if (this.transformFn) try {
|
|
2250
|
-
value = this.transformFn(raw);
|
|
2251
|
-
} catch (err) {
|
|
2252
|
-
throw new Error(`Invalid value for secret "${this.name}": transform failed (${err instanceof Error ? err.message : String(err)})`);
|
|
2253
|
-
}
|
|
2254
|
-
else value = raw;
|
|
2255
|
-
for (const fn of this.validators) {
|
|
2256
|
-
let result;
|
|
2257
|
-
try {
|
|
2258
|
-
result = fn(value);
|
|
2259
|
-
} catch (err) {
|
|
2260
|
-
throw new Error(`Invalid value for secret "${this.name}": ${err instanceof Error ? err.message : String(err)}`);
|
|
2261
|
-
}
|
|
2262
|
-
if (result === false) throw new Error(`Invalid value for secret "${this.name}": validation failed`);
|
|
2263
|
-
if (typeof result === "string") throw new Error(`Invalid value for secret "${this.name}": ${result}`);
|
|
2264
|
-
}
|
|
2265
|
-
return value;
|
|
2266
|
-
}
|
|
2267
|
-
/** Resolved (transformed, validated) value or `undefined`. Never throws on missing. */
|
|
2268
|
-
value(source = envSource) {
|
|
2269
|
-
const raw = this.resolveRaw(source);
|
|
2270
|
-
if (raw === void 0) return void 0;
|
|
2271
|
-
return this.coerce(raw);
|
|
2272
|
-
}
|
|
2273
|
-
/** Resolved value, or throws naming the missing/invalid secret. */
|
|
2274
|
-
require(source = envSource) {
|
|
2275
|
-
const raw = this.resolveRaw(source);
|
|
2276
|
-
if (raw === void 0) throw new Error(`Missing required secret "${this.name}": set it in .env (local) or the environment (prod)`);
|
|
2277
|
-
return this.coerce(raw);
|
|
2278
|
-
}
|
|
2279
|
-
/** True when a value would resolve (override, source, or default). */
|
|
2280
|
-
isSet(source = envSource) {
|
|
2281
|
-
return this.resolveRaw(source) !== void 0;
|
|
2282
|
-
}
|
|
2283
|
-
};
|
|
2284
|
-
/**
|
|
2285
|
-
* Declare a secret. Calling it again for the name returns the same ref. From
|
|
2286
|
-
* the same line (a module evaluated again) it starts the declaration over, so
|
|
2287
|
-
* its builder calls replace the earlier ones instead of adding to them.
|
|
2288
|
-
*/
|
|
2289
|
-
function defineSecret(name, options = {}) {
|
|
2290
|
-
const site = definitionSite();
|
|
2291
|
-
const existing = registry.get(name);
|
|
2292
|
-
if (existing) {
|
|
2293
|
-
if (site !== void 0 && sites.get(name) === site) {
|
|
2294
|
-
existing.options = options;
|
|
2295
|
-
existing["validators"] = [];
|
|
2296
|
-
existing["transformFn"] = void 0;
|
|
2297
|
-
}
|
|
2298
|
-
return existing;
|
|
2299
|
-
}
|
|
2300
|
-
sites.set(name, site);
|
|
2301
|
-
const ref = new SecretRef(name, options);
|
|
2302
|
-
registry.set(name, ref);
|
|
2303
|
-
return ref;
|
|
2304
|
-
}
|
|
2305
|
-
/**
|
|
2306
|
-
* Validate every registered secret at boot. Throws a single error listing
|
|
2307
|
-
* all missing required secrets. Returns the resolved values.
|
|
2308
|
-
*/
|
|
2309
|
-
function resolveSecrets(opts = {}) {
|
|
2310
|
-
const source = opts.source ?? envSource;
|
|
2311
|
-
const missing = [];
|
|
2312
|
-
const resolved = {};
|
|
2313
|
-
for (const ref of registry.values()) {
|
|
2314
|
-
const v = ref.value(source);
|
|
2315
|
-
if (v === void 0) missing.push(ref.name);
|
|
2316
|
-
else resolved[ref.name] = v;
|
|
4544
|
+
required: (inputSchema.required ?? []).filter((key) => !pathParams.includes(key))
|
|
4545
|
+
} : inputSchema;
|
|
4546
|
+
operation.requestBody = {
|
|
4547
|
+
required: true,
|
|
4548
|
+
content: {
|
|
4549
|
+
[fileFields(inputSchema).length ? "multipart/form-data" : "application/json"]: { schema: bodySchema },
|
|
4550
|
+
...webhook ? { "application/x-www-form-urlencoded": { schema: bodySchema } } : {}
|
|
4551
|
+
}
|
|
4552
|
+
};
|
|
4553
|
+
}
|
|
4554
|
+
if (parameters.length) operation.parameters = parameters;
|
|
4555
|
+
if (hasAuth) operation.security = [{ bearerAuth: [] }];
|
|
4556
|
+
paths[actionPath][method] = operation;
|
|
4557
|
+
}
|
|
2317
4558
|
}
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
}
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
4559
|
+
const spec = {
|
|
4560
|
+
openapi: "3.1.0",
|
|
4561
|
+
info: {
|
|
4562
|
+
title,
|
|
4563
|
+
version,
|
|
4564
|
+
description
|
|
4565
|
+
},
|
|
4566
|
+
paths,
|
|
4567
|
+
tags: Array.from(tags, ([name, description]) => ({
|
|
4568
|
+
name,
|
|
4569
|
+
description
|
|
4570
|
+
}))
|
|
4571
|
+
};
|
|
4572
|
+
spec.components = { schemas: { ErrorEnvelope: {
|
|
4573
|
+
type: "object",
|
|
4574
|
+
required: [
|
|
4575
|
+
"name",
|
|
4576
|
+
"code",
|
|
4577
|
+
"message",
|
|
4578
|
+
"status",
|
|
4579
|
+
"requestId"
|
|
4580
|
+
],
|
|
4581
|
+
properties: {
|
|
4582
|
+
name: { type: "string" },
|
|
4583
|
+
code: { type: "string" },
|
|
4584
|
+
message: { type: "string" },
|
|
4585
|
+
status: { type: "integer" },
|
|
4586
|
+
requestId: { type: "string" },
|
|
4587
|
+
details: {},
|
|
4588
|
+
errors: {
|
|
4589
|
+
type: "array",
|
|
4590
|
+
items: {
|
|
4591
|
+
type: "object",
|
|
4592
|
+
required: ["path", "message"],
|
|
4593
|
+
properties: {
|
|
4594
|
+
path: { type: "string" },
|
|
4595
|
+
message: { type: "string" }
|
|
4596
|
+
}
|
|
4597
|
+
}
|
|
4598
|
+
}
|
|
4599
|
+
}
|
|
4600
|
+
} } };
|
|
4601
|
+
if (hasAnyAuthorizedAction) Object.assign(spec.components, { securitySchemes: { bearerAuth: {
|
|
4602
|
+
type: "http",
|
|
4603
|
+
scheme: "bearer",
|
|
4604
|
+
bearerFormat: "JWT",
|
|
4605
|
+
description: "Enter your Bearer authentication token"
|
|
4606
|
+
} } });
|
|
4607
|
+
const events = Object.fromEntries(services.flatMap((service) => Object.values(service.events ?? {}).map((ref) => [ref.name, {
|
|
4608
|
+
service: service.name,
|
|
4609
|
+
payload: ref.schema,
|
|
4610
|
+
...ref.plugin ? { "x-brick-plugin": ref.plugin } : {}
|
|
4611
|
+
}])));
|
|
4612
|
+
if (Object.keys(events).length) spec["x-brick-events"] = events;
|
|
4613
|
+
const document = JSON.parse(JSON.stringify(spec));
|
|
4614
|
+
hoistAnchoredSchemas(document);
|
|
4615
|
+
return document;
|
|
2340
4616
|
}
|
|
2341
4617
|
// src/request-logger.ts
|
|
2342
4618
|
function formatLog(method, path, status, elapsedMs) {
|
|
@@ -2371,10 +4647,11 @@ function requestLoggingPlugin(opts = {}) {
|
|
|
2371
4647
|
const markStarted = ({ request }) => {
|
|
2372
4648
|
startedAt.set(request, Date.now());
|
|
2373
4649
|
};
|
|
2374
|
-
const logSuccess = ({ request, set }) => {
|
|
4650
|
+
const logSuccess = ({ request, set, responseValue }) => {
|
|
2375
4651
|
const start = startedAt.get(request) ?? Date.now();
|
|
2376
4652
|
const path = new URL(request.url).pathname;
|
|
2377
|
-
|
|
4653
|
+
const status = responseValue instanceof Response ? responseValue.status : set.status ?? 200;
|
|
4654
|
+
logger(formatLog(request.method, path, status, Date.now() - start));
|
|
2378
4655
|
};
|
|
2379
4656
|
const logError = ({ request, set, error }) => {
|
|
2380
4657
|
if (request) {
|
|
@@ -2600,44 +4877,44 @@ const OUTBOX_STATUSES = [
|
|
|
2600
4877
|
"dead"
|
|
2601
4878
|
];
|
|
2602
4879
|
function sqliteOutbox(name) {
|
|
2603
|
-
const timestampMs = (column) => integer(column, { mode: "timestamp_ms" });
|
|
4880
|
+
const timestampMs = (column) => integer$1(column, { mode: "timestamp_ms" });
|
|
2604
4881
|
return sqliteTable(name, {
|
|
2605
|
-
seq: integer("seq").primaryKey({ autoIncrement: true }),
|
|
2606
|
-
id: text("id").notNull().unique(),
|
|
2607
|
-
eventId: text("event_id").notNull(),
|
|
2608
|
-
listener: text("listener").notNull(),
|
|
2609
|
-
name: text("name").notNull(),
|
|
2610
|
-
payload: text("payload", { mode: "json" }).notNull(),
|
|
2611
|
-
traceId: text("trace_id"),
|
|
2612
|
-
source: text("source"),
|
|
4882
|
+
seq: integer$1("seq").primaryKey({ autoIncrement: true }),
|
|
4883
|
+
id: text$1("id").notNull().unique(),
|
|
4884
|
+
eventId: text$1("event_id").notNull(),
|
|
4885
|
+
listener: text$1("listener").notNull(),
|
|
4886
|
+
name: text$1("name").notNull(),
|
|
4887
|
+
payload: text$1("payload", { mode: "json" }).notNull(),
|
|
4888
|
+
traceId: text$1("trace_id"),
|
|
4889
|
+
source: text$1("source"),
|
|
2613
4890
|
occurredAt: timestampMs("occurred_at").notNull(),
|
|
2614
|
-
status: text("status").$type().notNull(),
|
|
2615
|
-
attempts: integer("attempts").notNull().default(0),
|
|
2616
|
-
lastError: text("last_error"),
|
|
4891
|
+
status: text$1("status").$type().notNull(),
|
|
4892
|
+
attempts: integer$1("attempts").notNull().default(0),
|
|
4893
|
+
lastError: text$1("last_error"),
|
|
2617
4894
|
availableAt: timestampMs("available_at").notNull(),
|
|
2618
4895
|
claimedAt: timestampMs("claimed_at"),
|
|
2619
4896
|
deliveredAt: timestampMs("delivered_at")
|
|
2620
|
-
}, (table) => [index(`${name}_due`).on(table.status, table.availableAt), index(`${name}_event`).on(table.eventId)]);
|
|
4897
|
+
}, (table) => [index$1(`${name}_due`).on(table.status, table.availableAt), index$1(`${name}_event`).on(table.eventId)]);
|
|
2621
4898
|
}
|
|
2622
4899
|
function postgresOutbox(name) {
|
|
2623
4900
|
const at = (column) => timestamp(column, { withTimezone: true });
|
|
2624
4901
|
return pgTable(name, {
|
|
2625
4902
|
seq: bigserial("seq", { mode: "number" }).primaryKey(),
|
|
2626
|
-
id: text
|
|
2627
|
-
eventId: text
|
|
2628
|
-
listener: text
|
|
2629
|
-
name: text
|
|
4903
|
+
id: text("id").notNull().unique(),
|
|
4904
|
+
eventId: text("event_id").notNull(),
|
|
4905
|
+
listener: text("listener").notNull(),
|
|
4906
|
+
name: text("name").notNull(),
|
|
2630
4907
|
payload: jsonb("payload").notNull(),
|
|
2631
|
-
traceId: text
|
|
2632
|
-
source: text
|
|
4908
|
+
traceId: text("trace_id"),
|
|
4909
|
+
source: text("source"),
|
|
2633
4910
|
occurredAt: at("occurred_at").notNull(),
|
|
2634
|
-
status: text
|
|
2635
|
-
attempts: integer
|
|
2636
|
-
lastError: text
|
|
4911
|
+
status: text("status").$type().notNull(),
|
|
4912
|
+
attempts: integer("attempts").notNull().default(0),
|
|
4913
|
+
lastError: text("last_error"),
|
|
2637
4914
|
availableAt: at("available_at").notNull(),
|
|
2638
4915
|
claimedAt: at("claimed_at"),
|
|
2639
4916
|
deliveredAt: at("delivered_at")
|
|
2640
|
-
}, (table) => [index
|
|
4917
|
+
}, (table) => [index(`${name}_due`).on(table.status, table.availableAt), index(`${name}_event`).on(table.eventId)]);
|
|
2641
4918
|
}
|
|
2642
4919
|
function outboxTable(engine, options = {}) {
|
|
2643
4920
|
const name = options.name ?? "brick_outbox";
|
|
@@ -2687,130 +4964,6 @@ function deliveryOf(row) {
|
|
|
2687
4964
|
function outboxEngine(table) {
|
|
2688
4965
|
return table[OUTBOX].engine;
|
|
2689
4966
|
}
|
|
2690
|
-
// src/events/transaction.ts
|
|
2691
|
-
const sqliteQueues = /* @__PURE__ */ new WeakMap();
|
|
2692
|
-
const active = new AsyncLocalStorage();
|
|
2693
|
-
function joined(db) {
|
|
2694
|
-
const open = active.getStore();
|
|
2695
|
-
return open?.open && open.handles.has(db) ? open : void 0;
|
|
2696
|
-
}
|
|
2697
|
-
function isSqliteDatabase(db) {
|
|
2698
|
-
return typeof db?.$client?.prepare === "function" && typeof db?.$client?.run === "function";
|
|
2699
|
-
}
|
|
2700
|
-
function rollbackQuietly(db, statement = "ROLLBACK") {
|
|
2701
|
-
try {
|
|
2702
|
-
db.$client.run(statement);
|
|
2703
|
-
} catch {
|
|
2704
|
-
return;
|
|
2705
|
-
}
|
|
2706
|
-
}
|
|
2707
|
-
async function nested(db, open, fn) {
|
|
2708
|
-
const commits = open.commits.length;
|
|
2709
|
-
try {
|
|
2710
|
-
if (!isSqliteDatabase(db)) return await db.transaction((tx) => {
|
|
2711
|
-
open.handles.add(tx);
|
|
2712
|
-
return fn(tx);
|
|
2713
|
-
});
|
|
2714
|
-
const name = `brick_${++open.savepoints}`;
|
|
2715
|
-
db.$client.run(`SAVEPOINT ${name}`);
|
|
2716
|
-
try {
|
|
2717
|
-
const result = await fn(db);
|
|
2718
|
-
db.$client.run(`RELEASE ${name}`);
|
|
2719
|
-
return result;
|
|
2720
|
-
} catch (error) {
|
|
2721
|
-
rollbackQuietly(db, `ROLLBACK TO ${name}`);
|
|
2722
|
-
rollbackQuietly(db, `RELEASE ${name}`);
|
|
2723
|
-
throw error;
|
|
2724
|
-
}
|
|
2725
|
-
} catch (error) {
|
|
2726
|
-
open.commits.length = commits;
|
|
2727
|
-
throw error;
|
|
2728
|
-
}
|
|
2729
|
-
}
|
|
2730
|
-
/**
|
|
2731
|
-
* Run `fn` in a database transaction: everything it writes through the `tx` it is
|
|
2732
|
-
* given is committed together when it returns, or undone if it throws.
|
|
2733
|
-
*
|
|
2734
|
-
* Postgres uses a real transaction on one connection. SQLite has one connection
|
|
2735
|
-
* and a synchronous driver, which Drizzle's own `transaction` cannot use with an
|
|
2736
|
-
* async callback (it would commit before the callback finished). So transactions
|
|
2737
|
-
* on one SQLite database take turns, each between `BEGIN IMMEDIATE` and `COMMIT`.
|
|
2738
|
-
* A write made elsewhere in the process during that time, outside this helper,
|
|
2739
|
-
* would join the transaction; use Postgres where that matters.
|
|
2740
|
-
*
|
|
2741
|
-
* A call made inside `fn` with the `tx` it was given (on SQLite, the database
|
|
2742
|
-
* itself) joins the open transaction as a savepoint instead of waiting for it: a
|
|
2743
|
-
* nested failure undoes only the nested work, and the outer transaction decides
|
|
2744
|
-
* the commit. Nested calls must run one at a time.
|
|
2745
|
-
*
|
|
2746
|
-
* @param db - A Drizzle database, from `service.getDb()`.
|
|
2747
|
-
* @param fn - Receives the transaction handle to run queries on.
|
|
2748
|
-
* @returns What `fn` returned.
|
|
2749
|
-
* @throws What `fn` threw, after rolling back.
|
|
2750
|
-
*/
|
|
2751
|
-
async function runInTransaction(db, fn) {
|
|
2752
|
-
const outer = joined(db);
|
|
2753
|
-
if (outer) return nested(db, outer, fn);
|
|
2754
|
-
const open = {
|
|
2755
|
-
handles: /* @__PURE__ */ new Set(),
|
|
2756
|
-
commits: [],
|
|
2757
|
-
open: true,
|
|
2758
|
-
savepoints: 0
|
|
2759
|
-
};
|
|
2760
|
-
let result;
|
|
2761
|
-
try {
|
|
2762
|
-
result = await active.run(open, () => begin(db, open, fn));
|
|
2763
|
-
} finally {
|
|
2764
|
-
open.open = false;
|
|
2765
|
-
}
|
|
2766
|
-
for (const commit of open.commits) await commit();
|
|
2767
|
-
return result;
|
|
2768
|
-
}
|
|
2769
|
-
async function begin(db, open, fn) {
|
|
2770
|
-
if (!isSqliteDatabase(db)) return db.transaction((tx) => {
|
|
2771
|
-
open.handles.add(tx);
|
|
2772
|
-
return fn(tx);
|
|
2773
|
-
});
|
|
2774
|
-
open.handles.add(db);
|
|
2775
|
-
const previous = sqliteQueues.get(db) ?? Promise.resolve();
|
|
2776
|
-
let release;
|
|
2777
|
-
const turn = new Promise((resolve) => {
|
|
2778
|
-
release = resolve;
|
|
2779
|
-
});
|
|
2780
|
-
sqliteQueues.set(db, previous.then(() => turn));
|
|
2781
|
-
await previous;
|
|
2782
|
-
try {
|
|
2783
|
-
db.$client.run("BEGIN IMMEDIATE");
|
|
2784
|
-
try {
|
|
2785
|
-
const result = await fn(db);
|
|
2786
|
-
db.$client.run("COMMIT");
|
|
2787
|
-
return result;
|
|
2788
|
-
} catch (error) {
|
|
2789
|
-
rollbackQuietly(db);
|
|
2790
|
-
throw error;
|
|
2791
|
-
}
|
|
2792
|
-
} finally {
|
|
2793
|
-
release();
|
|
2794
|
-
}
|
|
2795
|
-
}
|
|
2796
|
-
/** Whether `db` belongs to a transaction opened by `runInTransaction` that is still open. */
|
|
2797
|
-
function inTransaction(db) {
|
|
2798
|
-
return joined(db) !== void 0;
|
|
2799
|
-
}
|
|
2800
|
-
/**
|
|
2801
|
-
* Run `fn` once the transaction that `db` belongs to has committed, or now when
|
|
2802
|
-
* `db` is not in one opened by `runInTransaction`. It never runs when that
|
|
2803
|
-
* transaction, or the savepoint it was queued in, rolls back. An error it throws
|
|
2804
|
-
* reaches the caller of the outermost `runInTransaction`, after the commit.
|
|
2805
|
-
*
|
|
2806
|
-
* @param db - The handle the work ran on: a `tx`, or a database.
|
|
2807
|
-
* @param fn - The side effect, such as clearing a cache.
|
|
2808
|
-
*/
|
|
2809
|
-
async function onTransactionCommit(db, fn) {
|
|
2810
|
-
const open = joined(db);
|
|
2811
|
-
if (open) open.commits.push(fn);
|
|
2812
|
-
else await fn();
|
|
2813
|
-
}
|
|
2814
4967
|
// src/events/dispatcher.ts
|
|
2815
4968
|
function resolveDispatchOptions(options) {
|
|
2816
4969
|
return {
|
|
@@ -3692,8 +5845,8 @@ var EventsHub = class {
|
|
|
3692
5845
|
stopping;
|
|
3693
5846
|
/**
|
|
3694
5847
|
* @param options - The `events` option.
|
|
3695
|
-
* @param deps - The app's
|
|
3696
|
-
* listeners and workflow steps.
|
|
5848
|
+
* @param deps - The deps of the app's services, which `useDeps()` returns in
|
|
5849
|
+
* its listeners, schedules and workflow steps.
|
|
3697
5850
|
*/
|
|
3698
5851
|
constructor(options, deps = {}) {
|
|
3699
5852
|
this.deps = deps;
|
|
@@ -3893,10 +6046,10 @@ var EventsHub = class {
|
|
|
3893
6046
|
return found;
|
|
3894
6047
|
}
|
|
3895
6048
|
bind(table, check) {
|
|
3896
|
-
const startAndNotify = () => {
|
|
6049
|
+
const startAndNotify = () => outsideRedaction(() => {
|
|
3897
6050
|
this.start();
|
|
3898
6051
|
this.dispatchers.get(table)?.notify();
|
|
3899
|
-
};
|
|
6052
|
+
});
|
|
3900
6053
|
const insert = async (tx, context, name, payload) => {
|
|
3901
6054
|
check(name, payload);
|
|
3902
6055
|
const listeners = this.matching(name);
|
|
@@ -3956,6 +6109,7 @@ function corsHook(cors) {
|
|
|
3956
6109
|
if (allows(from, request)) {
|
|
3957
6110
|
headers["access-control-allow-origin"] = from;
|
|
3958
6111
|
if (credentials) headers["access-control-allow-credentials"] = "true";
|
|
6112
|
+
headers["access-control-expose-headers"] = "Retry-After";
|
|
3959
6113
|
}
|
|
3960
6114
|
if (!(request.method === "OPTIONS" && request.headers.has("access-control-request-method"))) {
|
|
3961
6115
|
Object.assign(set.headers, headers);
|
|
@@ -4060,9 +6214,11 @@ function defineServiceSocket(service, config, resolve) {
|
|
|
4060
6214
|
if (!Number.isInteger(maxRooms) || maxRooms < 1) throw new Error("Socket maxRooms must be a positive integer");
|
|
4061
6215
|
const replay = config.replay && { ...config.replay };
|
|
4062
6216
|
if (replay && !(Number.isInteger(replay.keep) && replay.keep > 0 && replay.maxAgeMs > 0 && Number.isFinite(replay.maxAgeMs))) throw new Error("Socket replay needs a positive integer keep and a positive finite maxAgeMs");
|
|
4063
|
-
for (const schema of [...Object.
|
|
4064
|
-
serializeSocketSchema(schema);
|
|
6217
|
+
for (const [path, schema] of [...Object.entries(input).map(([k, v]) => [`input.${k}`, v]), ...Object.entries(output).map(([k, v]) => [`output.${k}`, v])]) {
|
|
6218
|
+
serializeSocketSchema(schema, path);
|
|
4065
6219
|
getCompiledCheck(schema);
|
|
6220
|
+
const at = sensitivePointer(schema);
|
|
6221
|
+
if (at) throw new Error(`Service '${service}' socket '${config.name}': ${path} marks '${at}' t.Sensitive, which sockets do not support yet; keep the secret out of socket messages`);
|
|
4066
6222
|
}
|
|
4067
6223
|
const typed = (socket) => socket;
|
|
4068
6224
|
const error = buildErrorHelpers(config.errors);
|
|
@@ -4465,11 +6621,11 @@ function mountSockets(app, sockets, broker, secret) {
|
|
|
4465
6621
|
* @param options - `prefix` for action routes (default `/api`), `services`,
|
|
4466
6622
|
* `title`, `version`, and `description` for the OpenAPI document, `docs` and the
|
|
4467
6623
|
* paths of its pages, `requestLogging`, `reference`, `endpoints`, `secrets`,
|
|
4468
|
-
* `telemetry`, `documentation`,
|
|
6624
|
+
* `telemetry`, `documentation`, and `dashboard`. See `CreateServerOptions`.
|
|
4469
6625
|
* @returns The app, with `definition` (its services, prefix, and routes),
|
|
4470
6626
|
* `endpoint()` to add raw routes, and `listEndpoints()` to list them.
|
|
4471
6627
|
* @throws When a required secret is missing, `documentation` or `dashboard`
|
|
4472
|
-
* is invalid, or `deps`
|
|
6628
|
+
* is invalid, or `deps` is passed (it moved to `defineService({ deps })`).
|
|
4473
6629
|
* @example
|
|
4474
6630
|
* import { brick } from "@brickkit/core";
|
|
4475
6631
|
* import { pagesService } from "./services/pages";
|
|
@@ -4481,6 +6637,7 @@ function mountSockets(app, sockets, broker, secret) {
|
|
|
4481
6637
|
* });
|
|
4482
6638
|
*/
|
|
4483
6639
|
function brick(options = {}) {
|
|
6640
|
+
if ("deps" in options) throw new Error("Brick: brick({ deps }) was removed in 0.16. Move each value into the service that uses it: defineService(name, { deps: { ... } }).");
|
|
4484
6641
|
const prefix = options.prefix ?? options.compilation?.ir.prefix ?? "/api";
|
|
4485
6642
|
const title = options.title ?? OPENAPI_DEFAULTS.title;
|
|
4486
6643
|
const version = options.version ?? OPENAPI_DEFAULTS.version;
|
|
@@ -4494,9 +6651,18 @@ function brick(options = {}) {
|
|
|
4494
6651
|
if (options.secrets?.validate !== false) resolveSecrets({ source: options.secrets?.source });
|
|
4495
6652
|
const services = options.services ?? getGlobalRegistry().list();
|
|
4496
6653
|
const plugins = setupAppPlugins(services.flatMap((service) => installedPlugins(service)), options.plugins ?? []);
|
|
6654
|
+
const addressSource = {
|
|
6655
|
+
clientIp: options.clientIp,
|
|
6656
|
+
server: () => app.server
|
|
6657
|
+
};
|
|
6658
|
+
app.onRequest(({ request }) => {
|
|
6659
|
+
markDashboardArrival(request);
|
|
6660
|
+
markAddressSource(request, addressSource);
|
|
6661
|
+
});
|
|
4497
6662
|
if (options.cors) app.onRequest(corsHook(options.cors));
|
|
4498
6663
|
for (const handler of plugins.middleware) app.onRequest(handler);
|
|
4499
6664
|
const registeredRoutes = /* @__PURE__ */ new Map();
|
|
6665
|
+
const webhookRoutes = /* @__PURE__ */ new Map();
|
|
4500
6666
|
const builtIn = (path, handler) => {
|
|
4501
6667
|
app.get(path, handler);
|
|
4502
6668
|
registeredRoutes.set(routeKey("GET", path), false);
|
|
@@ -4517,15 +6683,17 @@ function brick(options = {}) {
|
|
|
4517
6683
|
if ((byName.get(service.name) ?? service) !== service) throw new DuplicateNameError(`Brick: duplicate service "${service.name}" in brick()`);
|
|
4518
6684
|
byName.set(service.name, service);
|
|
4519
6685
|
}
|
|
4520
|
-
bindDeps(services, options.deps);
|
|
4521
6686
|
const eventsOptions = plugins.listeners.length ? {
|
|
4522
6687
|
...options.events,
|
|
4523
6688
|
listeners: [...options.events?.listeners ?? [], ...plugins.listeners]
|
|
4524
6689
|
} : options.events;
|
|
4525
|
-
const events = eventsOptions ? new EventsHub(eventsOptions,
|
|
6690
|
+
const events = eventsOptions ? new EventsHub(eventsOptions, appDeps(services)).attach(services) : void 0;
|
|
4526
6691
|
if (events?.workflows) app.all(WEBHOOK_ROUTE, ({ request }) => events.webhook(request));
|
|
4527
6692
|
if (telemetry) for (const service of services) instrumentDatabase(service.getDb());
|
|
4528
6693
|
for (const service of services) service.build();
|
|
6694
|
+
for (const service of services) checkFileStorages(service, [portOf(service).deps, ...installedPlugins(service).map(pluginDepsOf)]);
|
|
6695
|
+
const localDirs = localFileDirs([...services.map((service) => portOf(service).deps), ...plugins.deps]);
|
|
6696
|
+
if (localDirs.size) builtIn(LOCAL_FILES_ROUTE, localFilesRoute(localDirs));
|
|
4529
6697
|
const endpointDefs = [];
|
|
4530
6698
|
let endpointRevision = 0;
|
|
4531
6699
|
const buildSpec = () => {
|
|
@@ -4563,15 +6731,19 @@ function brick(options = {}) {
|
|
|
4563
6731
|
if (registeredRoutes.has(key) || socketRoutes.has(key)) throw new DuplicateNameError(`Brick: duplicate socket route '${socket.path}'`);
|
|
4564
6732
|
socketRoutes.add(key);
|
|
4565
6733
|
}
|
|
4566
|
-
const mountRoute = (method, path, handler, plugin = false) => {
|
|
6734
|
+
const mountRoute = (method, path, handler, plugin = false, hook, webhook) => {
|
|
4567
6735
|
const key = routeKey(method, path);
|
|
4568
6736
|
if (socketRoutes.has(key)) throw new DuplicateNameError(`Brick: route '${method} ${path}' conflicts with a socket`);
|
|
4569
6737
|
if (registeredRoutes.has(key)) {
|
|
6738
|
+
const other = webhook ?? webhookRoutes.get(key);
|
|
6739
|
+
if (other) throw new DuplicateNameError(`Brick: route '${method} ${path}' is claimed by webhook '${other}' and by another route; a webhook cannot share its route`);
|
|
4570
6740
|
if (plugin || registeredRoutes.get(key)) throw new DuplicateNameError(`Brick: duplicate plugin route '${method} ${path}'`);
|
|
4571
6741
|
return false;
|
|
4572
6742
|
}
|
|
4573
|
-
app.route(method, path, handler);
|
|
6743
|
+
if (hook) app.route(method, path, hook, handler);
|
|
6744
|
+
else app.route(method, path, handler);
|
|
4574
6745
|
registeredRoutes.set(key, plugin);
|
|
6746
|
+
if (webhook) webhookRoutes.set(key, webhook);
|
|
4575
6747
|
return true;
|
|
4576
6748
|
};
|
|
4577
6749
|
const mountEndpoint = (def, plugin = false) => {
|
|
@@ -4612,14 +6784,15 @@ function brick(options = {}) {
|
|
|
4612
6784
|
if (compilation.ir.prefix !== prefix || JSON.stringify(compilation.ir.services) !== JSON.stringify(services.map((service) => service.name))) throw new Error("Brick compiler: server services/prefix differ from the bound compilation");
|
|
4613
6785
|
const mountedRoutes = [];
|
|
4614
6786
|
for (const route of compilation.routes) {
|
|
6787
|
+
const { handler } = route;
|
|
4615
6788
|
const invoke = (context) => {
|
|
4616
6789
|
const result = telemetry ? withSpan(`${SPAN.actionPrefix}${route.ir.service}.${route.ir.action}`, {
|
|
4617
6790
|
[ATTR.service]: route.ir.service,
|
|
4618
6791
|
[ATTR.action]: route.ir.action
|
|
4619
|
-
}, () =>
|
|
6792
|
+
}, () => handler(context)) : handler(context);
|
|
4620
6793
|
return result && typeof result.then === "function" ? Promise.resolve(result).then(jsonActionResult) : jsonActionResult(result);
|
|
4621
6794
|
};
|
|
4622
|
-
if (mountRoute(route.ir.method, route.ir.path, telemetry ? (context) => traceHttpRequest(context, route.ir.method, route.ir.path, () => invoke(context)) : invoke, Boolean(route.ir.plugin))) mountedRoutes.push(route.ir);
|
|
6795
|
+
if (mountRoute(route.ir.method, route.ir.path, telemetry ? (context) => traceHttpRequest(context, route.ir.method, route.ir.path, () => invoke(context)) : invoke, Boolean(route.ir.plugin), route.ir.kind === "webhook" ? { parse: rawBodyParser(route.ir.bodyLimit) } : route.ir.bodyLimit ? { parse: bodyLimitParser(route.ir.bodyLimit) } : void 0, route.ir.kind === "webhook" ? `${route.ir.service}.${route.ir.action}` : void 0)) mountedRoutes.push(route.ir);
|
|
4623
6796
|
}
|
|
4624
6797
|
mountSockets(app, sockets, options.sockets?.broker ?? localBroker(), options.sockets?.secret);
|
|
4625
6798
|
const definition = Object.freeze({
|
|
@@ -4640,13 +6813,14 @@ function brick(options = {}) {
|
|
|
4640
6813
|
Object.defineProperty(brickApp, "definition", { value: definition });
|
|
4641
6814
|
Object.defineProperty(brickApp, "events", { value: events });
|
|
4642
6815
|
const lifecycle = pluginLifecycle(plugins.lifecycles);
|
|
6816
|
+
const releaseStorages = useStorages([...services.map((service) => portOf(service).deps), ...plugins.deps]);
|
|
4643
6817
|
const listen = app.listen.bind(app);
|
|
4644
6818
|
const stop = app.stop.bind(app);
|
|
4645
6819
|
Object.defineProperty(brickApp, "start", { value: lifecycle.start });
|
|
4646
6820
|
brickApp.listen = ((...args) => {
|
|
4647
6821
|
lifecycle.start().catch((error) => {
|
|
4648
6822
|
console.error("[Brick-TS] A plugin failed to start:", error);
|
|
4649
|
-
return stop(true);
|
|
6823
|
+
return Promise.resolve(stop(true)).finally(releaseStorages).catch((stopError) => console.error("[Brick-TS] Stopping after a failed plugin start failed:", stopError));
|
|
4650
6824
|
});
|
|
4651
6825
|
return listen(...args);
|
|
4652
6826
|
});
|
|
@@ -4654,7 +6828,11 @@ function brick(options = {}) {
|
|
|
4654
6828
|
try {
|
|
4655
6829
|
await stop(closeActiveConnections);
|
|
4656
6830
|
} finally {
|
|
4657
|
-
|
|
6831
|
+
try {
|
|
6832
|
+
await lifecycle.stop();
|
|
6833
|
+
} finally {
|
|
6834
|
+
await releaseStorages();
|
|
6835
|
+
}
|
|
4658
6836
|
}
|
|
4659
6837
|
});
|
|
4660
6838
|
Object.defineProperty(brickApp, "serve", { value: async ({ port }) => {
|
|
@@ -4703,6 +6881,6 @@ function cachedJsonRoute(build, revision) {
|
|
|
4703
6881
|
return json;
|
|
4704
6882
|
};
|
|
4705
6883
|
}
|
|
4706
|
-
export {
|
|
6884
|
+
export { recordInline as $, isCrudEvent as A, definitionSite as At, isInstallingPlugin as B, signDashboardIdentity as Bt, resolveWorkflowPaths as C, defineSecret as Ct, crudEventName as D, resetSecrets as Dt, checkPayload as E, overrideSecret as Et, defineResourcePlugin as F, hasIdentity as Ft, errorsOf as G, withCallSpan as Gt, validateName as H, fileFields as Ht, defineServicePlugin as I, DASHBOARD_IDENTITY_HEADER as It, auditTable as J, isSensitive as Jt, deny as K, Sensitive as Kt, getPluginEndpoints as L, DASHBOARD_KEY_ENV as Lt, requireBrickApp as M, freezeAsBuiltDeps as Mt, createActionHandler as N, useDeps as Nt, crudEventSource as O, resolveSecrets as Ot, INTERNALS as P, portOf as Pt, recordAudit as Q, PLUGIN_KIND as Qt, hasPlugin as R, dashboardKey as Rt, WORKFLOW_BUNDLE as S, SecretRef as St, checkEvent as T, listSecrets as Tt, buildErrorHelpers as U, validateWithSchema as Ut, segmentClaimant as V, Type as Vt, defineAction as W, traceRoute as Wt, inlineAudit as X, sensitivity as Xt, entryOf as Y, redact as Yt, isAuditTable as Z, PLUGIN_COMMIT as Zt, getGlobalRegistry as _, redis as _t, defineSchedule as a, webhookOf as at, compileBrickApplication as b, s3 as bt, outboxTable as c, pickContextEnvelope as ct, scalarDocsHTML as d, clientAddress as dt, onTransactionCommit as et, requestLoggingPlugin as f, rateLimitsOf as ft, setActionAudit as g, memory as gt, setActionAccess as h, defineStorage as ht, stopAllEvents as i, isWebhook as it, isBrickApp as j, depsOverride as jt, eventRefs as k, claimName as kt, referencePlugin as l, resolvedDeps as lt, getActionAccess as m, StorageUnavailableError as mt, defineServiceSocket as n, checkWebhook as nt, Dispatcher as o, baseContext as ot, generateOpenApiSpec as p, withClientIp as pt, auditStage as q, hasSensitive as qt, recordingServices as r, defineWebhookMeta as rt, isOutboxTable as s, markResolved as st, brick as t, runInTransaction as tt, registerReferenceRoute as u, checkRateLimits as ut, resetGlobalRegistry as v, redisBroker as vt, defineListener as w, envSource as wt, loadCompiledBrickApp as x, scopeFiles as xt, bindCompiledApplication as y, hasFilesView as yt, installPlugin as z, dashboardUser as zt };
|
|
4707
6885
|
|
|
4708
6886
|
//# sourceMappingURL=server.js.map
|