@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/index.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import { $ as
|
|
2
|
-
import { G as
|
|
1
|
+
import { $ as recordInline, A as isCrudEvent, At as definitionSite, B as isInstallingPlugin, Bt as signDashboardIdentity, C as resolveWorkflowPaths, Ct as defineSecret, D as crudEventName, Dt as resetSecrets, E as checkPayload, Et as overrideSecret, F as defineResourcePlugin, Ft as hasIdentity, G as errorsOf, Gt as withCallSpan, H as validateName, Ht as fileFields, I as defineServicePlugin, It as DASHBOARD_IDENTITY_HEADER, J as auditTable, Jt as isSensitive, K as deny, Kt as Sensitive, L as getPluginEndpoints, Lt as DASHBOARD_KEY_ENV, M as requireBrickApp, Mt as freezeAsBuiltDeps, N as createActionHandler, Nt as useDeps, O as crudEventSource, Ot as resolveSecrets, P as INTERNALS, Pt as portOf, Q as recordAudit, Qt as PLUGIN_KIND, R as hasPlugin, Rt as dashboardKey, S as WORKFLOW_BUNDLE, St as SecretRef, T as checkEvent, Tt as listSecrets, U as buildErrorHelpers, Ut as validateWithSchema, V as segmentClaimant, Vt as Type, W as defineAction, Wt as traceRoute, X as inlineAudit, Xt as sensitivity, Y as entryOf, Yt as redact, Z as isAuditTable, Zt as PLUGIN_COMMIT, _ as getGlobalRegistry, _t as redis, a as defineSchedule, at as webhookOf, b as compileBrickApplication, bt as s3, c as outboxTable, ct as pickContextEnvelope, d as scalarDocsHTML, dt as clientAddress, et as onTransactionCommit, f as requestLoggingPlugin, ft as rateLimitsOf, g as setActionAudit, gt as memory, h as setActionAccess, ht as defineStorage, i as stopAllEvents, it as isWebhook, j as isBrickApp, jt as depsOverride, k as eventRefs, kt as claimName, l as referencePlugin, lt as resolvedDeps, m as getActionAccess, mt as StorageUnavailableError, n as defineServiceSocket, nt as checkWebhook, o as Dispatcher, ot as baseContext, p as generateOpenApiSpec, pt as withClientIp, q as auditStage, qt as hasSensitive, r as recordingServices, rt as defineWebhookMeta, s as isOutboxTable, st as markResolved, t as brick, tt as runInTransaction, u as registerReferenceRoute, ut as checkRateLimits, v as resetGlobalRegistry, vt as redisBroker, w as defineListener, wt as envSource, x as loadCompiledBrickApp, xt as scopeFiles, y as bindCompiledApplication, yt as hasFilesView, z as installPlugin, zt as dashboardUser } from "./chunks/server.js";
|
|
2
|
+
import { C as actionMeta, G as ActionExecutionError, H as ATTR, K as DuplicateNameError, S as kebabCase, U as GLOBAL_SYMBOL, W as SPAN, a as isBrickTransportError, f as getActionRoute, i as isBrickServerError, n as BrickTransportError, p as getPluginActionRoute, q as ValidationError, r as createBrickClient, s as serializeSocketSchema, t as BrickServerError, u as actionOwners } from "./chunks/client.js";
|
|
3
3
|
import { defineError, stepErrors, stepFailure } from "./workflow.js";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
|
+
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
|
|
5
6
|
import { dirname, isAbsolute, resolve } from "node:path";
|
|
6
7
|
import { fileURLToPath } from "node:url";
|
|
7
8
|
import { Value } from "@sinclair/typebox/value";
|
|
9
|
+
import { boolean, doublePrecision, getTableConfig, integer as integer$1, isPgEnum, jsonb, pgSchema, pgTable, text as text$1, timestamp } from "drizzle-orm/pg-core";
|
|
10
|
+
import { blob, foreignKey, index, integer, integer as integer$2, primaryKey, real, real as real$1, sqliteTable, sqliteTable as sqliteTable$1, text, text as text$2, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
8
11
|
import { Table, and, and as and$1, asc, desc, eq, eq as eq$1, getTableColumns, getTableColumns as getTableColumns$1, getTableName, getTableName as getTableName$1, gt, gte, ilike, inArray, inArray as inArray$1, is, isNotNull, isNull, like, lt, lte, ne, not, notInArray, or, relations, sql, sql as sql$1 } from "drizzle-orm";
|
|
9
|
-
import { blob, foreignKey, index, integer, integer as integer$1, primaryKey, real, real as real$1, sqliteTable, sqliteTable as sqliteTable$1, text, text as text$1, uniqueIndex } from "drizzle-orm/sqlite-core";
|
|
10
|
-
import { boolean, doublePrecision, getTableConfig, integer as integer$2, isPgEnum, jsonb, pgSchema, pgTable, text as text$2, timestamp } from "drizzle-orm/pg-core";
|
|
11
12
|
import { mkdirSync, readFileSync } from "node:fs";
|
|
12
13
|
import { migrate } from "drizzle-orm/postgres-js/migrator";
|
|
13
14
|
import { migrate as migrate$1 } from "drizzle-orm/bun-sqlite/migrator";
|
|
@@ -48,20 +49,20 @@ function pluginOwner(table) {
|
|
|
48
49
|
const sqliteBuilders = {
|
|
49
50
|
/** A table. Its name gets the plugin's prefix (`page_comments`). */
|
|
50
51
|
table: (name, columns) => sqliteTable$1(name, columns),
|
|
51
|
-
text: (name) => text$
|
|
52
|
-
integer: (name) => integer$
|
|
52
|
+
text: (name) => text$2(name),
|
|
53
|
+
integer: (name) => integer$2(name, { mode: "number" }),
|
|
53
54
|
real: (name) => real$1(name),
|
|
54
|
-
boolean: (name) => integer$
|
|
55
|
+
boolean: (name) => integer$2(name, { mode: "boolean" }),
|
|
55
56
|
/** A `Date`, stored as epoch milliseconds or `timestamptz`. */
|
|
56
|
-
timestamp: (name) => integer$
|
|
57
|
-
json: (name) => text$
|
|
57
|
+
timestamp: (name) => integer$2(name, { mode: "timestamp_ms" }),
|
|
58
|
+
json: (name) => text$2(name, { mode: "json" })
|
|
58
59
|
};
|
|
59
60
|
function builders(engine, tableName) {
|
|
60
61
|
if (engine === "postgres") return {
|
|
61
62
|
engine,
|
|
62
63
|
table: (name, columns) => pgTable(tableName(name), columns),
|
|
63
|
-
text: (name) => text$
|
|
64
|
-
integer: (name) => integer$
|
|
64
|
+
text: (name) => text$1(name),
|
|
65
|
+
integer: (name) => integer$1(name),
|
|
65
66
|
real: (name) => doublePrecision(name),
|
|
66
67
|
boolean: (name) => boolean(name),
|
|
67
68
|
timestamp: (name) => timestamp(name, {
|
|
@@ -344,16 +345,15 @@ function bindPluginDeps(plugin, action, deps, started) {
|
|
|
344
345
|
at: ++bindings
|
|
345
346
|
};
|
|
346
347
|
}
|
|
347
|
-
|
|
348
|
-
function checkDeps(plugin, camelName, ports, given = {}) {
|
|
348
|
+
function checkDeps(plugin, camelName, declaredDeps, given = {}) {
|
|
349
349
|
if (given === null || typeof given !== "object" || Array.isArray(given)) throw new Error(`${plugin}: deps must be an object`);
|
|
350
|
-
const declared = Object.keys(
|
|
350
|
+
const declared = Object.keys(declaredDeps ?? {});
|
|
351
351
|
const provided = given;
|
|
352
352
|
const extra = Object.keys(provided).filter((key) => !declared.includes(key));
|
|
353
353
|
if (extra.length) throw new Error(`${plugin} does not declare ${extra.map((key) => `deps.${key}`).join(", ")}; ${declared.length ? `it takes ${declared.join(", ")}` : "it takes no deps"}`);
|
|
354
354
|
const missing = declared.filter((key) => provided[key] === void 0);
|
|
355
355
|
if (missing.length) throw new Error(`${plugin} needs ${missing.map((key) => `deps.${key}`).join(", ")}; pass it when installing: ${camelName}(options, { deps: { ${missing.join(", ")} } })`);
|
|
356
|
-
return
|
|
356
|
+
return freezeAsBuiltDeps(Object.fromEntries(declared.map((key) => [key, provided[key]])));
|
|
357
357
|
}
|
|
358
358
|
function checkOptions(plugin, schema, input) {
|
|
359
359
|
if (input === null || typeof input !== "object" || Array.isArray(input)) throw new Error(`${plugin}: options must be an object`);
|
|
@@ -373,6 +373,7 @@ function checkOptions(plugin, schema, input) {
|
|
|
373
373
|
// src/tool.ts
|
|
374
374
|
function defineTool(config) {
|
|
375
375
|
if (config.input && config.input.type !== "object") throw new Error(`Tool '${config.name}' input must be an object schema`);
|
|
376
|
+
if (fileFields(config.input).length) throw new Error(`Tool '${config.name}' input has file fields; MCP carries JSON only, so take uploads in an action`);
|
|
376
377
|
const tool = defineAction(config);
|
|
377
378
|
Object.defineProperty(tool, "kind", { value: "tool" });
|
|
378
379
|
return tool;
|
|
@@ -878,8 +879,17 @@ function defineResourceAction(service, resource, config, command) {
|
|
|
878
879
|
input = Type.Object({
|
|
879
880
|
...own?.properties,
|
|
880
881
|
id: idSchema(resource.id)
|
|
881
|
-
},
|
|
882
|
+
}, {
|
|
883
|
+
...own?.additionalProperties !== void 0 && { additionalProperties: own.additionalProperties },
|
|
884
|
+
...own?.patternProperties !== void 0 && { patternProperties: own.patternProperties }
|
|
885
|
+
});
|
|
886
|
+
if (isSensitive(own)) input = Sensitive(input);
|
|
882
887
|
}
|
|
888
|
+
sensitivity({
|
|
889
|
+
...rest,
|
|
890
|
+
name,
|
|
891
|
+
input
|
|
892
|
+
}, service.name);
|
|
883
893
|
const action = defineAction({
|
|
884
894
|
...rest,
|
|
885
895
|
name,
|
|
@@ -949,6 +959,7 @@ function commandErrors(errors) {
|
|
|
949
959
|
}
|
|
950
960
|
function defineCommand(service, resource, name, config) {
|
|
951
961
|
const where = `Command '${resource.name}.${name}'`;
|
|
962
|
+
if (isAuditTable(resource.table)) throw new Error(`${where} is over the audit table, so it could rewrite audit rows. The audit log takes no commands.`);
|
|
952
963
|
if (typeof config.decide !== "function") throw new Error(`${where} needs a decide function`);
|
|
953
964
|
const loaded = (config.load?.children ?? []).map((child) => ({
|
|
954
965
|
name: child,
|
|
@@ -998,10 +1009,15 @@ function defineCommand(service, resource, name, config) {
|
|
|
998
1009
|
if (changes.delete?.length) await tx.delete(child.table).where(and$1(inArray$1(child.id, changes.delete), own));
|
|
999
1010
|
}
|
|
1000
1011
|
for (const [eventName, payload] of emits) await record(eventName, payload);
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1012
|
+
let reply = { id };
|
|
1013
|
+
if (config.output) {
|
|
1014
|
+
const [updated] = await tx.select().from(resource.table).where(eq$1(resource.id, id)).limit(1);
|
|
1015
|
+
for (const child of loaded) updated[child.name] = await tx.select().from(child.table).where(eq$1(child.parent, id));
|
|
1016
|
+
reply = Value.Clean(config.output, updated);
|
|
1017
|
+
}
|
|
1018
|
+
const audit = inlineAudit();
|
|
1019
|
+
if (audit) await recordInline(audit, tx, ctx, entryOf(audit, input, reply));
|
|
1020
|
+
return reply;
|
|
1005
1021
|
};
|
|
1006
1022
|
return recorder ? recorder.transaction(db, {
|
|
1007
1023
|
traceId: ctx.traceId,
|
|
@@ -1015,11 +1031,15 @@ function defineCommand(service, resource, name, config) {
|
|
|
1015
1031
|
tags: config.tags,
|
|
1016
1032
|
input: config.input,
|
|
1017
1033
|
output: config.output ?? Type.Object({ id: idSchema(resource.id) }),
|
|
1034
|
+
reveal: config.reveal,
|
|
1018
1035
|
errors: config.errors,
|
|
1019
1036
|
...config.access === void 0 ? {} : { access: config.access },
|
|
1020
1037
|
...config.authorize ? { authorize: config.authorize } : {},
|
|
1038
|
+
...config.rateLimit ? { rateLimit: config.rateLimit } : {},
|
|
1039
|
+
...config.audit === void 0 ? {} : { audit: config.audit },
|
|
1021
1040
|
execute: () => void 0
|
|
1022
1041
|
}, run);
|
|
1042
|
+
setActionAudit(action, "inline");
|
|
1023
1043
|
Object.assign(action, { decide });
|
|
1024
1044
|
return action;
|
|
1025
1045
|
}
|
|
@@ -1060,31 +1080,31 @@ function defineResource(service, config) {
|
|
|
1060
1080
|
// src/schedules/table.ts
|
|
1061
1081
|
const SCHEDULES = Symbol.for("brick.schedules");
|
|
1062
1082
|
function sqliteSchedules(name) {
|
|
1063
|
-
const at = (column) => integer$
|
|
1083
|
+
const at = (column) => integer$2(column, { mode: "timestamp_ms" });
|
|
1064
1084
|
return sqliteTable$1(name, {
|
|
1065
|
-
name: text$
|
|
1066
|
-
spec: text$
|
|
1085
|
+
name: text$2("name").primaryKey(),
|
|
1086
|
+
spec: text$2("spec").notNull(),
|
|
1067
1087
|
slot: at("slot").notNull(),
|
|
1068
1088
|
nextAt: at("next_at").notNull(),
|
|
1069
|
-
attempts: integer$
|
|
1070
|
-
trigger: text$
|
|
1071
|
-
runId: text$
|
|
1089
|
+
attempts: integer$2("attempts").notNull().default(0),
|
|
1090
|
+
trigger: text$2("trigger").$type().notNull(),
|
|
1091
|
+
runId: text$2("run_id"),
|
|
1072
1092
|
startedAt: at("started_at"),
|
|
1073
1093
|
leaseUntil: at("lease_until"),
|
|
1074
1094
|
lastSuccessAt: at("last_success_at"),
|
|
1075
|
-
runs: text$
|
|
1095
|
+
runs: text$2("runs", { mode: "json" }).$type().notNull()
|
|
1076
1096
|
});
|
|
1077
1097
|
}
|
|
1078
1098
|
function postgresSchedules(name) {
|
|
1079
1099
|
const at = (column) => timestamp(column, { withTimezone: true });
|
|
1080
1100
|
return pgTable(name, {
|
|
1081
|
-
name: text$
|
|
1082
|
-
spec: text$
|
|
1101
|
+
name: text$1("name").primaryKey(),
|
|
1102
|
+
spec: text$1("spec").notNull(),
|
|
1083
1103
|
slot: at("slot").notNull(),
|
|
1084
1104
|
nextAt: at("next_at").notNull(),
|
|
1085
|
-
attempts: integer$
|
|
1086
|
-
trigger: text$
|
|
1087
|
-
runId: text$
|
|
1105
|
+
attempts: integer$1("attempts").notNull().default(0),
|
|
1106
|
+
trigger: text$1("trigger").$type().notNull(),
|
|
1107
|
+
runId: text$1("run_id"),
|
|
1088
1108
|
startedAt: at("started_at"),
|
|
1089
1109
|
leaseUntil: at("lease_until"),
|
|
1090
1110
|
lastSuccessAt: at("last_success_at"),
|
|
@@ -1102,9 +1122,6 @@ function isScheduleTable(value) {
|
|
|
1102
1122
|
return typeof value === "object" && value !== null && SCHEDULES in value;
|
|
1103
1123
|
}
|
|
1104
1124
|
// src/service.ts
|
|
1105
|
-
const RESOLVED_SYMBOL = Symbol("resolved");
|
|
1106
|
-
/** The deps a resolved context was resolved with, to restore them when a plugin's copy comes back. */
|
|
1107
|
-
const OWN_DEPS = Symbol("ownDeps");
|
|
1108
1125
|
var ServiceImpl = class {
|
|
1109
1126
|
name;
|
|
1110
1127
|
options;
|
|
@@ -1117,19 +1134,40 @@ var ServiceImpl = class {
|
|
|
1117
1134
|
/** Where each `kind:name` was defined, to reject duplicates from another file. */
|
|
1118
1135
|
sites = /* @__PURE__ */ new Map();
|
|
1119
1136
|
database;
|
|
1137
|
+
auditTable;
|
|
1138
|
+
auditHooked = false;
|
|
1120
1139
|
_isBuilt = false;
|
|
1121
1140
|
_events;
|
|
1122
1141
|
/** What a write needs to record events. Set by `brick({ events })`. */
|
|
1123
1142
|
recorder;
|
|
1124
|
-
/** The values of this service's `deps`. Set by `brick({ deps })`. */
|
|
1125
1143
|
deps;
|
|
1126
1144
|
constructor(name, options = {}) {
|
|
1127
1145
|
this.name = name;
|
|
1128
1146
|
this.options = options;
|
|
1147
|
+
this.deps = ownDeps(name, options.deps);
|
|
1129
1148
|
this._events = eventRefs(name, options.events);
|
|
1130
1149
|
for (const key of Object.keys(this._events)) this.claim("event", key);
|
|
1131
1150
|
if (options.database !== void 0 && !isDatabaseHandle(options.database)) throw new Error("Service database must be created with defineDatabase()");
|
|
1132
1151
|
this.database = options.database;
|
|
1152
|
+
this.watchAudit();
|
|
1153
|
+
}
|
|
1154
|
+
watchAudit() {
|
|
1155
|
+
this.auditTable = Object.values(this.database?.tables ?? {}).find(isAuditTable);
|
|
1156
|
+
if (!this.auditTable || this.auditHooked) return;
|
|
1157
|
+
this.auditHooked = true;
|
|
1158
|
+
const record = (operation, { ctx, tx, resource, row, id }) => {
|
|
1159
|
+
const audit = inlineAudit();
|
|
1160
|
+
return audit && recordInline(audit, tx, ctx, {
|
|
1161
|
+
action: `${resource.name}.${operation}`,
|
|
1162
|
+
resource: resource.name,
|
|
1163
|
+
recordId: row ? row[resource.idField] : id
|
|
1164
|
+
});
|
|
1165
|
+
};
|
|
1166
|
+
addHostHooks(this, {
|
|
1167
|
+
afterCreate: [(args) => record("create", args)],
|
|
1168
|
+
afterUpdate: [(args) => record("update", args)],
|
|
1169
|
+
afterDelete: [(args) => record("delete", args)]
|
|
1170
|
+
});
|
|
1133
1171
|
}
|
|
1134
1172
|
/** The declared events: `service.events.<name>`. */
|
|
1135
1173
|
get events() {
|
|
@@ -1192,6 +1230,12 @@ var ServiceImpl = class {
|
|
|
1192
1230
|
const resource = info?.record && this.resources.get(info.resource);
|
|
1193
1231
|
if (resource) checkRecordAccess(resource, info);
|
|
1194
1232
|
}
|
|
1233
|
+
for (const action of [...this.actions.values(), ...this.tools.values()]) {
|
|
1234
|
+
const deps = actionMeta(action).deps?.values ?? this.deps;
|
|
1235
|
+
if (webhookOf(action)) checkWebhook(this, action, deps);
|
|
1236
|
+
else checkRateLimits(this, action, deps);
|
|
1237
|
+
}
|
|
1238
|
+
if (this.auditTable && !hasIdentity(this)) throw new Error(`Service "${this.name}": its database holds an audit table, but the service declares no identity, so the log would not say who. Add identity: (ctx) => ctx.user && { id: ctx.user.id } to defineService("${this.name}", { ... }).`);
|
|
1195
1239
|
this._isBuilt = true;
|
|
1196
1240
|
return this;
|
|
1197
1241
|
}
|
|
@@ -1231,8 +1275,11 @@ var ServiceImpl = class {
|
|
|
1231
1275
|
}
|
|
1232
1276
|
action(actionOrConfig) {
|
|
1233
1277
|
const isActionFunction = typeof actionOrConfig === "function" && "config" in actionOrConfig;
|
|
1278
|
+
if (!isActionFunction) sensitivity(actionOrConfig, this.name);
|
|
1234
1279
|
const actionInstance = isActionFunction ? actionOrConfig : defineAction(actionOrConfig);
|
|
1235
|
-
|
|
1280
|
+
const previous = this.actions.get(actionInstance.name);
|
|
1281
|
+
if (previous !== actionInstance) this.claim("action", actionInstance.name);
|
|
1282
|
+
if (previous && isWebhook(previous) !== isWebhook(actionInstance)) throw new DuplicateNameError(`Service '${this.name}': "${actionInstance.name}" is defined both as a webhook and as an action. Give one of them another name: an action of the same name would answer in place of the webhook, without its check.`);
|
|
1236
1283
|
if (isTool(actionInstance)) actionInstance.config.http = true;
|
|
1237
1284
|
actionInstance.serviceName = this.name;
|
|
1238
1285
|
actionMeta(actionInstance).service = this;
|
|
@@ -1240,8 +1287,20 @@ var ServiceImpl = class {
|
|
|
1240
1287
|
this.touch();
|
|
1241
1288
|
return isActionFunction ? this : actionInstance;
|
|
1242
1289
|
}
|
|
1290
|
+
webhook(config) {
|
|
1291
|
+
const webhook = defineWebhookMeta(this.name, config);
|
|
1292
|
+
const { verify: _verify, eventId: _eventId, replay: _replay, maxBodyBytes: _maxBodyBytes, ...action } = config;
|
|
1293
|
+
const instance = defineAction({
|
|
1294
|
+
...action,
|
|
1295
|
+
method: config.method ?? "POST"
|
|
1296
|
+
});
|
|
1297
|
+
actionMeta(instance).webhook = webhook;
|
|
1298
|
+
this.action(instance);
|
|
1299
|
+
return instance;
|
|
1300
|
+
}
|
|
1243
1301
|
tool(toolOrConfig) {
|
|
1244
1302
|
const existing = isTool(toolOrConfig);
|
|
1303
|
+
if (!existing) sensitivity(toolOrConfig, this.name);
|
|
1245
1304
|
const tool = existing ? toolOrConfig : defineTool(toolOrConfig);
|
|
1246
1305
|
this.claim("tool", tool.name);
|
|
1247
1306
|
tool.serviceName = this.name;
|
|
@@ -1287,6 +1346,9 @@ var ServiceImpl = class {
|
|
|
1287
1346
|
getScheduleTable() {
|
|
1288
1347
|
return Object.values(this.database?.tables ?? {}).find(isScheduleTable);
|
|
1289
1348
|
}
|
|
1349
|
+
getAuditTable() {
|
|
1350
|
+
return this.auditTable;
|
|
1351
|
+
}
|
|
1290
1352
|
setRecorder(recorder) {
|
|
1291
1353
|
this.recorder = recorder;
|
|
1292
1354
|
}
|
|
@@ -1297,12 +1359,10 @@ var ServiceImpl = class {
|
|
|
1297
1359
|
checkEvent(name, payload) {
|
|
1298
1360
|
checkEvent(this, name, payload);
|
|
1299
1361
|
}
|
|
1300
|
-
setDeps(deps) {
|
|
1301
|
-
this.deps = deps;
|
|
1302
|
-
}
|
|
1303
1362
|
setDb(database) {
|
|
1304
1363
|
if (!isDatabaseHandle(database)) throw new Error("Use defineDatabase() to set a service database");
|
|
1305
1364
|
this.database = database;
|
|
1365
|
+
this.watchAudit();
|
|
1306
1366
|
this.touch();
|
|
1307
1367
|
}
|
|
1308
1368
|
/**
|
|
@@ -1320,7 +1380,7 @@ var ServiceImpl = class {
|
|
|
1320
1380
|
tables: Object.keys(this.database.tables),
|
|
1321
1381
|
...pluginTables(this.database.tables)
|
|
1322
1382
|
} : void 0;
|
|
1323
|
-
const { database: _database, events: _events, ...config } = this.options;
|
|
1383
|
+
const { database: _database, events: _events, deps: _deps, ...config } = this.options;
|
|
1324
1384
|
const options = JSON.parse(JSON.stringify(config));
|
|
1325
1385
|
return {
|
|
1326
1386
|
name: this.name,
|
|
@@ -1341,6 +1401,12 @@ var ServiceImpl = class {
|
|
|
1341
1401
|
hasScope: access.hasScope,
|
|
1342
1402
|
accessPolicy: access.policy,
|
|
1343
1403
|
errors: act.config.errors,
|
|
1404
|
+
...auditStage(this, act) && { audited: true },
|
|
1405
|
+
...rateLimitsOf(act.config) && { rateLimit: rateLimitsOf(act.config).map(({ max, windowMs }) => ({
|
|
1406
|
+
max,
|
|
1407
|
+
windowMs
|
|
1408
|
+
})) },
|
|
1409
|
+
...webhookOf(act) && { webhook: true },
|
|
1344
1410
|
emits: act.config.emits,
|
|
1345
1411
|
tags: act.config.tags
|
|
1346
1412
|
};
|
|
@@ -1363,6 +1429,27 @@ function pluginTables(tables) {
|
|
|
1363
1429
|
});
|
|
1364
1430
|
return owners.length ? { plugins: Object.fromEntries(owners) } : {};
|
|
1365
1431
|
}
|
|
1432
|
+
function isPlainObject(value) {
|
|
1433
|
+
if (value === null || typeof value !== "object") return false;
|
|
1434
|
+
const proto = Object.getPrototypeOf(value);
|
|
1435
|
+
return proto === Object.prototype || proto === null;
|
|
1436
|
+
}
|
|
1437
|
+
function ownDeps(service, deps = {}) {
|
|
1438
|
+
if (!isPlainObject(deps)) throw new Error(`Service "${service}": deps must be a plain object of values by name, such as { carrier: createCarrier() }`);
|
|
1439
|
+
const snapshot = { ...deps };
|
|
1440
|
+
for (const [name, value] of Object.entries(snapshot)) if (value === void 0) throw new Error(`Service "${service}": dep "${name}" is undefined; pass a value or leave it out`);
|
|
1441
|
+
return freezeAsBuiltDeps(snapshot);
|
|
1442
|
+
}
|
|
1443
|
+
function withOverride(deps, override) {
|
|
1444
|
+
return freezeAsBuiltDeps({
|
|
1445
|
+
...deps,
|
|
1446
|
+
...override
|
|
1447
|
+
});
|
|
1448
|
+
}
|
|
1449
|
+
function frameworkDeps(service, override, pluginDeps) {
|
|
1450
|
+
return override && !pluginDeps ? withOverride(service.deps, override) : service.deps;
|
|
1451
|
+
}
|
|
1452
|
+
const alreadyHoldsDeps = (ctx, deps) => ctx.deps === deps || hasFilesView(ctx, deps);
|
|
1366
1453
|
/**
|
|
1367
1454
|
* The context of a call to one of the service's actions or sockets. The one
|
|
1368
1455
|
* rule for which deps it sees: those of the plugin install that created the
|
|
@@ -1370,13 +1457,15 @@ function pluginTables(tables) {
|
|
|
1370
1457
|
* `context` hook always sees the service's own.
|
|
1371
1458
|
*/
|
|
1372
1459
|
async function resolveServiceContext(service, callCtx, pluginDeps) {
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1460
|
+
const ownDeps = resolvedDeps(callCtx, service);
|
|
1461
|
+
if (ownDeps) {
|
|
1462
|
+
const deps = pluginDeps ?? ownDeps;
|
|
1463
|
+
if (alreadyHoldsDeps(callCtx, deps)) return callCtx;
|
|
1464
|
+
const ctx = { ...callCtx };
|
|
1465
|
+
ctx.deps = scopeFiles(deps, ctx);
|
|
1466
|
+
return ctx;
|
|
1379
1467
|
}
|
|
1468
|
+
const override = depsOverride(callCtx);
|
|
1380
1469
|
const framework = baseContext({
|
|
1381
1470
|
request: callCtx?.request,
|
|
1382
1471
|
db: service.getDb(),
|
|
@@ -1385,20 +1474,22 @@ async function resolveServiceContext(service, callCtx, pluginDeps) {
|
|
|
1385
1474
|
requestId: callCtx?.requestId,
|
|
1386
1475
|
services: callCtx?.services,
|
|
1387
1476
|
metadata: callCtx?.metadata,
|
|
1388
|
-
|
|
1477
|
+
dashboard: callCtx?.dashboard,
|
|
1478
|
+
deps: frameworkDeps(service, override, pluginDeps)
|
|
1389
1479
|
});
|
|
1390
1480
|
const fullBaseCtx = {
|
|
1391
1481
|
...framework,
|
|
1392
1482
|
...pickContextEnvelope(callCtx)
|
|
1393
1483
|
};
|
|
1394
1484
|
const resolvedExtra = service.options.context ? await service.options.context(fullBaseCtx) : {};
|
|
1395
|
-
|
|
1485
|
+
const finalCtx = {
|
|
1396
1486
|
...fullBaseCtx,
|
|
1397
1487
|
...resolvedExtra,
|
|
1398
|
-
deps: pluginDeps
|
|
1399
|
-
[RESOLVED_SYMBOL]: service,
|
|
1400
|
-
[OWN_DEPS]: framework.deps
|
|
1488
|
+
deps: pluginDeps ? override ? withOverride(pluginDeps, override) : pluginDeps : framework.deps
|
|
1401
1489
|
};
|
|
1490
|
+
markResolved(finalCtx, service, framework.deps);
|
|
1491
|
+
finalCtx.deps = scopeFiles(finalCtx.deps, finalCtx);
|
|
1492
|
+
return finalCtx;
|
|
1402
1493
|
}
|
|
1403
1494
|
/**
|
|
1404
1495
|
* Declare a service: a named group of actions, tools, and resources with its own
|
|
@@ -1411,9 +1502,11 @@ async function resolveServiceContext(service, callCtx, pluginDeps) {
|
|
|
1411
1502
|
* @param name - Unique name. It is the service's segment of every action route
|
|
1412
1503
|
* (`/api/<name>/<action>`) and appears in OpenAPI and the dashboard. Defining it
|
|
1413
1504
|
* again from the same file (a dev reload) replaces it; from another file throws.
|
|
1414
|
-
* @param options - `database` (a handle from `defineDatabase`), `deps` (
|
|
1415
|
-
*
|
|
1505
|
+
* @param options - `database` (a handle from `defineDatabase`), `deps` (the
|
|
1506
|
+
* values the service's code uses, such as clients, read as `ctx.deps`),
|
|
1416
1507
|
* `context` (adds fields such as the signed-in user to every action's `ctx`),
|
|
1508
|
+
* `identity` (who the caller is and their tenant, from that `ctx`, for the
|
|
1509
|
+
* features that need it),
|
|
1417
1510
|
* `events` (the event catalog: a payload schema per event name, recorded as
|
|
1418
1511
|
* `<service>.<name>` and offered as `service.events.<name>`).
|
|
1419
1512
|
* @returns The service.
|
|
@@ -1441,203 +1534,6 @@ function defineService(name, options) {
|
|
|
1441
1534
|
getGlobalRegistry().register(service);
|
|
1442
1535
|
return service;
|
|
1443
1536
|
}
|
|
1444
|
-
// src/socket-redis.ts
|
|
1445
|
-
/** Exponential backoff from 500 ms to 30 s, with jitter so processes don't reconnect in step. */
|
|
1446
|
-
function reconnectDelay(failures) {
|
|
1447
|
-
const ceiling = Math.min(3e4, 500 * 2 ** failures);
|
|
1448
|
-
return ceiling / 2 + Math.random() * (ceiling / 2);
|
|
1449
|
-
}
|
|
1450
|
-
/** How long a call waits for Redis to connect before going on without it. */
|
|
1451
|
-
const REDIS_WAIT_MS = 1e3;
|
|
1452
|
-
/** One Redis connection that reconnects by itself and reports each fresh connection. */
|
|
1453
|
-
function connection(url, connected) {
|
|
1454
|
-
let redis;
|
|
1455
|
-
let timer;
|
|
1456
|
-
let closed = false;
|
|
1457
|
-
let failures = 0;
|
|
1458
|
-
const waiters = [];
|
|
1459
|
-
const lost = (client) => {
|
|
1460
|
-
if (redis !== client) return;
|
|
1461
|
-
redis = void 0;
|
|
1462
|
-
if (closed || timer) return;
|
|
1463
|
-
timer = setTimeout(() => {
|
|
1464
|
-
timer = void 0;
|
|
1465
|
-
start();
|
|
1466
|
-
}, reconnectDelay(failures++));
|
|
1467
|
-
};
|
|
1468
|
-
const start = () => {
|
|
1469
|
-
if (closed || redis || timer) return;
|
|
1470
|
-
const client = new Bun.RedisClient(url, {
|
|
1471
|
-
autoReconnect: false,
|
|
1472
|
-
enableOfflineQueue: false
|
|
1473
|
-
});
|
|
1474
|
-
redis = client;
|
|
1475
|
-
client.onclose = () => lost(client);
|
|
1476
|
-
client.connect().then(() => {
|
|
1477
|
-
if (redis !== client) return;
|
|
1478
|
-
failures = 0;
|
|
1479
|
-
connected(client);
|
|
1480
|
-
for (const wake of waiters.splice(0)) wake();
|
|
1481
|
-
}, () => lost(client));
|
|
1482
|
-
};
|
|
1483
|
-
return {
|
|
1484
|
-
get() {
|
|
1485
|
-
start();
|
|
1486
|
-
return redis?.connected ? redis : void 0;
|
|
1487
|
-
},
|
|
1488
|
-
/** Resolves after the next connection is made and announced, or after `ms`. */
|
|
1489
|
-
opened(ms) {
|
|
1490
|
-
if (redis?.connected) return Promise.resolve();
|
|
1491
|
-
start();
|
|
1492
|
-
return new Promise((resolve) => {
|
|
1493
|
-
const timeout = setTimeout(resolve, ms);
|
|
1494
|
-
waiters.push(() => {
|
|
1495
|
-
clearTimeout(timeout);
|
|
1496
|
-
resolve();
|
|
1497
|
-
});
|
|
1498
|
-
});
|
|
1499
|
-
},
|
|
1500
|
-
close() {
|
|
1501
|
-
closed = true;
|
|
1502
|
-
clearTimeout(timer);
|
|
1503
|
-
for (const wake of waiters.splice(0)) wake();
|
|
1504
|
-
const client = redis;
|
|
1505
|
-
redis = void 0;
|
|
1506
|
-
client?.close();
|
|
1507
|
-
}
|
|
1508
|
-
};
|
|
1509
|
-
}
|
|
1510
|
-
/**
|
|
1511
|
-
* Fans socket emits and kicks out across processes through Redis pub/sub, one
|
|
1512
|
-
* channel per room topic. An emit is a PUBLISH only: every process, the emitting
|
|
1513
|
-
* one included, delivers it once to its own connections. Uses Bun's built-in
|
|
1514
|
-
* Redis client and two connections, one to publish and one to subscribe.
|
|
1515
|
-
*/
|
|
1516
|
-
function redisBroker(options = {}) {
|
|
1517
|
-
const limit = options.queue ?? 1e3;
|
|
1518
|
-
if (!Number.isInteger(limit) || limit < 0) throw new Error("redisBroker queue must be a nonnegative integer");
|
|
1519
|
-
const channel = (topic) => `brick:socket:${topic}`;
|
|
1520
|
-
const listeners = /* @__PURE__ */ new Map();
|
|
1521
|
-
const pending = /* @__PURE__ */ new Map();
|
|
1522
|
-
const stream = (topic) => `brick:socket:stream:${topic}`;
|
|
1523
|
-
const warned = /* @__PURE__ */ new Set();
|
|
1524
|
-
const warn = (what) => (error) => {
|
|
1525
|
-
if (warned.has(what)) return;
|
|
1526
|
-
warned.add(what);
|
|
1527
|
-
console.warn(`[Brick-TS] Redis socket broker: ${what} failed; later failures of it are not logged.`, error);
|
|
1528
|
-
};
|
|
1529
|
-
const queue = [];
|
|
1530
|
-
const send = (work) => {
|
|
1531
|
-
const redis = publisher.get();
|
|
1532
|
-
if (redis) return work(redis);
|
|
1533
|
-
queue.push(work);
|
|
1534
|
-
if (queue.length > limit) queue.shift();
|
|
1535
|
-
};
|
|
1536
|
-
const receive = (payload, name) => {
|
|
1537
|
-
let message;
|
|
1538
|
-
try {
|
|
1539
|
-
message = JSON.parse(payload);
|
|
1540
|
-
} catch {
|
|
1541
|
-
return;
|
|
1542
|
-
}
|
|
1543
|
-
for (const deliver of listeners.get(name) ?? []) deliver(message);
|
|
1544
|
-
};
|
|
1545
|
-
const subscribe = (redis, name) => {
|
|
1546
|
-
const done = redis.subscribe(name, receive).catch(warn("SUBSCRIBE"));
|
|
1547
|
-
pending.set(name, done);
|
|
1548
|
-
done.then(() => {
|
|
1549
|
-
if (pending.get(name) === done) pending.delete(name);
|
|
1550
|
-
});
|
|
1551
|
-
};
|
|
1552
|
-
const publisher = connection(options.url, (redis) => {
|
|
1553
|
-
for (const work of queue.splice(0)) work(redis);
|
|
1554
|
-
});
|
|
1555
|
-
const subscriber = connection(options.url, (redis) => {
|
|
1556
|
-
for (const name of listeners.keys()) subscribe(redis, name);
|
|
1557
|
-
});
|
|
1558
|
-
return {
|
|
1559
|
-
publish(message, replay) {
|
|
1560
|
-
const name = channel(message.topic);
|
|
1561
|
-
if (message.type !== "emit" || !replay) return send((redis) => void redis.publish(name, JSON.stringify(message)).catch(warn("PUBLISH")));
|
|
1562
|
-
const key = stream(message.topic);
|
|
1563
|
-
send((redis) => {
|
|
1564
|
-
redis.send("XADD", [
|
|
1565
|
-
key,
|
|
1566
|
-
"MAXLEN",
|
|
1567
|
-
"~",
|
|
1568
|
-
String(replay.keep),
|
|
1569
|
-
"*",
|
|
1570
|
-
"m",
|
|
1571
|
-
message.frame
|
|
1572
|
-
]).then((seq) => {
|
|
1573
|
-
redis.send("PEXPIRE", [key, String(replay.maxAgeMs)]).catch(warn("PEXPIRE"));
|
|
1574
|
-
return redis.publish(name, JSON.stringify({
|
|
1575
|
-
...message,
|
|
1576
|
-
seq
|
|
1577
|
-
}));
|
|
1578
|
-
}).catch(warn("XADD/PUBLISH"));
|
|
1579
|
-
});
|
|
1580
|
-
},
|
|
1581
|
-
async head() {
|
|
1582
|
-
try {
|
|
1583
|
-
await publisher.opened(REDIS_WAIT_MS);
|
|
1584
|
-
const [seconds, micros] = await publisher.get().send("TIME", []);
|
|
1585
|
-
return `${Number(seconds) * 1e3 + Math.floor(Number(micros) / 1e3) - 1}-0`;
|
|
1586
|
-
} catch {
|
|
1587
|
-
return `${Date.now() - 1}-0`;
|
|
1588
|
-
}
|
|
1589
|
-
},
|
|
1590
|
-
async history(topic, since, replay) {
|
|
1591
|
-
let raw;
|
|
1592
|
-
try {
|
|
1593
|
-
await publisher.opened(REDIS_WAIT_MS);
|
|
1594
|
-
raw = await publisher.get().send("XRANGE", [
|
|
1595
|
-
stream(topic),
|
|
1596
|
-
"-",
|
|
1597
|
-
"+"
|
|
1598
|
-
]);
|
|
1599
|
-
} catch {
|
|
1600
|
-
return;
|
|
1601
|
-
}
|
|
1602
|
-
const ms = (seq) => Number(seq.split("-")[0]);
|
|
1603
|
-
const after = raw.filter(([id]) => compareSocketSeq(id, since) > 0);
|
|
1604
|
-
if (after.length === raw.length && (raw.length >= replay.keep || (raw[0] ? ms(raw[0][0]) : Date.now()) - ms(since) >= replay.maxAgeMs)) return void 0;
|
|
1605
|
-
return after.map(([seq, fields]) => ({
|
|
1606
|
-
type: "emit",
|
|
1607
|
-
topic,
|
|
1608
|
-
frame: fields[fields.indexOf("m") + 1],
|
|
1609
|
-
seq
|
|
1610
|
-
}));
|
|
1611
|
-
},
|
|
1612
|
-
subscribe(topic, deliver) {
|
|
1613
|
-
const name = channel(topic);
|
|
1614
|
-
let local = listeners.get(name);
|
|
1615
|
-
if (!local) {
|
|
1616
|
-
local = /* @__PURE__ */ new Set();
|
|
1617
|
-
listeners.set(name, local);
|
|
1618
|
-
const redis = subscriber.get();
|
|
1619
|
-
if (redis) subscribe(redis, name);
|
|
1620
|
-
}
|
|
1621
|
-
local.add(deliver);
|
|
1622
|
-
return () => {
|
|
1623
|
-
local.delete(deliver);
|
|
1624
|
-
if (local.size || listeners.get(name) !== local) return;
|
|
1625
|
-
listeners.delete(name);
|
|
1626
|
-
pending.delete(name);
|
|
1627
|
-
subscriber.get()?.unsubscribe(name).catch(warn("UNSUBSCRIBE"));
|
|
1628
|
-
};
|
|
1629
|
-
},
|
|
1630
|
-
async ready(topic) {
|
|
1631
|
-
const name = channel(topic);
|
|
1632
|
-
if (!pending.has(name)) await subscriber.opened(REDIS_WAIT_MS);
|
|
1633
|
-
await pending.get(name);
|
|
1634
|
-
},
|
|
1635
|
-
close() {
|
|
1636
|
-
publisher.close();
|
|
1637
|
-
subscriber.close();
|
|
1638
|
-
}
|
|
1639
|
-
};
|
|
1640
|
-
}
|
|
1641
1537
|
// src/rpc.ts
|
|
1642
1538
|
/**
|
|
1643
1539
|
* Call another service's actions in-process, typed from that service. Each
|
|
@@ -1809,6 +1705,7 @@ function createMcpHandler(options) {
|
|
|
1809
1705
|
status: 405,
|
|
1810
1706
|
headers: { Allow: "POST" }
|
|
1811
1707
|
});
|
|
1708
|
+
if (options.clientIp) withClientIp(request, options.clientIp);
|
|
1812
1709
|
let body;
|
|
1813
1710
|
try {
|
|
1814
1711
|
body = await request.json();
|
|
@@ -1863,6 +1760,112 @@ function createMcpHandler(options) {
|
|
|
1863
1760
|
}
|
|
1864
1761
|
};
|
|
1865
1762
|
}
|
|
1866
|
-
|
|
1763
|
+
// src/webhook-verifiers.ts
|
|
1764
|
+
function valuesOf(secret) {
|
|
1765
|
+
const values = (Array.isArray(secret) ? secret : [secret]).map((item) => typeof item === "string" ? item : item.require());
|
|
1766
|
+
if (!values.length || values.some((value) => !value.trim())) throw new Error("A webhook secret is empty");
|
|
1767
|
+
return values;
|
|
1768
|
+
}
|
|
1769
|
+
function same(a, b) {
|
|
1770
|
+
const x = Buffer.from(a);
|
|
1771
|
+
const y = Buffer.from(b);
|
|
1772
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
1773
|
+
}
|
|
1774
|
+
const hasBody = (method) => method === "POST";
|
|
1775
|
+
function matchesAnyWithoutShortCircuit(given, candidates) {
|
|
1776
|
+
let found = false;
|
|
1777
|
+
for (const candidate of candidates) found = same(given, candidate) || found;
|
|
1778
|
+
return found;
|
|
1779
|
+
}
|
|
1780
|
+
/**
|
|
1781
|
+
* Verifies an HMAC of the raw body, compared in constant time with a header.
|
|
1782
|
+
* It signs the body alone and checks no timestamp. Give the webhook an
|
|
1783
|
+
* `eventId`: it stops a replayed capture only when it comes from the signed body.
|
|
1784
|
+
*
|
|
1785
|
+
* @example
|
|
1786
|
+
* verify: hmacSignature({ secret: githubSecret, header: "x-hub-signature-256", prefix: "sha256=" })
|
|
1787
|
+
*/
|
|
1788
|
+
function hmacSignature(options) {
|
|
1789
|
+
const { header, prefix = "", algorithm = "sha256", encoding = "hex" } = options;
|
|
1790
|
+
const verify = ({ rawBody, headers, method }) => {
|
|
1791
|
+
if (!hasBody(method)) return false;
|
|
1792
|
+
const value = headers.get(header);
|
|
1793
|
+
if (value === null || !value.startsWith(prefix)) return false;
|
|
1794
|
+
const given = value.slice(prefix.length);
|
|
1795
|
+
const expected = valuesOf(options.secret).map((secret) => createHmac(algorithm, secret).update(rawBody).digest(encoding));
|
|
1796
|
+
return matchesAnyWithoutShortCircuit(encoding === "hex" ? given.toLowerCase() : given, expected);
|
|
1797
|
+
};
|
|
1798
|
+
return Object.assign(verify, { signsBody: true });
|
|
1799
|
+
}
|
|
1800
|
+
function keyOf(secret) {
|
|
1801
|
+
const encoded = secret.trim().replace(/^whsec_/, "");
|
|
1802
|
+
const key = /^[A-Za-z0-9+/]+={0,2}$/.test(encoded) ? Buffer.from(encoded, "base64") : Buffer.alloc(0);
|
|
1803
|
+
if (!key.length) throw new Error("A Standard Webhooks secret is not base64, or is empty");
|
|
1804
|
+
return key;
|
|
1805
|
+
}
|
|
1806
|
+
/**
|
|
1807
|
+
* Verifies the Standard Webhooks scheme (standardwebhooks.com): a base64
|
|
1808
|
+
* HMAC-SHA256 of `id.timestamp.body` in `webhook-signature`, as `v1,<signature>`
|
|
1809
|
+
* entries separated by spaces, with the timestamp in `webhook-timestamp`.
|
|
1810
|
+
* Svix's `svix-id`, `svix-timestamp` and `svix-signature` are read the same way.
|
|
1811
|
+
* The id header is the event id, so the webhook needs no `eventId`.
|
|
1812
|
+
*
|
|
1813
|
+
* @example
|
|
1814
|
+
* verify: standardWebhooks({ secret: billingSecret })
|
|
1815
|
+
*/
|
|
1816
|
+
function standardWebhooks(options) {
|
|
1817
|
+
const toleranceMs = options.toleranceMs ?? 3e5;
|
|
1818
|
+
const verify = ({ rawBody, headers, method }) => {
|
|
1819
|
+
if (!hasBody(method)) return false;
|
|
1820
|
+
const header = (name) => headers.get(`webhook-${name}`) ?? headers.get(`svix-${name}`);
|
|
1821
|
+
const id = header("id");
|
|
1822
|
+
const timestamp = header("timestamp");
|
|
1823
|
+
const signatures = header("signature");
|
|
1824
|
+
if (!id || !timestamp || !signatures || !/^\d{1,15}$/.test(timestamp)) return false;
|
|
1825
|
+
if (Math.abs(Date.now() - Number(timestamp) * 1e3) > toleranceMs) return false;
|
|
1826
|
+
const signed = Buffer.concat([Buffer.from(`${id}.${timestamp}.`), rawBody]);
|
|
1827
|
+
const expected = valuesOf(options.secret).map((secret) => createHmac("sha256", keyOf(secret)).update(signed).digest("base64"));
|
|
1828
|
+
let ok = false;
|
|
1829
|
+
for (const entry of signatures.split(" ")) {
|
|
1830
|
+
const [version, signature] = entry.split(",");
|
|
1831
|
+
if (version === "v1" && signature) ok = matchesAnyWithoutShortCircuit(signature, expected) || ok;
|
|
1832
|
+
}
|
|
1833
|
+
return ok ? { eventId: id } : false;
|
|
1834
|
+
};
|
|
1835
|
+
return Object.assign(verify, {
|
|
1836
|
+
suppliesEventId: true,
|
|
1837
|
+
signsBody: true
|
|
1838
|
+
});
|
|
1839
|
+
}
|
|
1840
|
+
/**
|
|
1841
|
+
* Verifies Twilio's `X-Twilio-Signature`: a base64 HMAC-SHA1, keyed with the
|
|
1842
|
+
* auth token, of the URL followed by the form parameters sorted by name, each
|
|
1843
|
+
* as name and value. For a JSON body, Twilio signs the URL alone and puts the
|
|
1844
|
+
* body's SHA-256 (hex) in its `bodySHA256` query parameter, which is checked
|
|
1845
|
+
* against the body. For a GET, it signs the URL alone,
|
|
1846
|
+
* and a request whose query is not the signed URL's is refused. It supplies no event id: give the webhook an `eventId`.
|
|
1847
|
+
*
|
|
1848
|
+
* @example
|
|
1849
|
+
* verify: twilioSignature({ authToken, url: "https://api.example.com/api/telephony/voice-status" })
|
|
1850
|
+
*/
|
|
1851
|
+
function twilioSignature(options) {
|
|
1852
|
+
return async (request) => {
|
|
1853
|
+
const given = request.headers.get("x-twilio-signature");
|
|
1854
|
+
if (!given) return false;
|
|
1855
|
+
const url = typeof options.url === "string" ? options.url : await options.url(request);
|
|
1856
|
+
if (request.method !== "POST" && new URL(url).search !== new URL(request.url).search) return false;
|
|
1857
|
+
let signed = url;
|
|
1858
|
+
if (request.headers.get("content-type")?.includes("json")) {
|
|
1859
|
+
const claimed = new URL(url).searchParams.get("bodySHA256");
|
|
1860
|
+
const actual = createHash("sha256").update(request.rawBody).digest("hex");
|
|
1861
|
+
if (!claimed || !same(claimed.toLowerCase(), actual)) return false;
|
|
1862
|
+
} else if (request.method === "POST") {
|
|
1863
|
+
const form = new URLSearchParams(Buffer.from(request.rawBody).toString());
|
|
1864
|
+
for (const name of [...new Set(form.keys())].sort()) for (const value of [...new Set(form.getAll(name))].sort()) signed += name + value;
|
|
1865
|
+
}
|
|
1866
|
+
return matchesAnyWithoutShortCircuit(given, valuesOf(options.authToken).map((token) => createHmac("sha1", token).update(signed).digest("base64")));
|
|
1867
|
+
};
|
|
1868
|
+
}
|
|
1869
|
+
export { ATTR, ActionExecutionError, BrickServerError, BrickTransportError, DASHBOARD_IDENTITY_HEADER, DASHBOARD_KEY_ENV, Dispatcher, DuplicateNameError, GLOBAL_SYMBOL, SPAN, SecretRef, StorageUnavailableError, Table, Type, Type as t, UnknownToolError, ValidationError, WORKFLOW_BUNDLE, actionOwners, and, asc, attachDatabase, auditTable, bindCompiledApplication, blob, brick, buildErrorHelpers, buildFtsMatchQuery, clientAddress, columnValue, compileBrickApplication, createActionHandler, createBrickClient, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, crudEventName, crudEventSource, dashboardKey, dashboardUser, defineAction, defineDatabase, defineError, defineListener, definePlugin, defineResource, defineResourcePlugin, defineSchedule, defineSecret, defineService, defineServicePlugin, defineStorage, defineTool, deny, desc, drizzleSchema, emitEvent, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, errorsOf, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getActionAccess, getActionRoute, getGlobalRegistry, getHostHooks, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, hasSensitive, hmacSignature, idSchema, ilike, inArray, index, integer, is, isAuditTable, isBrickApp, isBrickServerError, isBrickTransportError, isCrudEvent, isDatabaseHandle, isNotNull, isNull, isTool, isWebhook, kebabCase, like, listSecrets, loadCompiledBrickApp, loadRecord, lt, lte, memory, migrateDatabase, ne, not, notInArray, onTransactionCommit, or, outboxTable, overrideSecret, primaryKey, real, recordAudit, redact, redis, redisBroker, referencePlugin, registerReferenceRoute, relations, requestLoggingPlugin, requireBrickApp, resetGlobalRegistry, resetSecrets, resolveSecrets, resolveWorkflowPaths, runInTransaction, s3, scalarDocsHTML, scheduleTable, serializeSocketSchema, setActionAccess, setActionAudit, signDashboardIdentity, sql, sqliteTable, standardWebhooks, stepErrors, stepFailure, stopAllEvents, syncSchema, text, traceRoute, twilioSignature, uniqueIndex, useDeps, useService, validateWithSchema };
|
|
1867
1870
|
|
|
1868
1871
|
//# sourceMappingURL=index.js.map
|