@brickkit/core 0.15.0 → 0.16.0-beta.1

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/index.js CHANGED
@@ -1,13 +1,14 @@
1
- import { $ as segmentClaimant, A as WORKFLOW_BUNDLE, B as requireBrickApp, C as getActionAccess, D as bindCompiledApplication, E as resetGlobalRegistry, F as crudEventName, G as port, H as claimName, I as crudEventSource, J as defineServicePlugin, K as useDeps, L as eventRefs, M as defineListener, N as checkEvent, O as compileBrickApplication, P as checkPayload, Q as isInstallingPlugin, R as isCrudEvent, S as generateOpenApiSpec, T as getGlobalRegistry, U as definitionSite, V as createActionHandler, W as INTERNALS, X as hasPlugin, Y as getPluginEndpoints, Z as installPlugin, _ as envSource, _t as withCallSpan, a as defineSchedule, at as deny, b as resetSecrets, c as runInTransaction, ct as DASHBOARD_IDENTITY_HEADER, d as referencePlugin, dt as dashboardUser, et as validateName, f as registerReferenceRoute, ft as signDashboardIdentity, g as defineSecret, gt as traceRoute, h as SecretRef, ht as validateWithSchema, i as stopAllEvents, it as errorsOf, j as resolveWorkflowPaths, k as loadCompiledBrickApp, l as isOutboxTable, lt as DASHBOARD_KEY_ENV, m as requestLoggingPlugin, mt as fileFields, n as defineServiceSocket, nt as buildErrorHelpers, o as Dispatcher, ot as baseContext, p as scalarDocsHTML, pt as Type, q as defineResourcePlugin, r as recordingServices, rt as defineAction, s as onTransactionCommit, st as pickContextEnvelope, t as brick, tt as portOf, u as outboxTable, ut as dashboardKey, v as listSecrets, vt as PLUGIN_COMMIT, w as setActionAccess, x as resolveSecrets, y as overrideSecret, yt as PLUGIN_KIND, z as isBrickApp } from "./chunks/server.js";
2
- import { G as DuplicateNameError, H as GLOBAL_SYMBOL, K as ValidationError, S as actionMeta, U as SPAN, V as ATTR, W as ActionExecutionError, a as isBrickTransportError, d as getActionRoute, f as getPluginActionRoute, i as isBrickServerError, j as compareSocketSeq, l as actionOwners, n as BrickTransportError, r as createBrickClient, s as serializeSocketSchema, t as BrickServerError, x as kebabCase } from "./chunks/client.js";
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$1(name),
52
- integer: (name) => integer$1(name, { mode: "number" }),
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$1(name, { mode: "boolean" }),
55
+ boolean: (name) => integer$2(name, { mode: "boolean" }),
55
56
  /** A `Date`, stored as epoch milliseconds or `timestamptz`. */
56
- timestamp: (name) => integer$1(name, { mode: "timestamp_ms" }),
57
- json: (name) => text$1(name, { mode: "json" })
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$2(name),
64
- integer: (name) => integer$2(name),
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
- /** Check the deps passed at install against the ports the plugin declares. */
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(ports ?? {});
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 Object.freeze(Object.fromEntries(declared.map((key) => [key, provided[key]])));
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`);
@@ -879,8 +879,17 @@ function defineResourceAction(service, resource, config, command) {
879
879
  input = Type.Object({
880
880
  ...own?.properties,
881
881
  id: idSchema(resource.id)
882
- }, own?.additionalProperties === void 0 ? {} : { additionalProperties: own.additionalProperties });
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);
883
887
  }
888
+ sensitivity({
889
+ ...rest,
890
+ name,
891
+ input
892
+ }, service.name);
884
893
  const action = defineAction({
885
894
  ...rest,
886
895
  name,
@@ -950,6 +959,7 @@ function commandErrors(errors) {
950
959
  }
951
960
  function defineCommand(service, resource, name, config) {
952
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.`);
953
963
  if (typeof config.decide !== "function") throw new Error(`${where} needs a decide function`);
954
964
  const loaded = (config.load?.children ?? []).map((child) => ({
955
965
  name: child,
@@ -999,10 +1009,15 @@ function defineCommand(service, resource, name, config) {
999
1009
  if (changes.delete?.length) await tx.delete(child.table).where(and$1(inArray$1(child.id, changes.delete), own));
1000
1010
  }
1001
1011
  for (const [eventName, payload] of emits) await record(eventName, payload);
1002
- if (!config.output) return { id };
1003
- const [updated] = await tx.select().from(resource.table).where(eq$1(resource.id, id)).limit(1);
1004
- for (const child of loaded) updated[child.name] = await tx.select().from(child.table).where(eq$1(child.parent, id));
1005
- return Value.Clean(config.output, updated);
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;
1006
1021
  };
1007
1022
  return recorder ? recorder.transaction(db, {
1008
1023
  traceId: ctx.traceId,
@@ -1016,11 +1031,15 @@ function defineCommand(service, resource, name, config) {
1016
1031
  tags: config.tags,
1017
1032
  input: config.input,
1018
1033
  output: config.output ?? Type.Object({ id: idSchema(resource.id) }),
1034
+ reveal: config.reveal,
1019
1035
  errors: config.errors,
1020
1036
  ...config.access === void 0 ? {} : { access: config.access },
1021
1037
  ...config.authorize ? { authorize: config.authorize } : {},
1038
+ ...config.rateLimit ? { rateLimit: config.rateLimit } : {},
1039
+ ...config.audit === void 0 ? {} : { audit: config.audit },
1022
1040
  execute: () => void 0
1023
1041
  }, run);
1042
+ setActionAudit(action, "inline");
1024
1043
  Object.assign(action, { decide });
1025
1044
  return action;
1026
1045
  }
@@ -1061,31 +1080,31 @@ function defineResource(service, config) {
1061
1080
  // src/schedules/table.ts
1062
1081
  const SCHEDULES = Symbol.for("brick.schedules");
1063
1082
  function sqliteSchedules(name) {
1064
- const at = (column) => integer$1(column, { mode: "timestamp_ms" });
1083
+ const at = (column) => integer$2(column, { mode: "timestamp_ms" });
1065
1084
  return sqliteTable$1(name, {
1066
- name: text$1("name").primaryKey(),
1067
- spec: text$1("spec").notNull(),
1085
+ name: text$2("name").primaryKey(),
1086
+ spec: text$2("spec").notNull(),
1068
1087
  slot: at("slot").notNull(),
1069
1088
  nextAt: at("next_at").notNull(),
1070
- attempts: integer$1("attempts").notNull().default(0),
1071
- trigger: text$1("trigger").$type().notNull(),
1072
- runId: text$1("run_id"),
1089
+ attempts: integer$2("attempts").notNull().default(0),
1090
+ trigger: text$2("trigger").$type().notNull(),
1091
+ runId: text$2("run_id"),
1073
1092
  startedAt: at("started_at"),
1074
1093
  leaseUntil: at("lease_until"),
1075
1094
  lastSuccessAt: at("last_success_at"),
1076
- runs: text$1("runs", { mode: "json" }).$type().notNull()
1095
+ runs: text$2("runs", { mode: "json" }).$type().notNull()
1077
1096
  });
1078
1097
  }
1079
1098
  function postgresSchedules(name) {
1080
1099
  const at = (column) => timestamp(column, { withTimezone: true });
1081
1100
  return pgTable(name, {
1082
- name: text$2("name").primaryKey(),
1083
- spec: text$2("spec").notNull(),
1101
+ name: text$1("name").primaryKey(),
1102
+ spec: text$1("spec").notNull(),
1084
1103
  slot: at("slot").notNull(),
1085
1104
  nextAt: at("next_at").notNull(),
1086
- attempts: integer$2("attempts").notNull().default(0),
1087
- trigger: text$2("trigger").$type().notNull(),
1088
- runId: text$2("run_id"),
1105
+ attempts: integer$1("attempts").notNull().default(0),
1106
+ trigger: text$1("trigger").$type().notNull(),
1107
+ runId: text$1("run_id"),
1089
1108
  startedAt: at("started_at"),
1090
1109
  leaseUntil: at("lease_until"),
1091
1110
  lastSuccessAt: at("last_success_at"),
@@ -1103,9 +1122,6 @@ function isScheduleTable(value) {
1103
1122
  return typeof value === "object" && value !== null && SCHEDULES in value;
1104
1123
  }
1105
1124
  // src/service.ts
1106
- const RESOLVED_SYMBOL = Symbol("resolved");
1107
- /** The deps a resolved context was resolved with, to restore them when a plugin's copy comes back. */
1108
- const OWN_DEPS = Symbol("ownDeps");
1109
1125
  var ServiceImpl = class {
1110
1126
  name;
1111
1127
  options;
@@ -1118,19 +1134,40 @@ var ServiceImpl = class {
1118
1134
  /** Where each `kind:name` was defined, to reject duplicates from another file. */
1119
1135
  sites = /* @__PURE__ */ new Map();
1120
1136
  database;
1137
+ auditTable;
1138
+ auditHooked = false;
1121
1139
  _isBuilt = false;
1122
1140
  _events;
1123
1141
  /** What a write needs to record events. Set by `brick({ events })`. */
1124
1142
  recorder;
1125
- /** The values of this service's `deps`. Set by `brick({ deps })`. */
1126
1143
  deps;
1127
1144
  constructor(name, options = {}) {
1128
1145
  this.name = name;
1129
1146
  this.options = options;
1147
+ this.deps = ownDeps(name, options.deps);
1130
1148
  this._events = eventRefs(name, options.events);
1131
1149
  for (const key of Object.keys(this._events)) this.claim("event", key);
1132
1150
  if (options.database !== void 0 && !isDatabaseHandle(options.database)) throw new Error("Service database must be created with defineDatabase()");
1133
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
+ });
1134
1171
  }
1135
1172
  /** The declared events: `service.events.<name>`. */
1136
1173
  get events() {
@@ -1193,6 +1230,12 @@ var ServiceImpl = class {
1193
1230
  const resource = info?.record && this.resources.get(info.resource);
1194
1231
  if (resource) checkRecordAccess(resource, info);
1195
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}", { ... }).`);
1196
1239
  this._isBuilt = true;
1197
1240
  return this;
1198
1241
  }
@@ -1232,8 +1275,11 @@ var ServiceImpl = class {
1232
1275
  }
1233
1276
  action(actionOrConfig) {
1234
1277
  const isActionFunction = typeof actionOrConfig === "function" && "config" in actionOrConfig;
1278
+ if (!isActionFunction) sensitivity(actionOrConfig, this.name);
1235
1279
  const actionInstance = isActionFunction ? actionOrConfig : defineAction(actionOrConfig);
1236
- if (this.actions.get(actionInstance.name) !== actionInstance) this.claim("action", actionInstance.name);
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.`);
1237
1283
  if (isTool(actionInstance)) actionInstance.config.http = true;
1238
1284
  actionInstance.serviceName = this.name;
1239
1285
  actionMeta(actionInstance).service = this;
@@ -1241,8 +1287,20 @@ var ServiceImpl = class {
1241
1287
  this.touch();
1242
1288
  return isActionFunction ? this : actionInstance;
1243
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
+ }
1244
1301
  tool(toolOrConfig) {
1245
1302
  const existing = isTool(toolOrConfig);
1303
+ if (!existing) sensitivity(toolOrConfig, this.name);
1246
1304
  const tool = existing ? toolOrConfig : defineTool(toolOrConfig);
1247
1305
  this.claim("tool", tool.name);
1248
1306
  tool.serviceName = this.name;
@@ -1288,6 +1346,9 @@ var ServiceImpl = class {
1288
1346
  getScheduleTable() {
1289
1347
  return Object.values(this.database?.tables ?? {}).find(isScheduleTable);
1290
1348
  }
1349
+ getAuditTable() {
1350
+ return this.auditTable;
1351
+ }
1291
1352
  setRecorder(recorder) {
1292
1353
  this.recorder = recorder;
1293
1354
  }
@@ -1298,12 +1359,10 @@ var ServiceImpl = class {
1298
1359
  checkEvent(name, payload) {
1299
1360
  checkEvent(this, name, payload);
1300
1361
  }
1301
- setDeps(deps) {
1302
- this.deps = deps;
1303
- }
1304
1362
  setDb(database) {
1305
1363
  if (!isDatabaseHandle(database)) throw new Error("Use defineDatabase() to set a service database");
1306
1364
  this.database = database;
1365
+ this.watchAudit();
1307
1366
  this.touch();
1308
1367
  }
1309
1368
  /**
@@ -1321,7 +1380,7 @@ var ServiceImpl = class {
1321
1380
  tables: Object.keys(this.database.tables),
1322
1381
  ...pluginTables(this.database.tables)
1323
1382
  } : void 0;
1324
- const { database: _database, events: _events, ...config } = this.options;
1383
+ const { database: _database, events: _events, deps: _deps, ...config } = this.options;
1325
1384
  const options = JSON.parse(JSON.stringify(config));
1326
1385
  return {
1327
1386
  name: this.name,
@@ -1342,6 +1401,12 @@ var ServiceImpl = class {
1342
1401
  hasScope: access.hasScope,
1343
1402
  accessPolicy: access.policy,
1344
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 },
1345
1410
  emits: act.config.emits,
1346
1411
  tags: act.config.tags
1347
1412
  };
@@ -1364,6 +1429,27 @@ function pluginTables(tables) {
1364
1429
  });
1365
1430
  return owners.length ? { plugins: Object.fromEntries(owners) } : {};
1366
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);
1367
1453
  /**
1368
1454
  * The context of a call to one of the service's actions or sockets. The one
1369
1455
  * rule for which deps it sees: those of the plugin install that created the
@@ -1371,13 +1457,15 @@ function pluginTables(tables) {
1371
1457
  * `context` hook always sees the service's own.
1372
1458
  */
1373
1459
  async function resolveServiceContext(service, callCtx, pluginDeps) {
1374
- if (callCtx?.[RESOLVED_SYMBOL] === service) {
1375
- const deps = pluginDeps ?? callCtx[OWN_DEPS];
1376
- return callCtx.deps === deps ? callCtx : {
1377
- ...callCtx,
1378
- deps
1379
- };
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;
1380
1467
  }
1468
+ const override = depsOverride(callCtx);
1381
1469
  const framework = baseContext({
1382
1470
  request: callCtx?.request,
1383
1471
  db: service.getDb(),
@@ -1387,20 +1475,21 @@ async function resolveServiceContext(service, callCtx, pluginDeps) {
1387
1475
  services: callCtx?.services,
1388
1476
  metadata: callCtx?.metadata,
1389
1477
  dashboard: callCtx?.dashboard,
1390
- deps: service.deps ?? (callCtx?.[RESOLVED_SYMBOL] ? void 0 : callCtx?.deps)
1478
+ deps: frameworkDeps(service, override, pluginDeps)
1391
1479
  });
1392
1480
  const fullBaseCtx = {
1393
1481
  ...framework,
1394
1482
  ...pickContextEnvelope(callCtx)
1395
1483
  };
1396
1484
  const resolvedExtra = service.options.context ? await service.options.context(fullBaseCtx) : {};
1397
- return {
1485
+ const finalCtx = {
1398
1486
  ...fullBaseCtx,
1399
1487
  ...resolvedExtra,
1400
- deps: pluginDeps ?? framework.deps,
1401
- [RESOLVED_SYMBOL]: service,
1402
- [OWN_DEPS]: framework.deps
1488
+ deps: pluginDeps ? override ? withOverride(pluginDeps, override) : pluginDeps : framework.deps
1403
1489
  };
1490
+ markResolved(finalCtx, service, framework.deps);
1491
+ finalCtx.deps = scopeFiles(finalCtx.deps, finalCtx);
1492
+ return finalCtx;
1404
1493
  }
1405
1494
  /**
1406
1495
  * Declare a service: a named group of actions, tools, and resources with its own
@@ -1413,9 +1502,11 @@ async function resolveServiceContext(service, callCtx, pluginDeps) {
1413
1502
  * @param name - Unique name. It is the service's segment of every action route
1414
1503
  * (`/api/<name>/<action>`) and appears in OpenAPI and the dashboard. Defining it
1415
1504
  * again from the same file (a dev reload) replaces it; from another file throws.
1416
- * @param options - `database` (a handle from `defineDatabase`), `deps` (typed
1417
- * slots from `port<T>()` that `brick({ deps })` fills, read as `ctx.deps`),
1505
+ * @param options - `database` (a handle from `defineDatabase`), `deps` (the
1506
+ * values the service's code uses, such as clients, read as `ctx.deps`),
1418
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),
1419
1510
  * `events` (the event catalog: a payload schema per event name, recorded as
1420
1511
  * `<service>.<name>` and offered as `service.events.<name>`).
1421
1512
  * @returns The service.
@@ -1443,203 +1534,6 @@ function defineService(name, options) {
1443
1534
  getGlobalRegistry().register(service);
1444
1535
  return service;
1445
1536
  }
1446
- // src/socket-redis.ts
1447
- /** Exponential backoff from 500 ms to 30 s, with jitter so processes don't reconnect in step. */
1448
- function reconnectDelay(failures) {
1449
- const ceiling = Math.min(3e4, 500 * 2 ** failures);
1450
- return ceiling / 2 + Math.random() * (ceiling / 2);
1451
- }
1452
- /** How long a call waits for Redis to connect before going on without it. */
1453
- const REDIS_WAIT_MS = 1e3;
1454
- /** One Redis connection that reconnects by itself and reports each fresh connection. */
1455
- function connection(url, connected) {
1456
- let redis;
1457
- let timer;
1458
- let closed = false;
1459
- let failures = 0;
1460
- const waiters = [];
1461
- const lost = (client) => {
1462
- if (redis !== client) return;
1463
- redis = void 0;
1464
- if (closed || timer) return;
1465
- timer = setTimeout(() => {
1466
- timer = void 0;
1467
- start();
1468
- }, reconnectDelay(failures++));
1469
- };
1470
- const start = () => {
1471
- if (closed || redis || timer) return;
1472
- const client = new Bun.RedisClient(url, {
1473
- autoReconnect: false,
1474
- enableOfflineQueue: false
1475
- });
1476
- redis = client;
1477
- client.onclose = () => lost(client);
1478
- client.connect().then(() => {
1479
- if (redis !== client) return;
1480
- failures = 0;
1481
- connected(client);
1482
- for (const wake of waiters.splice(0)) wake();
1483
- }, () => lost(client));
1484
- };
1485
- return {
1486
- get() {
1487
- start();
1488
- return redis?.connected ? redis : void 0;
1489
- },
1490
- /** Resolves after the next connection is made and announced, or after `ms`. */
1491
- opened(ms) {
1492
- if (redis?.connected) return Promise.resolve();
1493
- start();
1494
- return new Promise((resolve) => {
1495
- const timeout = setTimeout(resolve, ms);
1496
- waiters.push(() => {
1497
- clearTimeout(timeout);
1498
- resolve();
1499
- });
1500
- });
1501
- },
1502
- close() {
1503
- closed = true;
1504
- clearTimeout(timer);
1505
- for (const wake of waiters.splice(0)) wake();
1506
- const client = redis;
1507
- redis = void 0;
1508
- client?.close();
1509
- }
1510
- };
1511
- }
1512
- /**
1513
- * Fans socket emits and kicks out across processes through Redis pub/sub, one
1514
- * channel per room topic. An emit is a PUBLISH only: every process, the emitting
1515
- * one included, delivers it once to its own connections. Uses Bun's built-in
1516
- * Redis client and two connections, one to publish and one to subscribe.
1517
- */
1518
- function redisBroker(options = {}) {
1519
- const limit = options.queue ?? 1e3;
1520
- if (!Number.isInteger(limit) || limit < 0) throw new Error("redisBroker queue must be a nonnegative integer");
1521
- const channel = (topic) => `brick:socket:${topic}`;
1522
- const listeners = /* @__PURE__ */ new Map();
1523
- const pending = /* @__PURE__ */ new Map();
1524
- const stream = (topic) => `brick:socket:stream:${topic}`;
1525
- const warned = /* @__PURE__ */ new Set();
1526
- const warn = (what) => (error) => {
1527
- if (warned.has(what)) return;
1528
- warned.add(what);
1529
- console.warn(`[Brick-TS] Redis socket broker: ${what} failed; later failures of it are not logged.`, error);
1530
- };
1531
- const queue = [];
1532
- const send = (work) => {
1533
- const redis = publisher.get();
1534
- if (redis) return work(redis);
1535
- queue.push(work);
1536
- if (queue.length > limit) queue.shift();
1537
- };
1538
- const receive = (payload, name) => {
1539
- let message;
1540
- try {
1541
- message = JSON.parse(payload);
1542
- } catch {
1543
- return;
1544
- }
1545
- for (const deliver of listeners.get(name) ?? []) deliver(message);
1546
- };
1547
- const subscribe = (redis, name) => {
1548
- const done = redis.subscribe(name, receive).catch(warn("SUBSCRIBE"));
1549
- pending.set(name, done);
1550
- done.then(() => {
1551
- if (pending.get(name) === done) pending.delete(name);
1552
- });
1553
- };
1554
- const publisher = connection(options.url, (redis) => {
1555
- for (const work of queue.splice(0)) work(redis);
1556
- });
1557
- const subscriber = connection(options.url, (redis) => {
1558
- for (const name of listeners.keys()) subscribe(redis, name);
1559
- });
1560
- return {
1561
- publish(message, replay) {
1562
- const name = channel(message.topic);
1563
- if (message.type !== "emit" || !replay) return send((redis) => void redis.publish(name, JSON.stringify(message)).catch(warn("PUBLISH")));
1564
- const key = stream(message.topic);
1565
- send((redis) => {
1566
- redis.send("XADD", [
1567
- key,
1568
- "MAXLEN",
1569
- "~",
1570
- String(replay.keep),
1571
- "*",
1572
- "m",
1573
- message.frame
1574
- ]).then((seq) => {
1575
- redis.send("PEXPIRE", [key, String(replay.maxAgeMs)]).catch(warn("PEXPIRE"));
1576
- return redis.publish(name, JSON.stringify({
1577
- ...message,
1578
- seq
1579
- }));
1580
- }).catch(warn("XADD/PUBLISH"));
1581
- });
1582
- },
1583
- async head() {
1584
- try {
1585
- await publisher.opened(REDIS_WAIT_MS);
1586
- const [seconds, micros] = await publisher.get().send("TIME", []);
1587
- return `${Number(seconds) * 1e3 + Math.floor(Number(micros) / 1e3) - 1}-0`;
1588
- } catch {
1589
- return `${Date.now() - 1}-0`;
1590
- }
1591
- },
1592
- async history(topic, since, replay) {
1593
- let raw;
1594
- try {
1595
- await publisher.opened(REDIS_WAIT_MS);
1596
- raw = await publisher.get().send("XRANGE", [
1597
- stream(topic),
1598
- "-",
1599
- "+"
1600
- ]);
1601
- } catch {
1602
- return;
1603
- }
1604
- const ms = (seq) => Number(seq.split("-")[0]);
1605
- const after = raw.filter(([id]) => compareSocketSeq(id, since) > 0);
1606
- if (after.length === raw.length && (raw.length >= replay.keep || (raw[0] ? ms(raw[0][0]) : Date.now()) - ms(since) >= replay.maxAgeMs)) return void 0;
1607
- return after.map(([seq, fields]) => ({
1608
- type: "emit",
1609
- topic,
1610
- frame: fields[fields.indexOf("m") + 1],
1611
- seq
1612
- }));
1613
- },
1614
- subscribe(topic, deliver) {
1615
- const name = channel(topic);
1616
- let local = listeners.get(name);
1617
- if (!local) {
1618
- local = /* @__PURE__ */ new Set();
1619
- listeners.set(name, local);
1620
- const redis = subscriber.get();
1621
- if (redis) subscribe(redis, name);
1622
- }
1623
- local.add(deliver);
1624
- return () => {
1625
- local.delete(deliver);
1626
- if (local.size || listeners.get(name) !== local) return;
1627
- listeners.delete(name);
1628
- pending.delete(name);
1629
- subscriber.get()?.unsubscribe(name).catch(warn("UNSUBSCRIBE"));
1630
- };
1631
- },
1632
- async ready(topic) {
1633
- const name = channel(topic);
1634
- if (!pending.has(name)) await subscriber.opened(REDIS_WAIT_MS);
1635
- await pending.get(name);
1636
- },
1637
- close() {
1638
- publisher.close();
1639
- subscriber.close();
1640
- }
1641
- };
1642
- }
1643
1537
  // src/rpc.ts
1644
1538
  /**
1645
1539
  * Call another service's actions in-process, typed from that service. Each
@@ -1811,6 +1705,7 @@ function createMcpHandler(options) {
1811
1705
  status: 405,
1812
1706
  headers: { Allow: "POST" }
1813
1707
  });
1708
+ if (options.clientIp) withClientIp(request, options.clientIp);
1814
1709
  let body;
1815
1710
  try {
1816
1711
  body = await request.json();
@@ -1865,6 +1760,112 @@ function createMcpHandler(options) {
1865
1760
  }
1866
1761
  };
1867
1762
  }
1868
- export { ATTR, ActionExecutionError, BrickServerError, BrickTransportError, DASHBOARD_IDENTITY_HEADER, DASHBOARD_KEY_ENV, Dispatcher, DuplicateNameError, GLOBAL_SYMBOL, SPAN, SecretRef, Table, Type, Type as t, UnknownToolError, ValidationError, WORKFLOW_BUNDLE, actionOwners, and, asc, attachDatabase, bindCompiledApplication, blob, brick, buildErrorHelpers, buildFtsMatchQuery, columnValue, compileBrickApplication, createActionHandler, createBrickClient, createMcpHandler, createMcpRegistry, createPostgresDatabase, createSQLiteDatabase, crudEventName, crudEventSource, dashboardKey, dashboardUser, defineAction, defineDatabase, defineError, defineListener, definePlugin, defineResource, defineResourcePlugin, defineSchedule, defineSecret, defineService, defineServicePlugin, defineTool, deny, desc, drizzleSchema, emitEvent, ensureResourceIndexes, ensureSQLiteFts, envSource, eq, errorsOf, foreignKey, generateOpenApiSpec, generateSQLiteIndexDdl, generateSQLiteTableDdl, getActionAccess, getActionRoute, getGlobalRegistry, getHostHooks, getPluginActionRoute, getPluginEndpoints, getTableColumns, getTableName, gt, gte, idSchema, ilike, inArray, index, integer, is, isBrickApp, isBrickServerError, isBrickTransportError, isCrudEvent, isDatabaseHandle, isNotNull, isNull, isTool, kebabCase, like, listSecrets, loadCompiledBrickApp, loadRecord, lt, lte, migrateDatabase, ne, not, notInArray, onTransactionCommit, or, outboxTable, overrideSecret, port, primaryKey, real, redisBroker, referencePlugin, registerReferenceRoute, relations, requestLoggingPlugin, requireBrickApp, resetGlobalRegistry, resetSecrets, resolveSecrets, resolveWorkflowPaths, runInTransaction, scalarDocsHTML, scheduleTable, serializeSocketSchema, setActionAccess, signDashboardIdentity, sql, sqliteTable, stepErrors, stepFailure, stopAllEvents, syncSchema, text, traceRoute, uniqueIndex, useDeps, useService, validateWithSchema };
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 };
1869
1870
 
1870
1871
  //# sourceMappingURL=index.js.map