@mnmal-ai/substrate 1.0.0-alpha.1 → 1.0.0-alpha.2

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.
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __binCreateRequire } from 'node:module'; const require = __binCreateRequire(import.meta.url);
2
- import { A as expandFlat, D as isActiveAdminKeyRow, F as parseGrantEntries, I as decodeList, L as encodeList, M as grantEntryError, P as intersectGrants, S as and, T as SYSTEM_NAMESPACE, d as confersAnywhere, f as coversNamespace, g as checkUpdatable, h as checkRevocable, l as requireNamespace, m as grantedIn, p as grantOf, r as allowAll, s as requireCapability, t as applyRowFilters, u as allCapabilities, v as grantEntriesConfer } from "./row-DK7lPZVe.js";
3
- import { S as assertNever, c as isPlainRequestData, f as encodeEnvelope, o as decodeWsEnvelope, p as encodePositional, s as encodeWsFrame, t as WS_SUBPROTOCOL_SUBSTRATE_PACK, x as parseQualifiedKey } from "./src-C4DzaIQZ.js";
2
+ import { A as expandFlat, D as isActiveAdminKeyRow, F as parseGrantEntries, I as decodeList, L as encodeList, M as grantEntryError, P as intersectGrants, S as and, T as SYSTEM_NAMESPACE, d as confersAnywhere, f as coversNamespace, g as checkUpdatable, h as checkRevocable, l as requireNamespace, m as grantedIn, p as grantOf, s as requireCapability, t as applyRowFilters, u as allCapabilities, v as grantEntriesConfer } from "./row-DZ0Fnpc6.js";
3
+ import { S as assertNever, c as isPlainRequestData, f as encodeEnvelope, o as decodeWsEnvelope, p as encodePositional, s as encodeWsFrame, t as WS_SUBPROTOCOL_SUBSTRATE_PACK, x as parseQualifiedKey } from "./src-BLgbLq2k.js";
4
4
  import { n as acceptsPack, t as PACK_MIME } from "./content-type-C7T28xNb.js";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { createCipheriv, createDecipheriv, createHash, createHmac, createPrivateKey, createPublicKey, createVerify, hkdfSync, randomBytes, randomUUID, sign, timingSafeEqual, verify } from "node:crypto";
@@ -703,7 +703,7 @@ function parseAuthConfig(env) {
703
703
  }
704
704
  /** True for a postgres `SUBSTRATE_DATABASE_URL`, which is what makes the DB key registry available. */
705
705
  function isPostgresStore(store) {
706
- return store?.startsWith("postgres://") ?? false;
706
+ return (store?.startsWith("postgres://") || store?.startsWith("postgresql://")) ?? false;
707
707
  }
708
708
  /** Mode defaults to `required` — the safe end — when unset. */
709
709
  function applyMode(cfg, mode) {
@@ -794,7 +794,7 @@ function base64UrlDecode(segment) {
794
794
  return Buffer.from(b64, "base64");
795
795
  }
796
796
  function base64UrlEncode(buf) {
797
- return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
797
+ return buf.toString("base64url");
798
798
  }
799
799
  function parseSegments(token) {
800
800
  const parts = token.split(".");
@@ -1018,7 +1018,7 @@ function watchCredential(identity, cfg, onLapse) {
1018
1018
  }
1019
1019
  function extractBearer(authorization) {
1020
1020
  if (authorization === void 0) return null;
1021
- const match = /^Bearer\s+(.+)$/i.exec(authorization.trim());
1021
+ const match = /^Bearer\s+(\S.*)$/i.exec(authorization.trim());
1022
1022
  if (match === null) return null;
1023
1023
  const token = match[1]?.trim();
1024
1024
  if (token === void 0 || token.length === 0) return null;
@@ -2013,6 +2013,14 @@ function getFieldValue(row, name) {
2013
2013
  if (projector !== void 0) return projector(row);
2014
2014
  return row[name];
2015
2015
  }
2016
+ /**
2017
+ * Whether `field` holds a date: the `createdAt`/`updatedAt` columns always do,
2018
+ * a body field when its declaration says so. Date fields compare as instants.
2019
+ */
2020
+ function isDateField(field, fieldDefOf) {
2021
+ const def = METADATA_FILTER_FIELDS[field] ?? fieldDefOf?.(field);
2022
+ return def?.kind === "scalar" && def.type === "date";
2023
+ }
2016
2024
  const KNOWN_OPS = /* @__PURE__ */ new Set([
2017
2025
  "eq",
2018
2026
  "neq",
@@ -2087,27 +2095,35 @@ function assertFieldPredicateHonourable(field, predicate) {
2087
2095
  case "endsWith": if (typeof operand !== "string") throw new UnsupportedFilterError(field, op, "requires a string value");
2088
2096
  }
2089
2097
  }
2090
- function evaluateWhere(row, where) {
2098
+ /**
2099
+ * `fieldDefOf` names the row type's declared fields, so `date` fields compare
2100
+ * as instants (as pg's timestamptz does). Without it, only `createdAt` and
2101
+ * `updatedAt` do; nested struct fields always compare as written.
2102
+ */
2103
+ function evaluateWhere(row, where, fieldDefOf) {
2091
2104
  if (where === null || typeof where !== "object" || Array.isArray(where)) return true;
2092
2105
  for (const [k, child] of Object.entries(where)) if (k === "AND") {
2093
2106
  if (Array.isArray(child)) {
2094
- for (const sub of child) if (!evaluateWhere(row, sub)) return false;
2107
+ for (const sub of child) if (!evaluateWhere(row, sub, fieldDefOf)) return false;
2095
2108
  }
2096
2109
  } else if (k === "OR") {
2097
2110
  if (Array.isArray(child)) {
2098
2111
  let any = false;
2099
- for (const sub of child) if (evaluateWhere(row, sub)) {
2112
+ for (const sub of child) if (evaluateWhere(row, sub, fieldDefOf)) {
2100
2113
  any = true;
2101
2114
  break;
2102
2115
  }
2103
2116
  if (!any) return false;
2104
2117
  }
2105
2118
  } else if (k === "NOT") {
2106
- if (evaluateWhere(row, child)) return false;
2107
- } else if (!evaluateFieldPredicate(k, getFieldValue(row, k), child)) return false;
2119
+ if (evaluateWhere(row, child, fieldDefOf)) return false;
2120
+ } else {
2121
+ const asDate = isDateField(k, fieldDefOf);
2122
+ if (!evaluateFieldPredicate(k, getFieldValue(row, k), child, asDate)) return false;
2123
+ }
2108
2124
  return true;
2109
2125
  }
2110
- function evaluateFieldPredicate(field, value, predicate) {
2126
+ function evaluateFieldPredicate(field, value, predicate, asDate = false) {
2111
2127
  if (predicate === null || typeof predicate !== "object" || Array.isArray(predicate)) throw new UnsupportedFilterError(field, "<none>", `expected a predicate object such as { eq: ... }, got ${Array.isArray(predicate) ? "an array" : typeof predicate}`);
2112
2128
  if (isJsonPathPredicate(predicate)) return evaluateJsonPathPredicate(field, value, predicate);
2113
2129
  const p = predicate;
@@ -2119,34 +2135,34 @@ function evaluateFieldPredicate(field, value, predicate) {
2119
2135
  }
2120
2136
  for (const op of keys) {
2121
2137
  const operand = p[op];
2122
- if (!applyOp(field, op, value, operand)) return false;
2138
+ if (!applyOp(field, op, value, operand, asDate)) return false;
2123
2139
  }
2124
2140
  return true;
2125
2141
  }
2126
- function applyOp(field, op, value, operand) {
2142
+ function applyOp(field, op, value, operand, asDate) {
2127
2143
  switch (op) {
2128
- case "eq": return equals(value, operand);
2129
- case "neq": return !equals(value, operand);
2144
+ case "eq": return equals(value, operand, asDate);
2145
+ case "neq": return !equals(value, operand, asDate);
2130
2146
  case "gt":
2131
2147
  if (value == null) return false;
2132
- return compare$1(value, operand) > 0;
2148
+ return compareFilterValues(value, operand, asDate) > 0;
2133
2149
  case "gte":
2134
2150
  if (value == null) return false;
2135
- return compare$1(value, operand) >= 0;
2151
+ return compareFilterValues(value, operand, asDate) >= 0;
2136
2152
  case "lt":
2137
2153
  if (value == null) return false;
2138
- return compare$1(value, operand) < 0;
2154
+ return compareFilterValues(value, operand, asDate) < 0;
2139
2155
  case "lte":
2140
2156
  if (value == null) return false;
2141
- return compare$1(value, operand) <= 0;
2157
+ return compareFilterValues(value, operand, asDate) <= 0;
2142
2158
  case "between":
2143
2159
  if (!Array.isArray(operand) || operand.length !== 2) throw new UnsupportedFilterError(field, op, "requires a two-element [low, high] array");
2144
2160
  if (value == null) return false;
2145
- return compare$1(value, operand[0]) >= 0 && compare$1(value, operand[1]) <= 0;
2161
+ return compareFilterValues(value, operand[0], asDate) >= 0 && compareFilterValues(value, operand[1], asDate) <= 0;
2146
2162
  case "in":
2147
2163
  case "nin": {
2148
2164
  if (!Array.isArray(operand)) throw new UnsupportedFilterError(field, op, "requires an array value");
2149
- const member = operand.some((e) => equals(value, e));
2165
+ const member = operand.some((e) => equals(value, e, asDate));
2150
2166
  return op === "in" ? member : !member;
2151
2167
  }
2152
2168
  case "contains":
@@ -2164,26 +2180,44 @@ function applyOp(field, op, value, operand) {
2164
2180
  default: throw new UnsupportedFilterError(field, op, "is not a recognised filter operator");
2165
2181
  }
2166
2182
  }
2167
- function equals(a, b) {
2183
+ function equals(a, b, asDate = false) {
2168
2184
  if (a == null && b == null) return true;
2169
- if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
2170
- if (a instanceof Date && typeof b === "string") return a.toISOString() === b;
2171
- if (b instanceof Date && typeof a === "string") return b.toISOString() === a;
2185
+ if (asDate || a instanceof Date || b instanceof Date) {
2186
+ const at = toMicros(a);
2187
+ const bt = toMicros(b);
2188
+ if (at !== void 0 && bt !== void 0) return at === bt;
2189
+ }
2172
2190
  return a === b;
2173
2191
  }
2174
- function compare$1(a, b) {
2192
+ /**
2193
+ * Orders two filter values: nullish last, dates (when `asDate`, or either side
2194
+ * is a `Date`) by instant, numbers numerically, anything else as text by code point.
2195
+ */
2196
+ function compareFilterValues(a, b, asDate = false) {
2175
2197
  if (a == null && b == null) return 0;
2176
2198
  if (a == null) return 1;
2177
2199
  if (b == null) return -1;
2178
- if (a instanceof Date || b instanceof Date) {
2179
- const at = a instanceof Date ? a.getTime() : typeof a === "string" ? Date.parse(a) : Number(a);
2180
- const bt = b instanceof Date ? b.getTime() : typeof b === "string" ? Date.parse(b) : Number(b);
2181
- return at < bt ? -1 : at > bt ? 1 : 0;
2200
+ if (asDate || a instanceof Date || b instanceof Date) {
2201
+ const at = toMicros(a);
2202
+ const bt = toMicros(b);
2203
+ if (at !== void 0 && bt !== void 0) return at < bt ? -1 : at > bt ? 1 : 0;
2182
2204
  }
2183
2205
  if (typeof a === "number" && typeof b === "number") return a < b ? -1 : a > b ? 1 : 0;
2184
- const as = String(a);
2185
- const bs = String(b);
2186
- return as < bs ? -1 : as > bs ? 1 : 0;
2206
+ return compareCodePoints(String(a), String(b));
2207
+ }
2208
+ /**
2209
+ * Microseconds since the epoch, pg's timestamptz precision. `Date.parse` keeps
2210
+ * only milliseconds, so the 4th–6th fraction digits are added back. A number
2211
+ * is read as epoch milliseconds; anything unparseable is `undefined`.
2212
+ */
2213
+ function toMicros(v) {
2214
+ if (v instanceof Date) return v.getTime() * 1e3;
2215
+ if (typeof v === "number") return Number.isFinite(v) ? v * 1e3 : void 0;
2216
+ if (typeof v !== "string") return void 0;
2217
+ const ms = Date.parse(v);
2218
+ if (Number.isNaN(ms)) return void 0;
2219
+ const frac = /T[\d:]+\.(\d+)/.exec(v)?.[1] ?? "";
2220
+ return ms * 1e3 + Number(frac.padEnd(6, "0").slice(3, 6));
2187
2221
  }
2188
2222
 
2189
2223
  //#endregion
@@ -2193,6 +2227,7 @@ const SWEEP_ACTOR = {
2193
2227
  kind: "system",
2194
2228
  id: "sweep"
2195
2229
  };
2230
+ /** `UNKNOWN`: the bridge could not answer (down, or refused), so nothing may be applied. */
2196
2231
  async function resolveTarget(ref, deps) {
2197
2232
  const ds = deps.datasets.get(ref.ns);
2198
2233
  if (ds) {
@@ -2210,7 +2245,7 @@ async function resolveTarget(ref, deps) {
2210
2245
  if (row === null) return "MISSING";
2211
2246
  return row._deletedAt != null ? "DELETED" : "EXISTS";
2212
2247
  } catch (err) {
2213
- if (err instanceof BridgeUnreachableError) return "MISSING";
2248
+ if (err instanceof BridgeUnreachableError) return "UNKNOWN";
2214
2249
  throw err;
2215
2250
  }
2216
2251
  return "MISSING";
@@ -2314,6 +2349,7 @@ async function sweepBatch(base, deps) {
2314
2349
  id: edge.id,
2315
2350
  lastSweptAt: deps.now()
2316
2351
  });
2352
+ else if (target === "UNKNOWN") deps.metric("bridge_unreachable", edge.to.ns);
2317
2353
  else if (target === "DELETED") await applyPolicy(edge, cascadeQueue, deps);
2318
2354
  else if (edge.to.bridged === true && deps.bridges.isUnreachable(edge.to.ns)) deps.metric("bridge_unreachable", edge.to.ns);
2319
2355
  else await applyPolicy(edge, cascadeQueue, deps);
@@ -2327,7 +2363,7 @@ async function sweepBatch(base, deps) {
2327
2363
  return worklist.length;
2328
2364
  }
2329
2365
  const SWEEP_CURSOR_TYPE = "SweepCursor";
2330
- const SWEEP_CURSOR_ID = "edges";
2366
+ const SWEEP_CURSOR_ID = "5ee9c0a5-0000-4000-8000-000000000001";
2331
2367
  /** Reads the sweep cursor persisted by `saveSweepState`, or the scan head. */
2332
2368
  async function loadSweepState(ds) {
2333
2369
  const { rows } = await ds.read(SWEEP_CURSOR_TYPE, {
@@ -2734,12 +2770,30 @@ function toBridgeFrame(bucket) {
2734
2770
  return out;
2735
2771
  }
2736
2772
  /**
2773
+ * Scope each forwarded `idempotencyKey` to the local caller. The peer sees
2774
+ * every forwarded write under the bridge's one credential, so a key passed
2775
+ * verbatim lets two callers who pick the same key share one cached reply
2776
+ * there. The same caller retrying still forwards the same key.
2777
+ */
2778
+ function scopeBridgeIdempotency(bucket, caller) {
2779
+ const out = {};
2780
+ for (const [key, entry] of Object.entries(bucket)) out[key] = !Array.isArray(entry) && typeof entry.idempotencyKey === "string" ? {
2781
+ ...entry,
2782
+ idempotencyKey: createHash("sha256").update(JSON.stringify([caller, entry.idempotencyKey])).digest("hex")
2783
+ } : entry;
2784
+ return out;
2785
+ }
2786
+ /**
2737
2787
  * Snapshot obligation gate. Mirrors `applyRowFilters` from the SDK but on a
2738
2788
  * single row — we can't wrap every live push in an allocation when the vast
2739
2789
  * majority of rows pass the filter.
2740
2790
  */
2741
2791
  function obligationsPermitRow(obligations, ctx, row) {
2742
- for (const ob of obligations) if (!ob.predicate(ctx, row)) return false;
2792
+ for (const ob of obligations) try {
2793
+ if (!ob.predicate(ctx, row)) return false;
2794
+ } catch {
2795
+ return false;
2796
+ }
2743
2797
  return true;
2744
2798
  }
2745
2799
  function normaliseToRows(result) {
@@ -3790,7 +3844,23 @@ var StreamSubsystem = class {
3790
3844
  if (input.signal.aborted) controller.abort();
3791
3845
  else input.signal.addEventListener("abort", () => controller.abort(), { once: true });
3792
3846
  }
3793
- this.#runStream(input, keys[0], controller);
3847
+ this.#runStream(input, keys[0], controller).catch((err) => {
3848
+ const key = keys[0];
3849
+ deliverFrame(input.onFrame, {
3850
+ id: input.id,
3851
+ kind: "error",
3852
+ errors: [{
3853
+ message: clientErrorMessage(err, this.#metric, key),
3854
+ code: "resolver_error",
3855
+ path: [key]
3856
+ }]
3857
+ }, this.#metric);
3858
+ deliverFrame(input.onFrame, {
3859
+ id: input.id,
3860
+ kind: "end",
3861
+ final: true
3862
+ }, this.#metric);
3863
+ });
3794
3864
  return {
3795
3865
  id: input.id,
3796
3866
  cancel: () => {
@@ -4671,7 +4741,8 @@ var SubscribeSubsystem = class {
4671
4741
  const obligationsAllow = obligationsPermitRow(entry.obligations, entry.ctx, row);
4672
4742
  let whereMatches;
4673
4743
  try {
4674
- whereMatches = entry.where === void 0 ? true : evaluateWhere(row, entry.where);
4744
+ const fields = this.#schemaFor(entry.ns).types[entry.type]?.fields;
4745
+ whereMatches = entry.where === void 0 ? true : evaluateWhere(row, entry.where, (f) => fields?.[f]);
4675
4746
  } catch (err) {
4676
4747
  const code = isResolverFrameError(err) ? err.code : "resolver_error";
4677
4748
  this.#enqueueFrame(entry, {
@@ -5339,7 +5410,7 @@ var Engine = class {
5339
5410
  const ctx = this.#buildContext(input.ctx, "mutate");
5340
5411
  const signal = input.signal;
5341
5412
  const bridgePromises = [];
5342
- for (const [ns, bucket] of bridgeBuckets) bridgePromises.push(this.#bridgeProxy.runMutate(ns, bucket, envelope));
5413
+ for (const [ns, bucket] of bridgeBuckets) bridgePromises.push(this.#bridgeProxy.runMutate(ns, scopeBridgeIdempotency(bucket, callerKey), envelope));
5343
5414
  const writeBatch = [];
5344
5415
  const onWrite = (event) => {
5345
5416
  writeBatch.push(event);
@@ -5416,9 +5487,9 @@ var Engine = class {
5416
5487
  } catch (err) {
5417
5488
  if (!(err instanceof SharedTxRefusal)) throw err;
5418
5489
  for (const key of singleFrameKeys) {
5419
- if (!(key in envelope.data)) continue;
5420
5490
  const ns = parsedByKey.get(key)?.ns;
5421
5491
  if (ns !== void 0 && this.#namespaces.get(ns)?.virtual === true) continue;
5492
+ if (!(key in envelope.data) && envelope.errors?.some((e) => e.path?.[0] === key)) continue;
5422
5493
  delete envelope.data[key];
5423
5494
  delete envelope.shapes[key];
5424
5495
  addError(envelope, [key], `mutate rolled back: '${refusedKey}' refused`, "frame_rolled_back");
@@ -5472,7 +5543,7 @@ var Engine = class {
5472
5543
  * `mutate` so both honour the dedup contract.
5473
5544
  */
5474
5545
  async #finaliseMutateEnvelope(envelope, keys, resolution, callerKey) {
5475
- if (resolution.kind === "present" && this.#idempotency !== void 0 && (envelope.errors === void 0 || envelope.errors.length === 0)) {
5546
+ if (resolution.kind === "present" && this.#idempotency !== void 0 && keys.some((key) => key in envelope.data)) {
5476
5547
  const dedupKey = makeDedupKey(keys, resolution.value, callerKey);
5477
5548
  try {
5478
5549
  await this.#idempotency.store.put(dedupKey, envelope, this.#idempotency.defaultTtlMs);
@@ -6944,6 +7015,45 @@ function assertNoNullOnNonNullable(params, fieldDefs, phase) {
6944
7015
  phase
6945
7016
  });
6946
7017
  }
7018
+ const ISO_TIMESTAMP = /^(\d{4})-(\d{2})-(\d{2})(?:[T ]([01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,9})?)?)?(?:Z|[+-](?:0\d|1[0-5])(?::?[0-5]\d)?)?$/;
7019
+ /**
7020
+ * Is this a timestamp pg will cast? `Date.parse` alone is not the test: it
7021
+ * accepts `"1"` (2001), `"Oct 21 2026"`, and rolls `"2026-02-30"` to March,
7022
+ * all of which pg's `::timestamptz` rejects, which is the failure this guards.
7023
+ */
7024
+ function isIsoTimestamp(v) {
7025
+ const m = ISO_TIMESTAMP.exec(v);
7026
+ if (m === null) return false;
7027
+ const [y, mo, d] = [
7028
+ Number(m[1]),
7029
+ Number(m[2]),
7030
+ Number(m[3])
7031
+ ];
7032
+ if (y < 1 || mo < 1 || mo > 12 || d < 1) return false;
7033
+ const probe = /* @__PURE__ */ new Date(0);
7034
+ probe.setUTCFullYear(y, mo - 1, d);
7035
+ return probe.getUTCDate() === d;
7036
+ }
7037
+ /**
7038
+ * Refuse a supplied value whose JS type does not match a `number`, `boolean`
7039
+ * or `date` scalar. pg sorts and date-filters these by casting
7040
+ * `body->>field` to numeric, boolean or timestamptz, so one stored
7041
+ * `dueAt: "next week"` fails every such read of the type, for every caller.
7042
+ * `string` and `json` fields are left alone: nothing casts them. `null` is
7043
+ * the null guard's business, not this one's.
7044
+ */
7045
+ function assertScalarTypes(params, fieldDefs, phase) {
7046
+ for (const [name, def] of Object.entries(fieldDefs)) {
7047
+ if (def.kind !== "scalar" || !Object.hasOwn(params, name)) continue;
7048
+ const v = params[name];
7049
+ if (v === null) continue;
7050
+ if (!(def.type === "number" ? typeof v === "number" && Number.isFinite(v) : def.type === "boolean" ? typeof v === "boolean" : def.type === "date" ? typeof v === "string" ? isIsoTimestamp(v) : v instanceof Date && Number.isFinite(v.getTime()) : true)) throw new ResolverFrameError("invalid_field_type", `Cannot ${phase} '${name}' with ${JSON.stringify(v)}: expected a ${def.type === "date" ? "date (ISO 8601 string)" : def.type}.`, {
7051
+ field: name,
7052
+ expected: def.type,
7053
+ phase
7054
+ });
7055
+ }
7056
+ }
6947
7057
  /**
6948
7058
  * Fill `create` defaults: for every declared scalar field with a `default` that
6949
7059
  * the caller omitted, set it on `params`. Mutates the supplied bag in place
@@ -7064,6 +7174,7 @@ function createResolver(typeName, dataset, options = {}) {
7064
7174
  if (options.fields) assertNoUnknownFields(params, options.fields, "create");
7065
7175
  if (options.fields) {
7066
7176
  assertNoNullOnNonNullable(params, options.fields, "create");
7177
+ assertScalarTypes(params, options.fields, "create");
7067
7178
  applyScalarDefaults(params, options.fields);
7068
7179
  assertRequiredFields(params, options.fields);
7069
7180
  }
@@ -7411,6 +7522,7 @@ function updateResolver(typeName, dataset, edges, options = {}) {
7411
7522
  if (options.fields) {
7412
7523
  assertNoUnknownFields(inParams, options.fields, "update");
7413
7524
  assertNoNullOnNonNullable(inParams, options.fields, "update");
7525
+ assertScalarTypes(inParams, options.fields, "update");
7414
7526
  }
7415
7527
  const rowId = await resolveEntityId(ds, typeName, id);
7416
7528
  if (rowId === null) throw new ResolverFrameError("not_found", `updateResolver('${typeName}'): no row with id '${String(id)}'`, { field: "id" });
@@ -8040,26 +8152,6 @@ const ENUM_VERDICT_FIELDS = {
8040
8152
  verdictKey: field.string()
8041
8153
  };
8042
8154
  const AUDIT_EVENT_TYPE = "AuditEvent";
8043
- /**
8044
- * Public-policy projection of `Key`. Returns only verification material.
8045
- * Named `SigningKey` to follow the `_system` namespace convention (every
8046
- * type in `_system` carries the `Substrate` prefix as identity, independent of
8047
- * policy posture). Policy posture is documented per-resolver: this one accepts
8048
- * `identity: null` and gates only on namespace presence. See `./signing-key.ts`
8049
- * for the resolver implementation.
8050
- */
8051
- const SIGNING_KEY_TYPE = "SigningKey";
8052
- /**
8053
- * Field surface for `_system/SigningKey`. Mirrors the subset of `Key`
8054
- * that a JWT verifier needs: `id` (the kid, auto-included by the schema
8055
- * publisher for every type) plus `publicKey` and `algorithm`. Capabilities,
8056
- * namespaces, and `revokedAt` are NOT exposed — they're admin-only on the
8057
- * parent type.
8058
- */
8059
- const SIGNING_KEY_FIELDS = {
8060
- publicKey: field.string({ indexed: false }),
8061
- algorithm: field.string()
8062
- };
8063
8155
  const KEY_ALGORITHMS = /* @__PURE__ */ new Set([
8064
8156
  "EdDSA",
8065
8157
  "RS256",
@@ -8128,6 +8220,7 @@ function createKeyRegistry(opts) {
8128
8220
  const now = opts.now ?? (() => /* @__PURE__ */ new Date());
8129
8221
  const warn = opts.onWarn ?? (() => void 0);
8130
8222
  let cache = /* @__PURE__ */ new Map();
8223
+ let generation = 0;
8131
8224
  function isLive(record) {
8132
8225
  if (record.revokedAt === null) return true;
8133
8226
  return record.revokedAt.getTime() > now().getTime();
@@ -8161,6 +8254,7 @@ function createKeyRegistry(opts) {
8161
8254
  function installRow(row) {
8162
8255
  const projected = projectRow(row);
8163
8256
  if (projected === null) return false;
8257
+ generation++;
8164
8258
  cache.set(projected.kid, projected);
8165
8259
  return true;
8166
8260
  }
@@ -8168,8 +8262,9 @@ function createKeyRegistry(opts) {
8168
8262
  const reprimeIntervalMs = opts.reprimeIntervalMs;
8169
8263
  if (reprimeIntervalMs !== void 0 && Number.isFinite(reprimeIntervalMs) && reprimeIntervalMs > 0) {
8170
8264
  timer = setInterval(() => {
8265
+ const started = generation;
8171
8266
  loadAll().then((next) => {
8172
- cache = next;
8267
+ if (generation === started) cache = next;
8173
8268
  }).catch((err) => {
8174
8269
  warn("substrate_key_registry_reprime_failed", { error: err instanceof Error ? err.message : String(err) });
8175
8270
  });
@@ -8191,11 +8286,13 @@ function createKeyRegistry(opts) {
8191
8286
  }) ?? void 0;
8192
8287
  if (row === void 0) {
8193
8288
  warn("substrate_key_registry_no_live_row", { kid });
8289
+ generation++;
8194
8290
  cache.delete(kid);
8195
8291
  return;
8196
8292
  }
8197
8293
  if (!installRow(row)) {
8198
8294
  warn("substrate_key_registry_malformed_row", { kid });
8295
+ generation++;
8199
8296
  cache.delete(kid);
8200
8297
  }
8201
8298
  },
@@ -8203,6 +8300,7 @@ function createKeyRegistry(opts) {
8203
8300
  return installRow(row);
8204
8301
  },
8205
8302
  evict(kid) {
8303
+ generation++;
8206
8304
  cache.delete(kid);
8207
8305
  },
8208
8306
  async primeFromDataset() {
@@ -8217,67 +8315,14 @@ function createKeyRegistry(opts) {
8217
8315
  };
8218
8316
  }
8219
8317
 
8220
- //#endregion
8221
- //#region ../../packages/substrate-compose/src/_system/signing-key.ts
8222
- /**
8223
- * Extract the `kid` string from a `where` clause that has exactly the shape
8224
- * `{ id: { eq: <non-empty string> } }`. Any other shape is rejected:
8225
- *
8226
- * - Compound predicates (AND / OR / NOT discriminators) are unsupported and
8227
- * emit `engine_signing_key_unsupported_where` with `reason: 'compound'`.
8228
- * - Extra top-level keys alongside `id` are unsupported and emit the metric
8229
- * with `reason: 'extra_fields'`. Callers who add defence-in-depth filters
8230
- * (e.g. `revokedAt: { eq: null }`) believe they are filtering, but this
8231
- * resolver cannot honour them — surfacing the mismatch explicitly is safer
8232
- * than silently ignoring it.
8233
- * - Everything else (wrong operator, wrong type, missing where) returns null
8234
- * without a metric because those are expected call shapes (e.g. "no filter
8235
- * supplied").
8236
- */
8237
- function extractKid(where, metric) {
8238
- if (where === void 0 || where === null) return null;
8239
- if (typeof where !== "object") return null;
8240
- if ("AND" in where || "OR" in where || "NOT" in where) {
8241
- metric?.("engine_signing_key_unsupported_where", { reason: "compound" });
8242
- return null;
8243
- }
8244
- const keys = Object.keys(where);
8245
- if (keys.length !== 1 || keys[0] !== "id") {
8246
- metric?.("engine_signing_key_unsupported_where", {
8247
- reason: "extra_fields",
8248
- keys
8249
- });
8250
- return null;
8251
- }
8252
- const id = where.id;
8253
- if (id === null || typeof id !== "object") return null;
8254
- const eq = id.eq;
8255
- return typeof eq === "string" && eq.length > 0 ? eq : null;
8256
- }
8257
- function createSigningKeyResolver(registry, opts) {
8258
- const metric = opts?.onMetric;
8259
- return async (_ctx, args) => {
8260
- const kid = extractKid(args.params?.where, metric);
8261
- if (kid === null) return [];
8262
- const record = registry.lookup(kid);
8263
- if (record === null) return [];
8264
- return [{
8265
- id: record.kid,
8266
- publicKey: record.publicKey,
8267
- algorithm: record.algorithm
8268
- }];
8269
- };
8270
- }
8271
-
8272
8318
  //#endregion
8273
8319
  //#region ../../packages/substrate-compose/src/_system/install.ts
8274
8320
  /**
8275
8321
  * `_system` namespace wire-up. Spec §5.12.
8276
8322
  *
8277
- * Registers `Key`, `Invite`, `AuditEvent` and the enum-verdict
8278
- * type with admin-gated autoCRUD, plus the public `SigningKey`
8279
- * projection. Returns a live `KeyRegistry` whose cache is synchronously
8280
- * updated by `Key` create/update/delete/purge.
8323
+ * Registers `Key`, `Invite`, `AuditEvent` and the enum-verdict type with
8324
+ * admin-gated autoCRUD. Returns a live `KeyRegistry` whose cache is
8325
+ * synchronously updated by `Key` create/update/delete/purge.
8281
8326
  *
8282
8327
  * Invalidation strategy: we wrap the `Registry` surface that
8283
8328
  * `installAutoCrud` writes into. The `Key` mutations get their resolver
@@ -8302,6 +8347,8 @@ function createSigningKeyResolver(registry, opts) {
8302
8347
  * (algorithm is a param on the frame, not a property of the identity) and
8303
8348
  * the client deserves a dedicated code to branch on.
8304
8349
  */
8350
+ /** Advisory-lock key held by key writes that can remove an admin. */
8351
+ const KEY_WRITE_LOCK = "substrate-system:key-write";
8305
8352
  /**
8306
8353
  * Wrap a `Registry` so `register` AND `replace` calls for the configured
8307
8354
  * mutation names route their resolver through `wrap(resolver, mutationName)`.
@@ -8525,9 +8572,29 @@ async function installSystemNamespace(opts) {
8525
8572
  if (opts.onWarn !== void 0) keyRegistryOpts.onWarn = opts.onWarn;
8526
8573
  if (opts.reprimeIntervalMs !== void 0) keyRegistryOpts.reprimeIntervalMs = opts.reprimeIntervalMs;
8527
8574
  const keyRegistry = createKeyRegistry(keyRegistryOpts);
8575
+ const keysFor = async (args) => (await (args.dataset ?? opts.dataset).read("Key", {})).rows;
8576
+ const assertGrantParses = (row) => {
8577
+ const err = grantEntryError(decodeList(row.namespaces), decodeList(row.capabilities));
8578
+ if (err !== null) throw new ResolverFrameError("invalid_grant_entry", `${err} — each entry is '<namespace>' or '<namespace>:<cap>[+<cap>...]'.`);
8579
+ };
8580
+ const assertAdminSurvives = (rows, targetId, next) => {
8581
+ const isAdmin = (r) => isActiveAdminKeyRow(r, adminCapability);
8582
+ const after = [...rows.filter((r) => r.id !== targetId), ...next === null ? [] : [next]];
8583
+ if (rows.some(isAdmin) && !after.some(isAdmin)) throw new ResolverFrameError("last_active_admin", "refusing a key write that would leave no active admin key — rotate instead via `substrate-admin rotate`.");
8584
+ };
8585
+ const localKeyLock = createKeyedMutex();
8586
+ const lockedKeyWrite = (fn) => (ctx, args) => {
8587
+ const ds = args.dataset ?? opts.dataset;
8588
+ const run = () => fn(ctx, args);
8589
+ return ds.withAdvisoryLock !== void 0 ? ds.withAdvisoryLock(KEY_WRITE_LOCK, run) : localKeyLock(KEY_WRITE_LOCK, run);
8590
+ };
8591
+ const isLive = (row) => row !== void 0 && row.revokedAt == null && row._deletedAt == null;
8528
8592
  const wrappedForSubstrateKey = wrapRegistryMutations(opts.registry, {
8529
- createKey: (base) => async (ctx, args) => {
8593
+ createKey: (base) => lockedKeyWrite(async (ctx, args) => {
8530
8594
  assertAllowedAlgorithm(args.params);
8595
+ assertGrantParses(args.params ?? {});
8596
+ const newKid = args.params?.kid;
8597
+ if (isLive(args.params) && (await keysFor(args)).some((r) => r.kid === newKid && isLive(r))) throw new ResolverFrameError("kid_already_live", `kid '${String(newKid)}' is already registered and live — rotate or revoke it before re-registering`);
8531
8598
  const result = await base(ctx, args);
8532
8599
  const kid = extractKidForInvalidation(result);
8533
8600
  if (kid !== null) {
@@ -8547,13 +8614,25 @@ async function installSystemNamespace(opts) {
8547
8614
  installFromResult(keyRegistry, result, kid, opts.onWarn);
8548
8615
  }
8549
8616
  return result;
8550
- },
8551
- updateKey: (base) => async (ctx, args) => {
8617
+ }),
8618
+ updateKey: (base) => lockedKeyWrite(async (ctx, args) => {
8552
8619
  if (args.params?.kid !== void 0) throw new Error("Key.kid is immutable; rotate or re-register instead of changing kid");
8553
8620
  if (args.params?.algorithm !== void 0) assertAllowedAlgorithm(args.params);
8621
+ const params = args.params ?? {};
8622
+ const rows = await keysFor(args);
8623
+ const target = rows.find((r) => r.id === params.id);
8624
+ if (target !== void 0) {
8625
+ const next = {
8626
+ ...target,
8627
+ ...params
8628
+ };
8629
+ if (params.namespaces !== void 0 || params.capabilities !== void 0) assertGrantParses(next);
8630
+ assertAdminSurvives(rows, target.id, next);
8631
+ }
8632
+ const wasLive = isLive(target);
8554
8633
  const result = await base(ctx, args);
8555
8634
  const kid = extractKidForInvalidation(result);
8556
- if (kid !== null) {
8635
+ if (kid !== null && wasLive) {
8557
8636
  const revokedAt = args.params?.revokedAt;
8558
8637
  if (revokedAt !== void 0 && revokedAt !== null && revokedAt !== "") await emitAuditInTx(ctx, args, {
8559
8638
  actorKid: resolveActorKid(ctx),
@@ -8566,19 +8645,21 @@ async function installSystemNamespace(opts) {
8566
8645
  installFromResult(keyRegistry, result, kid, opts.onWarn);
8567
8646
  }
8568
8647
  return result;
8569
- },
8570
- deleteKey: (base) => async (ctx, args) => {
8648
+ }),
8649
+ deleteKey: (base) => lockedKeyWrite(async (ctx, args) => {
8571
8650
  const targetId = typeof args.params?.id === "string" ? args.params.id : void 0;
8572
8651
  let kidToEvict = null;
8573
8652
  if (targetId !== void 0) {
8574
- const { rows } = await (args.dataset ?? opts.dataset).read("Key", { id: targetId });
8575
- kidToEvict = extractKidForInvalidation(rows[0]);
8653
+ const rows = await keysFor(args);
8654
+ const target = rows.find((r) => r.id === targetId);
8655
+ assertAdminSurvives(rows, targetId, null);
8656
+ if (isLive(target)) kidToEvict = extractKidForInvalidation(target);
8576
8657
  }
8577
8658
  const result = await base(ctx, args);
8578
8659
  if (kidToEvict !== null) keyRegistry.evict(kidToEvict);
8579
8660
  return result;
8580
- },
8581
- purgeKey: (base) => async (ctx, args) => {
8661
+ }),
8662
+ purgeKey: (base) => lockedKeyWrite(async (ctx, args) => {
8582
8663
  const targetId = typeof args.params?.id === "string" ? args.params.id : void 0;
8583
8664
  let kidToEvict = null;
8584
8665
  if (targetId !== void 0) {
@@ -8586,7 +8667,8 @@ async function installSystemNamespace(opts) {
8586
8667
  id: targetId,
8587
8668
  includeDeleted: true
8588
8669
  });
8589
- kidToEvict = extractKidForInvalidation(rows[0]);
8670
+ assertAdminSurvives(await keysFor(args), targetId, null);
8671
+ if (isLive(rows[0])) kidToEvict = extractKidForInvalidation(rows[0]);
8590
8672
  }
8591
8673
  try {
8592
8674
  const result = await base(ctx, args);
@@ -8599,7 +8681,7 @@ async function installSystemNamespace(opts) {
8599
8681
  }
8600
8682
  throw err;
8601
8683
  }
8602
- }
8684
+ })
8603
8685
  });
8604
8686
  installAutoCrud(wrappedForSubstrateKey, "Key", opts.dataset, opts.edges, {
8605
8687
  fields: mergeIdField(KEY_FIELDS),
@@ -8669,12 +8751,6 @@ async function installSystemNamespace(opts) {
8669
8751
  purgeable: true,
8670
8752
  adminCapability
8671
8753
  });
8672
- opts.registry.register(SIGNING_KEY_TYPE, {
8673
- resolver: createSigningKeyResolver(keyRegistry, opts.onMetric !== void 0 ? { onMetric: opts.onMetric } : void 0),
8674
- kind: "type",
8675
- policy: allowAll(),
8676
- fields: SIGNING_KEY_FIELDS
8677
- });
8678
8754
  await backfillBootstrapAuditIfNeeded(opts.dataset);
8679
8755
  return { keyRegistry };
8680
8756
  }
@@ -9697,7 +9773,7 @@ function keysRoute(engine, opts) {
9697
9773
  const keyErr = errorFor(keyFrameKey);
9698
9774
  if (keyErr !== void 0) {
9699
9775
  const code = keyErr.code ?? "internal_error";
9700
- return jsonResponse(code === "policy_denied" ? 403 : 500, {
9776
+ return jsonResponse(code === "policy_denied" ? 403 : code === "kid_already_live" ? 409 : 500, {
9701
9777
  code,
9702
9778
  message: keyErr.message ?? "key registration failed"
9703
9779
  });
@@ -10132,6 +10208,7 @@ function mergeRowMetadata(existing, incoming) {
10132
10208
  var MemoryDataset = class MemoryDataset {
10133
10209
  namespace;
10134
10210
  txScopeId;
10211
+ #fieldDefLookup;
10135
10212
  capabilities = {
10136
10213
  operators: fullBuiltinOperators(),
10137
10214
  orderBy: true,
@@ -10150,6 +10227,7 @@ var MemoryDataset = class MemoryDataset {
10150
10227
  constructor(options) {
10151
10228
  this.namespace = options.namespace;
10152
10229
  this.txScopeId = options.txScopeId ?? `mem:${randomUUID()}`;
10230
+ this.#fieldDefLookup = options.fieldDefLookup;
10153
10231
  }
10154
10232
  bucket(type) {
10155
10233
  let b = this.store.get(type);
@@ -10167,6 +10245,8 @@ var MemoryDataset = class MemoryDataset {
10167
10245
  hasMore: false
10168
10246
  };
10169
10247
  const includeDeleted = params.includeDeleted === true;
10248
+ const lookup = this.#fieldDefLookup;
10249
+ const fieldDefOf = (field) => lookup?.(type, field);
10170
10250
  const idFilter = /* @__PURE__ */ new Set();
10171
10251
  let hasIdFilter = false;
10172
10252
  if (params.id !== void 0) {
@@ -10199,15 +10279,15 @@ var MemoryDataset = class MemoryDataset {
10199
10279
  })() : b.values();
10200
10280
  for (const row of candidates) {
10201
10281
  if (!includeDeleted && row._deletedAt != null) continue;
10202
- if (resolvedWhere !== void 0 && !evaluateWhere(row, resolvedWhere)) continue;
10282
+ if (resolvedWhere !== void 0 && !evaluateWhere(row, resolvedWhere, fieldDefOf)) continue;
10203
10283
  pool.push(row);
10204
10284
  }
10205
10285
  const orderBy = normalizeOrderBy(params.orderBy);
10206
- pool.sort((a, b2) => compareByClauses(a, b2, orderBy));
10286
+ pool.sort((a, b2) => compareByClauses(a, b2, orderBy, fieldDefOf));
10207
10287
  let startIdx = 0;
10208
10288
  if (params.cursor !== void 0 && params.cursor !== "") {
10209
10289
  const cursor = decodeCursor(params.cursor);
10210
- startIdx = findCursorStart(pool, orderBy, cursor.orderByValues, cursor.id);
10290
+ startIdx = findCursorStart(pool, orderBy, cursor.orderByValues, cursor.id, fieldDefOf);
10211
10291
  }
10212
10292
  let hasMore = false;
10213
10293
  let slice;
@@ -10468,7 +10548,10 @@ var MemoryDataset = class MemoryDataset {
10468
10548
  return this.shortIds.getShortIdForRow(this.namespace, type, rowId);
10469
10549
  }
10470
10550
  forNamespace(namespace) {
10471
- return new MemoryDataset({ namespace });
10551
+ return new MemoryDataset({
10552
+ namespace,
10553
+ ...this.#fieldDefLookup !== void 0 ? { fieldDefLookup: this.#fieldDefLookup } : {}
10554
+ });
10472
10555
  }
10473
10556
  };
10474
10557
  /**
@@ -10486,20 +10569,6 @@ function conditionalMatchEq(actual, expected) {
10486
10569
  }
10487
10570
  return actual === expected;
10488
10571
  }
10489
- function compare(a, b) {
10490
- if (a == null && b == null) return 0;
10491
- if (a == null) return 1;
10492
- if (b == null) return -1;
10493
- if (a instanceof Date || b instanceof Date) {
10494
- const at = a instanceof Date ? a.getTime() : typeof a === "string" ? Date.parse(a) : Number(a);
10495
- const bt = b instanceof Date ? b.getTime() : typeof b === "string" ? Date.parse(b) : Number(b);
10496
- return at < bt ? -1 : at > bt ? 1 : 0;
10497
- }
10498
- if (typeof a === "number" && typeof b === "number") return a < b ? -1 : a > b ? 1 : 0;
10499
- const as = String(a);
10500
- const bs = String(b);
10501
- return as < bs ? -1 : as > bs ? 1 : 0;
10502
- }
10503
10572
  function normalizeOrderBy(orderBy) {
10504
10573
  const out = [];
10505
10574
  let hasIdTail = false;
@@ -10513,19 +10582,19 @@ function normalizeOrderBy(orderBy) {
10513
10582
  if (!hasIdTail) out.push(["id", "asc"]);
10514
10583
  return out;
10515
10584
  }
10516
- function compareByClauses(a, b, orderBy) {
10585
+ function compareByClauses(a, b, orderBy, fieldDefOf) {
10517
10586
  for (const [field, dir] of orderBy) {
10518
10587
  const av = getFieldValue(a, field);
10519
10588
  const bv = getFieldValue(b, field);
10520
10589
  if (av == null && bv == null) continue;
10521
10590
  if (av == null) return 1;
10522
10591
  if (bv == null) return -1;
10523
- const cmp = compare(av, bv);
10592
+ const cmp = compareFilterValues(av, bv, isDateField(field, fieldDefOf));
10524
10593
  if (cmp !== 0) return dir === "asc" ? cmp : -cmp;
10525
10594
  }
10526
10595
  return 0;
10527
10596
  }
10528
- function findCursorStart(pool, orderBy, cursorValues, cursorId) {
10597
+ function findCursorStart(pool, orderBy, cursorValues, cursorId, fieldDefOf) {
10529
10598
  const cursorRow = { id: cursorId };
10530
10599
  const meta = {};
10531
10600
  const createdBy = {};
@@ -10546,7 +10615,7 @@ function findCursorStart(pool, orderBy, cursorValues, cursorId) {
10546
10615
  for (let i = 0; i < pool.length; i++) {
10547
10616
  const row = pool[i];
10548
10617
  if (row === void 0) continue;
10549
- if (compareByClauses(row, cursorRow, orderBy) > 0) return i;
10618
+ if (compareByClauses(row, cursorRow, orderBy, fieldDefOf) > 0) return i;
10550
10619
  }
10551
10620
  return pool.length;
10552
10621
  }
@@ -12279,6 +12348,8 @@ const STREAM_CAPABILITY = "read";
12279
12348
  *
12280
12349
  * The values must be checked here: `StreamSession` reads `entry.fields` off
12281
12350
  * each one, and a throw after the transport opens leaks its heartbeat timer.
12351
+ * The WS route uses it too, where that throw would escape the message
12352
+ * listener and exit the process.
12282
12353
  *
12283
12354
  * Unlike `validateFrame` in `helpers.ts`, array values (the §5.13
12284
12355
  * batched-mutate shape) are rejected: streams cannot carry them, so this
@@ -12534,6 +12605,7 @@ function parseRequestFrame(buf, mode) {
12534
12605
  const v = value;
12535
12606
  if (typeof v.id !== "string") return null;
12536
12607
  if (v.op !== "subscribe" && v.op !== "stream" && v.op !== "cancel" && v.op !== "whoami") return null;
12608
+ if (v.frame !== void 0 && !isFrameRecord(v.frame)) return null;
12537
12609
  return value;
12538
12610
  } catch {
12539
12611
  return null;
@@ -13189,8 +13261,7 @@ async function composeInner(opts, cleanup) {
13189
13261
  const installSubstrateOpts = {
13190
13262
  registry: substrateRegistry,
13191
13263
  dataset: substrateDataset,
13192
- edges,
13193
- onMetric: routeMetric
13264
+ edges
13194
13265
  };
13195
13266
  if (opts.auth?.adminCapability !== void 0) installSubstrateOpts.adminCapability = opts.auth.adminCapability;
13196
13267
  if (opts.auth !== void 0 && opts.keyReprimeIntervalMs !== void 0) installSubstrateOpts.reprimeIntervalMs = opts.keyReprimeIntervalMs;