@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/README.md +81 -12
- package/dist/authorizer.d.ts +41 -4
- package/dist/authorizer.d.ts.map +1 -1
- package/dist/builder.d.ts +6 -1
- package/dist/builder.d.ts.map +1 -1
- package/dist/crypto.d.ts +7 -0
- package/dist/crypto.d.ts.map +1 -1
- package/dist/datalog.d.ts +14 -0
- package/dist/datalog.d.ts.map +1 -1
- package/dist/index.d.ts +10 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +425 -131
- package/dist/parser.d.ts +14 -3
- package/dist/parser.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/authorizer.ts +127 -27
- package/src/builder.ts +31 -9
- package/src/crypto.ts +164 -18
- package/src/datalog.ts +60 -4
- package/src/index.ts +26 -2
- package/src/parser.ts +84 -15
package/src/datalog.ts
CHANGED
|
@@ -570,6 +570,8 @@ function* combine(
|
|
|
570
570
|
facts: FactIndex,
|
|
571
571
|
bindings: Bindings,
|
|
572
572
|
variables: Set<number>,
|
|
573
|
+
/** called once per candidate fact: the join is where a budget has to bite */
|
|
574
|
+
tick: () => void,
|
|
573
575
|
): Generator<[Origin, Bindings]> {
|
|
574
576
|
if (predicates.length === 0) {
|
|
575
577
|
for (const v of variables) if (!bindings.has(v)) return;
|
|
@@ -578,6 +580,7 @@ function* combine(
|
|
|
578
580
|
}
|
|
579
581
|
const [head, ...rest] = predicates;
|
|
580
582
|
for (const [origin, fact] of facts.get(`${head.name}/${head.terms.length}`) ?? []) {
|
|
583
|
+
tick();
|
|
581
584
|
if (!matchPredicate(head, fact.predicate)) continue;
|
|
582
585
|
const next = new Map(bindings);
|
|
583
586
|
let ok = true;
|
|
@@ -592,7 +595,7 @@ function* combine(
|
|
|
592
595
|
}
|
|
593
596
|
}
|
|
594
597
|
if (!ok) continue;
|
|
595
|
-
for (const [subOrigin, result] of combine(rest, facts, next, variables))
|
|
598
|
+
for (const [subOrigin, result] of combine(rest, facts, next, variables, tick))
|
|
596
599
|
yield [subOrigin.union(origin), result];
|
|
597
600
|
}
|
|
598
601
|
}
|
|
@@ -605,6 +608,25 @@ export class World {
|
|
|
605
608
|
iterations = 0;
|
|
606
609
|
private generation = 0;
|
|
607
610
|
private indexCache = new Map<string, { generation: number; index: FactIndex }>();
|
|
611
|
+
/** wall-clock budget of the evaluation in progress; Infinity outside one */
|
|
612
|
+
private deadline = Number.POSITIVE_INFINITY;
|
|
613
|
+
private steps = 0;
|
|
614
|
+
|
|
615
|
+
/**
|
|
616
|
+
* The time limit, enforced where the work is. Checking only between
|
|
617
|
+
* iterations let one combinatorial rule — or one check that derives nothing —
|
|
618
|
+
* run for seconds whatever `maxTimeMs` said. Polled every 1024 candidate
|
|
619
|
+
* facts, so the clock costs nothing measurable.
|
|
620
|
+
*/
|
|
621
|
+
private readonly tick = (): void => {
|
|
622
|
+
if ((++this.steps & 1023) === 0 && Date.now() >= this.deadline)
|
|
623
|
+
throw new ExecutionError("Timeout");
|
|
624
|
+
};
|
|
625
|
+
|
|
626
|
+
/** Close the budget: queries made after an evaluation are not charged against it. */
|
|
627
|
+
endBudget(): void {
|
|
628
|
+
this.deadline = Number.POSITIVE_INFINITY;
|
|
629
|
+
}
|
|
608
630
|
|
|
609
631
|
addFact(origin: Origin, fact: Fact): void {
|
|
610
632
|
let bucket = this.facts.get(origin.key);
|
|
@@ -649,13 +671,31 @@ export class World {
|
|
|
649
671
|
|
|
650
672
|
/** naive fixpoint: apply every rule until no new fact appears */
|
|
651
673
|
run(limits: RunLimits = DEFAULT_LIMITS): void {
|
|
674
|
+
// The budget stays open after `run` returns, so the checks and policies the
|
|
675
|
+
// authorizer evaluates next are bounded by it too; `endBudget` closes it.
|
|
652
676
|
const deadline = Date.now() + limits.maxTimeMs;
|
|
677
|
+
this.deadline = deadline;
|
|
653
678
|
let index = 0;
|
|
654
679
|
for (;;) {
|
|
655
680
|
const generated: [Origin, Fact][] = [];
|
|
681
|
+
// Distinct facts this iteration adds. Counted as they are derived, so
|
|
682
|
+
// `maxFacts` fires the moment the world WOULD exceed it — the verdict the
|
|
683
|
+
// end-of-iteration check reaches, without enumerating the rest of the
|
|
684
|
+
// product first. On the last permitted iteration the reference reports
|
|
685
|
+
// TooManyIterations ahead of TooManyFacts, so the early exit stands aside.
|
|
686
|
+
const fresh = new Set<string>();
|
|
687
|
+
const base = this.factCount();
|
|
688
|
+
const lastIteration = index + 1 === limits.maxIterations;
|
|
656
689
|
for (const { origin, trusted, rule } of this.rules) {
|
|
657
690
|
const facts = this.visible(trusted);
|
|
658
|
-
for (const [o, f] of this.apply(rule, facts, origin))
|
|
691
|
+
for (const [o, f] of this.apply(rule, facts, origin)) {
|
|
692
|
+
generated.push([o, f]);
|
|
693
|
+
const key = factKey(f);
|
|
694
|
+
if (this.facts.get(o.key)?.items.has(key)) continue;
|
|
695
|
+
fresh.add(`${o.key}|${key}`);
|
|
696
|
+
if (!lastIteration && base + fresh.size >= limits.maxFacts)
|
|
697
|
+
throw new ExecutionError("TooManyFacts");
|
|
698
|
+
}
|
|
659
699
|
}
|
|
660
700
|
const before = this.factCount();
|
|
661
701
|
for (const [o, f] of generated) this.addFact(o, f);
|
|
@@ -671,7 +711,7 @@ export class World {
|
|
|
671
711
|
|
|
672
712
|
*apply(rule: Rule, facts: FactIndex, ruleOrigin: number): Generator<[Origin, Fact]> {
|
|
673
713
|
const variables = variablesOf(rule);
|
|
674
|
-
for (const [origin, bindings] of combine(rule.body, facts, new Map(), variables)) {
|
|
714
|
+
for (const [origin, bindings] of combine(rule.body, facts, new Map(), variables, this.tick)) {
|
|
675
715
|
let pass = true;
|
|
676
716
|
for (const ops of rule.expressions) {
|
|
677
717
|
const res = evaluateExpression(ops, bindings, this.externs);
|
|
@@ -699,6 +739,16 @@ export class World {
|
|
|
699
739
|
}
|
|
700
740
|
}
|
|
701
741
|
|
|
742
|
+
/** every distinct fact `rule` derives from the facts `trusted` can see */
|
|
743
|
+
query(rule: Rule, trusted: TrustedOrigins): Predicate[] {
|
|
744
|
+
const seen = new Map<string, Predicate>();
|
|
745
|
+
for (const [, fact] of this.apply(rule, this.visible(trusted), AUTHORIZER)) {
|
|
746
|
+
const key = factKey(fact);
|
|
747
|
+
if (!seen.has(key)) seen.set(key, fact.predicate);
|
|
748
|
+
}
|
|
749
|
+
return [...seen.values()];
|
|
750
|
+
}
|
|
751
|
+
|
|
702
752
|
/** `check if` / policies: does at least one combination match? */
|
|
703
753
|
queryMatch(rule: Rule, origin: number, trusted: TrustedOrigins): boolean {
|
|
704
754
|
for (const _ of this.apply(rule, this.visible(trusted), origin)) return true;
|
|
@@ -709,7 +759,13 @@ export class World {
|
|
|
709
759
|
queryMatchAll(rule: Rule, trusted: TrustedOrigins): boolean {
|
|
710
760
|
const variables = variablesOf(rule);
|
|
711
761
|
let found = false;
|
|
712
|
-
for (const [, bindings] of combine(
|
|
762
|
+
for (const [, bindings] of combine(
|
|
763
|
+
rule.body,
|
|
764
|
+
this.visible(trusted),
|
|
765
|
+
new Map(),
|
|
766
|
+
variables,
|
|
767
|
+
this.tick,
|
|
768
|
+
)) {
|
|
713
769
|
found = true;
|
|
714
770
|
for (const ops of rule.expressions) {
|
|
715
771
|
const res = evaluateExpression(ops, bindings, this.externs);
|
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 {
|
|
35
|
-
|
|
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 }
|
|
@@ -27,19 +76,31 @@ export type Statement =
|
|
|
27
76
|
| { k: "policy"; kind: "allow" | "deny"; queries: Rule[] }
|
|
28
77
|
| { k: "blockScope"; scopes: Scope[] };
|
|
29
78
|
|
|
30
|
-
|
|
31
|
-
|
|
79
|
+
/**
|
|
80
|
+
* A predicate or variable name is one or more of `[A-Za-z0-9_:]`, and any of them
|
|
81
|
+
* may come first — ASCII only. That is what the reference parser accepts, measured
|
|
82
|
+
* rather than read from the specification (`tests/grammar-cases.ts`): `_m`, `1a`
|
|
83
|
+
* and `::` are names, `ärger` is not.
|
|
84
|
+
*/
|
|
85
|
+
const NAME_CHAR = /[A-Za-z0-9_:]/;
|
|
32
86
|
|
|
33
87
|
export class Parser {
|
|
34
88
|
private i = 0;
|
|
35
89
|
private readonly vars: Map<string, number>;
|
|
90
|
+
private readonly usedParams = new Set<string>();
|
|
36
91
|
constructor(
|
|
37
92
|
private readonly src: string,
|
|
38
93
|
vars?: Map<string, number>,
|
|
94
|
+
private readonly params: Params = {},
|
|
39
95
|
) {
|
|
40
96
|
this.vars = vars ?? new Map();
|
|
41
97
|
}
|
|
42
98
|
|
|
99
|
+
/** names in `params` that the source never referred to */
|
|
100
|
+
unusedParameters(): string[] {
|
|
101
|
+
return Object.keys(this.params).filter((name) => !this.usedParams.has(name));
|
|
102
|
+
}
|
|
103
|
+
|
|
43
104
|
/** id -> name, for printing rules back out */
|
|
44
105
|
variableNames(): Map<number, string> {
|
|
45
106
|
const out = new Map<number, string>();
|
|
@@ -99,9 +160,8 @@ export class Parser {
|
|
|
99
160
|
this.i += k.length;
|
|
100
161
|
return true;
|
|
101
162
|
}
|
|
102
|
-
/**
|
|
163
|
+
/** the name directly after `$` — `$ x` is not a variable, as in the reference */
|
|
103
164
|
private variableName(): string {
|
|
104
|
-
this.ws();
|
|
105
165
|
const start = this.i;
|
|
106
166
|
while (this.i < this.src.length && NAME_CHAR.test(this.src[this.i])) this.i++;
|
|
107
167
|
if (this.i === start) throw new ParseError(`expected a variable name at offset ${this.i}`);
|
|
@@ -111,10 +171,8 @@ export class Parser {
|
|
|
111
171
|
private name(): string {
|
|
112
172
|
this.ws();
|
|
113
173
|
const start = this.i;
|
|
114
|
-
if (this.i >= this.src.length || !NAME_START.test(this.src[this.i]))
|
|
115
|
-
throw new ParseError(`expected a name at offset ${this.i}`);
|
|
116
|
-
this.i++;
|
|
117
174
|
while (this.i < this.src.length && NAME_CHAR.test(this.src[this.i])) this.i++;
|
|
175
|
+
if (this.i === start) throw new ParseError(`expected a name at offset ${this.i}`);
|
|
118
176
|
return this.src.slice(start, this.i);
|
|
119
177
|
}
|
|
120
178
|
|
|
@@ -188,7 +246,7 @@ export class Parser {
|
|
|
188
246
|
return { t: "bytes", v: bytes };
|
|
189
247
|
}
|
|
190
248
|
if (this.peek("[")) return this.array(allowVariables);
|
|
191
|
-
if (this.peek("{")) return this.setOrMap(allowVariables);
|
|
249
|
+
if (this.peek("{")) return this.parameter() ?? this.setOrMap(allowVariables);
|
|
192
250
|
|
|
193
251
|
const m = /^-?\d+/.exec(this.src.slice(this.i));
|
|
194
252
|
if (m) {
|
|
@@ -200,6 +258,16 @@ export class Parser {
|
|
|
200
258
|
);
|
|
201
259
|
}
|
|
202
260
|
|
|
261
|
+
private parameter(): Term | null {
|
|
262
|
+
const m = PARAMETER.exec(this.src.slice(this.i));
|
|
263
|
+
if (!m || m[1] === "true" || m[1] === "false" || m[1] === "null") return null;
|
|
264
|
+
const name = m[1];
|
|
265
|
+
if (!Object.hasOwn(this.params, name)) throw new ParseError(`unbound parameter {${name}}`);
|
|
266
|
+
this.i += m[0].length;
|
|
267
|
+
this.usedParams.add(name);
|
|
268
|
+
return paramTerm(name, this.params[name]);
|
|
269
|
+
}
|
|
270
|
+
|
|
203
271
|
private array(allowVariables: boolean): Term {
|
|
204
272
|
this.expect("[");
|
|
205
273
|
const items: Term[] = [];
|
|
@@ -250,12 +318,12 @@ export class Parser {
|
|
|
250
318
|
predicate(allowVariables = true): Predicate {
|
|
251
319
|
const name = this.name();
|
|
252
320
|
this.expect("(");
|
|
321
|
+
// at least one term, as in the reference: `f()` is not a predicate
|
|
322
|
+
if (this.peek(")")) throw new ParseError(`predicate ${name} takes at least one term`);
|
|
253
323
|
const terms: Term[] = [];
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
} while (this.eat(","));
|
|
258
|
-
}
|
|
324
|
+
do {
|
|
325
|
+
terms.push(this.term(allowVariables));
|
|
326
|
+
} while (this.eat(","));
|
|
259
327
|
this.expect(")");
|
|
260
328
|
return { name, terms };
|
|
261
329
|
}
|
|
@@ -536,7 +604,7 @@ export class Parser {
|
|
|
536
604
|
const save = this.i;
|
|
537
605
|
try {
|
|
538
606
|
this.ws();
|
|
539
|
-
if (!
|
|
607
|
+
if (!NAME_CHAR.test(this.src[this.i] ?? "")) return null;
|
|
540
608
|
const p = this.predicate();
|
|
541
609
|
this.ws();
|
|
542
610
|
const rest = this.src.slice(this.i);
|
|
@@ -603,4 +671,5 @@ export class Parser {
|
|
|
603
671
|
}
|
|
604
672
|
}
|
|
605
673
|
|
|
606
|
-
export const parse = (src: string): Statement[] =>
|
|
674
|
+
export const parse = (src: string, params?: Params): Statement[] =>
|
|
675
|
+
new Parser(src, undefined, params).parse();
|