@mnmal-ai/substrate 1.0.0-alpha.0 → 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(".");
@@ -962,7 +962,8 @@ function authenticateBearer(token, cfg) {
962
962
  }
963
963
  /** What a 401 should add for a reason whose fix is a server knob, not the token. */
964
964
  function rejectionDetail(reason) {
965
- return reason === "lifetime_exceeds_max" ? "the token expires further ahead than this server accepts; mint a shorter-lived token or raise SUBSTRATE_JWT_MAX_TTL_SECONDS" : void 0;
965
+ if (reason === "lifetime_exceeds_max") return "the token expires further ahead than this server accepts; mint a shorter-lived token or raise SUBSTRATE_JWT_MAX_TTL_SECONDS";
966
+ if (reason === "wrong_audience") return "the token's aud is not one of this server's origins; connect through an origin listed in SUBSTRATE_PUBLIC_ORIGIN, or add this one there";
966
967
  }
967
968
  /**
968
969
  * The parts of a Key row a verification relied on. A string, so it survives
@@ -1017,7 +1018,7 @@ function watchCredential(identity, cfg, onLapse) {
1017
1018
  }
1018
1019
  function extractBearer(authorization) {
1019
1020
  if (authorization === void 0) return null;
1020
- const match = /^Bearer\s+(.+)$/i.exec(authorization.trim());
1021
+ const match = /^Bearer\s+(\S.*)$/i.exec(authorization.trim());
1021
1022
  if (match === null) return null;
1022
1023
  const token = match[1]?.trim();
1023
1024
  if (token === void 0 || token.length === 0) return null;
@@ -2012,6 +2013,14 @@ function getFieldValue(row, name) {
2012
2013
  if (projector !== void 0) return projector(row);
2013
2014
  return row[name];
2014
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
+ }
2015
2024
  const KNOWN_OPS = /* @__PURE__ */ new Set([
2016
2025
  "eq",
2017
2026
  "neq",
@@ -2086,27 +2095,35 @@ function assertFieldPredicateHonourable(field, predicate) {
2086
2095
  case "endsWith": if (typeof operand !== "string") throw new UnsupportedFilterError(field, op, "requires a string value");
2087
2096
  }
2088
2097
  }
2089
- 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) {
2090
2104
  if (where === null || typeof where !== "object" || Array.isArray(where)) return true;
2091
2105
  for (const [k, child] of Object.entries(where)) if (k === "AND") {
2092
2106
  if (Array.isArray(child)) {
2093
- for (const sub of child) if (!evaluateWhere(row, sub)) return false;
2107
+ for (const sub of child) if (!evaluateWhere(row, sub, fieldDefOf)) return false;
2094
2108
  }
2095
2109
  } else if (k === "OR") {
2096
2110
  if (Array.isArray(child)) {
2097
2111
  let any = false;
2098
- for (const sub of child) if (evaluateWhere(row, sub)) {
2112
+ for (const sub of child) if (evaluateWhere(row, sub, fieldDefOf)) {
2099
2113
  any = true;
2100
2114
  break;
2101
2115
  }
2102
2116
  if (!any) return false;
2103
2117
  }
2104
2118
  } else if (k === "NOT") {
2105
- if (evaluateWhere(row, child)) return false;
2106
- } 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
+ }
2107
2124
  return true;
2108
2125
  }
2109
- function evaluateFieldPredicate(field, value, predicate) {
2126
+ function evaluateFieldPredicate(field, value, predicate, asDate = false) {
2110
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}`);
2111
2128
  if (isJsonPathPredicate(predicate)) return evaluateJsonPathPredicate(field, value, predicate);
2112
2129
  const p = predicate;
@@ -2118,34 +2135,34 @@ function evaluateFieldPredicate(field, value, predicate) {
2118
2135
  }
2119
2136
  for (const op of keys) {
2120
2137
  const operand = p[op];
2121
- if (!applyOp(field, op, value, operand)) return false;
2138
+ if (!applyOp(field, op, value, operand, asDate)) return false;
2122
2139
  }
2123
2140
  return true;
2124
2141
  }
2125
- function applyOp(field, op, value, operand) {
2142
+ function applyOp(field, op, value, operand, asDate) {
2126
2143
  switch (op) {
2127
- case "eq": return equals(value, operand);
2128
- case "neq": return !equals(value, operand);
2144
+ case "eq": return equals(value, operand, asDate);
2145
+ case "neq": return !equals(value, operand, asDate);
2129
2146
  case "gt":
2130
2147
  if (value == null) return false;
2131
- return compare$1(value, operand) > 0;
2148
+ return compareFilterValues(value, operand, asDate) > 0;
2132
2149
  case "gte":
2133
2150
  if (value == null) return false;
2134
- return compare$1(value, operand) >= 0;
2151
+ return compareFilterValues(value, operand, asDate) >= 0;
2135
2152
  case "lt":
2136
2153
  if (value == null) return false;
2137
- return compare$1(value, operand) < 0;
2154
+ return compareFilterValues(value, operand, asDate) < 0;
2138
2155
  case "lte":
2139
2156
  if (value == null) return false;
2140
- return compare$1(value, operand) <= 0;
2157
+ return compareFilterValues(value, operand, asDate) <= 0;
2141
2158
  case "between":
2142
2159
  if (!Array.isArray(operand) || operand.length !== 2) throw new UnsupportedFilterError(field, op, "requires a two-element [low, high] array");
2143
2160
  if (value == null) return false;
2144
- 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;
2145
2162
  case "in":
2146
2163
  case "nin": {
2147
2164
  if (!Array.isArray(operand)) throw new UnsupportedFilterError(field, op, "requires an array value");
2148
- const member = operand.some((e) => equals(value, e));
2165
+ const member = operand.some((e) => equals(value, e, asDate));
2149
2166
  return op === "in" ? member : !member;
2150
2167
  }
2151
2168
  case "contains":
@@ -2163,26 +2180,44 @@ function applyOp(field, op, value, operand) {
2163
2180
  default: throw new UnsupportedFilterError(field, op, "is not a recognised filter operator");
2164
2181
  }
2165
2182
  }
2166
- function equals(a, b) {
2183
+ function equals(a, b, asDate = false) {
2167
2184
  if (a == null && b == null) return true;
2168
- if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
2169
- if (a instanceof Date && typeof b === "string") return a.toISOString() === b;
2170
- 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
+ }
2171
2190
  return a === b;
2172
2191
  }
2173
- 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) {
2174
2197
  if (a == null && b == null) return 0;
2175
2198
  if (a == null) return 1;
2176
2199
  if (b == null) return -1;
2177
- if (a instanceof Date || b instanceof Date) {
2178
- const at = a instanceof Date ? a.getTime() : typeof a === "string" ? Date.parse(a) : Number(a);
2179
- const bt = b instanceof Date ? b.getTime() : typeof b === "string" ? Date.parse(b) : Number(b);
2180
- 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;
2181
2204
  }
2182
2205
  if (typeof a === "number" && typeof b === "number") return a < b ? -1 : a > b ? 1 : 0;
2183
- const as = String(a);
2184
- const bs = String(b);
2185
- 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));
2186
2221
  }
2187
2222
 
2188
2223
  //#endregion
@@ -2192,6 +2227,7 @@ const SWEEP_ACTOR = {
2192
2227
  kind: "system",
2193
2228
  id: "sweep"
2194
2229
  };
2230
+ /** `UNKNOWN`: the bridge could not answer (down, or refused), so nothing may be applied. */
2195
2231
  async function resolveTarget(ref, deps) {
2196
2232
  const ds = deps.datasets.get(ref.ns);
2197
2233
  if (ds) {
@@ -2209,7 +2245,7 @@ async function resolveTarget(ref, deps) {
2209
2245
  if (row === null) return "MISSING";
2210
2246
  return row._deletedAt != null ? "DELETED" : "EXISTS";
2211
2247
  } catch (err) {
2212
- if (err instanceof BridgeUnreachableError) return "MISSING";
2248
+ if (err instanceof BridgeUnreachableError) return "UNKNOWN";
2213
2249
  throw err;
2214
2250
  }
2215
2251
  return "MISSING";
@@ -2313,6 +2349,7 @@ async function sweepBatch(base, deps) {
2313
2349
  id: edge.id,
2314
2350
  lastSweptAt: deps.now()
2315
2351
  });
2352
+ else if (target === "UNKNOWN") deps.metric("bridge_unreachable", edge.to.ns);
2316
2353
  else if (target === "DELETED") await applyPolicy(edge, cascadeQueue, deps);
2317
2354
  else if (edge.to.bridged === true && deps.bridges.isUnreachable(edge.to.ns)) deps.metric("bridge_unreachable", edge.to.ns);
2318
2355
  else await applyPolicy(edge, cascadeQueue, deps);
@@ -2326,7 +2363,7 @@ async function sweepBatch(base, deps) {
2326
2363
  return worklist.length;
2327
2364
  }
2328
2365
  const SWEEP_CURSOR_TYPE = "SweepCursor";
2329
- const SWEEP_CURSOR_ID = "edges";
2366
+ const SWEEP_CURSOR_ID = "5ee9c0a5-0000-4000-8000-000000000001";
2330
2367
  /** Reads the sweep cursor persisted by `saveSweepState`, or the scan head. */
2331
2368
  async function loadSweepState(ds) {
2332
2369
  const { rows } = await ds.read(SWEEP_CURSOR_TYPE, {
@@ -2733,12 +2770,30 @@ function toBridgeFrame(bucket) {
2733
2770
  return out;
2734
2771
  }
2735
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
+ /**
2736
2787
  * Snapshot obligation gate. Mirrors `applyRowFilters` from the SDK but on a
2737
2788
  * single row — we can't wrap every live push in an allocation when the vast
2738
2789
  * majority of rows pass the filter.
2739
2790
  */
2740
2791
  function obligationsPermitRow(obligations, ctx, row) {
2741
- 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
+ }
2742
2797
  return true;
2743
2798
  }
2744
2799
  function normaliseToRows(result) {
@@ -3789,7 +3844,23 @@ var StreamSubsystem = class {
3789
3844
  if (input.signal.aborted) controller.abort();
3790
3845
  else input.signal.addEventListener("abort", () => controller.abort(), { once: true });
3791
3846
  }
3792
- 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
+ });
3793
3864
  return {
3794
3865
  id: input.id,
3795
3866
  cancel: () => {
@@ -4670,7 +4741,8 @@ var SubscribeSubsystem = class {
4670
4741
  const obligationsAllow = obligationsPermitRow(entry.obligations, entry.ctx, row);
4671
4742
  let whereMatches;
4672
4743
  try {
4673
- 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]);
4674
4746
  } catch (err) {
4675
4747
  const code = isResolverFrameError(err) ? err.code : "resolver_error";
4676
4748
  this.#enqueueFrame(entry, {
@@ -5338,7 +5410,7 @@ var Engine = class {
5338
5410
  const ctx = this.#buildContext(input.ctx, "mutate");
5339
5411
  const signal = input.signal;
5340
5412
  const bridgePromises = [];
5341
- 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));
5342
5414
  const writeBatch = [];
5343
5415
  const onWrite = (event) => {
5344
5416
  writeBatch.push(event);
@@ -5415,9 +5487,9 @@ var Engine = class {
5415
5487
  } catch (err) {
5416
5488
  if (!(err instanceof SharedTxRefusal)) throw err;
5417
5489
  for (const key of singleFrameKeys) {
5418
- if (!(key in envelope.data)) continue;
5419
5490
  const ns = parsedByKey.get(key)?.ns;
5420
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;
5421
5493
  delete envelope.data[key];
5422
5494
  delete envelope.shapes[key];
5423
5495
  addError(envelope, [key], `mutate rolled back: '${refusedKey}' refused`, "frame_rolled_back");
@@ -5471,7 +5543,7 @@ var Engine = class {
5471
5543
  * `mutate` so both honour the dedup contract.
5472
5544
  */
5473
5545
  async #finaliseMutateEnvelope(envelope, keys, resolution, callerKey) {
5474
- 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)) {
5475
5547
  const dedupKey = makeDedupKey(keys, resolution.value, callerKey);
5476
5548
  try {
5477
5549
  await this.#idempotency.store.put(dedupKey, envelope, this.#idempotency.defaultTtlMs);
@@ -6943,6 +7015,45 @@ function assertNoNullOnNonNullable(params, fieldDefs, phase) {
6943
7015
  phase
6944
7016
  });
6945
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
+ }
6946
7057
  /**
6947
7058
  * Fill `create` defaults: for every declared scalar field with a `default` that
6948
7059
  * the caller omitted, set it on `params`. Mutates the supplied bag in place
@@ -7063,6 +7174,7 @@ function createResolver(typeName, dataset, options = {}) {
7063
7174
  if (options.fields) assertNoUnknownFields(params, options.fields, "create");
7064
7175
  if (options.fields) {
7065
7176
  assertNoNullOnNonNullable(params, options.fields, "create");
7177
+ assertScalarTypes(params, options.fields, "create");
7066
7178
  applyScalarDefaults(params, options.fields);
7067
7179
  assertRequiredFields(params, options.fields);
7068
7180
  }
@@ -7410,6 +7522,7 @@ function updateResolver(typeName, dataset, edges, options = {}) {
7410
7522
  if (options.fields) {
7411
7523
  assertNoUnknownFields(inParams, options.fields, "update");
7412
7524
  assertNoNullOnNonNullable(inParams, options.fields, "update");
7525
+ assertScalarTypes(inParams, options.fields, "update");
7413
7526
  }
7414
7527
  const rowId = await resolveEntityId(ds, typeName, id);
7415
7528
  if (rowId === null) throw new ResolverFrameError("not_found", `updateResolver('${typeName}'): no row with id '${String(id)}'`, { field: "id" });
@@ -8039,26 +8152,6 @@ const ENUM_VERDICT_FIELDS = {
8039
8152
  verdictKey: field.string()
8040
8153
  };
8041
8154
  const AUDIT_EVENT_TYPE = "AuditEvent";
8042
- /**
8043
- * Public-policy projection of `Key`. Returns only verification material.
8044
- * Named `SigningKey` to follow the `_system` namespace convention (every
8045
- * type in `_system` carries the `Substrate` prefix as identity, independent of
8046
- * policy posture). Policy posture is documented per-resolver: this one accepts
8047
- * `identity: null` and gates only on namespace presence. See `./signing-key.ts`
8048
- * for the resolver implementation.
8049
- */
8050
- const SIGNING_KEY_TYPE = "SigningKey";
8051
- /**
8052
- * Field surface for `_system/SigningKey`. Mirrors the subset of `Key`
8053
- * that a JWT verifier needs: `id` (the kid, auto-included by the schema
8054
- * publisher for every type) plus `publicKey` and `algorithm`. Capabilities,
8055
- * namespaces, and `revokedAt` are NOT exposed — they're admin-only on the
8056
- * parent type.
8057
- */
8058
- const SIGNING_KEY_FIELDS = {
8059
- publicKey: field.string({ indexed: false }),
8060
- algorithm: field.string()
8061
- };
8062
8155
  const KEY_ALGORITHMS = /* @__PURE__ */ new Set([
8063
8156
  "EdDSA",
8064
8157
  "RS256",
@@ -8127,6 +8220,7 @@ function createKeyRegistry(opts) {
8127
8220
  const now = opts.now ?? (() => /* @__PURE__ */ new Date());
8128
8221
  const warn = opts.onWarn ?? (() => void 0);
8129
8222
  let cache = /* @__PURE__ */ new Map();
8223
+ let generation = 0;
8130
8224
  function isLive(record) {
8131
8225
  if (record.revokedAt === null) return true;
8132
8226
  return record.revokedAt.getTime() > now().getTime();
@@ -8160,6 +8254,7 @@ function createKeyRegistry(opts) {
8160
8254
  function installRow(row) {
8161
8255
  const projected = projectRow(row);
8162
8256
  if (projected === null) return false;
8257
+ generation++;
8163
8258
  cache.set(projected.kid, projected);
8164
8259
  return true;
8165
8260
  }
@@ -8167,8 +8262,9 @@ function createKeyRegistry(opts) {
8167
8262
  const reprimeIntervalMs = opts.reprimeIntervalMs;
8168
8263
  if (reprimeIntervalMs !== void 0 && Number.isFinite(reprimeIntervalMs) && reprimeIntervalMs > 0) {
8169
8264
  timer = setInterval(() => {
8265
+ const started = generation;
8170
8266
  loadAll().then((next) => {
8171
- cache = next;
8267
+ if (generation === started) cache = next;
8172
8268
  }).catch((err) => {
8173
8269
  warn("substrate_key_registry_reprime_failed", { error: err instanceof Error ? err.message : String(err) });
8174
8270
  });
@@ -8190,11 +8286,13 @@ function createKeyRegistry(opts) {
8190
8286
  }) ?? void 0;
8191
8287
  if (row === void 0) {
8192
8288
  warn("substrate_key_registry_no_live_row", { kid });
8289
+ generation++;
8193
8290
  cache.delete(kid);
8194
8291
  return;
8195
8292
  }
8196
8293
  if (!installRow(row)) {
8197
8294
  warn("substrate_key_registry_malformed_row", { kid });
8295
+ generation++;
8198
8296
  cache.delete(kid);
8199
8297
  }
8200
8298
  },
@@ -8202,6 +8300,7 @@ function createKeyRegistry(opts) {
8202
8300
  return installRow(row);
8203
8301
  },
8204
8302
  evict(kid) {
8303
+ generation++;
8205
8304
  cache.delete(kid);
8206
8305
  },
8207
8306
  async primeFromDataset() {
@@ -8216,67 +8315,14 @@ function createKeyRegistry(opts) {
8216
8315
  };
8217
8316
  }
8218
8317
 
8219
- //#endregion
8220
- //#region ../../packages/substrate-compose/src/_system/signing-key.ts
8221
- /**
8222
- * Extract the `kid` string from a `where` clause that has exactly the shape
8223
- * `{ id: { eq: <non-empty string> } }`. Any other shape is rejected:
8224
- *
8225
- * - Compound predicates (AND / OR / NOT discriminators) are unsupported and
8226
- * emit `engine_signing_key_unsupported_where` with `reason: 'compound'`.
8227
- * - Extra top-level keys alongside `id` are unsupported and emit the metric
8228
- * with `reason: 'extra_fields'`. Callers who add defence-in-depth filters
8229
- * (e.g. `revokedAt: { eq: null }`) believe they are filtering, but this
8230
- * resolver cannot honour them — surfacing the mismatch explicitly is safer
8231
- * than silently ignoring it.
8232
- * - Everything else (wrong operator, wrong type, missing where) returns null
8233
- * without a metric because those are expected call shapes (e.g. "no filter
8234
- * supplied").
8235
- */
8236
- function extractKid(where, metric) {
8237
- if (where === void 0 || where === null) return null;
8238
- if (typeof where !== "object") return null;
8239
- if ("AND" in where || "OR" in where || "NOT" in where) {
8240
- metric?.("engine_signing_key_unsupported_where", { reason: "compound" });
8241
- return null;
8242
- }
8243
- const keys = Object.keys(where);
8244
- if (keys.length !== 1 || keys[0] !== "id") {
8245
- metric?.("engine_signing_key_unsupported_where", {
8246
- reason: "extra_fields",
8247
- keys
8248
- });
8249
- return null;
8250
- }
8251
- const id = where.id;
8252
- if (id === null || typeof id !== "object") return null;
8253
- const eq = id.eq;
8254
- return typeof eq === "string" && eq.length > 0 ? eq : null;
8255
- }
8256
- function createSigningKeyResolver(registry, opts) {
8257
- const metric = opts?.onMetric;
8258
- return async (_ctx, args) => {
8259
- const kid = extractKid(args.params?.where, metric);
8260
- if (kid === null) return [];
8261
- const record = registry.lookup(kid);
8262
- if (record === null) return [];
8263
- return [{
8264
- id: record.kid,
8265
- publicKey: record.publicKey,
8266
- algorithm: record.algorithm
8267
- }];
8268
- };
8269
- }
8270
-
8271
8318
  //#endregion
8272
8319
  //#region ../../packages/substrate-compose/src/_system/install.ts
8273
8320
  /**
8274
8321
  * `_system` namespace wire-up. Spec §5.12.
8275
8322
  *
8276
- * Registers `Key`, `Invite`, `AuditEvent` and the enum-verdict
8277
- * type with admin-gated autoCRUD, plus the public `SigningKey`
8278
- * projection. Returns a live `KeyRegistry` whose cache is synchronously
8279
- * 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.
8280
8326
  *
8281
8327
  * Invalidation strategy: we wrap the `Registry` surface that
8282
8328
  * `installAutoCrud` writes into. The `Key` mutations get their resolver
@@ -8301,6 +8347,8 @@ function createSigningKeyResolver(registry, opts) {
8301
8347
  * (algorithm is a param on the frame, not a property of the identity) and
8302
8348
  * the client deserves a dedicated code to branch on.
8303
8349
  */
8350
+ /** Advisory-lock key held by key writes that can remove an admin. */
8351
+ const KEY_WRITE_LOCK = "substrate-system:key-write";
8304
8352
  /**
8305
8353
  * Wrap a `Registry` so `register` AND `replace` calls for the configured
8306
8354
  * mutation names route their resolver through `wrap(resolver, mutationName)`.
@@ -8524,9 +8572,29 @@ async function installSystemNamespace(opts) {
8524
8572
  if (opts.onWarn !== void 0) keyRegistryOpts.onWarn = opts.onWarn;
8525
8573
  if (opts.reprimeIntervalMs !== void 0) keyRegistryOpts.reprimeIntervalMs = opts.reprimeIntervalMs;
8526
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;
8527
8592
  const wrappedForSubstrateKey = wrapRegistryMutations(opts.registry, {
8528
- createKey: (base) => async (ctx, args) => {
8593
+ createKey: (base) => lockedKeyWrite(async (ctx, args) => {
8529
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`);
8530
8598
  const result = await base(ctx, args);
8531
8599
  const kid = extractKidForInvalidation(result);
8532
8600
  if (kid !== null) {
@@ -8546,13 +8614,25 @@ async function installSystemNamespace(opts) {
8546
8614
  installFromResult(keyRegistry, result, kid, opts.onWarn);
8547
8615
  }
8548
8616
  return result;
8549
- },
8550
- updateKey: (base) => async (ctx, args) => {
8617
+ }),
8618
+ updateKey: (base) => lockedKeyWrite(async (ctx, args) => {
8551
8619
  if (args.params?.kid !== void 0) throw new Error("Key.kid is immutable; rotate or re-register instead of changing kid");
8552
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);
8553
8633
  const result = await base(ctx, args);
8554
8634
  const kid = extractKidForInvalidation(result);
8555
- if (kid !== null) {
8635
+ if (kid !== null && wasLive) {
8556
8636
  const revokedAt = args.params?.revokedAt;
8557
8637
  if (revokedAt !== void 0 && revokedAt !== null && revokedAt !== "") await emitAuditInTx(ctx, args, {
8558
8638
  actorKid: resolveActorKid(ctx),
@@ -8565,19 +8645,21 @@ async function installSystemNamespace(opts) {
8565
8645
  installFromResult(keyRegistry, result, kid, opts.onWarn);
8566
8646
  }
8567
8647
  return result;
8568
- },
8569
- deleteKey: (base) => async (ctx, args) => {
8648
+ }),
8649
+ deleteKey: (base) => lockedKeyWrite(async (ctx, args) => {
8570
8650
  const targetId = typeof args.params?.id === "string" ? args.params.id : void 0;
8571
8651
  let kidToEvict = null;
8572
8652
  if (targetId !== void 0) {
8573
- const { rows } = await (args.dataset ?? opts.dataset).read("Key", { id: targetId });
8574
- 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);
8575
8657
  }
8576
8658
  const result = await base(ctx, args);
8577
8659
  if (kidToEvict !== null) keyRegistry.evict(kidToEvict);
8578
8660
  return result;
8579
- },
8580
- purgeKey: (base) => async (ctx, args) => {
8661
+ }),
8662
+ purgeKey: (base) => lockedKeyWrite(async (ctx, args) => {
8581
8663
  const targetId = typeof args.params?.id === "string" ? args.params.id : void 0;
8582
8664
  let kidToEvict = null;
8583
8665
  if (targetId !== void 0) {
@@ -8585,7 +8667,8 @@ async function installSystemNamespace(opts) {
8585
8667
  id: targetId,
8586
8668
  includeDeleted: true
8587
8669
  });
8588
- kidToEvict = extractKidForInvalidation(rows[0]);
8670
+ assertAdminSurvives(await keysFor(args), targetId, null);
8671
+ if (isLive(rows[0])) kidToEvict = extractKidForInvalidation(rows[0]);
8589
8672
  }
8590
8673
  try {
8591
8674
  const result = await base(ctx, args);
@@ -8598,7 +8681,7 @@ async function installSystemNamespace(opts) {
8598
8681
  }
8599
8682
  throw err;
8600
8683
  }
8601
- }
8684
+ })
8602
8685
  });
8603
8686
  installAutoCrud(wrappedForSubstrateKey, "Key", opts.dataset, opts.edges, {
8604
8687
  fields: mergeIdField(KEY_FIELDS),
@@ -8668,12 +8751,6 @@ async function installSystemNamespace(opts) {
8668
8751
  purgeable: true,
8669
8752
  adminCapability
8670
8753
  });
8671
- opts.registry.register(SIGNING_KEY_TYPE, {
8672
- resolver: createSigningKeyResolver(keyRegistry, opts.onMetric !== void 0 ? { onMetric: opts.onMetric } : void 0),
8673
- kind: "type",
8674
- policy: allowAll(),
8675
- fields: SIGNING_KEY_FIELDS
8676
- });
8677
8754
  await backfillBootstrapAuditIfNeeded(opts.dataset);
8678
8755
  return { keyRegistry };
8679
8756
  }
@@ -9696,7 +9773,7 @@ function keysRoute(engine, opts) {
9696
9773
  const keyErr = errorFor(keyFrameKey);
9697
9774
  if (keyErr !== void 0) {
9698
9775
  const code = keyErr.code ?? "internal_error";
9699
- return jsonResponse(code === "policy_denied" ? 403 : 500, {
9776
+ return jsonResponse(code === "policy_denied" ? 403 : code === "kid_already_live" ? 409 : 500, {
9700
9777
  code,
9701
9778
  message: keyErr.message ?? "key registration failed"
9702
9779
  });
@@ -10131,6 +10208,7 @@ function mergeRowMetadata(existing, incoming) {
10131
10208
  var MemoryDataset = class MemoryDataset {
10132
10209
  namespace;
10133
10210
  txScopeId;
10211
+ #fieldDefLookup;
10134
10212
  capabilities = {
10135
10213
  operators: fullBuiltinOperators(),
10136
10214
  orderBy: true,
@@ -10149,6 +10227,7 @@ var MemoryDataset = class MemoryDataset {
10149
10227
  constructor(options) {
10150
10228
  this.namespace = options.namespace;
10151
10229
  this.txScopeId = options.txScopeId ?? `mem:${randomUUID()}`;
10230
+ this.#fieldDefLookup = options.fieldDefLookup;
10152
10231
  }
10153
10232
  bucket(type) {
10154
10233
  let b = this.store.get(type);
@@ -10166,6 +10245,8 @@ var MemoryDataset = class MemoryDataset {
10166
10245
  hasMore: false
10167
10246
  };
10168
10247
  const includeDeleted = params.includeDeleted === true;
10248
+ const lookup = this.#fieldDefLookup;
10249
+ const fieldDefOf = (field) => lookup?.(type, field);
10169
10250
  const idFilter = /* @__PURE__ */ new Set();
10170
10251
  let hasIdFilter = false;
10171
10252
  if (params.id !== void 0) {
@@ -10198,15 +10279,15 @@ var MemoryDataset = class MemoryDataset {
10198
10279
  })() : b.values();
10199
10280
  for (const row of candidates) {
10200
10281
  if (!includeDeleted && row._deletedAt != null) continue;
10201
- if (resolvedWhere !== void 0 && !evaluateWhere(row, resolvedWhere)) continue;
10282
+ if (resolvedWhere !== void 0 && !evaluateWhere(row, resolvedWhere, fieldDefOf)) continue;
10202
10283
  pool.push(row);
10203
10284
  }
10204
10285
  const orderBy = normalizeOrderBy(params.orderBy);
10205
- pool.sort((a, b2) => compareByClauses(a, b2, orderBy));
10286
+ pool.sort((a, b2) => compareByClauses(a, b2, orderBy, fieldDefOf));
10206
10287
  let startIdx = 0;
10207
10288
  if (params.cursor !== void 0 && params.cursor !== "") {
10208
10289
  const cursor = decodeCursor(params.cursor);
10209
- startIdx = findCursorStart(pool, orderBy, cursor.orderByValues, cursor.id);
10290
+ startIdx = findCursorStart(pool, orderBy, cursor.orderByValues, cursor.id, fieldDefOf);
10210
10291
  }
10211
10292
  let hasMore = false;
10212
10293
  let slice;
@@ -10467,7 +10548,10 @@ var MemoryDataset = class MemoryDataset {
10467
10548
  return this.shortIds.getShortIdForRow(this.namespace, type, rowId);
10468
10549
  }
10469
10550
  forNamespace(namespace) {
10470
- return new MemoryDataset({ namespace });
10551
+ return new MemoryDataset({
10552
+ namespace,
10553
+ ...this.#fieldDefLookup !== void 0 ? { fieldDefLookup: this.#fieldDefLookup } : {}
10554
+ });
10471
10555
  }
10472
10556
  };
10473
10557
  /**
@@ -10485,20 +10569,6 @@ function conditionalMatchEq(actual, expected) {
10485
10569
  }
10486
10570
  return actual === expected;
10487
10571
  }
10488
- function compare(a, b) {
10489
- if (a == null && b == null) return 0;
10490
- if (a == null) return 1;
10491
- if (b == null) return -1;
10492
- if (a instanceof Date || b instanceof Date) {
10493
- const at = a instanceof Date ? a.getTime() : typeof a === "string" ? Date.parse(a) : Number(a);
10494
- const bt = b instanceof Date ? b.getTime() : typeof b === "string" ? Date.parse(b) : Number(b);
10495
- return at < bt ? -1 : at > bt ? 1 : 0;
10496
- }
10497
- if (typeof a === "number" && typeof b === "number") return a < b ? -1 : a > b ? 1 : 0;
10498
- const as = String(a);
10499
- const bs = String(b);
10500
- return as < bs ? -1 : as > bs ? 1 : 0;
10501
- }
10502
10572
  function normalizeOrderBy(orderBy) {
10503
10573
  const out = [];
10504
10574
  let hasIdTail = false;
@@ -10512,19 +10582,19 @@ function normalizeOrderBy(orderBy) {
10512
10582
  if (!hasIdTail) out.push(["id", "asc"]);
10513
10583
  return out;
10514
10584
  }
10515
- function compareByClauses(a, b, orderBy) {
10585
+ function compareByClauses(a, b, orderBy, fieldDefOf) {
10516
10586
  for (const [field, dir] of orderBy) {
10517
10587
  const av = getFieldValue(a, field);
10518
10588
  const bv = getFieldValue(b, field);
10519
10589
  if (av == null && bv == null) continue;
10520
10590
  if (av == null) return 1;
10521
10591
  if (bv == null) return -1;
10522
- const cmp = compare(av, bv);
10592
+ const cmp = compareFilterValues(av, bv, isDateField(field, fieldDefOf));
10523
10593
  if (cmp !== 0) return dir === "asc" ? cmp : -cmp;
10524
10594
  }
10525
10595
  return 0;
10526
10596
  }
10527
- function findCursorStart(pool, orderBy, cursorValues, cursorId) {
10597
+ function findCursorStart(pool, orderBy, cursorValues, cursorId, fieldDefOf) {
10528
10598
  const cursorRow = { id: cursorId };
10529
10599
  const meta = {};
10530
10600
  const createdBy = {};
@@ -10545,7 +10615,7 @@ function findCursorStart(pool, orderBy, cursorValues, cursorId) {
10545
10615
  for (let i = 0; i < pool.length; i++) {
10546
10616
  const row = pool[i];
10547
10617
  if (row === void 0) continue;
10548
- if (compareByClauses(row, cursorRow, orderBy) > 0) return i;
10618
+ if (compareByClauses(row, cursorRow, orderBy, fieldDefOf) > 0) return i;
10549
10619
  }
10550
10620
  return pool.length;
10551
10621
  }
@@ -12278,6 +12348,8 @@ const STREAM_CAPABILITY = "read";
12278
12348
  *
12279
12349
  * The values must be checked here: `StreamSession` reads `entry.fields` off
12280
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.
12281
12353
  *
12282
12354
  * Unlike `validateFrame` in `helpers.ts`, array values (the §5.13
12283
12355
  * batched-mutate shape) are rejected: streams cannot carry them, so this
@@ -12533,6 +12605,7 @@ function parseRequestFrame(buf, mode) {
12533
12605
  const v = value;
12534
12606
  if (typeof v.id !== "string") return null;
12535
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;
12536
12609
  return value;
12537
12610
  } catch {
12538
12611
  return null;
@@ -13188,8 +13261,7 @@ async function composeInner(opts, cleanup) {
13188
13261
  const installSubstrateOpts = {
13189
13262
  registry: substrateRegistry,
13190
13263
  dataset: substrateDataset,
13191
- edges,
13192
- onMetric: routeMetric
13264
+ edges
13193
13265
  };
13194
13266
  if (opts.auth?.adminCapability !== void 0) installSubstrateOpts.adminCapability = opts.auth.adminCapability;
13195
13267
  if (opts.auth !== void 0 && opts.keyReprimeIntervalMs !== void 0) installSubstrateOpts.reprimeIntervalMs = opts.keyReprimeIntervalMs;