@bounded-authority-protocol/verifier 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.
Files changed (49) hide show
  1. package/LICENSE +190 -0
  2. package/NOTICE +10 -0
  3. package/README.md +183 -0
  4. package/dist/src/base64url.d.ts +2 -0
  5. package/dist/src/base64url.js +115 -0
  6. package/dist/src/base64url.js.map +1 -0
  7. package/dist/src/bounds.d.ts +50 -0
  8. package/dist/src/bounds.js +114 -0
  9. package/dist/src/bounds.js.map +1 -0
  10. package/dist/src/compact.d.ts +19 -0
  11. package/dist/src/compact.js +111 -0
  12. package/dist/src/compact.js.map +1 -0
  13. package/dist/src/digest.d.ts +8 -0
  14. package/dist/src/digest.js +116 -0
  15. package/dist/src/digest.js.map +1 -0
  16. package/dist/src/ed25519.d.ts +7 -0
  17. package/dist/src/ed25519.js +61 -0
  18. package/dist/src/ed25519.js.map +1 -0
  19. package/dist/src/error.d.ts +15 -0
  20. package/dist/src/error.js +34 -0
  21. package/dist/src/error.js.map +1 -0
  22. package/dist/src/facts.d.ts +104 -0
  23. package/dist/src/facts.js +6 -0
  24. package/dist/src/facts.js.map +1 -0
  25. package/dist/src/index.d.ts +16 -0
  26. package/dist/src/index.js +31 -0
  27. package/dist/src/index.js.map +1 -0
  28. package/dist/src/jcs.d.ts +3 -0
  29. package/dist/src/jcs.js +285 -0
  30. package/dist/src/jcs.js.map +1 -0
  31. package/dist/src/json.d.ts +25 -0
  32. package/dist/src/json.js +473 -0
  33. package/dist/src/json.js.map +1 -0
  34. package/dist/src/jwk.d.ts +14 -0
  35. package/dist/src/jwk.js +77 -0
  36. package/dist/src/jwk.js.map +1 -0
  37. package/dist/src/selector.d.ts +16 -0
  38. package/dist/src/selector.js +142 -0
  39. package/dist/src/selector.js.map +1 -0
  40. package/dist/src/uri.d.ts +4 -0
  41. package/dist/src/uri.js +280 -0
  42. package/dist/src/uri.js.map +1 -0
  43. package/dist/src/v1.d.ts +211 -0
  44. package/dist/src/v1.js +2206 -0
  45. package/dist/src/v1.js.map +1 -0
  46. package/dist/src/v2.d.ts +291 -0
  47. package/dist/src/v2.js +2300 -0
  48. package/dist/src/v2.js.map +1 -0
  49. package/package.json +46 -0
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all other
162
+ commercial damages or losses), even if such Contributor has been
163
+ advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 BaseLabs
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,10 @@
1
+ @bounded-authority/verifier
2
+ Copyright 2026 BaseLabs
3
+
4
+ This product includes software developed by BaseLabs.
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License");
7
+ you may not use this file except in compliance with the License.
8
+ You may obtain a copy of the License at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
package/README.md ADDED
@@ -0,0 +1,183 @@
1
+ # @bounded-authority-protocol/verifier
2
+
3
+ [![npm](https://img.shields.io/npm/v/@bounded-authority-protocol/verifier)](https://www.npmjs.com/package/@bounded-authority-protocol/verifier)
4
+ [![CI](https://github.com/baselabs/bounded_authority_protocol_typescript/actions/workflows/ci.yml/badge.svg)](https://github.com/baselabs/bounded_authority_protocol_typescript/actions/workflows/ci.yml)
5
+ [![license](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
6
+
7
+ Deterministic, fail-closed verification for the **Bounded Authority Protocol** — bounded
8
+ proof-of-possession authority for services and AI agents, in pure TypeScript.
9
+
10
+ The SDK verifies the protocol's two wire profiles (contract-majors 1 and 2): compact-JWS
11
+ grants, holder proofs, consumption chains, boundary anchors, key transitions, and archived
12
+ exports. It is a TypeScript reimplementation of the reference profile — derived from the
13
+ published specifications and certified conformance corpora, with zero runtime dependencies
14
+ (Ed25519 via `node:crypto`; canonicalization hand-rolled from the RFCs).
15
+
16
+ **It verifies; it never authorizes.** A successful result proves that caller-supplied bytes
17
+ satisfy caller-supplied trusted inputs and expected context — nothing more. There is no
18
+ `allowed`, no `authorized`, no decision anywhere in the API: results are value-bearing,
19
+ redacted facts, and every failure is a single closed rejection.
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ npm install @bounded-authority-protocol/verifier
25
+ ```
26
+
27
+ Requires Node.js `>= 22`. Zero runtime dependencies.
28
+
29
+ ## Quickstart — verify a grant
30
+
31
+ ```ts
32
+ import { verifyGrant } from "@bounded-authority-protocol/verifier";
33
+
34
+ // The raw compact-JWS grant bytes (ASCII), produced out-of-band by an issuer.
35
+ const grantCompact = Buffer.from(
36
+ "eyJhbGciOiJFZERTQSIsInR5cCI6ImJhK2NhcCIsImtpZCI6Imlzc3Vlci1rZXkifQ." +
37
+ "<payload>.<signature>",
38
+ "ascii",
39
+ );
40
+
41
+ const result = verifyGrant(
42
+ grantCompact,
43
+ {
44
+ keyId: "issuer-key", // must match the grant header `kid` exactly
45
+ publicKey: issuerPublicKey32, // raw 32-byte Ed25519 public key — public keys only
46
+ },
47
+ {
48
+ issuer: "https://issuer.example",
49
+ audience: "https://resource.example",
50
+ evaluationTime: 1_731_728_000, // caller-supplied, seconds since epoch — the SDK reads no clock
51
+ clockSkew: 60,
52
+ },
53
+ );
54
+
55
+ if (result.ok) {
56
+ const facts = result.value; // GrantFacts — value-bearing, redacted
57
+ facts.holderThumbprint; // Uint8Array(32) — the bound holder key
58
+ facts.authorization; // "not_evaluated" — verification is not authority
59
+ } else {
60
+ // { ok: false } — every structural, signature, header, claim, or time-window
61
+ // failure lands here. Closed and value-free: no reason, no partial data.
62
+ }
63
+ ```
64
+
65
+ Every public function returns the same `Result<T>` shape — `{ ok: true, value }` or
66
+ `{ ok: false }` — mirroring the reference's `{:ok, value} | {:error, :invalid}`.
67
+
68
+ ## Wire contract-majors
69
+
70
+ The protocol versions its wire formats as complete, parallel **contract-majors**. Both live in
71
+ this package; each verifies only its own bytes — there is no fallback or downgrade in either
72
+ direction.
73
+
74
+ | Major | Import | Selector kinds | Notes |
75
+ |---|---|---|---|
76
+ | 1 | `import { verifyGrant, ... }` | `all`, `equals`, `one_of` | The original profile |
77
+ | 2 | `import { v2 } from "@bounded-authority-protocol/verifier"` | `+ lte`, `gte` | Adds inclusive same-tag range selectors (intervals compose conjunctively) |
78
+
79
+ The `v2` namespace mirrors the full v1 surface — `v2.verifyGrant`, `v2.checkEnvelope`,
80
+ `v2.grantSigningInput`, and so on — under the major-2 separators, suite name, and `v: 2`
81
+ payloads.
82
+
83
+ ```ts
84
+ import { v2 } from "@bounded-authority-protocol/verifier";
85
+
86
+ const result = v2.checkEnvelope(grantV2, proofV2, {
87
+ trustedIssuer: { keyId: "issuer-key", publicKey: issuerPublicKey32 },
88
+ issuer: "https://issuer.example",
89
+ audience: "https://resource.example",
90
+ method: "POST",
91
+ targetUri: "https://api.example.test/invoke",
92
+ invocationId: "…", operation: "transfer",
93
+ castArguments: { t: "object", v: new Map([["amount", { t: "int", v: 5000 }]]) },
94
+ evaluationTime: 1_731_728_000, clockSkew: 60, proofMaxAge: 300,
95
+ nonce: { kind: "not_required" },
96
+ });
97
+ // The grant above may carry { kind: "lte", path: ["amount"], value: 5000 } —
98
+ // amount 5001 rejects; 5000 verifies inclusively; cross-tag operands never match.
99
+ ```
100
+
101
+ `castArguments` uses the SDK's tagged JSON algebra (int/float/string/object tags carry the
102
+ selector operand domain); the [`Tagged` type](src/json.ts) is exported from the package root.
103
+
104
+ ## API surface
105
+
106
+ The v1 façade (the `v2` namespace mirrors it):
107
+
108
+ | Function | Returns | Purpose |
109
+ |---|---|---|
110
+ | `verifyGrant` | `Result<GrantFacts>` | Verify a compact grant against a trusted issuer + expected context |
111
+ | `checkEnvelope` | `Result<EnvelopeFacts>` | Re-verify the grant and bind the holder proof, request, nonce, and selectors |
112
+ | `decodeGrant` / `decodeProof` | `Result<GrantDecoded \| ProofDecoded>` | Structural decode (verification: not_evaluated) |
113
+ | `untrustedKeyLocator` | `Result<KeyLocator>` | Header-only key id (trust: not_evaluated) |
114
+ | `requestDigest` | `Uint8Array(32)` | Typed, type-preserving request hash (major-bound domain prefix) |
115
+ | `encodeConsumptionEntry` / `checkChain` | `Result<EncodedConsumptionEntry \| ChainFacts>` | Canonical consumption rows + range verification |
116
+ | `grantSigningInput` / `proofSigningInput` | `Result<SigningInput>` | Deterministic producer signing inputs |
117
+ | `assembleCompact` | `Uint8Array` | External signature assembly — the SDK holds no private keys |
118
+ | `boundaryAnchorSigningInput` / `keyTransitionSigningInput` | `Result<SigningInput>` | Anchor and historical-key-transition producers |
119
+ | `encodeAnchoredExport` / `verifyAnchoredExport` | `Result<EncodedAnchoredExport \| AnchoredExportFacts>` | Deterministic archive framing + atomic verification |
120
+ | `verifyHistoricalAnchor` / `verifyKeyTransition` | `Result<AnchorFacts \| KeyTransitionFacts>` | Historical boundary + authenticated rollover verification |
121
+
122
+ Plus the versioned primitives (`jwkEncodePublic`, `thumbprint`, `uriNormalize`, `boundsNew`,
123
+ `jcsEncode`, `base64urlDecode`/`Encode`, the tagged JSON algebra) and the byte-distinct
124
+ local-development proof profile (`localLoopbackHttpProofSigningInput` and friends — literal
125
+ `127.0.0.1`/`[::1]` targets only, mandatory nonce; standard `dpop+jwt` rejects its bytes).
126
+ The full export list is [`src/index.ts`](src/index.ts).
127
+
128
+ ## Certified, not self-tested
129
+
130
+ Every release of this SDK is verified against the protocol's published, cryptographically
131
+ certified conformance corpora — **283 vectors** for contract-major 1 and **268** for
132
+ contract-major 2 — recomputing every verdict from scratch, with the corpus `index.json`
133
+ SHA-256 asserted at load so a drifted snapshot fails loudly. Permissiveness bugs (a parser
134
+ accepting what the spec forbids) are invisible to corpus agreement by construction, so the
135
+ suite additionally carries a per-language mutation gate that proves each closure
136
+ **red-capable**: mechanically remove a check, watch its test fail.
137
+
138
+ CI runs the full matrix on every push: strict typecheck, build, lint (including a library
139
+ purity rule — no I/O, clock, or randomness in `src/`), license check, unit tests, the
140
+ mutation gate, and both conformance corpora against the vendored snapshots.
141
+
142
+ Releases are published only from this repository's release workflow, via npm trusted
143
+ publishing (GitHub Actions OIDC — no long-lived tokens) with npm provenance on every
144
+ artifact.
145
+
146
+ ## Versioning
147
+
148
+ Package versions follow SemVer. Wire contract-majors are a separate axis: a new
149
+ contract-major lands **additively** (a minor release — this package already carries majors 1
150
+ and 2 side by side), and a package major is owed only when a shipped profile or public API is
151
+ removed or changes verdicts. Wire artifacts self-declare their major (payload `v`, the
152
+ `BAP<n>-…` suite name, major-bound domain separators), so the package number never needs to
153
+ encode it.
154
+
155
+ ## What this SDK does not do
156
+
157
+ It is a verifier, not an authority runtime. It holds no private keys, makes no network or
158
+ filesystem calls, reads no clock, and performs no replay reservation, revocation check, or
159
+ policy decision. Selecting trusted keys, reserving replay, and granting execution belong to
160
+ the host — a facts value is evidence, never a credential.
161
+
162
+ ## Protocol documentation
163
+
164
+ - [BAP v1 specification](https://github.com/baselabs/bounded_authority_protocol/blob/main/spec/bap-v1.md) ·
165
+ [v2 specification](https://github.com/baselabs/bounded_authority_protocol/blob/main/spec/bap-v2.md)
166
+ - [Certified conformance corpora](https://github.com/baselabs/bounded_authority_protocol/tree/main/priv/conformance/)
167
+ - [ADR 0014 — cross-language verifier SDKs](https://github.com/baselabs/bounded_authority_protocol/blob/main/docs/adr/0014-cross-language-verifier-sdks.md) ·
168
+ [ADR 0015 — graduation and publish topology](https://github.com/baselabs/bounded_authority_protocol/blob/main/docs/adr/0015-sdk-graduation-and-publish-topology.md)
169
+
170
+ ## Development
171
+
172
+ ```bash
173
+ pnpm install
174
+ pnpm typecheck && pnpm build && pnpm lint && pnpm license-check
175
+ pnpm test # unit + struct + façade corpus-vector tests
176
+ pnpm test:permissiveness # the mutation gate
177
+ pnpm conformance # 283/283 + key census (vendored v1 snapshot)
178
+ pnpm conformance:v2 # 268/268 + key census (vendored v2 snapshot)
179
+ ```
180
+
181
+ ## License
182
+
183
+ Apache-2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
@@ -0,0 +1,2 @@
1
+ export declare function base64urlDecode(input: Uint8Array, maxDecodedBytes?: number): Uint8Array;
2
+ export declare function base64urlEncode(input: Uint8Array): Uint8Array;
@@ -0,0 +1,115 @@
1
+ import { fail } from "./error.js";
2
+ // Unpadded base64url decode + encode, canonical per REQ1-B64-* (spec/bap-v1.md):
3
+ // - REQ1-B64-alphabet: only A-Za-z0-9-_ (no +/, no padding =, no whitespace)
4
+ // - REQ1-B64-no-padding: padding/whitespace forbidden
5
+ // - REQ1-B64-length: length mod 4 == 1 is invalid (cannot decode)
6
+ // - REQ1-B64-canonical: decode succeeds only if unpadded re-encode reproduces the input exactly
7
+ //
8
+ // Derived from spec/bap-v1.md § base64url + RFC 4648 §5. NOT using Buffer.from(s, "base64url") for
9
+ // decode because Node's base64url accepts padding/whitespace and is permissive; the bounds-checked
10
+ // canonical decoder is hand-rolled.
11
+ const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
12
+ const REV = new Int8Array(128).fill(-1);
13
+ for (let i = 0; i < ALPHABET.length; i++)
14
+ REV[ALPHABET.charCodeAt(i)] = i;
15
+ // Reject any byte that is not in the alphabet (covers +, /, = padding, whitespace, control chars).
16
+ function classifyByte(byte) {
17
+ return byte >= 0 && byte < 128 ? REV[byte] : -1;
18
+ }
19
+ export function base64urlDecode(input, maxDecodedBytes) {
20
+ const len = input.length;
21
+ // REQ1-B64-length: length mod 4 == 1 is structurally invalid.
22
+ if (len % 4 === 1)
23
+ fail("base64url: invalid length mod 4 == 1");
24
+ // The decoded length is deterministic from the input length + tail.
25
+ let outLen = (len >> 2) * 3;
26
+ if (len % 4 === 2)
27
+ outLen += 1;
28
+ else if (len % 4 === 3)
29
+ outLen += 2;
30
+ if (maxDecodedBytes !== undefined && outLen > maxDecodedBytes) {
31
+ fail("base64url: decoded length exceeds bound");
32
+ }
33
+ const out = new Uint8Array(outLen);
34
+ let op = 0;
35
+ let i = 0;
36
+ // Full 4-char groups → 3 bytes.
37
+ const full = len - (len % 4 === 0 ? 0 : len % 4);
38
+ while (i < full) {
39
+ const a = classifyByte(input[i++]);
40
+ const b = classifyByte(input[i++]);
41
+ const c = classifyByte(input[i++]);
42
+ const d = classifyByte(input[i++]);
43
+ if (a < 0 || b < 0 || c < 0 || d < 0)
44
+ fail("base64url: non-alphabet byte");
45
+ out[op++] = (a << 2) | (b >> 4);
46
+ out[op++] = (b << 4) | (c >> 2);
47
+ out[op++] = (c << 6) | d;
48
+ }
49
+ // Tail group.
50
+ const rem = len - i;
51
+ if (rem === 2) {
52
+ const a = classifyByte(input[i++]);
53
+ const b = classifyByte(input[i++]);
54
+ if (a < 0 || b < 0)
55
+ fail("base64url: non-alphabet byte");
56
+ out[op++] = (a << 2) | (b >> 4);
57
+ }
58
+ else if (rem === 3) {
59
+ const a = classifyByte(input[i++]);
60
+ const b = classifyByte(input[i++]);
61
+ const c = classifyByte(input[i++]);
62
+ if (a < 0 || b < 0 || c < 0)
63
+ fail("base64url: non-alphabet byte");
64
+ out[op++] = (a << 2) | (b >> 4);
65
+ out[op++] = (b << 4) | (c >> 2);
66
+ }
67
+ // REQ1-B64-canonical: re-encode the decoded bytes; the unpadded form must reproduce the input.
68
+ const reEncoded = base64urlEncode(out.subarray(0, op));
69
+ if (reEncoded.length !== len || !bytesEqual(reEncoded, input)) {
70
+ fail("base64url: non-canonical input");
71
+ }
72
+ return out.subarray(0, op);
73
+ }
74
+ export function base64urlEncode(input) {
75
+ const len = input.length;
76
+ const outLen = ((len + 2) / 3 | 0) * 4;
77
+ // Trim the padding: unpadded output length.
78
+ const rem = len % 3;
79
+ const padded = rem === 0 ? outLen : outLen - (3 - rem);
80
+ const out = new Uint8Array(padded);
81
+ let op = 0;
82
+ let i = 0;
83
+ const full = len - rem;
84
+ while (i < full) {
85
+ const a = input[i++];
86
+ const b = input[i++];
87
+ const c = input[i++];
88
+ out[op++] = ALPHABET.charCodeAt(a >> 2);
89
+ out[op++] = ALPHABET.charCodeAt(((a & 0x03) << 4) | (b >> 4));
90
+ out[op++] = ALPHABET.charCodeAt(((b & 0x0f) << 2) | (c >> 6));
91
+ out[op++] = ALPHABET.charCodeAt(c & 0x3f);
92
+ }
93
+ if (rem === 1) {
94
+ const a = input[i++];
95
+ out[op++] = ALPHABET.charCodeAt(a >> 2);
96
+ out[op++] = ALPHABET.charCodeAt((a & 0x03) << 4);
97
+ }
98
+ else if (rem === 2) {
99
+ const a = input[i++];
100
+ const b = input[i++];
101
+ out[op++] = ALPHABET.charCodeAt(a >> 2);
102
+ out[op++] = ALPHABET.charCodeAt(((a & 0x03) << 4) | (b >> 4));
103
+ out[op++] = ALPHABET.charCodeAt((b & 0x0f) << 2);
104
+ }
105
+ return out;
106
+ }
107
+ function bytesEqual(a, b) {
108
+ if (a.length !== b.length)
109
+ return false;
110
+ for (let i = 0; i < a.length; i++)
111
+ if (a[i] !== b[i])
112
+ return false;
113
+ return true;
114
+ }
115
+ //# sourceMappingURL=base64url.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base64url.js","sourceRoot":"","sources":["../../src/base64url.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAElC,iFAAiF;AACjF,+EAA+E;AAC/E,wDAAwD;AACxD,oEAAoE;AACpE,kGAAkG;AAClG,EAAE;AACF,mGAAmG;AACnG,mGAAmG;AACnG,oCAAoC;AAEpC,MAAM,QAAQ,GAAG,kEAAkE,CAAC;AACpF,MAAM,GAAG,GAAG,IAAI,SAAS,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AACxC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE;IAAE,GAAG,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AAE1E,mGAAmG;AACnG,SAAS,YAAY,CAAC,IAAY;IAChC,OAAO,IAAI,IAAI,CAAC,IAAI,IAAI,GAAG,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACnD,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,KAAiB,EAAE,eAAwB;IACzE,MAAM,GAAG,GAAG,KAAK,CAAC,MAAM,CAAC;IACzB,8DAA8D;IAC9D,IAAI,GAAG,GAAG,CAAC,KAAK,CAAC;QAAE,IAAI,CAAC,sCAAsC,CAAC,CAAC;IAChE,oEAAoE;IACpE,IAAI,MAAM,GAAG,CAAC,G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GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAC9D,GAAG,CAAC,EAAE,EAAE,CAAC,GAAG,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IACnD,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,UAAU,CAAC,CAAa,EAAE,CAAa;IAC9C,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IACxC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE;QAAE,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAAE,OAAO,KAAK,CAAC;IACnE,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,50 @@
1
+ export declare const MAXIMA: {
2
+ readonly compact_bytes: 65536;
3
+ readonly encoded_segment_bytes: 32768;
4
+ readonly decoded_segment_bytes: 24576;
5
+ readonly json_bytes: 65536;
6
+ readonly depth: 32;
7
+ readonly object_members: 64;
8
+ readonly array_items: 256;
9
+ readonly total_nodes: 4096;
10
+ readonly string_bytes: 8192;
11
+ readonly key_bytes: 128;
12
+ readonly number_lexeme_bytes: 64;
13
+ readonly integer_magnitude: 9007199254740991;
14
+ readonly float_magnitude: 9007199254740991;
15
+ readonly kid_bytes: 128;
16
+ readonly jcs_bytes: 65536;
17
+ readonly uri_bytes: 8192;
18
+ readonly identifier_bytes: 512;
19
+ readonly nonce_bytes: 512;
20
+ readonly method_bytes: 32;
21
+ readonly operation_bytes: 128;
22
+ readonly audiences: 64;
23
+ readonly operations: 64;
24
+ readonly selectors: 64;
25
+ readonly path_segments: 32;
26
+ readonly one_of_values: 256;
27
+ readonly public_key_bytes: 32;
28
+ readonly signature_bytes: 64;
29
+ readonly digest_bytes: 32;
30
+ readonly clock_skew: 60;
31
+ readonly proof_max_age: 300;
32
+ readonly chain_row_bytes: 4096;
33
+ readonly chain_rows: 65536;
34
+ readonly anchor_bytes: 8192;
35
+ readonly archive_header_bytes: 8192;
36
+ readonly archive_chunks: 65796;
37
+ readonly archive_bytes: 270820384;
38
+ readonly object_version_bytes: 512;
39
+ readonly key_transitions: 256;
40
+ };
41
+ export type MaximaKey = keyof typeof MAXIMA;
42
+ export interface Bounds {
43
+ readonly maximum: typeof MAXIMA;
44
+ readonly overrides: ReadonlyMap<MaximaKey, number>;
45
+ }
46
+ export declare const MAXIMUM_BOUNDS: Bounds;
47
+ export declare function boundsMaximum(): Bounds;
48
+ export declare function boundsNew(tightening?: Readonly<Record<string, number>>): Bounds;
49
+ export declare function coerceBounds(b: Bounds): Bounds;
50
+ export declare function resolve(b: Bounds, key: MaximaKey): number;