@statewalker/webrun-biscuit 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/datalog.ts CHANGED
@@ -699,6 +699,16 @@ export class World {
699
699
  }
700
700
  }
701
701
 
702
+ /** every distinct fact `rule` derives from the facts `trusted` can see */
703
+ query(rule: Rule, trusted: TrustedOrigins): Predicate[] {
704
+ const seen = new Map<string, Predicate>();
705
+ for (const [, fact] of this.apply(rule, this.visible(trusted), AUTHORIZER)) {
706
+ const key = factKey(fact);
707
+ if (!seen.has(key)) seen.set(key, fact.predicate);
708
+ }
709
+ return [...seen.values()];
710
+ }
711
+
702
712
  /** `check if` / policies: does at least one combination match? */
703
713
  queryMatch(rule: Rule, origin: number, trusted: TrustedOrigins): boolean {
704
714
  for (const _ of this.apply(rule, this.visible(trusted), origin)) return true;
package/src/index.ts CHANGED
@@ -11,8 +11,11 @@ import {
11
11
  type AuthorizationResult,
12
12
  type AuthorizeOptions,
13
13
  authorize,
14
+ type Evaluation,
15
+ evaluate,
14
16
  type LoadedToken,
15
17
  loadToken,
18
+ loadTokenAsync,
16
19
  } from "./authorizer.js";
17
20
  import { fromBase64, toBase64 } from "./base64.js";
18
21
  import {
@@ -31,8 +34,14 @@ export * from "./authorizer.js";
31
34
  export * from "./base64.js";
32
35
  export * from "./builder.js";
33
36
  export { SignatureError } from "./crypto.js";
34
- export { ExecutionError, type ExternFn, type Term } from "./datalog.js";
35
- export { ParseError } from "./parser.js";
37
+ export {
38
+ ExecutionError,
39
+ type ExternFn,
40
+ type Predicate,
41
+ type RunLimits,
42
+ type Term,
43
+ } from "./datalog.js";
44
+ export { type ParamValue, type Params, ParseError } from "./parser.js";
36
45
  export { ProtoError } from "./proto.js";
37
46
  export * from "./version.js";
38
47
 
@@ -70,6 +79,17 @@ export class Biscuit {
70
79
  verify(rootPublicKey: Uint8Array, rootAlgorithm: 0 | 1 = 0): VerifiedBiscuit {
71
80
  return new VerifiedBiscuit(loadToken(this.bytes, rootPublicKey, rootAlgorithm), this.bytes);
72
81
  }
82
+
83
+ /**
84
+ * `verify`, using WebCrypto Ed25519 where the platform has it — roughly ten
85
+ * times faster than the pure-JS path. Rejects exactly where `verify` throws.
86
+ */
87
+ async verifyAsync(rootPublicKey: Uint8Array, rootAlgorithm: 0 | 1 = 0): Promise<VerifiedBiscuit> {
88
+ return new VerifiedBiscuit(
89
+ await loadTokenAsync(this.bytes, rootPublicKey, rootAlgorithm),
90
+ this.bytes,
91
+ );
92
+ }
73
93
  }
74
94
 
75
95
  /** A token whose signature chain has been checked against a root key. */
@@ -88,6 +108,10 @@ export class VerifiedBiscuit {
88
108
  authorize(authorizerCode: string, options?: AuthorizeOptions): AuthorizationResult {
89
109
  return authorize(this.token, authorizerCode, options);
90
110
  }
111
+ /** Authorize, keeping the evaluated world available to `query`. */
112
+ evaluate(authorizerCode: string, options?: AuthorizeOptions): Evaluation {
113
+ return evaluate(this.token, authorizerCode, options);
114
+ }
91
115
  }
92
116
 
93
117
  export { generateKeypair, thirdPartyBlock };
package/src/parser.ts CHANGED
@@ -20,6 +20,55 @@ import {
20
20
 
21
21
  export class ParseError extends Error {}
22
22
 
23
+ /**
24
+ * A value bound to a `{name}` parameter. It becomes a TERM, never source text,
25
+ * so no string can change the shape of the program it is bound into.
26
+ */
27
+ export type ParamValue =
28
+ | string
29
+ | number
30
+ | bigint
31
+ | boolean
32
+ | null
33
+ | Date
34
+ | Uint8Array
35
+ | readonly ParamValue[]
36
+ | ReadonlySet<ParamValue>;
37
+
38
+ export type Params = Readonly<Record<string, ParamValue>>;
39
+
40
+ const I64_MIN = -(2n ** 63n);
41
+ const I64_MAX = 2n ** 63n - 1n;
42
+
43
+ function paramTerm(name: string, value: ParamValue): Term {
44
+ if (typeof value === "string") return { t: "str", v: value };
45
+ if (typeof value === "boolean") return { t: "bool", v: value };
46
+ if (value === null) return { t: "null" };
47
+ if (typeof value === "number") {
48
+ if (!Number.isSafeInteger(value))
49
+ throw new ParseError(`parameter {${name}}: ${value} is not a safe integer`);
50
+ return { t: "int", v: BigInt(value) };
51
+ }
52
+ if (typeof value === "bigint") {
53
+ if (value < I64_MIN || value > I64_MAX)
54
+ throw new ParseError(`parameter {${name}}: ${value} does not fit in i64`);
55
+ return { t: "int", v: value };
56
+ }
57
+ if (value instanceof Date) {
58
+ const ms = value.getTime();
59
+ if (Number.isNaN(ms)) throw new ParseError(`parameter {${name}}: invalid date`);
60
+ return { t: "date", v: BigInt(Math.floor(ms / 1000)) };
61
+ }
62
+ if (value instanceof Uint8Array) return { t: "bytes", v: value };
63
+ if (Array.isArray(value)) return { t: "array", v: value.map((x) => paramTerm(name, x)) };
64
+ if (value instanceof Set)
65
+ return { t: "set", v: normalizeSet([...value].map((x) => paramTerm(name, x))) };
66
+ throw new ParseError(`parameter {${name}}: no Datalog term for this value`);
67
+ }
68
+
69
+ /** `{name}` in term position; `{true}`, `{false}` and `{null}` stay one-element sets */
70
+ const PARAMETER = /^\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}/;
71
+
23
72
  export type Statement =
24
73
  | { k: "fact"; fact: Fact }
25
74
  | { k: "rule"; rule: Rule }
@@ -33,13 +82,20 @@ const NAME_CHAR = /[\p{L}\p{N}_:]/u;
33
82
  export class Parser {
34
83
  private i = 0;
35
84
  private readonly vars: Map<string, number>;
85
+ private readonly usedParams = new Set<string>();
36
86
  constructor(
37
87
  private readonly src: string,
38
88
  vars?: Map<string, number>,
89
+ private readonly params: Params = {},
39
90
  ) {
40
91
  this.vars = vars ?? new Map();
41
92
  }
42
93
 
94
+ /** names in `params` that the source never referred to */
95
+ unusedParameters(): string[] {
96
+ return Object.keys(this.params).filter((name) => !this.usedParams.has(name));
97
+ }
98
+
43
99
  /** id -> name, for printing rules back out */
44
100
  variableNames(): Map<number, string> {
45
101
  const out = new Map<number, string>();
@@ -188,7 +244,7 @@ export class Parser {
188
244
  return { t: "bytes", v: bytes };
189
245
  }
190
246
  if (this.peek("[")) return this.array(allowVariables);
191
- if (this.peek("{")) return this.setOrMap(allowVariables);
247
+ if (this.peek("{")) return this.parameter() ?? this.setOrMap(allowVariables);
192
248
 
193
249
  const m = /^-?\d+/.exec(this.src.slice(this.i));
194
250
  if (m) {
@@ -200,6 +256,16 @@ export class Parser {
200
256
  );
201
257
  }
202
258
 
259
+ private parameter(): Term | null {
260
+ const m = PARAMETER.exec(this.src.slice(this.i));
261
+ if (!m || m[1] === "true" || m[1] === "false" || m[1] === "null") return null;
262
+ const name = m[1];
263
+ if (!Object.hasOwn(this.params, name)) throw new ParseError(`unbound parameter {${name}}`);
264
+ this.i += m[0].length;
265
+ this.usedParams.add(name);
266
+ return paramTerm(name, this.params[name]);
267
+ }
268
+
203
269
  private array(allowVariables: boolean): Term {
204
270
  this.expect("[");
205
271
  const items: Term[] = [];
@@ -603,4 +669,5 @@ export class Parser {
603
669
  }
604
670
  }
605
671
 
606
- export const parse = (src: string): Statement[] => new Parser(src).parse();
672
+ export const parse = (src: string, params?: Params): Statement[] =>
673
+ new Parser(src, undefined, params).parse();
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2022-2026 statewalker
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.