@statewalker/webrun-biscuit 0.2.2 → 0.3.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/README.md +79 -34
- package/dist/code.d.ts +30 -0
- package/dist/code.d.ts.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +131 -31
- package/dist/print.d.ts +19 -0
- package/dist/print.d.ts.map +1 -1
- package/dist/revocation.d.ts +25 -0
- package/dist/revocation.d.ts.map +1 -0
- package/package.json +7 -4
- package/src/code.ts +53 -0
- package/src/index.ts +21 -0
- package/src/print.ts +57 -1
- package/src/revocation.ts +44 -0
package/README.md
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
# @statewalker/webrun-biscuit
|
|
2
2
|
|
|
3
|
+
## What it is
|
|
4
|
+
|
|
3
5
|
[Biscuit](https://biscuitsec.org) authorization tokens in pure TypeScript: the protobuf codec, the
|
|
4
6
|
signature chain, the Datalog engine, the text parser, the authorizer and the token builder. No WASM,
|
|
5
|
-
no Node built-ins in `src/`, two runtime dependencies. It runs
|
|
6
|
-
|
|
7
|
+
no Node built-ins in `src/`, two runtime dependencies. It runs in Node, browsers, Workers and Durable
|
|
8
|
+
Objects. It mints, attenuates, seals, verifies and authorizes tokens, and evaluates Datalog with or
|
|
9
|
+
without a token.
|
|
7
10
|
|
|
8
|
-
## Why
|
|
11
|
+
## Why it exists
|
|
9
12
|
|
|
10
13
|
There is no other pure JS/TS Biscuit implementation. npm carries `@biscuit-auth/biscuit-wasm` — the
|
|
11
14
|
Rust crate compiled to WebAssembly — and a web-components package built on it. Nothing else.
|
|
@@ -18,10 +21,10 @@ megabyte of WebAssembly to do so.
|
|
|
18
21
|
So this is a reimplementation, and the entire testing strategy below exists because a reimplementation
|
|
19
22
|
of a security primitive is only worth having if you can show it agrees with the original.
|
|
20
23
|
|
|
21
|
-
##
|
|
24
|
+
## How to use
|
|
22
25
|
|
|
23
26
|
```sh
|
|
24
|
-
|
|
27
|
+
pnpm add @statewalker/webrun-biscuit
|
|
25
28
|
```
|
|
26
29
|
|
|
27
30
|
Two runtime dependencies, both external to the published bundle:
|
|
@@ -49,6 +52,8 @@ const result = verified.authorize('operation("read"); allow if user("alice");');
|
|
|
49
52
|
type system then prevents authorizing a token whose signature chain was never checked, which is the
|
|
50
53
|
mistake worth designing against.
|
|
51
54
|
|
|
55
|
+
## Examples
|
|
56
|
+
|
|
52
57
|
### Parameters: never splice a value into Datalog
|
|
53
58
|
|
|
54
59
|
Anything that did not come from you — a user id, a request path, a role name —
|
|
@@ -67,6 +72,50 @@ arrays and `Set`s are accepted. An unbound parameter and an unused one are both
|
|
|
67
72
|
`ParseError`, as in the reference; `{true}`, `{false}` and `{null}` remain one-element
|
|
68
73
|
sets.
|
|
69
74
|
|
|
75
|
+
### Building code with values: the `Datalog` template
|
|
76
|
+
|
|
77
|
+
`Datalog` turns the rule above into the easy path. `add` is a tagged template, and every
|
|
78
|
+
`${value}` in it becomes a `{pN}` parameter, so a block is written as it reads and no value is
|
|
79
|
+
ever spliced into its text:
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import { Biscuit, datalog } from "@statewalker/webrun-biscuit";
|
|
83
|
+
|
|
84
|
+
const code = datalog`user(${userId});`
|
|
85
|
+
.add`check if time($t), $t < ${new Date(Date.now() + 3_600_000)};`;
|
|
86
|
+
// code.source: "user({p0});\ncheck if time($t), $t < {p1};"
|
|
87
|
+
const token = Biscuit.build(root.secretKey, code.source, { params: code.params });
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
`raw(text)` appends source that interpolates nothing, for rules you wrote yourself.
|
|
91
|
+
|
|
92
|
+
### Revocation
|
|
93
|
+
|
|
94
|
+
Each block has a revocation id (lowercase hex), and a token is revoked when any of its ids is in
|
|
95
|
+
your revoked set. Revoking an authority block's id revokes every token attenuated from it. Check
|
|
96
|
+
after `verify`, before authorizing:
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
import { assertNotRevoked, isRevoked } from "@statewalker/webrun-biscuit";
|
|
100
|
+
|
|
101
|
+
const verified = Biscuit.fromBase64(token).verify(root.publicKey);
|
|
102
|
+
if (isRevoked(verified, revokedIds)) throw new Error("revoked"); // revokedIds: Set<string>
|
|
103
|
+
assertNotRevoked(verified, revokedIds); // the same, throwing RevokedTokenError
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### Showing a token: `print`
|
|
107
|
+
|
|
108
|
+
`verified.print()` returns each block as Datalog source, authority first: the text an approval
|
|
109
|
+
screen or a log shows, and the text that builds the same block again. `printBlock`, `printRule`,
|
|
110
|
+
`printCheck`, `printPolicy`, `printPredicate` and `printTerm` are exported for pieces of it.
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
Biscuit.build(root.secretKey, 'user("alice");').attenuate('check if operation("read");')
|
|
114
|
+
.verify(root.publicKey)
|
|
115
|
+
.print();
|
|
116
|
+
// ['user("alice");', 'check if operation("read");']
|
|
117
|
+
```
|
|
118
|
+
|
|
70
119
|
### Querying the evaluated world
|
|
71
120
|
|
|
72
121
|
`evaluate` is `authorize` that keeps the world, so facts can be read back — the
|
|
@@ -75,9 +124,9 @@ block and authorizer facts) unless it says `trusting`, so an attenuation block c
|
|
|
75
124
|
inject what it reads:
|
|
76
125
|
|
|
77
126
|
```ts
|
|
78
|
-
const ev = verified.evaluate("allow if true;
|
|
127
|
+
const ev = verified.evaluate('operation("read"); allow if true;');
|
|
79
128
|
ev.result; // { kind: "ok", policy: 0 }
|
|
80
|
-
ev.query("claim($s) <-
|
|
129
|
+
ev.query("claim($s) <- user($s)"); // [{ name: "claim", terms: [{ t: "str", v: "alice" }] }]
|
|
81
130
|
```
|
|
82
131
|
|
|
83
132
|
Pass `null` instead of a token to decide from the authorizer's own facts and rules:
|
|
@@ -102,7 +151,7 @@ consume one list of signature checks, so neither can skip a check the other make
|
|
|
102
151
|
const verified = await Biscuit.fromBase64(token).verifyAsync(root.publicKey);
|
|
103
152
|
```
|
|
104
153
|
|
|
105
|
-
###
|
|
154
|
+
### secp256r1, key ids and third-party blocks
|
|
106
155
|
|
|
107
156
|
secp256r1 works the same way, with the algorithm passed at both ends:
|
|
108
157
|
|
|
@@ -121,7 +170,8 @@ import { peekRootKeyId } from "@statewalker/webrun-biscuit";
|
|
|
121
170
|
const key = roots[peekRootKeyId(bytes) ?? 0];
|
|
122
171
|
```
|
|
123
172
|
|
|
124
|
-
A third party can sign a block without ever holding the token
|
|
173
|
+
A third party can sign a block without ever holding the token. The token must not be sealed —
|
|
174
|
+
`appendThirdParty` on a sealed token throws `BuilderError`:
|
|
125
175
|
|
|
126
176
|
```ts
|
|
127
177
|
const request = Biscuit.fromBase64(token).thirdPartyRequest();
|
|
@@ -141,11 +191,13 @@ Each module depends only on the ones above it.
|
|
|
141
191
|
| `src/crypto.ts` | Ed25519 + secp256r1 chain, payload v0/v1, sealing, external signatures |
|
|
142
192
|
| `src/datalog.ts` | term model, canonical keys, origin-tracked fixpoint engine, expression VM |
|
|
143
193
|
| `src/parser.ts` | Datalog text syntax to the runtime model |
|
|
144
|
-
| `src/print.ts` | pretty-printer for error messages
|
|
194
|
+
| `src/print.ts` | pretty-printer for error messages, world snapshots and `print()` |
|
|
145
195
|
| `src/version.ts` | block version bounds and Datalog feature gates |
|
|
146
196
|
| `src/authorizer.ts` | symbol resolution, block loading, authorization, world snapshots |
|
|
147
197
|
| `src/builder.ts` | minting, attenuation, sealing, third-party blocks |
|
|
148
198
|
| `src/base64.ts` | URL-safe base64, runtime-agnostic |
|
|
199
|
+
| `src/code.ts` | the `Datalog` template: source with its values bound as parameters |
|
|
200
|
+
| `src/revocation.ts` | `isRevoked`, `assertNotRevoked` against a revoked-id set |
|
|
149
201
|
| `src/index.ts` | the public API — `Biscuit`, `VerifiedBiscuit` |
|
|
150
202
|
|
|
151
203
|
The one awkward edge is that `builder` imports `parseAuthorizer` and `DEFAULT_SYMBOLS` from
|
|
@@ -174,7 +226,7 @@ millisecond, which is unreachably tight for a cold JS engine; this one defaults
|
|
|
174
226
|
exposed to untrusted tokens should lower it deliberately rather than treat the default as a
|
|
175
227
|
denial-of-service bound. The limit is enforced where the work happens — inside the join, for rules,
|
|
176
228
|
checks and policies alike — so it bounds a single combinatorial rule, not only the number of
|
|
177
|
-
iterations
|
|
229
|
+
iterations.
|
|
178
230
|
|
|
179
231
|
### The corpus is fetched, not vendored
|
|
180
232
|
|
|
@@ -198,11 +250,13 @@ not to change the verdict.
|
|
|
198
250
|
|
|
199
251
|
### A green suite is not the claim; a suite that can fail is
|
|
200
252
|
|
|
253
|
+
Run from `packages/webrun-biscuit` (or prefix with `pnpm --filter @statewalker/webrun-biscuit`):
|
|
254
|
+
|
|
201
255
|
```sh
|
|
202
|
-
pnpm test # the main suite
|
|
203
|
-
pnpm test:cross # against the reference implementation
|
|
256
|
+
pnpm test # the main suite (fetches the corpus first)
|
|
257
|
+
pnpm test:cross # against the reference implementation
|
|
204
258
|
pnpm test:all # both
|
|
205
|
-
pnpm mutate # inject
|
|
259
|
+
pnpm mutate # inject known defects, require the suite to catch each
|
|
206
260
|
pnpm build # dist/ plus declarations
|
|
207
261
|
```
|
|
208
262
|
|
|
@@ -221,13 +275,13 @@ pnpm build # dist/ plus declarations
|
|
|
221
275
|
| `11-parameters` | `{name}` binding, hostile strings, unbound and unused parameters |
|
|
222
276
|
| `12-evaluate` | queries, their scope, token-less evaluation, failed-check rule text |
|
|
223
277
|
|
|
224
|
-
`scripts/mutate.mjs` is the check on all of it. It injects
|
|
278
|
+
`scripts/mutate.mjs` is the check on all of it. It injects seventeen defects — a lenient protobuf decoder,
|
|
225
279
|
wrapping i64 arithmetic, `check all` degraded to `check if`, a universally trusting authorizer, `deny`
|
|
226
280
|
treated as `allow`, unchecked seal signatures, an async verifier that ignores WebCrypto's verdict, a
|
|
227
281
|
query that can read an attenuation block's facts, silently ignored parameters, zero-term predicates, non-ASCII names, missing version bounds,
|
|
228
282
|
and more — and requires each to break at least one test. A surviving mutation is a hole in the tests,
|
|
229
|
-
not a success. All
|
|
230
|
-
|
|
283
|
+
not a success. All of them are caught; the forged-seal and matching-`deny` mutations are the ones a
|
|
284
|
+
suite without `06-builder`'s negative cases would miss.
|
|
231
285
|
|
|
232
286
|
Each mutation's `find` string is a literal excerpt of the source, and must match exactly once. That is
|
|
233
287
|
why a reformat of `src/` makes the harness fail loudly rather than quietly stop testing anything.
|
|
@@ -254,7 +308,7 @@ because uniform sampling produces mostly `noMatchingPolicy`, where the engine ba
|
|
|
254
308
|
That suite is kept out of `pnpm test` on purpose, and it skips gracefully when the reference is not
|
|
255
309
|
installed, so it never becomes a hard dependency of the main suite.
|
|
256
310
|
|
|
257
|
-
|
|
311
|
+
### What will surprise you
|
|
258
312
|
|
|
259
313
|
**The reference build's first `authorize` call reports a timeout that is not real.** Every fresh
|
|
260
314
|
Authorizer reports a `RunLimit` timeout on its first call even with a 60-second budget; later calls on
|
|
@@ -275,25 +329,23 @@ reliable accessor.
|
|
|
275
329
|
walking up to `node_modules`, reads the `.wasm`, and supplies its imports by hand. Running Node with
|
|
276
330
|
`--experimental-wasm-modules` does work, but needing a flag for `pnpm test` is worse.
|
|
277
331
|
|
|
278
|
-
**
|
|
279
|
-
|
|
280
|
-
fetch
|
|
281
|
-
files
|
|
282
|
-
are also pooled at six with retries, because `raw.githubusercontent.com` resets connections when
|
|
332
|
+
**An interrupted corpus download must not look complete.** `scripts/fetch-samples.mjs` writes the
|
|
333
|
+
`samples.json` manifest last, and its "already fetched" guard checks every file the manifest names;
|
|
334
|
+
otherwise an interrupted fetch would leave a directory every later run skips, and the tests would fail
|
|
335
|
+
on missing files. Downloads are pooled at six with retries, because `raw.githubusercontent.com` resets connections when
|
|
283
336
|
several dozen requests arrive at once and surfaces it as a bare `TypeError: fetch failed`.
|
|
284
337
|
|
|
285
338
|
**`pnpm test` fetches the corpus explicitly, not through `pretest`.** pnpm does not run `pre`/`post`
|
|
286
339
|
scripts by default, so a `pretest` hook would silently never fire and the suite would fail on a clean
|
|
287
340
|
checkout with missing samples.
|
|
288
341
|
|
|
289
|
-
|
|
342
|
+
### Known deviations from the reference
|
|
290
343
|
|
|
291
344
|
**Names follow the reference parser, not the specification's prose.** A predicate or variable name
|
|
292
345
|
is one or more of `[A-Za-z0-9_:]`, ASCII, with any of them first — so `_m`, `1a` and `::` are names
|
|
293
346
|
and `ärger` is not — and a predicate takes at least one term. That is what
|
|
294
347
|
`@biscuit-auth/biscuit-wasm` accepts; `tests/grammar-cases.ts` records it and `05-grammar` re-asks the
|
|
295
|
-
reference, including for generated names.
|
|
296
|
-
accepted `f()`.
|
|
348
|
+
reference, including for generated names.
|
|
297
349
|
|
|
298
350
|
**Regex uses JS `RegExp`, not RE2.** Every corpus pattern matches, but backreferences and lookaround
|
|
299
351
|
are accepted where Rust would reject them. Documented, not enforced.
|
|
@@ -319,13 +371,6 @@ third-party flow works and is tested, but the cross-implementation one does not.
|
|
|
319
371
|
Semi-naive evaluation is not implemented either. The fixpoint re-derives every fact each round; the
|
|
320
372
|
index makes that cheap at token scale, but not at request scale with large fact sets.
|
|
321
373
|
|
|
322
|
-
## Design notes
|
|
323
|
-
|
|
324
|
-
`docs/webrun-biscuit/` in this repository carries the working documents from the implementation
|
|
325
|
-
sessions: how the reference actually works, why `mapbox/pbf` was rejected for the protobuf layer, what
|
|
326
|
-
the red-green cycle caught, the corpus findings, and what it took to make random differential testing
|
|
327
|
-
actually detect a defect.
|
|
328
|
-
|
|
329
374
|
## License
|
|
330
375
|
|
|
331
|
-
MIT
|
|
376
|
+
MIT
|
package/dist/code.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Datalog source with its values bound as parameters.
|
|
3
|
+
*
|
|
4
|
+
* const code = new Datalog().add`user(${userId});`.add`check if time($t), $t < ${expiry};`;
|
|
5
|
+
* Biscuit.build(root.secretKey, code.source, { params: code.params });
|
|
6
|
+
*
|
|
7
|
+
* `add` is a tagged template: every `${value}` becomes a `{pN}` parameter, bound
|
|
8
|
+
* as a TERM by the parser. A value is never spliced into the source text, so no
|
|
9
|
+
* string — `"); role("admin` included — can change the program's shape.
|
|
10
|
+
*/
|
|
11
|
+
import type { ParamValue } from "./parser.js";
|
|
12
|
+
export declare class Datalog {
|
|
13
|
+
private readonly lines;
|
|
14
|
+
private readonly bound;
|
|
15
|
+
private next;
|
|
16
|
+
/** Append source. Every `${value}` becomes a `{pN}` parameter — a term, never text. */
|
|
17
|
+
add(strings: TemplateStringsArray, ...values: ParamValue[]): this;
|
|
18
|
+
/**
|
|
19
|
+
* Append source that interpolates nothing. Only for text you wrote yourself:
|
|
20
|
+
* a `{name}` in it must not collide with the `{pN}` names `add` generates.
|
|
21
|
+
*/
|
|
22
|
+
raw(source: string): this;
|
|
23
|
+
/** the source, one `add`/`raw` call per line */
|
|
24
|
+
get source(): string;
|
|
25
|
+
/** the values the source's `{pN}` parameters are bound to */
|
|
26
|
+
get params(): Readonly<Record<string, ParamValue>>;
|
|
27
|
+
}
|
|
28
|
+
/** `datalog\`user(${id});\`` — a new `Datalog` holding one parameterised line. */
|
|
29
|
+
export declare function datalog(strings: TemplateStringsArray, ...values: ParamValue[]): Datalog;
|
|
30
|
+
//# sourceMappingURL=code.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"code.d.ts","sourceRoot":"","sources":["../src/code.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE9C,qBAAa,OAAO;IAClB,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAgB;IACtC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAkC;IACxD,OAAO,CAAC,IAAI,CAAK;IAEjB,uFAAuF;IACvF,GAAG,CAAC,OAAO,EAAE,oBAAoB,EAAE,GAAG,MAAM,EAAE,UAAU,EAAE,GAAG,IAAI,CAShE;IAED;;;OAGG;IACH,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAGxB;IAED,gDAAgD;IAChD,IAAI,MAAM,IAAI,MAAM,CAEnB;IAED,6DAA6D;IAC7D,IAAI,MAAM,IAAI,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,CAEjD;CACF;AAED,kFAAkF;AAClF,wBAAgB,OAAO,CAAC,OAAO,EAAE,oBAAoB,EAAE,GAAG,MAAM,EAAE,UAAU,EAAE,GAAG,OAAO,CAEvF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -11,10 +11,13 @@ import { type BuildOptions, generateKeypair, type ThirdPartyResponse, thirdParty
|
|
|
11
11
|
export * from "./authorizer.js";
|
|
12
12
|
export * from "./base64.js";
|
|
13
13
|
export * from "./builder.js";
|
|
14
|
+
export * from "./code.js";
|
|
14
15
|
export { SignatureError } from "./crypto.js";
|
|
15
16
|
export { ExecutionError, type ExternFn, type Predicate, type RunLimits, type Term, } from "./datalog.js";
|
|
16
17
|
export { type Params, type ParamValue, ParseError } from "./parser.js";
|
|
18
|
+
export { type PrintableBlock, printBlock, printCheck, printPolicy, printPredicate, printRule, printTerm, } from "./print.js";
|
|
17
19
|
export { ProtoError } from "./proto.js";
|
|
20
|
+
export * from "./revocation.js";
|
|
18
21
|
export * from "./version.js";
|
|
19
22
|
/** An unverified token: it can be attenuated and re-serialized. */
|
|
20
23
|
export declare class Biscuit {
|
|
@@ -42,6 +45,10 @@ export declare class VerifiedBiscuit {
|
|
|
42
45
|
readonly bytes: Uint8Array;
|
|
43
46
|
constructor(token: LoadedToken, bytes: Uint8Array);
|
|
44
47
|
get revocationIds(): string[];
|
|
48
|
+
/** Whether any block's revocation id is in `revoked` — see `isRevoked`. */
|
|
49
|
+
isRevoked(revoked: ReadonlySet<string>): boolean;
|
|
50
|
+
/** Every block as Datalog source, authority first — see `printBlock`. */
|
|
51
|
+
print(): string[];
|
|
45
52
|
/** the issuer's key identifier, when the token carries one */
|
|
46
53
|
get rootKeyId(): number | undefined;
|
|
47
54
|
authorize(authorizerCode: string, options?: AuthorizeOptions): AuthorizationResult;
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EACL,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EAErB,KAAK,UAAU,EAEf,KAAK,WAAW,EAGjB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAGL,KAAK,YAAY,EAEjB,eAAe,EAEf,KAAK,kBAAkB,EACvB,eAAe,EAEhB,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EACL,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EAErB,KAAK,UAAU,EAEf,KAAK,WAAW,EAGjB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAGL,KAAK,YAAY,EAEjB,eAAe,EAEf,KAAK,kBAAkB,EACvB,eAAe,EAEhB,MAAM,cAAc,CAAC;AAItB,cAAc,iBAAiB,CAAC;AAChC,cAAc,aAAa,CAAC;AAC5B,cAAc,cAAc,CAAC;AAC7B,cAAc,WAAW,CAAC;AAC1B,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EACL,cAAc,EACd,KAAK,QAAQ,EACb,KAAK,SAAS,EACd,KAAK,SAAS,EACd,KAAK,IAAI,GACV,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,KAAK,MAAM,EAAE,KAAK,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,EACL,KAAK,cAAc,EACnB,UAAU,EACV,UAAU,EACV,WAAW,EACX,cAAc,EACd,SAAS,EACT,SAAS,GACV,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,cAAc,iBAAiB,CAAC;AAChC,cAAc,cAAc,CAAC;AAE7B,mEAAmE;AACnE,qBAAa,OAAO;IACE,QAAQ,CAAC,KAAK,EAAE,UAAU;IAA9C,OAAO,eAA2C;IAElD,MAAM,CAAC,KAAK,CAAC,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAElF;IACD,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAE3C;IACD,MAAM,CAAC,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEvC;IAED,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAEvD;IACD,gBAAgB,CAAC,QAAQ,EAAE,kBAAkB,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAE9E;IACD,iBAAiB,6CAEhB;IACD,IAAI,IAAI,OAAO,CAEd;IACD,QAAQ,IAAI,MAAM,CAEjB;IAED,wEAAwE;IACxE,MAAM,CAAC,aAAa,EAAE,UAAU,EAAE,aAAa,GAAE,CAAC,GAAG,CAAK,GAAG,eAAe,CAE3E;IAED;;;OAGG;IACG,WAAW,CAAC,aAAa,EAAE,UAAU,EAAE,aAAa,GAAE,CAAC,GAAG,CAAK,GAAG,OAAO,CAAC,eAAe,CAAC,CAK/F;CACF;AAED,yEAAyE;AACzE,qBAAa,eAAe;IAExB,QAAQ,CAAC,KAAK,EAAE,WAAW;IAC3B,QAAQ,CAAC,KAAK,EAAE,UAAU;IAF5B,YACW,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE,UAAU,EACxB;IACJ,IAAI,aAAa,IAAI,MAAM,EAAE,CAE5B;IACD,2EAA2E;IAC3E,SAAS,CAAC,OAAO,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,OAAO,CAE/C;IACD,yEAAyE;IACzE,KAAK,IAAI,MAAM,EAAE,CAEhB;IACD,8DAA8D;IAC9D,IAAI,SAAS,IAAI,MAAM,GAAG,SAAS,CAElC;IACD,SAAS,CAAC,cAAc,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,mBAAmB,CAEjF;IACD,mEAAmE;IACnE,QAAQ,CAAC,cAAc,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,UAAU,CAEvE;CACF;AAED,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ed25519 } from "@noble/curves/ed25519.js";
|
|
2
2
|
import { p256 } from "@noble/curves/nist.js";
|
|
3
|
-
|
|
3
|
+
// src/base64.ts
|
|
4
4
|
/** URL-safe base64 without padding, the wire form of a Biscuit token.
|
|
5
5
|
* Implemented directly so the library stays runtime-agnostic (no Buffer,
|
|
6
6
|
* no atob/btoa). */
|
|
@@ -41,8 +41,7 @@ function fromBase64(text) {
|
|
|
41
41
|
}
|
|
42
42
|
return out.subarray(0, o);
|
|
43
43
|
}
|
|
44
|
-
|
|
45
|
-
//#region src/crypto.ts
|
|
44
|
+
// src/crypto.ts
|
|
46
45
|
/**
|
|
47
46
|
* Biscuit cryptography: chained block signatures, sealing, third-party
|
|
48
47
|
* (external) signatures. Ed25519 and ECDSA/secp256r1, per SPECIFICATIONS.md.
|
|
@@ -271,13 +270,12 @@ async function publicKeyFromSecretAsync(secret, algorithm) {
|
|
|
271
270
|
function revocationIds(token) {
|
|
272
271
|
return [token.authority, ...token.blocks].map((b) => b.signature);
|
|
273
272
|
}
|
|
274
|
-
|
|
275
|
-
//#region src/datalog.ts
|
|
273
|
+
// src/datalog.ts
|
|
276
274
|
/**
|
|
277
275
|
* Biscuit Datalog: term model, fact/rule evaluation with origin tracking, and
|
|
278
276
|
* the stack-based expression virtual machine.
|
|
279
277
|
*/
|
|
280
|
-
const AUTHORIZER =
|
|
278
|
+
const AUTHORIZER = 0xffffffff;
|
|
281
279
|
const hex$2 = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
282
280
|
/** Canonical string key: JS Map/Set are reference-keyed, so every structural
|
|
283
281
|
* comparison and every de-duplication in the engine goes through this. */
|
|
@@ -353,7 +351,7 @@ function trustedOriginsFromScopes(ruleScopes, defaults, currentBlock, publicKeyT
|
|
|
353
351
|
const ids = /* @__PURE__ */ new Set([AUTHORIZER, currentBlock]);
|
|
354
352
|
for (const scope of ruleScopes) if (scope.kind === "authority") ids.add(0);
|
|
355
353
|
else if (scope.kind === "previous") {
|
|
356
|
-
if (currentBlock !==
|
|
354
|
+
if (currentBlock !== 0xffffffff) for (let i = 0; i <= currentBlock; i++) ids.add(i);
|
|
357
355
|
} else for (const id of publicKeyToBlockIds.get(scope.key) ?? []) ids.add(id);
|
|
358
356
|
return new TrustedOrigins(ids);
|
|
359
357
|
}
|
|
@@ -911,8 +909,7 @@ var World = class {
|
|
|
911
909
|
return found;
|
|
912
910
|
}
|
|
913
911
|
};
|
|
914
|
-
|
|
915
|
-
//#region src/parser.ts
|
|
912
|
+
// src/parser.ts
|
|
916
913
|
/**
|
|
917
914
|
* Parser for the Biscuit Datalog text syntax (SPECIFICATIONS.md grammar).
|
|
918
915
|
* Hand-written recursive descent + precedence climbing; expressions are
|
|
@@ -1711,13 +1708,26 @@ var Parser = class {
|
|
|
1711
1708
|
return out;
|
|
1712
1709
|
}
|
|
1713
1710
|
};
|
|
1714
|
-
|
|
1715
|
-
//#region src/print.ts
|
|
1711
|
+
// src/print.ts
|
|
1716
1712
|
/** Datalog pretty-printer (used for error messages and world snapshots). */
|
|
1717
1713
|
const hex$1 = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
1718
1714
|
/** Datalog string literal: only the quote and the backslash are escaped.
|
|
1719
1715
|
* Control characters are emitted raw, unlike JSON.stringify. */
|
|
1720
|
-
const
|
|
1716
|
+
const referenceQuote = (v) => `"${v.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`;
|
|
1717
|
+
/** Characters a display would render as a line break, hide, or reorder: C0/C1
|
|
1718
|
+
* controls, DEL, the Unicode line/paragraph separators and the bidi controls. */
|
|
1719
|
+
const DISPLAY_UNSAFE = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
|
|
1720
|
+
const NAMED_ESCAPES = {
|
|
1721
|
+
"\n": "\\n",
|
|
1722
|
+
"\r": "\\r",
|
|
1723
|
+
" ": "\\t",
|
|
1724
|
+
"\0": "\\0"
|
|
1725
|
+
};
|
|
1726
|
+
/** A string literal safe to show a person: every display-unsafe character is
|
|
1727
|
+
* escaped, so one string can never look like more than one statement. The
|
|
1728
|
+
* parser reads the escapes back to the same string. */
|
|
1729
|
+
const displayQuote = (v) => referenceQuote(v).replace(DISPLAY_UNSAFE, (c) => NAMED_ESCAPES[c] ?? `\\u{${(c.codePointAt(0) ?? 0).toString(16)}}`);
|
|
1730
|
+
let quote = referenceQuote;
|
|
1721
1731
|
function printTerm(t, varName) {
|
|
1722
1732
|
switch (t.t) {
|
|
1723
1733
|
case "var": return `$${varName(t.v)}`;
|
|
@@ -1802,8 +1812,28 @@ function printRule(r, varName) {
|
|
|
1802
1812
|
const parts = [...r.body.map((p) => printPredicate(p, varName)), ...r.expressions.map((e) => printExpression(e, varName))];
|
|
1803
1813
|
return `${printPredicate(r.head, varName)} <- ${parts.join(", ")}` + printScopes(r.scopes);
|
|
1804
1814
|
}
|
|
1805
|
-
|
|
1806
|
-
|
|
1815
|
+
/**
|
|
1816
|
+
* One block as Datalog source: its block-level `trusting` line, then its facts,
|
|
1817
|
+
* rules and checks, one statement per line, each ending with `;`. The text parses
|
|
1818
|
+
* back to the same block — show it on an approval screen or in a log. Strings
|
|
1819
|
+
* have their control, line-separator and bidi characters escaped (`\n`,
|
|
1820
|
+
* `\u{202e}`), so a value cannot display as extra statements.
|
|
1821
|
+
*/
|
|
1822
|
+
function printBlock(block) {
|
|
1823
|
+
const varName = (id) => block.varNames?.get(id) ?? String(id);
|
|
1824
|
+
const lines = [];
|
|
1825
|
+
quote = displayQuote;
|
|
1826
|
+
try {
|
|
1827
|
+
if (block.scopes.length > 0) lines.push(`${printScopes(block.scopes).trim()};`);
|
|
1828
|
+
for (const f of block.facts) lines.push(`${printPredicate(f.predicate, varName)};`);
|
|
1829
|
+
for (const r of block.rules) lines.push(`${printRule(r, varName)};`);
|
|
1830
|
+
for (const c of block.checks) lines.push(`${printCheck(c, varName)};`);
|
|
1831
|
+
} finally {
|
|
1832
|
+
quote = referenceQuote;
|
|
1833
|
+
}
|
|
1834
|
+
return lines.join("\n");
|
|
1835
|
+
}
|
|
1836
|
+
// src/proto.ts
|
|
1807
1837
|
/**
|
|
1808
1838
|
* Strict proto2 codec for the Biscuit schema.
|
|
1809
1839
|
*
|
|
@@ -2470,8 +2500,7 @@ function encodeBlock(b) {
|
|
|
2470
2500
|
for (const k of b.publicKeys) w.messageField(8, writePublicKey, k);
|
|
2471
2501
|
return w.finish();
|
|
2472
2502
|
}
|
|
2473
|
-
|
|
2474
|
-
//#region src/version.ts
|
|
2503
|
+
// src/version.ts
|
|
2475
2504
|
/**
|
|
2476
2505
|
* Datalog block versioning.
|
|
2477
2506
|
*
|
|
@@ -2542,8 +2571,7 @@ function validateBlockVersion(declared, rawChecks, hasExternalKey, content) {
|
|
|
2542
2571
|
if (f.checkAll) throw new VersionError("check all is only supported in datalog v3.1+");
|
|
2543
2572
|
} else if (version < 6 && f.v33) throw new VersionError("maps, arrays, null, closures are only supported in datalog v3.3+");
|
|
2544
2573
|
}
|
|
2545
|
-
|
|
2546
|
-
//#region src/authorizer.ts
|
|
2574
|
+
// src/authorizer.ts
|
|
2547
2575
|
/**
|
|
2548
2576
|
* Turns a serialized token plus authorizer code into an authorization result,
|
|
2549
2577
|
* mirroring the evaluation order of the reference implementation.
|
|
@@ -2892,10 +2920,10 @@ function evaluate(loadedToken, authorizerSrc, options = {}) {
|
|
|
2892
2920
|
const authorizerOrigin = Origin.of(AUTHORIZER);
|
|
2893
2921
|
for (const f of code.facts) world.addFact(authorizerOrigin, f);
|
|
2894
2922
|
for (const r of code.rules) world.addRule(AUTHORIZER, trustedOriginsFromScopes(r.scopes, authorizerTrusted, AUTHORIZER, keys), r);
|
|
2895
|
-
const name = (id) => id ===
|
|
2896
|
-
const blockId = (id) => id ===
|
|
2923
|
+
const name = (id) => id === 0xffffffff ? (v) => code.varNames.get(v) ?? String(v) : (v) => token.blocks[id]?.varNames.get(v) ?? String(v);
|
|
2924
|
+
const blockId = (id) => id === 0xffffffff ? null : id;
|
|
2897
2925
|
const AUTHORIZER_U64 = Number(18446744073709551615n);
|
|
2898
|
-
const ruleOrigin = (id) => id ===
|
|
2926
|
+
const ruleOrigin = (id) => id === 0xffffffff ? AUTHORIZER_U64 : id;
|
|
2899
2927
|
const snapshot = () => {
|
|
2900
2928
|
const factGroups = [...world.facts.values()].filter((b) => b.items.size > 0).map((b) => ({
|
|
2901
2929
|
origin: b.origin.ids.map(blockId).sort((x, y) => (x ?? -1) - (y ?? -1)),
|
|
@@ -2973,7 +3001,7 @@ function evaluate(loadedToken, authorizerSrc, options = {}) {
|
|
|
2973
3001
|
};
|
|
2974
3002
|
try {
|
|
2975
3003
|
code.checks.forEach((check, i) => {
|
|
2976
|
-
if (!runCheck(check,
|
|
3004
|
+
if (!runCheck(check, 0xffffffff, authorizerTrusted)) errors.push({
|
|
2977
3005
|
source: "authorizer",
|
|
2978
3006
|
checkId: i,
|
|
2979
3007
|
rule: printCheck(check, name(AUTHORIZER))
|
|
@@ -2990,7 +3018,7 @@ function evaluate(loadedToken, authorizerSrc, options = {}) {
|
|
|
2990
3018
|
let policyResult = null;
|
|
2991
3019
|
outer: for (const [i, policy] of code.policies.entries()) for (const query of policy.queries) {
|
|
2992
3020
|
const trusted = trustedOriginsFromScopes(query.scopes, authorizerTrusted, AUTHORIZER, keys);
|
|
2993
|
-
if (world.queryMatch(query,
|
|
3021
|
+
if (world.queryMatch(query, 0xffffffff, trusted)) {
|
|
2994
3022
|
policyResult = policy.kind === "allow" ? { allow: i } : { deny: i };
|
|
2995
3023
|
break outer;
|
|
2996
3024
|
}
|
|
@@ -3037,14 +3065,13 @@ function unusable(result) {
|
|
|
3037
3065
|
}
|
|
3038
3066
|
function compareOrigins(a, b) {
|
|
3039
3067
|
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
|
3040
|
-
const x = a[i] === void 0 ? -
|
|
3041
|
-
const y = b[i] === void 0 ? -
|
|
3068
|
+
const x = a[i] === void 0 ? -1e400 : a[i] ?? -1;
|
|
3069
|
+
const y = b[i] === void 0 ? -1e400 : b[i] ?? -1;
|
|
3042
3070
|
if (x !== y) return x - y;
|
|
3043
3071
|
}
|
|
3044
3072
|
return 0;
|
|
3045
3073
|
}
|
|
3046
|
-
|
|
3047
|
-
//#region src/builder.ts
|
|
3074
|
+
// src/builder.ts
|
|
3048
3075
|
/**
|
|
3049
3076
|
* The write path: minting tokens, attenuating them with extra blocks, and
|
|
3050
3077
|
* sealing them. New blocks are signed with signature payload version 1, and
|
|
@@ -3345,8 +3372,74 @@ function appendThirdParty(tokenBytes, response, options = {}) {
|
|
|
3345
3372
|
};
|
|
3346
3373
|
return encodeBiscuit(token);
|
|
3347
3374
|
}
|
|
3348
|
-
|
|
3349
|
-
|
|
3375
|
+
// src/revocation.ts
|
|
3376
|
+
/** Thrown by `assertNotRevoked`. `revocationId` is the first id found revoked. */
|
|
3377
|
+
var RevokedTokenError = class extends Error {
|
|
3378
|
+
revocationId;
|
|
3379
|
+
constructor(revocationId) {
|
|
3380
|
+
super(`token revoked: ${revocationId}`);
|
|
3381
|
+
this.revocationId = revocationId;
|
|
3382
|
+
this.name = "RevokedTokenError";
|
|
3383
|
+
}
|
|
3384
|
+
};
|
|
3385
|
+
/**
|
|
3386
|
+
* The first of the token's revocation ids found in `revoked`, if any. The
|
|
3387
|
+
* token's ids are lowercase hex; `revoked` may hold them lowercase or
|
|
3388
|
+
* uppercase (a set of mixed-case ids should be lowercased by its owner).
|
|
3389
|
+
*/
|
|
3390
|
+
function revokedId(token, revoked) {
|
|
3391
|
+
return token.revocationIds.find((id) => {
|
|
3392
|
+
const lower = id.toLowerCase();
|
|
3393
|
+
return revoked.has(lower) || revoked.has(lower.toUpperCase());
|
|
3394
|
+
});
|
|
3395
|
+
}
|
|
3396
|
+
/** Whether any of the token's revocation ids is in `revoked` (hex ids, either case). */
|
|
3397
|
+
function isRevoked(token, revoked) {
|
|
3398
|
+
return revokedId(token, revoked) !== void 0;
|
|
3399
|
+
}
|
|
3400
|
+
/** Throw `RevokedTokenError` when any of the token's revocation ids is in `revoked`. */
|
|
3401
|
+
function assertNotRevoked(token, revoked) {
|
|
3402
|
+
const id = revokedId(token, revoked);
|
|
3403
|
+
if (id !== void 0) throw new RevokedTokenError(id);
|
|
3404
|
+
}
|
|
3405
|
+
// src/code.ts
|
|
3406
|
+
var Datalog = class {
|
|
3407
|
+
lines = [];
|
|
3408
|
+
bound = {};
|
|
3409
|
+
next = 0;
|
|
3410
|
+
/** Append source. Every `${value}` becomes a `{pN}` parameter — a term, never text. */
|
|
3411
|
+
add(strings, ...values) {
|
|
3412
|
+
let line = strings[0] ?? "";
|
|
3413
|
+
values.forEach((value, i) => {
|
|
3414
|
+
const name = `p${this.next++}`;
|
|
3415
|
+
this.bound[name] = value;
|
|
3416
|
+
line += `{${name}}${strings[i + 1] ?? ""}`;
|
|
3417
|
+
});
|
|
3418
|
+
this.lines.push(line);
|
|
3419
|
+
return this;
|
|
3420
|
+
}
|
|
3421
|
+
/**
|
|
3422
|
+
* Append source that interpolates nothing. Only for text you wrote yourself:
|
|
3423
|
+
* a `{name}` in it must not collide with the `{pN}` names `add` generates.
|
|
3424
|
+
*/
|
|
3425
|
+
raw(source) {
|
|
3426
|
+
this.lines.push(source);
|
|
3427
|
+
return this;
|
|
3428
|
+
}
|
|
3429
|
+
/** the source, one `add`/`raw` call per line */
|
|
3430
|
+
get source() {
|
|
3431
|
+
return this.lines.join("\n");
|
|
3432
|
+
}
|
|
3433
|
+
/** the values the source's `{pN}` parameters are bound to */
|
|
3434
|
+
get params() {
|
|
3435
|
+
return this.bound;
|
|
3436
|
+
}
|
|
3437
|
+
};
|
|
3438
|
+
/** `datalog\`user(${id});\`` — a new `Datalog` holding one parameterised line. */
|
|
3439
|
+
function datalog(strings, ...values) {
|
|
3440
|
+
return new Datalog().add(strings, ...values);
|
|
3441
|
+
}
|
|
3442
|
+
// src/index.ts
|
|
3350
3443
|
/**
|
|
3351
3444
|
* biscuit-ts — pure TypeScript Biscuit tokens.
|
|
3352
3445
|
*
|
|
@@ -3408,6 +3501,14 @@ var VerifiedBiscuit = class {
|
|
|
3408
3501
|
get revocationIds() {
|
|
3409
3502
|
return this.token.revocationIds;
|
|
3410
3503
|
}
|
|
3504
|
+
/** Whether any block's revocation id is in `revoked` — see `isRevoked`. */
|
|
3505
|
+
isRevoked(revoked) {
|
|
3506
|
+
return isRevoked(this.token, revoked);
|
|
3507
|
+
}
|
|
3508
|
+
/** Every block as Datalog source, authority first — see `printBlock`. */
|
|
3509
|
+
print() {
|
|
3510
|
+
return this.token.blocks.map(printBlock);
|
|
3511
|
+
}
|
|
3411
3512
|
/** the issuer's key identifier, when the token carries one */
|
|
3412
3513
|
get rootKeyId() {
|
|
3413
3514
|
return this.token.rootKeyId;
|
|
@@ -3420,5 +3521,4 @@ var VerifiedBiscuit = class {
|
|
|
3420
3521
|
return evaluate(this.token, authorizerCode, options);
|
|
3421
3522
|
}
|
|
3422
3523
|
};
|
|
3423
|
-
|
|
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 };
|
|
3524
|
+
export { Biscuit, BuilderError, DATALOG_3_1, DATALOG_3_2, DATALOG_3_3, DEFAULT_SYMBOLS, Datalog, ExecutionError, MAX_SCHEMA_VERSION, MIN_SCHEMA_VERSION, ParseError, ProtoError, RevokedTokenError, SignatureError, TokenError, VerifiedBiscuit, VersionError, appendThirdParty, assertNotRevoked, attenuate, authorize, authorizeDetailed, blockFeatures, buildBlockMsg, buildToken, datalog, evaluate, fromBase64, generateKeypair, isRevoked, loadToken, loadTokenAsync, parseAuthorizer, peekRootKeyId, printBlock, printCheck, printPolicy, printPredicate, printRule, printTerm, requiredVersion, revokedId, sealToken, thirdPartyBlock, thirdPartyRequest, toBase64, validateBlockVersion };
|
package/dist/print.d.ts
CHANGED
|
@@ -9,4 +9,23 @@ export declare function printQuery(r: Rule, varName: (id: number) => string): st
|
|
|
9
9
|
export declare function printCheck(c: Check, varName: (id: number) => string): string;
|
|
10
10
|
export declare function printPolicy(kind: "allow" | "deny", queries: Rule[], varName: (id: number) => string): string;
|
|
11
11
|
export declare function printRule(r: Rule, varName: (id: number) => string): string;
|
|
12
|
+
/** The parts of a block `printBlock` reads: a loaded token's `RuntimeBlock` has them. */
|
|
13
|
+
export interface PrintableBlock {
|
|
14
|
+
facts: {
|
|
15
|
+
predicate: Predicate;
|
|
16
|
+
}[];
|
|
17
|
+
rules: Rule[];
|
|
18
|
+
checks: Check[];
|
|
19
|
+
scopes: Scope[];
|
|
20
|
+
/** variable id -> name; without it variables print as `$<id>` */
|
|
21
|
+
varNames?: Map<number, string>;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* One block as Datalog source: its block-level `trusting` line, then its facts,
|
|
25
|
+
* rules and checks, one statement per line, each ending with `;`. The text parses
|
|
26
|
+
* back to the same block — show it on an approval screen or in a log. Strings
|
|
27
|
+
* have their control, line-separator and bidi characters escaped (`\n`,
|
|
28
|
+
* `\u{202e}`), so a value cannot display as extra statements.
|
|
29
|
+
*/
|
|
30
|
+
export declare function printBlock(block: PrintableBlock): string;
|
|
12
31
|
//# sourceMappingURL=print.d.ts.map
|
package/dist/print.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"print.d.ts","sourceRoot":"","sources":["../src/print.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,OAAO,EAEL,KAAK,KAAK,EAEV,KAAK,EAAE,EACP,KAAK,SAAS,EACd,KAAK,IAAI,EACT,KAAK,KAAK,EACV,KAAK,IAAI,EAEV,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"print.d.ts","sourceRoot":"","sources":["../src/print.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,OAAO,EAEL,KAAK,KAAK,EAEV,KAAK,EAAE,EACP,KAAK,SAAS,EACd,KAAK,IAAI,EACT,KAAK,KAAK,EACV,KAAK,IAAI,EAEV,MAAM,cAAc,CAAC;AAiCtB,wBAAgB,SAAS,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,MAAM,GAAG,MAAM,CAyB1E;AAED,eAAO,MAAM,cAAc,MAAO,SAAS,WAAW,CAAC,EAAE,EAAE,MAAM,KAAK,MAAM,KAAG,MACT,CAAC;AAwCvE,wBAAgB,eAAe,CAAC,GAAG,EAAE,EAAE,EAAE,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,MAAM,GAAG,MAAM,CAoBlF;AAED,wBAAgB,WAAW,CAAC,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,CAMnD;AAED,wEAAwE;AACxE,wBAAgB,UAAU,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,MAAM,GAAG,MAAM,CAM3E;AAED,wBAAgB,UAAU,CAAC,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,MAAM,GAAG,MAAM,CAG5E;AAED,wBAAgB,WAAW,CACzB,IAAI,EAAE,OAAO,GAAG,MAAM,EACtB,OAAO,EAAE,IAAI,EAAE,EACf,OAAO,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,MAAM,GAC9B,MAAM,CAER;AAED,wBAAgB,SAAS,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,MAAM,GAAG,MAAM,CAM1E;AAED,yFAAyF;AACzF,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE;QAAE,SAAS,EAAE,SAAS,CAAA;KAAE,EAAE,CAAC;IAClC,KAAK,EAAE,IAAI,EAAE,CAAC;IACd,MAAM,EAAE,KAAK,EAAE,CAAC;IAChB,MAAM,EAAE,KAAK,EAAE,CAAC;IAChB,iEAAiE;IACjE,QAAQ,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAChC;AAED;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,cAAc,GAAG,MAAM,CAaxD"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Revocation: a token is revoked when any of its blocks' revocation ids is in
|
|
3
|
+
* the revoked set. Revoking a block's id revokes every token derived from it,
|
|
4
|
+
* since each attenuation keeps the ids of the blocks before it.
|
|
5
|
+
*/
|
|
6
|
+
/** Anything carrying a token's revocation ids: a `VerifiedBiscuit` or a `LoadedToken`. */
|
|
7
|
+
export interface HasRevocationIds {
|
|
8
|
+
readonly revocationIds: readonly string[];
|
|
9
|
+
}
|
|
10
|
+
/** Thrown by `assertNotRevoked`. `revocationId` is the first id found revoked. */
|
|
11
|
+
export declare class RevokedTokenError extends Error {
|
|
12
|
+
readonly revocationId: string;
|
|
13
|
+
constructor(revocationId: string);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The first of the token's revocation ids found in `revoked`, if any. The
|
|
17
|
+
* token's ids are lowercase hex; `revoked` may hold them lowercase or
|
|
18
|
+
* uppercase (a set of mixed-case ids should be lowercased by its owner).
|
|
19
|
+
*/
|
|
20
|
+
export declare function revokedId(token: HasRevocationIds, revoked: ReadonlySet<string>): string | undefined;
|
|
21
|
+
/** Whether any of the token's revocation ids is in `revoked` (hex ids, either case). */
|
|
22
|
+
export declare function isRevoked(token: HasRevocationIds, revoked: ReadonlySet<string>): boolean;
|
|
23
|
+
/** Throw `RevokedTokenError` when any of the token's revocation ids is in `revoked`. */
|
|
24
|
+
export declare function assertNotRevoked(token: HasRevocationIds, revoked: ReadonlySet<string>): void;
|
|
25
|
+
//# sourceMappingURL=revocation.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"revocation.d.ts","sourceRoot":"","sources":["../src/revocation.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,0FAA0F;AAC1F,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;CAC3C;AAED,kFAAkF;AAClF,qBAAa,iBAAkB,SAAQ,KAAK;IAC9B,QAAQ,CAAC,YAAY,EAAE,MAAM;IAAzC,YAAqB,YAAY,EAAE,MAAM,EAGxC;CACF;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CACvB,KAAK,EAAE,gBAAgB,EACvB,OAAO,EAAE,WAAW,CAAC,MAAM,CAAC,GAC3B,MAAM,GAAG,SAAS,CAKpB;AAED,wFAAwF;AACxF,wBAAgB,SAAS,CAAC,KAAK,EAAE,gBAAgB,EAAE,OAAO,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,OAAO,CAExF;AAED,wFAAwF;AACxF,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,gBAAgB,EAAE,OAAO,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,IAAI,CAG5F"}
|
package/package.json
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@statewalker/webrun-biscuit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Biscuit authorization tokens in pure TypeScript: proto2 codec, Ed25519 and secp256r1 signature chain, Datalog engine, parser, authorizer and builder. No WASM, no Node built-ins — runs in Node, browsers, Workers and Durable Objects.",
|
|
7
|
-
"
|
|
7
|
+
"bugs": {
|
|
8
|
+
"url": "https://github.com/statewalker/httpeers/issues"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/statewalker/httpeers/tree/main/packages/webrun-biscuit#readme",
|
|
8
11
|
"author": {
|
|
9
12
|
"name": "Mikhail Kotelnikov",
|
|
10
13
|
"email": "mikhail.kotelnikov@gmail.com"
|
|
@@ -12,7 +15,7 @@
|
|
|
12
15
|
"license": "MIT",
|
|
13
16
|
"repository": {
|
|
14
17
|
"type": "git",
|
|
15
|
-
"url": "git
|
|
18
|
+
"url": "git+https://github.com/statewalker/httpeers.git",
|
|
16
19
|
"directory": "packages/webrun-biscuit"
|
|
17
20
|
},
|
|
18
21
|
"exports": {
|
|
@@ -35,7 +38,7 @@
|
|
|
35
38
|
"rimraf": "^6.1.3",
|
|
36
39
|
"rolldown": "^1.2.12",
|
|
37
40
|
"typescript": "^7.0.2",
|
|
38
|
-
"vitest": "^5.0.
|
|
41
|
+
"vitest": "^5.0.5"
|
|
39
42
|
},
|
|
40
43
|
"sideEffects": false,
|
|
41
44
|
"publishConfig": {
|
package/src/code.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Datalog source with its values bound as parameters.
|
|
3
|
+
*
|
|
4
|
+
* const code = new Datalog().add`user(${userId});`.add`check if time($t), $t < ${expiry};`;
|
|
5
|
+
* Biscuit.build(root.secretKey, code.source, { params: code.params });
|
|
6
|
+
*
|
|
7
|
+
* `add` is a tagged template: every `${value}` becomes a `{pN}` parameter, bound
|
|
8
|
+
* as a TERM by the parser. A value is never spliced into the source text, so no
|
|
9
|
+
* string — `"); role("admin` included — can change the program's shape.
|
|
10
|
+
*/
|
|
11
|
+
import type { ParamValue } from "./parser.js";
|
|
12
|
+
|
|
13
|
+
export class Datalog {
|
|
14
|
+
private readonly lines: string[] = [];
|
|
15
|
+
private readonly bound: Record<string, ParamValue> = {};
|
|
16
|
+
private next = 0;
|
|
17
|
+
|
|
18
|
+
/** Append source. Every `${value}` becomes a `{pN}` parameter — a term, never text. */
|
|
19
|
+
add(strings: TemplateStringsArray, ...values: ParamValue[]): this {
|
|
20
|
+
let line = strings[0] ?? "";
|
|
21
|
+
values.forEach((value, i) => {
|
|
22
|
+
const name = `p${this.next++}`;
|
|
23
|
+
this.bound[name] = value;
|
|
24
|
+
line += `{${name}}${strings[i + 1] ?? ""}`;
|
|
25
|
+
});
|
|
26
|
+
this.lines.push(line);
|
|
27
|
+
return this;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Append source that interpolates nothing. Only for text you wrote yourself:
|
|
32
|
+
* a `{name}` in it must not collide with the `{pN}` names `add` generates.
|
|
33
|
+
*/
|
|
34
|
+
raw(source: string): this {
|
|
35
|
+
this.lines.push(source);
|
|
36
|
+
return this;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** the source, one `add`/`raw` call per line */
|
|
40
|
+
get source(): string {
|
|
41
|
+
return this.lines.join("\n");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** the values the source's `{pN}` parameters are bound to */
|
|
45
|
+
get params(): Readonly<Record<string, ParamValue>> {
|
|
46
|
+
return this.bound;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** `datalog\`user(${id});\`` — a new `Datalog` holding one parameterised line. */
|
|
51
|
+
export function datalog(strings: TemplateStringsArray, ...values: ParamValue[]): Datalog {
|
|
52
|
+
return new Datalog().add(strings, ...values);
|
|
53
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -29,10 +29,13 @@ import {
|
|
|
29
29
|
thirdPartyBlock,
|
|
30
30
|
thirdPartyRequest,
|
|
31
31
|
} from "./builder.js";
|
|
32
|
+
import { printBlock } from "./print.js";
|
|
33
|
+
import { isRevoked } from "./revocation.js";
|
|
32
34
|
|
|
33
35
|
export * from "./authorizer.js";
|
|
34
36
|
export * from "./base64.js";
|
|
35
37
|
export * from "./builder.js";
|
|
38
|
+
export * from "./code.js";
|
|
36
39
|
export { SignatureError } from "./crypto.js";
|
|
37
40
|
export {
|
|
38
41
|
ExecutionError,
|
|
@@ -42,7 +45,17 @@ export {
|
|
|
42
45
|
type Term,
|
|
43
46
|
} from "./datalog.js";
|
|
44
47
|
export { type Params, type ParamValue, ParseError } from "./parser.js";
|
|
48
|
+
export {
|
|
49
|
+
type PrintableBlock,
|
|
50
|
+
printBlock,
|
|
51
|
+
printCheck,
|
|
52
|
+
printPolicy,
|
|
53
|
+
printPredicate,
|
|
54
|
+
printRule,
|
|
55
|
+
printTerm,
|
|
56
|
+
} from "./print.js";
|
|
45
57
|
export { ProtoError } from "./proto.js";
|
|
58
|
+
export * from "./revocation.js";
|
|
46
59
|
export * from "./version.js";
|
|
47
60
|
|
|
48
61
|
/** An unverified token: it can be attenuated and re-serialized. */
|
|
@@ -101,6 +114,14 @@ export class VerifiedBiscuit {
|
|
|
101
114
|
get revocationIds(): string[] {
|
|
102
115
|
return this.token.revocationIds;
|
|
103
116
|
}
|
|
117
|
+
/** Whether any block's revocation id is in `revoked` — see `isRevoked`. */
|
|
118
|
+
isRevoked(revoked: ReadonlySet<string>): boolean {
|
|
119
|
+
return isRevoked(this.token, revoked);
|
|
120
|
+
}
|
|
121
|
+
/** Every block as Datalog source, authority first — see `printBlock`. */
|
|
122
|
+
print(): string[] {
|
|
123
|
+
return this.token.blocks.map(printBlock);
|
|
124
|
+
}
|
|
104
125
|
/** the issuer's key identifier, when the token carries one */
|
|
105
126
|
get rootKeyId(): number | undefined {
|
|
106
127
|
return this.token.rootKeyId;
|
package/src/print.ts
CHANGED
|
@@ -16,7 +16,31 @@ const hex = (b: Uint8Array): string =>
|
|
|
16
16
|
|
|
17
17
|
/** Datalog string literal: only the quote and the backslash are escaped.
|
|
18
18
|
* Control characters are emitted raw, unlike JSON.stringify. */
|
|
19
|
-
const
|
|
19
|
+
const referenceQuote = (v: string): string => `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
|
20
|
+
|
|
21
|
+
/** Characters a display would render as a line break, hide, or reorder: C0/C1
|
|
22
|
+
* controls, DEL, the Unicode line/paragraph separators and the bidi controls. */
|
|
23
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: matching them is the point
|
|
24
|
+
const DISPLAY_UNSAFE = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
|
|
25
|
+
const NAMED_ESCAPES: Record<string, string> = {
|
|
26
|
+
"\n": "\\n",
|
|
27
|
+
"\r": "\\r",
|
|
28
|
+
"\t": "\\t",
|
|
29
|
+
"\0": "\\0",
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** A string literal safe to show a person: every display-unsafe character is
|
|
33
|
+
* escaped, so one string can never look like more than one statement. The
|
|
34
|
+
* parser reads the escapes back to the same string. */
|
|
35
|
+
const displayQuote = (v: string): string =>
|
|
36
|
+
referenceQuote(v).replace(
|
|
37
|
+
DISPLAY_UNSAFE,
|
|
38
|
+
(c) => NAMED_ESCAPES[c] ?? `\\u{${(c.codePointAt(0) ?? 0).toString(16)}}`,
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
// `printBlock` switches to `displayQuote` for its own (synchronous) call; error
|
|
42
|
+
// messages and world snapshots keep the reference printer's exact text.
|
|
43
|
+
let quote = referenceQuote;
|
|
20
44
|
|
|
21
45
|
export function printTerm(t: Term, varName: (id: number) => string): string {
|
|
22
46
|
switch (t.t) {
|
|
@@ -145,3 +169,35 @@ export function printRule(r: Rule, varName: (id: number) => string): string {
|
|
|
145
169
|
];
|
|
146
170
|
return `${printPredicate(r.head, varName)} <- ${parts.join(", ")}` + printScopes(r.scopes);
|
|
147
171
|
}
|
|
172
|
+
|
|
173
|
+
/** The parts of a block `printBlock` reads: a loaded token's `RuntimeBlock` has them. */
|
|
174
|
+
export interface PrintableBlock {
|
|
175
|
+
facts: { predicate: Predicate }[];
|
|
176
|
+
rules: Rule[];
|
|
177
|
+
checks: Check[];
|
|
178
|
+
scopes: Scope[];
|
|
179
|
+
/** variable id -> name; without it variables print as `$<id>` */
|
|
180
|
+
varNames?: Map<number, string>;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* One block as Datalog source: its block-level `trusting` line, then its facts,
|
|
185
|
+
* rules and checks, one statement per line, each ending with `;`. The text parses
|
|
186
|
+
* back to the same block — show it on an approval screen or in a log. Strings
|
|
187
|
+
* have their control, line-separator and bidi characters escaped (`\n`,
|
|
188
|
+
* `\u{202e}`), so a value cannot display as extra statements.
|
|
189
|
+
*/
|
|
190
|
+
export function printBlock(block: PrintableBlock): string {
|
|
191
|
+
const varName = (id: number): string => block.varNames?.get(id) ?? String(id);
|
|
192
|
+
const lines: string[] = [];
|
|
193
|
+
quote = displayQuote;
|
|
194
|
+
try {
|
|
195
|
+
if (block.scopes.length > 0) lines.push(`${printScopes(block.scopes).trim()};`);
|
|
196
|
+
for (const f of block.facts) lines.push(`${printPredicate(f.predicate, varName)};`);
|
|
197
|
+
for (const r of block.rules) lines.push(`${printRule(r, varName)};`);
|
|
198
|
+
for (const c of block.checks) lines.push(`${printCheck(c, varName)};`);
|
|
199
|
+
} finally {
|
|
200
|
+
quote = referenceQuote;
|
|
201
|
+
}
|
|
202
|
+
return lines.join("\n");
|
|
203
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Revocation: a token is revoked when any of its blocks' revocation ids is in
|
|
3
|
+
* the revoked set. Revoking a block's id revokes every token derived from it,
|
|
4
|
+
* since each attenuation keeps the ids of the blocks before it.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** Anything carrying a token's revocation ids: a `VerifiedBiscuit` or a `LoadedToken`. */
|
|
8
|
+
export interface HasRevocationIds {
|
|
9
|
+
readonly revocationIds: readonly string[];
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Thrown by `assertNotRevoked`. `revocationId` is the first id found revoked. */
|
|
13
|
+
export class RevokedTokenError extends Error {
|
|
14
|
+
constructor(readonly revocationId: string) {
|
|
15
|
+
super(`token revoked: ${revocationId}`);
|
|
16
|
+
this.name = "RevokedTokenError";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The first of the token's revocation ids found in `revoked`, if any. The
|
|
22
|
+
* token's ids are lowercase hex; `revoked` may hold them lowercase or
|
|
23
|
+
* uppercase (a set of mixed-case ids should be lowercased by its owner).
|
|
24
|
+
*/
|
|
25
|
+
export function revokedId(
|
|
26
|
+
token: HasRevocationIds,
|
|
27
|
+
revoked: ReadonlySet<string>,
|
|
28
|
+
): string | undefined {
|
|
29
|
+
return token.revocationIds.find((id) => {
|
|
30
|
+
const lower = id.toLowerCase();
|
|
31
|
+
return revoked.has(lower) || revoked.has(lower.toUpperCase());
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Whether any of the token's revocation ids is in `revoked` (hex ids, either case). */
|
|
36
|
+
export function isRevoked(token: HasRevocationIds, revoked: ReadonlySet<string>): boolean {
|
|
37
|
+
return revokedId(token, revoked) !== undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Throw `RevokedTokenError` when any of the token's revocation ids is in `revoked`. */
|
|
41
|
+
export function assertNotRevoked(token: HasRevocationIds, revoked: ReadonlySet<string>): void {
|
|
42
|
+
const id = revokedId(token, revoked);
|
|
43
|
+
if (id !== undefined) throw new RevokedTokenError(id);
|
|
44
|
+
}
|