@statewalker/webrun-biscuit 0.1.0 → 0.2.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,5 +1,47 @@
1
1
  import { ed25519 } from "@noble/curves/ed25519.js";
2
2
  import { p256 } from "@noble/curves/nist.js";
3
+ //#region src/base64.ts
4
+ /** URL-safe base64 without padding, the wire form of a Biscuit token.
5
+ * Implemented directly so the library stays runtime-agnostic (no Buffer,
6
+ * no atob/btoa). */
7
+ const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
8
+ const REVERSE = new Map([...ALPHABET].map((c, i) => [c, i]));
9
+ REVERSE.set("+", 62);
10
+ REVERSE.set("/", 63);
11
+ function toBase64(bytes) {
12
+ let out = "";
13
+ for (let i = 0; i < bytes.length; i += 3) {
14
+ const b0 = bytes[i];
15
+ const b1 = bytes[i + 1];
16
+ const b2 = bytes[i + 2];
17
+ out += ALPHABET[b0 >> 2];
18
+ out += ALPHABET[(b0 & 3) << 4 | (b1 ?? 0) >> 4];
19
+ if (b1 === void 0) break;
20
+ out += ALPHABET[(b1 & 15) << 2 | (b2 ?? 0) >> 6];
21
+ if (b2 === void 0) break;
22
+ out += ALPHABET[b2 & 63];
23
+ }
24
+ return out;
25
+ }
26
+ function fromBase64(text) {
27
+ const s = text.trim().replace(/=+$/, "");
28
+ const out = new Uint8Array(Math.floor(s.length * 3 / 4));
29
+ let o = 0;
30
+ let acc = 0;
31
+ let bits = 0;
32
+ for (const c of s) {
33
+ const v = REVERSE.get(c);
34
+ if (v === void 0) throw new Error(`invalid base64 character ${JSON.stringify(c)}`);
35
+ acc = acc << 6 | v;
36
+ bits += 6;
37
+ if (bits >= 8) {
38
+ bits -= 8;
39
+ out[o++] = acc >> bits & 255;
40
+ }
41
+ }
42
+ return out.subarray(0, o);
43
+ }
44
+ //#endregion
3
45
  //#region src/crypto.ts
4
46
  /**
5
47
  * Biscuit cryptography: chained block signatures, sealing, third-party
@@ -75,17 +117,30 @@ function generateKeypair(algorithm = 0) {
75
117
  publicKey: publicKeyFromSecret(secretKey, algorithm)
76
118
  };
77
119
  }
78
- /** Verifies the full signature chain and the proof. Throws on failure. */
79
- function verifyToken(token, rootPublicKey, rootAlgorithm = 0) {
120
+ /**
121
+ * Everything verifying a token requires, as data: the signatures to check, in
122
+ * chain order, and — for an unsealed token — the proof secret whose public key
123
+ * must equal the last block's next key. Structural problems throw here, before
124
+ * any signature is looked at. `verifyToken` and `verifyTokenAsync` both consume
125
+ * this, so neither can skip a check the other makes.
126
+ */
127
+ function chainChecks(token, rootPublicKey, rootAlgorithm) {
80
128
  const root = {
81
129
  algorithm: rootAlgorithm,
82
130
  key: rootPublicKey
83
131
  };
132
+ const checks = [];
84
133
  if (token.authority.externalSignature) throw new SignatureError("the authority block must not carry an external signature");
85
134
  const authVersion = token.authority.version ?? 0;
86
- if (!verifySignature(root, authVersion === 0 ? blockPayloadV0(token.authority.block, token.authority.nextKey) : authVersion === 1 ? authorityPayloadV1(token.authority.block, token.authority.nextKey, authVersion) : (() => {
135
+ const authPayload = authVersion === 0 ? blockPayloadV0(token.authority.block, token.authority.nextKey) : authVersion === 1 ? authorityPayloadV1(token.authority.block, token.authority.nextKey, authVersion) : (() => {
87
136
  throw new SignatureError(`unsupported block version ${authVersion}`);
88
- })(), token.authority.signature)) throw new SignatureError("invalid authority block signature");
137
+ })();
138
+ checks.push({
139
+ key: root,
140
+ payload: authPayload,
141
+ signature: token.authority.signature,
142
+ error: "invalid authority block signature"
143
+ });
89
144
  let currentKey = token.authority.nextKey;
90
145
  let previousSignature = token.authority.signature;
91
146
  for (const block of token.blocks) {
@@ -95,21 +150,121 @@ function verifyToken(token, rootPublicKey, rootAlgorithm = 0) {
95
150
  if (version === 0) payload = blockPayloadV0(block.block, block.nextKey, externalSig);
96
151
  else if (version === 1) payload = blockPayloadV1(block.block, block.nextKey, externalSig, previousSignature, version);
97
152
  else throw new SignatureError(`unsupported block version ${version}`);
98
- if (!verifySignature(currentKey, payload, block.signature)) throw new SignatureError("invalid block signature");
153
+ checks.push({
154
+ key: currentKey,
155
+ payload,
156
+ signature: block.signature,
157
+ error: "invalid block signature"
158
+ });
99
159
  if (block.externalSignature) {
100
160
  if (version !== 1) throw new SignatureError("unsupported third party block version");
101
- const ext = externalPayloadV1(block.block, previousSignature, version);
102
- if (!verifySignature(block.externalSignature.publicKey, ext, block.externalSignature.signature)) throw new SignatureError("invalid external signature");
161
+ checks.push({
162
+ key: block.externalSignature.publicKey,
163
+ payload: externalPayloadV1(block.block, previousSignature, version),
164
+ signature: block.externalSignature.signature,
165
+ error: "invalid external signature"
166
+ });
103
167
  }
104
168
  currentKey = block.nextKey;
105
169
  previousSignature = block.signature;
106
170
  }
107
- if (token.proof.kind === "nextSecret") {
108
- const derived = publicKeyFromSecret(token.proof.value, currentKey.algorithm);
109
- if (!bytesEqual(derived, currentKey.key)) throw new SignatureError("the last public key does not match the private key");
110
- } else {
111
- const last = token.blocks.length ? token.blocks[token.blocks.length - 1] : token.authority;
112
- if (!verifySignature(currentKey, sealPayloadV0(last), token.proof.value)) throw new SignatureError("invalid seal signature");
171
+ if (token.proof.kind === "nextSecret") return {
172
+ checks,
173
+ proof: {
174
+ secret: token.proof.value,
175
+ key: currentKey
176
+ }
177
+ };
178
+ const last = token.blocks.length ? token.blocks[token.blocks.length - 1] : token.authority;
179
+ checks.push({
180
+ key: currentKey,
181
+ payload: sealPayloadV0(last),
182
+ signature: token.proof.value,
183
+ error: "invalid seal signature"
184
+ });
185
+ return { checks };
186
+ }
187
+ /** Verifies the full signature chain and the proof. Throws on failure. */
188
+ function verifyToken(token, rootPublicKey, rootAlgorithm = 0) {
189
+ const { checks, proof } = chainChecks(token, rootPublicKey, rootAlgorithm);
190
+ for (const check of checks) if (!verifySignature(check.key, check.payload, check.signature)) throw new SignatureError(check.error);
191
+ if (proof && !bytesEqual(publicKeyFromSecret(proof.secret, proof.key.algorithm), proof.key.key)) throw new SignatureError("the last public key does not match the private key");
192
+ }
193
+ /**
194
+ * `verifyToken`, using the platform's WebCrypto for Ed25519 where it offers it
195
+ * — about ten times faster than the pure-JS path in Node and current browsers.
196
+ * secp256r1, and any runtime without WebCrypto Ed25519, fall back to
197
+ * `@noble/curves`, so the result never depends on where it runs.
198
+ */
199
+ async function verifyTokenAsync(token, rootPublicKey, rootAlgorithm = 0) {
200
+ const { checks, proof } = chainChecks(token, rootPublicKey, rootAlgorithm);
201
+ const [verdicts, derived] = await Promise.all([Promise.all(checks.map((c) => verifySignatureAsync(c.key, c.payload, c.signature))), proof ? publicKeyFromSecretAsync(proof.secret, proof.key.algorithm) : void 0]);
202
+ verdicts.forEach((ok, i) => {
203
+ if (!ok) throw new SignatureError(checks[i].error);
204
+ });
205
+ if (proof && !bytesEqual(derived, proof.key.key)) throw new SignatureError("the last public key does not match the private key");
206
+ }
207
+ const subtle = globalThis.crypto?.subtle;
208
+ /** PKCS#8 wrapping of a raw 32-byte Ed25519 seed (RFC 8410) */
209
+ const PKCS8_ED25519 = Uint8Array.from([
210
+ 48,
211
+ 46,
212
+ 2,
213
+ 1,
214
+ 0,
215
+ 48,
216
+ 5,
217
+ 6,
218
+ 3,
219
+ 43,
220
+ 101,
221
+ 112,
222
+ 4,
223
+ 34,
224
+ 4,
225
+ 32
226
+ ]);
227
+ let ed25519Native;
228
+ /** Whether this runtime's WebCrypto verifies Ed25519, and does so correctly. Probed once. */
229
+ function nativeEd25519() {
230
+ ed25519Native ??= (async () => {
231
+ if (!subtle) return false;
232
+ try {
233
+ const secret = (/* @__PURE__ */ new Uint8Array(32)).fill(7);
234
+ const message = ascii("webrun-biscuit");
235
+ const signature = ed25519.sign(message, secret);
236
+ const key = await subtle.importKey("raw", ed25519.getPublicKey(secret), { name: "Ed25519" }, false, ["verify"]);
237
+ const forged = signature.slice();
238
+ forged[0] ^= 1;
239
+ return await subtle.verify("Ed25519", key, signature, message) && !await subtle.verify("Ed25519", key, forged, message);
240
+ } catch {
241
+ return false;
242
+ }
243
+ })();
244
+ return ed25519Native;
245
+ }
246
+ async function verifySignatureAsync(key, payload, sig) {
247
+ if (key.algorithm !== ALG_ED25519 || !subtle || !await nativeEd25519()) return verifySignature(key, payload, sig);
248
+ if (key.key.length !== 32 || sig.length !== 64) return false;
249
+ try {
250
+ const imported = await subtle.importKey("raw", key.key, { name: "Ed25519" }, false, ["verify"]);
251
+ return await subtle.verify("Ed25519", imported, sig, payload);
252
+ } catch {
253
+ return false;
254
+ }
255
+ }
256
+ async function publicKeyFromSecretAsync(secret, algorithm) {
257
+ if (algorithm !== ALG_ED25519 || secret.length !== 32 || !subtle || !await nativeEd25519()) return publicKeyFromSecret(secret, algorithm);
258
+ try {
259
+ const pkcs8 = new Uint8Array(PKCS8_ED25519.length + 32);
260
+ pkcs8.set(PKCS8_ED25519);
261
+ pkcs8.set(secret, PKCS8_ED25519.length);
262
+ const key = await subtle.importKey("pkcs8", pkcs8, { name: "Ed25519" }, true, ["sign"]);
263
+ const { x } = await subtle.exportKey("jwk", key);
264
+ if (x === void 0) return publicKeyFromSecret(secret, algorithm);
265
+ return fromBase64(x);
266
+ } catch {
267
+ return publicKeyFromSecret(secret, algorithm);
113
268
  }
114
269
  }
115
270
  /** Revocation identifier of each block: its signature bytes. */
@@ -250,10 +405,10 @@ const B = {
250
405
  };
251
406
  const BinaryOp = B;
252
407
  const UnaryOp = U;
253
- const I64_MIN = -(2n ** 63n);
254
- const I64_MAX = 2n ** 63n - 1n;
408
+ const I64_MIN$1 = -(2n ** 63n);
409
+ const I64_MAX$1 = 2n ** 63n - 1n;
255
410
  function checkedI64(v) {
256
- if (v < I64_MIN || v > I64_MAX) throw new ExecutionError("Overflow");
411
+ if (v < I64_MIN$1 || v > I64_MAX$1) throw new ExecutionError("Overflow");
257
412
  return {
258
413
  t: "int",
259
414
  v
@@ -571,7 +726,7 @@ function variablesOf(rule) {
571
726
  return out;
572
727
  }
573
728
  /** backtracking join over the rule body, mirroring Rust's CombineIt */
574
- function* combine(predicates, facts, bindings, variables) {
729
+ function* combine(predicates, facts, bindings, variables, tick) {
575
730
  if (predicates.length === 0) {
576
731
  for (const v of variables) if (!bindings.has(v)) return;
577
732
  yield [Origin.of(), new Map(bindings)];
@@ -579,6 +734,7 @@ function* combine(predicates, facts, bindings, variables) {
579
734
  }
580
735
  const [head, ...rest] = predicates;
581
736
  for (const [origin, fact] of facts.get(`${head.name}/${head.terms.length}`) ?? []) {
737
+ tick();
582
738
  if (!matchPredicate(head, fact.predicate)) continue;
583
739
  const next = new Map(bindings);
584
740
  let ok = true;
@@ -593,7 +749,7 @@ function* combine(predicates, facts, bindings, variables) {
593
749
  }
594
750
  }
595
751
  if (!ok) continue;
596
- for (const [subOrigin, result] of combine(rest, facts, next, variables)) yield [subOrigin.union(origin), result];
752
+ for (const [subOrigin, result] of combine(rest, facts, next, variables, tick)) yield [subOrigin.union(origin), result];
597
753
  }
598
754
  }
599
755
  var World = class {
@@ -604,6 +760,22 @@ var World = class {
604
760
  iterations = 0;
605
761
  generation = 0;
606
762
  indexCache = /* @__PURE__ */ new Map();
763
+ /** wall-clock budget of the evaluation in progress; Infinity outside one */
764
+ deadline = Number.POSITIVE_INFINITY;
765
+ steps = 0;
766
+ /**
767
+ * The time limit, enforced where the work is. Checking only between
768
+ * iterations let one combinatorial rule — or one check that derives nothing —
769
+ * run for seconds whatever `maxTimeMs` said. Polled every 1024 candidate
770
+ * facts, so the clock costs nothing measurable.
771
+ */
772
+ tick = () => {
773
+ if ((++this.steps & 1023) === 0 && Date.now() >= this.deadline) throw new ExecutionError("Timeout");
774
+ };
775
+ /** Close the budget: queries made after an evaluation are not charged against it. */
776
+ endBudget() {
777
+ this.deadline = Number.POSITIVE_INFINITY;
778
+ }
607
779
  addFact(origin, fact) {
608
780
  let bucket = this.facts.get(origin.key);
609
781
  if (!bucket) {
@@ -653,12 +825,22 @@ var World = class {
653
825
  /** naive fixpoint: apply every rule until no new fact appears */
654
826
  run(limits = DEFAULT_LIMITS) {
655
827
  const deadline = Date.now() + limits.maxTimeMs;
828
+ this.deadline = deadline;
656
829
  let index = 0;
657
830
  for (;;) {
658
831
  const generated = [];
832
+ const fresh = /* @__PURE__ */ new Set();
833
+ const base = this.factCount();
834
+ const lastIteration = index + 1 === limits.maxIterations;
659
835
  for (const { origin, trusted, rule } of this.rules) {
660
836
  const facts = this.visible(trusted);
661
- for (const [o, f] of this.apply(rule, facts, origin)) generated.push([o, f]);
837
+ for (const [o, f] of this.apply(rule, facts, origin)) {
838
+ generated.push([o, f]);
839
+ const key = factKey(f);
840
+ if (this.facts.get(o.key)?.items.has(key)) continue;
841
+ fresh.add(`${o.key}|${key}`);
842
+ if (!lastIteration && base + fresh.size >= limits.maxFacts) throw new ExecutionError("TooManyFacts");
843
+ }
662
844
  }
663
845
  const before = this.factCount();
664
846
  for (const [o, f] of generated) this.addFact(o, f);
@@ -672,7 +854,7 @@ var World = class {
672
854
  }
673
855
  *apply(rule, facts, ruleOrigin) {
674
856
  const variables = variablesOf(rule);
675
- for (const [origin, bindings] of combine(rule.body, facts, /* @__PURE__ */ new Map(), variables)) {
857
+ for (const [origin, bindings] of combine(rule.body, facts, /* @__PURE__ */ new Map(), variables, this.tick)) {
676
858
  let pass = true;
677
859
  for (const ops of rule.expressions) {
678
860
  const res = evaluateExpression(ops, bindings, this.externs);
@@ -700,6 +882,15 @@ var World = class {
700
882
  } }];
701
883
  }
702
884
  }
885
+ /** every distinct fact `rule` derives from the facts `trusted` can see */
886
+ query(rule, trusted) {
887
+ const seen = /* @__PURE__ */ new Map();
888
+ for (const [, fact] of this.apply(rule, this.visible(trusted), AUTHORIZER)) {
889
+ const key = factKey(fact);
890
+ if (!seen.has(key)) seen.set(key, fact.predicate);
891
+ }
892
+ return [...seen.values()];
893
+ }
703
894
  /** `check if` / policies: does at least one combination match? */
704
895
  queryMatch(rule, origin, trusted) {
705
896
  for (const _ of this.apply(rule, this.visible(trusted), origin)) return true;
@@ -709,7 +900,7 @@ var World = class {
709
900
  queryMatchAll(rule, trusted) {
710
901
  const variables = variablesOf(rule);
711
902
  let found = false;
712
- for (const [, bindings] of combine(rule.body, this.visible(trusted), /* @__PURE__ */ new Map(), variables)) {
903
+ for (const [, bindings] of combine(rule.body, this.visible(trusted), /* @__PURE__ */ new Map(), variables, this.tick)) {
713
904
  found = true;
714
905
  for (const ops of rule.expressions) {
715
906
  const res = evaluateExpression(ops, bindings, this.externs);
@@ -728,16 +919,78 @@ var World = class {
728
919
  * compiled straight to the opcode form the VM executes.
729
920
  */
730
921
  var ParseError = class extends Error {};
731
- const NAME_START = /[\p{L}]/u;
732
- const NAME_CHAR = /[\p{L}\p{N}_:]/u;
922
+ const I64_MIN = -(2n ** 63n);
923
+ const I64_MAX = 2n ** 63n - 1n;
924
+ function paramTerm(name, value) {
925
+ if (typeof value === "string") return {
926
+ t: "str",
927
+ v: value
928
+ };
929
+ if (typeof value === "boolean") return {
930
+ t: "bool",
931
+ v: value
932
+ };
933
+ if (value === null) return { t: "null" };
934
+ if (typeof value === "number") {
935
+ if (!Number.isSafeInteger(value)) throw new ParseError(`parameter {${name}}: ${value} is not a safe integer`);
936
+ return {
937
+ t: "int",
938
+ v: BigInt(value)
939
+ };
940
+ }
941
+ if (typeof value === "bigint") {
942
+ if (value < I64_MIN || value > I64_MAX) throw new ParseError(`parameter {${name}}: ${value} does not fit in i64`);
943
+ return {
944
+ t: "int",
945
+ v: value
946
+ };
947
+ }
948
+ if (value instanceof Date) {
949
+ const ms = value.getTime();
950
+ if (Number.isNaN(ms)) throw new ParseError(`parameter {${name}}: invalid date`);
951
+ return {
952
+ t: "date",
953
+ v: BigInt(Math.floor(ms / 1e3))
954
+ };
955
+ }
956
+ if (value instanceof Uint8Array) return {
957
+ t: "bytes",
958
+ v: value
959
+ };
960
+ if (Array.isArray(value)) return {
961
+ t: "array",
962
+ v: value.map((x) => paramTerm(name, x))
963
+ };
964
+ if (value instanceof Set) return {
965
+ t: "set",
966
+ v: normalizeSet([...value].map((x) => paramTerm(name, x)))
967
+ };
968
+ throw new ParseError(`parameter {${name}}: no Datalog term for this value`);
969
+ }
970
+ /** `{name}` in term position; `{true}`, `{false}` and `{null}` stay one-element sets */
971
+ const PARAMETER = /^\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}/;
972
+ /**
973
+ * A predicate or variable name is one or more of `[A-Za-z0-9_:]`, and any of them
974
+ * may come first — ASCII only. That is what the reference parser accepts, measured
975
+ * rather than read from the specification (`tests/grammar-cases.ts`): `_m`, `1a`
976
+ * and `::` are names, `ärger` is not.
977
+ */
978
+ const NAME_CHAR = /[A-Za-z0-9_:]/;
733
979
  var Parser = class {
734
980
  src;
981
+ params;
735
982
  i = 0;
736
983
  vars;
737
- constructor(src, vars) {
984
+ usedParams = /* @__PURE__ */ new Set();
985
+ constructor(src, vars, params = {}) {
738
986
  this.src = src;
987
+ this.params = params;
739
988
  this.vars = vars ?? /* @__PURE__ */ new Map();
740
989
  }
990
+ /** names in `params` that the source never referred to */
991
+ unusedParameters() {
992
+ return Object.keys(this.params).filter((name) => !this.usedParams.has(name));
993
+ }
741
994
  /** id -> name, for printing rules back out */
742
995
  variableNames() {
743
996
  const out = /* @__PURE__ */ new Map();
@@ -793,9 +1046,8 @@ var Parser = class {
793
1046
  this.i += k.length;
794
1047
  return true;
795
1048
  }
796
- /** variable names, unlike predicate names, may start with a digit ($0) */
1049
+ /** the name directly after `$` — `$ x` is not a variable, as in the reference */
797
1050
  variableName() {
798
- this.ws();
799
1051
  const start = this.i;
800
1052
  while (this.i < this.src.length && NAME_CHAR.test(this.src[this.i])) this.i++;
801
1053
  if (this.i === start) throw new ParseError(`expected a variable name at offset ${this.i}`);
@@ -804,9 +1056,8 @@ var Parser = class {
804
1056
  name() {
805
1057
  this.ws();
806
1058
  const start = this.i;
807
- if (this.i >= this.src.length || !NAME_START.test(this.src[this.i])) throw new ParseError(`expected a name at offset ${this.i}`);
808
- this.i++;
809
1059
  while (this.i < this.src.length && NAME_CHAR.test(this.src[this.i])) this.i++;
1060
+ if (this.i === start) throw new ParseError(`expected a name at offset ${this.i}`);
810
1061
  return this.src.slice(start, this.i);
811
1062
  }
812
1063
  string() {
@@ -890,7 +1141,7 @@ var Parser = class {
890
1141
  };
891
1142
  }
892
1143
  if (this.peek("[")) return this.array(allowVariables);
893
- if (this.peek("{")) return this.setOrMap(allowVariables);
1144
+ if (this.peek("{")) return this.parameter() ?? this.setOrMap(allowVariables);
894
1145
  const m = /^-?\d+/.exec(this.src.slice(this.i));
895
1146
  if (m) {
896
1147
  this.i += m[0].length;
@@ -901,6 +1152,15 @@ var Parser = class {
901
1152
  }
902
1153
  throw new ParseError(`unexpected term at offset ${this.i}: ${this.src.slice(this.i, this.i + 20)}`);
903
1154
  }
1155
+ parameter() {
1156
+ const m = PARAMETER.exec(this.src.slice(this.i));
1157
+ if (!m || m[1] === "true" || m[1] === "false" || m[1] === "null") return null;
1158
+ const name = m[1];
1159
+ if (!Object.hasOwn(this.params, name)) throw new ParseError(`unbound parameter {${name}}`);
1160
+ this.i += m[0].length;
1161
+ this.usedParams.add(name);
1162
+ return paramTerm(name, this.params[name]);
1163
+ }
904
1164
  array(allowVariables) {
905
1165
  this.expect("[");
906
1166
  const items = [];
@@ -970,8 +1230,9 @@ var Parser = class {
970
1230
  predicate(allowVariables = true) {
971
1231
  const name = this.name();
972
1232
  this.expect("(");
1233
+ if (this.peek(")")) throw new ParseError(`predicate ${name} takes at least one term`);
973
1234
  const terms = [];
974
- if (!this.peek(")")) do
1235
+ do
975
1236
  terms.push(this.term(allowVariables));
976
1237
  while (this.eat(","));
977
1238
  this.expect(")");
@@ -1347,7 +1608,7 @@ var Parser = class {
1347
1608
  const save = this.i;
1348
1609
  try {
1349
1610
  this.ws();
1350
- if (!NAME_START.test(this.src[this.i] ?? "")) return null;
1611
+ if (!NAME_CHAR.test(this.src[this.i] ?? "")) return null;
1351
1612
  const p = this.predicate();
1352
1613
  this.ws();
1353
1614
  const rest = this.src.slice(this.i);
@@ -2474,6 +2735,18 @@ function convBlock(b, s, externalKey) {
2474
2735
  function loadToken(bytes, rootPublicKey, rootAlgorithm = 0) {
2475
2736
  const token = decodeBiscuit(bytes);
2476
2737
  verifyToken(token, rootPublicKey, rootAlgorithm);
2738
+ return toLoadedToken(token);
2739
+ }
2740
+ /**
2741
+ * `loadToken`, verifying signatures with the platform's WebCrypto Ed25519 where
2742
+ * available — see `verifyTokenAsync`. Same result, same errors.
2743
+ */
2744
+ async function loadTokenAsync(bytes, rootPublicKey, rootAlgorithm = 0) {
2745
+ const token = decodeBiscuit(bytes);
2746
+ await verifyTokenAsync(token, rootPublicKey, rootAlgorithm);
2747
+ return toLoadedToken(token);
2748
+ }
2749
+ function toLoadedToken(token) {
2477
2750
  const signed = [token.authority, ...token.blocks];
2478
2751
  const decoded = signed.map((sb) => decodeBlock(sb.block));
2479
2752
  const globalSymbols = [];
@@ -2528,7 +2801,12 @@ function headVariablesAreBound(rule) {
2528
2801
  for (const p of rule.body) for (const t of p.terms) if (t.t === "var") bound.add(t.v);
2529
2802
  return rule.head.terms.every((t) => t.t !== "var" || bound.has(t.v));
2530
2803
  }
2531
- function parseAuthorizer(src) {
2804
+ /**
2805
+ * Parse authorizer (or block) source. `{name}` parameters are bound from
2806
+ * `params` as terms; an unbound or an unused parameter is a `ParseError`, as it
2807
+ * is in the reference.
2808
+ */
2809
+ function parseAuthorizer(src, params) {
2532
2810
  const out = {
2533
2811
  facts: [],
2534
2812
  rules: [],
@@ -2537,8 +2815,10 @@ function parseAuthorizer(src) {
2537
2815
  scopes: [],
2538
2816
  varNames: /* @__PURE__ */ new Map()
2539
2817
  };
2540
- const parser = new Parser(src);
2818
+ const parser = new Parser(src, void 0, params);
2541
2819
  const statements = parser.parse();
2820
+ const unused = parser.unusedParameters();
2821
+ if (unused.length > 0) throw new ParseError(`unused parameter${unused.length > 1 ? "s" : ""} {${unused.join("}, {")}}`);
2542
2822
  out.varNames = parser.variableNames();
2543
2823
  for (const st of statements) if (st.k === "fact") out.facts.push(st.fact);
2544
2824
  else if (st.k === "rule") out.rules.push(st.rule);
@@ -2551,7 +2831,7 @@ function parseAuthorizer(src) {
2551
2831
  return out;
2552
2832
  }
2553
2833
  function authorize(token, authorizerSrc, options = {}) {
2554
- return authorizeDetailed(token, authorizerSrc, options).result;
2834
+ return evaluate(token, authorizerSrc, options).result;
2555
2835
  }
2556
2836
  const EMPTY_WORLD = {
2557
2837
  facts: [],
@@ -2562,18 +2842,32 @@ const EMPTY_WORLD = {
2562
2842
  /** Same as `authorize`, and also returns the post-run world, in the shape the
2563
2843
  * official sample corpus records it. */
2564
2844
  function authorizeDetailed(token, authorizerSrc, options = {}) {
2845
+ const evaluation = evaluate(token, authorizerSrc, options);
2846
+ return {
2847
+ result: evaluation.result,
2848
+ world: evaluation.snapshot()
2849
+ };
2850
+ }
2851
+ const NO_TOKEN = {
2852
+ blocks: [],
2853
+ publicKeyToBlockIds: /* @__PURE__ */ new Map(),
2854
+ revocationIds: []
2855
+ };
2856
+ /**
2857
+ * Run the authorizer against a verified token — or against no token at all,
2858
+ * for a decision made from the authorizer's own facts and rules.
2859
+ */
2860
+ function evaluate(loadedToken, authorizerSrc, options = {}) {
2861
+ const token = loadedToken ?? NO_TOKEN;
2565
2862
  const limits = options.limits ?? DEFAULT_LIMITS;
2566
2863
  let code;
2567
2864
  try {
2568
- code = parseAuthorizer(authorizerSrc);
2865
+ code = parseAuthorizer(authorizerSrc, options.params);
2569
2866
  } catch (e) {
2570
- return {
2571
- result: {
2572
- kind: "format",
2573
- error: e.message
2574
- },
2575
- world: EMPTY_WORLD
2576
- };
2867
+ return unusable({
2868
+ kind: "format",
2869
+ error: e.message
2870
+ });
2577
2871
  }
2578
2872
  const world = new World();
2579
2873
  if (options.externs) world.externs = options.externs;
@@ -2586,14 +2880,11 @@ function authorizeDetailed(token, authorizerSrc, options = {}) {
2586
2880
  const origin = Origin.of(id);
2587
2881
  for (const f of block.facts) world.addFact(origin, f);
2588
2882
  for (const r of block.rules) {
2589
- if (!headVariablesAreBound(r)) return {
2590
- result: {
2591
- kind: "invalidBlockRule",
2592
- blockId: 0,
2593
- rule: printRule(r, (v) => block.varNames.get(v) ?? String(v))
2594
- },
2595
- world: EMPTY_WORLD
2596
- };
2883
+ if (!headVariablesAreBound(r)) return unusable({
2884
+ kind: "invalidBlockRule",
2885
+ blockId: 0,
2886
+ rule: printRule(r, (v) => block.varNames.get(v) ?? String(v))
2887
+ });
2597
2888
  world.addRule(id, trustedOriginsFromScopes(r.scopes, trusted, id, keys), r);
2598
2889
  }
2599
2890
  }
@@ -2643,16 +2934,33 @@ function authorizeDetailed(token, authorizerSrc, options = {}) {
2643
2934
  policies: code.policies.map((p) => printPolicy(p.kind, p.queries, name(AUTHORIZER)))
2644
2935
  };
2645
2936
  };
2937
+ let failure;
2938
+ const settled = (result) => {
2939
+ world.endBudget();
2940
+ return evaluation(result);
2941
+ };
2942
+ const evaluation = (result) => ({
2943
+ result,
2944
+ snapshot,
2945
+ query(src, queryOptions = {}) {
2946
+ if (failure) throw failure;
2947
+ const parsed = parseAuthorizer(`${src};`, queryOptions.params);
2948
+ if (parsed.facts.length + parsed.rules.length + parsed.checks.length + parsed.policies.length !== 1 || parsed.rules.length !== 1) throw new ParseError("a query must be exactly one rule");
2949
+ const rule = parsed.rules[0];
2950
+ const trusted = trustedOriginsFromScopes(rule.scopes, authorizerTrusted, AUTHORIZER, keys);
2951
+ return world.query(rule, trusted);
2952
+ }
2953
+ });
2646
2954
  try {
2647
2955
  world.run(limits);
2648
2956
  } catch (e) {
2649
- if (e instanceof ExecutionError) return {
2650
- result: {
2957
+ if (e instanceof ExecutionError) {
2958
+ failure = e;
2959
+ return settled({
2651
2960
  kind: "execution",
2652
2961
  error: e.kind
2653
- },
2654
- world: snapshot()
2655
- };
2962
+ });
2963
+ }
2656
2964
  throw e;
2657
2965
  }
2658
2966
  const errors = [];
@@ -2667,14 +2975,16 @@ function authorizeDetailed(token, authorizerSrc, options = {}) {
2667
2975
  code.checks.forEach((check, i) => {
2668
2976
  if (!runCheck(check, 4294967295, authorizerTrusted)) errors.push({
2669
2977
  source: "authorizer",
2670
- checkId: i
2978
+ checkId: i,
2979
+ rule: printCheck(check, name(AUTHORIZER))
2671
2980
  });
2672
2981
  });
2673
2982
  token.blocks[0]?.checks.forEach((check, j) => {
2674
2983
  if (!runCheck(check, 0, blockTrusted[0])) errors.push({
2675
2984
  source: "block",
2676
2985
  blockId: 0,
2677
- checkId: j
2986
+ checkId: j,
2987
+ rule: printCheck(check, name(0))
2678
2988
  });
2679
2989
  });
2680
2990
  let policyResult = null;
@@ -2689,34 +2999,42 @@ function authorizeDetailed(token, authorizerSrc, options = {}) {
2689
2999
  if (!runCheck(check, id, blockTrusted[id])) errors.push({
2690
3000
  source: "block",
2691
3001
  blockId: id,
2692
- checkId: j
3002
+ checkId: j,
3003
+ rule: printCheck(check, name(id))
2693
3004
  });
2694
3005
  });
2695
- return {
2696
- result: policyResult === null ? {
2697
- kind: "noMatchingPolicy",
2698
- checks: errors
2699
- } : "allow" in policyResult && errors.length === 0 ? {
2700
- kind: "ok",
2701
- policy: policyResult.allow
2702
- } : {
2703
- kind: "unauthorized",
2704
- policy: policyResult,
2705
- checks: errors
2706
- },
2707
- world: snapshot()
2708
- };
3006
+ return settled(policyResult === null ? {
3007
+ kind: "noMatchingPolicy",
3008
+ checks: errors
3009
+ } : "allow" in policyResult && errors.length === 0 ? {
3010
+ kind: "ok",
3011
+ policy: policyResult.allow
3012
+ } : {
3013
+ kind: "unauthorized",
3014
+ policy: policyResult,
3015
+ checks: errors
3016
+ });
2709
3017
  } catch (e) {
2710
- if (e instanceof ExecutionError) return {
2711
- result: {
3018
+ if (e instanceof ExecutionError) {
3019
+ failure = e;
3020
+ return settled({
2712
3021
  kind: "execution",
2713
3022
  error: e.kind
2714
- },
2715
- world: snapshot()
2716
- };
3023
+ });
3024
+ }
2717
3025
  throw e;
2718
3026
  }
2719
3027
  }
3028
+ /** An evaluation that never produced a world: the result says why, and queries refuse. */
3029
+ function unusable(result) {
3030
+ return {
3031
+ result,
3032
+ snapshot: () => EMPTY_WORLD,
3033
+ query() {
3034
+ throw new Error(`cannot query an evaluation that ended in ${result.kind}`);
3035
+ }
3036
+ };
3037
+ }
2720
3038
  function compareOrigins(a, b) {
2721
3039
  for (let i = 0; i < Math.max(a.length, b.length); i++) {
2722
3040
  const x = a[i] === void 0 ? -Infinity : a[i] ?? -1;
@@ -2726,48 +3044,6 @@ function compareOrigins(a, b) {
2726
3044
  return 0;
2727
3045
  }
2728
3046
  //#endregion
2729
- //#region src/base64.ts
2730
- /** URL-safe base64 without padding, the wire form of a Biscuit token.
2731
- * Implemented directly so the library stays runtime-agnostic (no Buffer,
2732
- * no atob/btoa). */
2733
- const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
2734
- const REVERSE = new Map([...ALPHABET].map((c, i) => [c, i]));
2735
- REVERSE.set("+", 62);
2736
- REVERSE.set("/", 63);
2737
- function toBase64(bytes) {
2738
- let out = "";
2739
- for (let i = 0; i < bytes.length; i += 3) {
2740
- const b0 = bytes[i];
2741
- const b1 = bytes[i + 1];
2742
- const b2 = bytes[i + 2];
2743
- out += ALPHABET[b0 >> 2];
2744
- out += ALPHABET[(b0 & 3) << 4 | (b1 ?? 0) >> 4];
2745
- if (b1 === void 0) break;
2746
- out += ALPHABET[(b1 & 15) << 2 | (b2 ?? 0) >> 6];
2747
- if (b2 === void 0) break;
2748
- out += ALPHABET[b2 & 63];
2749
- }
2750
- return out;
2751
- }
2752
- function fromBase64(text) {
2753
- const s = text.trim().replace(/=+$/, "");
2754
- const out = new Uint8Array(Math.floor(s.length * 3 / 4));
2755
- let o = 0;
2756
- let acc = 0;
2757
- let bits = 0;
2758
- for (const c of s) {
2759
- const v = REVERSE.get(c);
2760
- if (v === void 0) throw new Error(`invalid base64 character ${JSON.stringify(c)}`);
2761
- acc = acc << 6 | v;
2762
- bits += 6;
2763
- if (bits >= 8) {
2764
- bits -= 8;
2765
- out[o++] = acc >> bits & 255;
2766
- }
2767
- }
2768
- return out.subarray(0, o);
2769
- }
2770
- //#endregion
2771
3047
  //#region src/builder.ts
2772
3048
  /**
2773
3049
  * The write path: minting tokens, attenuating them with extra blocks, and
@@ -2780,12 +3056,18 @@ var BuilderError = class extends Error {};
2780
3056
  var SymbolWriter = class {
2781
3057
  known;
2782
3058
  knownKeys;
3059
+ varNames;
2783
3060
  /** symbols added by this block, in insertion order */
2784
3061
  added = [];
2785
3062
  addedKeys = [];
2786
- constructor(known = [], knownKeys = []) {
3063
+ constructor(known = [], knownKeys = [], varNames = /* @__PURE__ */ new Map()) {
2787
3064
  this.known = known;
2788
3065
  this.knownKeys = knownKeys;
3066
+ this.varNames = varNames;
3067
+ }
3068
+ /** A variable's wire id is the symbol index of its NAME, not the parser's local id. */
3069
+ variable(id) {
3070
+ return this.insert(this.varNames.get(id) ?? String(id));
2789
3071
  }
2790
3072
  insert(s) {
2791
3073
  const d = DEFAULT_SYMBOLS.indexOf(s);
@@ -2817,7 +3099,7 @@ function toTerm(t, w) {
2817
3099
  switch (t.t) {
2818
3100
  case "var": return {
2819
3101
  kind: "variable",
2820
- value: t.v
3102
+ value: w.variable(t.v)
2821
3103
  };
2822
3104
  case "int": return {
2823
3105
  kind: "integer",
@@ -2885,7 +3167,7 @@ const toOps = (ops, w) => ops.map((op) => {
2885
3167
  };
2886
3168
  case "closure": return {
2887
3169
  kind: "closure",
2888
- params: op.params,
3170
+ params: op.params.map((p) => w.variable(p)),
2889
3171
  ops: toOps(op.ops, w)
2890
3172
  };
2891
3173
  default: throw new Error(`unknown expression op kind ${op.kind}`);
@@ -2908,7 +3190,7 @@ const toRule = (r, w) => ({
2908
3190
  scope: r.scopes.map((s) => toScope(s, w))
2909
3191
  });
2910
3192
  function buildBlockMsg(content, knownSymbols = [], knownKeys = [], minVersion = 0) {
2911
- const w = new SymbolWriter(knownSymbols, knownKeys);
3193
+ const w = new SymbolWriter(knownSymbols, knownKeys, content.varNames);
2912
3194
  const facts = content.facts.map((f) => toPredicate(f.predicate, w));
2913
3195
  const rules = content.rules.map((r) => toRule(r, w));
2914
3196
  const checks = content.checks.map((c) => ({
@@ -2926,14 +3208,15 @@ function buildBlockMsg(content, knownSymbols = [], knownKeys = [], minVersion =
2926
3208
  publicKeys: w.addedKeys.map(parseKeyString)
2927
3209
  };
2928
3210
  }
2929
- const contentFromCode = (code) => {
2930
- const parsed = parseAuthorizer(code);
3211
+ const contentFromCode = (code, params) => {
3212
+ const parsed = parseAuthorizer(code, params);
2931
3213
  if (parsed.policies.length) throw new BuilderError("allow/deny policies belong to the authorizer, not to a block");
2932
3214
  return {
2933
3215
  facts: parsed.facts,
2934
3216
  rules: parsed.rules,
2935
3217
  checks: parsed.checks,
2936
- scopes: parsed.scopes
3218
+ scopes: parsed.scopes,
3219
+ varNames: parsed.varNames
2937
3220
  };
2938
3221
  };
2939
3222
  function knownTables(token) {
@@ -2956,7 +3239,7 @@ function knownTables(token) {
2956
3239
  /** Mint a new token whose authority block holds `code`. */
2957
3240
  function buildToken(rootSecret, code, options = {}) {
2958
3241
  const algorithm = options.algorithm ?? 0;
2959
- const blockBytes = encodeBlock(buildBlockMsg(typeof code === "string" ? contentFromCode(code) : code));
3242
+ const blockBytes = encodeBlock(buildBlockMsg(typeof code === "string" ? contentFromCode(code, options.params) : code));
2960
3243
  const next = options.nextKeypair ?? generateKeypair(algorithm);
2961
3244
  const nextKey = {
2962
3245
  algorithm,
@@ -2987,7 +3270,7 @@ function attenuate(tokenBytes, code, options = {}) {
2987
3270
  const previous = token.blocks.length ? token.blocks[token.blocks.length - 1] : token.authority;
2988
3271
  const currentAlgorithm = previous.nextKey.algorithm;
2989
3272
  const tables = knownTables(token);
2990
- const blockBytes = encodeBlock(buildBlockMsg(typeof code === "string" ? contentFromCode(code) : code, tables.symbols, tables.keys));
3273
+ const blockBytes = encodeBlock(buildBlockMsg(typeof code === "string" ? contentFromCode(code, options.params) : code, tables.symbols, tables.keys));
2991
3274
  const next = options.nextKeypair ?? generateKeypair(algorithm);
2992
3275
  const nextKey = {
2993
3276
  algorithm,
@@ -3023,8 +3306,8 @@ function thirdPartyRequest(tokenBytes) {
3023
3306
  return { previousSignature: (token.blocks.length ? token.blocks[token.blocks.length - 1] : token.authority).signature };
3024
3307
  }
3025
3308
  /** The third party builds and signs a block without holding the token. */
3026
- function thirdPartyBlock(request, externalSecret, code, algorithm = 0) {
3027
- const blockBytes = encodeBlock(buildBlockMsg(typeof code === "string" ? contentFromCode(code) : code, [], [], 5));
3309
+ function thirdPartyBlock(request, externalSecret, code, algorithm = 0, params) {
3310
+ const blockBytes = encodeBlock(buildBlockMsg(typeof code === "string" ? contentFromCode(code, params) : code, [], [], 5));
3028
3311
  return {
3029
3312
  block: blockBytes,
3030
3313
  signature: sign(externalPayloadV1(blockBytes, request.previousSignature, SIGNATURE_VERSION), externalSecret, algorithm),
@@ -3106,6 +3389,13 @@ var Biscuit = class Biscuit {
3106
3389
  verify(rootPublicKey, rootAlgorithm = 0) {
3107
3390
  return new VerifiedBiscuit(loadToken(this.bytes, rootPublicKey, rootAlgorithm), this.bytes);
3108
3391
  }
3392
+ /**
3393
+ * `verify`, using WebCrypto Ed25519 where the platform has it — roughly ten
3394
+ * times faster than the pure-JS path. Rejects exactly where `verify` throws.
3395
+ */
3396
+ async verifyAsync(rootPublicKey, rootAlgorithm = 0) {
3397
+ return new VerifiedBiscuit(await loadTokenAsync(this.bytes, rootPublicKey, rootAlgorithm), this.bytes);
3398
+ }
3109
3399
  };
3110
3400
  /** A token whose signature chain has been checked against a root key. */
3111
3401
  var VerifiedBiscuit = class {
@@ -3125,6 +3415,10 @@ var VerifiedBiscuit = class {
3125
3415
  authorize(authorizerCode, options) {
3126
3416
  return authorize(this.token, authorizerCode, options);
3127
3417
  }
3418
+ /** Authorize, keeping the evaluated world available to `query`. */
3419
+ evaluate(authorizerCode, options) {
3420
+ return evaluate(this.token, authorizerCode, options);
3421
+ }
3128
3422
  };
3129
3423
  //#endregion
3130
- export { Biscuit, BuilderError, DATALOG_3_1, DATALOG_3_2, DATALOG_3_3, DEFAULT_SYMBOLS, ExecutionError, MAX_SCHEMA_VERSION, MIN_SCHEMA_VERSION, ParseError, ProtoError, SignatureError, TokenError, VerifiedBiscuit, VersionError, appendThirdParty, attenuate, authorize, authorizeDetailed, blockFeatures, buildBlockMsg, buildToken, fromBase64, generateKeypair, loadToken, parseAuthorizer, peekRootKeyId, requiredVersion, sealToken, thirdPartyBlock, thirdPartyRequest, toBase64, validateBlockVersion };
3424
+ export { Biscuit, BuilderError, DATALOG_3_1, DATALOG_3_2, DATALOG_3_3, DEFAULT_SYMBOLS, ExecutionError, MAX_SCHEMA_VERSION, MIN_SCHEMA_VERSION, ParseError, ProtoError, SignatureError, TokenError, VerifiedBiscuit, VersionError, appendThirdParty, attenuate, authorize, authorizeDetailed, blockFeatures, buildBlockMsg, buildToken, evaluate, fromBase64, generateKeypair, loadToken, loadTokenAsync, parseAuthorizer, peekRootKeyId, requiredVersion, sealToken, thirdPartyBlock, thirdPartyRequest, toBase64, validateBlockVersion };