tsp-verify 0.1.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/LICENSE ADDED
@@ -0,0 +1,177 @@
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
162
+ other commercial damages or losses), even if such Contributor
163
+ has been 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
+
package/NOTICE ADDED
@@ -0,0 +1,7 @@
1
+ TSP Gateway
2
+ Copyright 2026 LexiCo AS (Tønsberg, Norway)
3
+
4
+ This product includes software developed at LexiCo AS, including the TSP v3
5
+ verifier core vendored from the Trust Standard Protocol reference
6
+ implementation (github.com/Lexi-TSP/Trust-Standard-Protocol, Apache-2.0) —
7
+ see src/core/PROVENANCE.md for the exact vendoring record.
package/README.md ADDED
@@ -0,0 +1,65 @@
1
+ # tsp-verify — JavaScript port of the TSP reference verifier core
2
+
3
+ Verify [Trust Standard Protocol](https://truststandardprotocol.com) evidence
4
+ from JavaScript: canonicalization (RFC 8785 JCS, byte-identical to the reference),
5
+ trust envelope + trust manifest validation, Ed25519 local verification with the
6
+ granular check profile, and offline **license-artifact** verification
7
+ (`tsp.license.v1`, ADR-0010).
8
+
9
+ **Zero dependencies** — Node ≥ 20 only (uses the built-in Web Crypto API).
10
+
11
+ ```js
12
+ import { verifyLocal } from "tsp-verify";
13
+
14
+ const result = await verifyLocal(envelope, { knownPublicKey });
15
+ console.log(result.valid); // true / false — fail-closed
16
+ console.log(result.checks.ledgerHash); // granular per-check verdicts
17
+ ```
18
+
19
+ It also verifies **commercial licenses** (TSP License Artifact v1) — a sibling
20
+ artifact validated fully offline through `license → issuer → pinned license-root`,
21
+ reusing the same crypto substrate:
22
+
23
+ ```js
24
+ import { verifyLicense } from "tsp-verify";
25
+
26
+ const r = await verifyLicense(
27
+ bundle, // a tsp.license-bundle.v1
28
+ {
29
+ origin: "https://customer.example", // this deployment's manifest origin
30
+ trustedRootKeys: [pinnedRoot], // [{ rootKeyId, publicKey }]
31
+ requiredModules: ["gateway-pro"], // default-deny per module
32
+ },
33
+ new Date(), // or an ISO-8601 string
34
+ );
35
+ console.log(r.ok, r.reason); // e.g. true "valid" | false "license_expired"
36
+ ```
37
+
38
+ ## Conformance is the correctness claim
39
+
40
+ This port is correct because it reproduces the normative verdicts of the
41
+ [tsp-spec](https://github.com/Lexi-TSP/tsp-spec) fixture suites — the v3.0
42
+ TrustEnvelope vectors (including the ADR-0002 tamper-rejection profile) and the
43
+ ADR-0010 license vectors — not because anyone says so. Two separate
44
+ checksum-pinned tracks, never mixed. Prove it:
45
+
46
+ ```bash
47
+ npm run conformance
48
+ # integrity: 10 v3.0 fixtures match pinned SHA256SUMS
49
+ # integrity: 9 license fixtures match pinned SHA256SUMS
50
+ # ✓ all 23 conformance vectors pass against the JS port
51
+ ```
52
+
53
+ A failure of that runner is a bug in this port, never grounds to adjust the
54
+ fixtures (ADR-0008: the spec owns the truth).
55
+
56
+ ## API
57
+
58
+ - `canonicalize(value)` — RFC 8785 JCS canonical string.
59
+ - `sha256Hex(string)` — SHA-256 hex of a UTF-8 string.
60
+ - `validateTrustEnvelopeShape(envelope)` / `validateTrustManifest(manifest)` — structural validation.
61
+ - `verifyLocal(envelope, { knownPublicKey })` — local-plane verify (schema + content + ledger + Ed25519 signatures).
62
+ - `validateLicenseBundleShape(bundle)` / `verifyLicense(bundle, config, now)` — offline license-artifact verification.
63
+
64
+ Verification only: this package holds no private keys and signs nothing. Part of
65
+ the `tsp-verify` family alongside the Python, Rust, and Go ports.
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "tsp-verify",
3
+ "version": "0.1.0",
4
+ "description": "JavaScript port of the Trust Standard Protocol (TSP) verifier core: RFC 8785 canonicalization, trust envelope + manifest validation, Ed25519 local verification, and offline license-artifact verification (tsp.license.v1). Zero dependencies.",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "exports": { ".": "./src/index.js" },
8
+ "files": ["src", "LICENSE", "NOTICE", "README.md"],
9
+ "engines": { "node": ">=20" },
10
+ "scripts": {
11
+ "test": "node --test test/*.test.mjs",
12
+ "conformance": "node conformance/run-conformance.mjs"
13
+ },
14
+ "keywords": ["tsp", "trust", "provenance", "verification", "ed25519", "license", "canonicalization"],
15
+ "license": "Apache-2.0",
16
+ "repository": { "type": "git", "url": "git+https://github.com/Lexi-TSP/tsp-js.git" },
17
+ "homepage": "https://truststandardprotocol.com",
18
+ "author": "LexiCo AS <hello@truststandardprotocol.com>",
19
+ "dependencies": {},
20
+ "devDependencies": {}
21
+ }
@@ -0,0 +1,67 @@
1
+ const REQUIRES_ESCAPE = /[\x00-\x1f"\\]/g;
2
+
3
+ const ESCAPE_MAP = {
4
+ '\b': '\\b',
5
+ '\t': '\\t',
6
+ '\n': '\\n',
7
+ '\f': '\\f',
8
+ '\r': '\\r',
9
+ '"': '\\"',
10
+ '\\': '\\\\',
11
+ };
12
+
13
+ const escapeChar = (char) => {
14
+ if (char in ESCAPE_MAP) {
15
+ return ESCAPE_MAP[char];
16
+ }
17
+
18
+ return `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`;
19
+ };
20
+
21
+ const canonicalString = (value) => `"${value.replace(REQUIRES_ESCAPE, escapeChar)}"`;
22
+
23
+ const canonicalNumber = (value) => {
24
+ if (!Number.isFinite(value)) {
25
+ throw new Error(`canonicalize: non-finite number not allowed: ${value}`);
26
+ }
27
+
28
+ if (Object.is(value, -0)) {
29
+ return '0';
30
+ }
31
+
32
+ return JSON.stringify(value);
33
+ };
34
+
35
+ export const canonicalize = (value) => {
36
+ if (value === null) {
37
+ return 'null';
38
+ }
39
+
40
+ if (typeof value === 'boolean') {
41
+ return value ? 'true' : 'false';
42
+ }
43
+
44
+ if (typeof value === 'number') {
45
+ return canonicalNumber(value);
46
+ }
47
+
48
+ if (typeof value === 'string') {
49
+ return canonicalString(value);
50
+ }
51
+
52
+ if (Array.isArray(value)) {
53
+ return `[${value.map(canonicalize).join(',')}]`;
54
+ }
55
+
56
+ if (typeof value === 'object') {
57
+ const keys = Object.keys(value).sort((a, b) => {
58
+ if (a < b) return -1;
59
+ if (a > b) return 1;
60
+ return 0;
61
+ });
62
+
63
+ return `{${keys.map((key) => `${canonicalString(key)}:${canonicalize(value[key])}`).join(',')}}`;
64
+ }
65
+
66
+ throw new Error(`canonicalize: unsupported value type: ${typeof value}`);
67
+ };
package/src/crypto.js ADDED
@@ -0,0 +1,15 @@
1
+ const ED25519_ALGORITHM = { name: 'Ed25519' };
2
+
3
+ export const importPublicKeyJwk = (jwk) =>
4
+ crypto.subtle.importKey('jwk', jwk, ED25519_ALGORITHM, true, ['verify']);
5
+
6
+ export const verifyEd25519 = (publicKey, signature, data) =>
7
+ crypto.subtle.verify(ED25519_ALGORITHM, publicKey, signature, data);
8
+
9
+ export const base64ToBytes = (value) => {
10
+ if (typeof atob === 'function') {
11
+ return Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
12
+ }
13
+
14
+ return Uint8Array.from(Buffer.from(value, 'base64'));
15
+ };
package/src/domains.js ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * TSP v3.0 canonical signing/ledger domain construction — SINGLE SOURCE.
3
+ *
4
+ * The domain rule is a crypto invariant (ADR-0002: executionProvenance is
5
+ * bound into both the ledger and signature domains; optional envelope fields
6
+ * are included if and only if present). It must exist exactly once so the
7
+ * local and online verifiers cannot diverge. Semantics are pinned by the
8
+ * tsp-spec v3.0 fixture suite (valid-with-provenance / tampered-provenance);
9
+ * normative authority is tsp-spec per ADR-0008 — do not edit this module to
10
+ * make a verifier pass, fix the verifier.
11
+ */
12
+
13
+ /**
14
+ * Ledger domain: everything the ledger hash covers — the envelope minus
15
+ * ledger.hash itself. Includes signatures; includes executionProvenance
16
+ * when present (ADR-0002).
17
+ */
18
+ export const buildLedgerDomain = (envelope) => {
19
+ const domain = {
20
+ tsp: envelope.tsp,
21
+ content: envelope.content,
22
+ process: envelope.process,
23
+ signatures: envelope.signatures,
24
+ ledger: { id: envelope.ledger.id, prevHash: envelope.ledger.prevHash },
25
+ };
26
+
27
+ if (envelope.declaration !== undefined) domain.declaration = envelope.declaration;
28
+ if (envelope.alignment !== undefined) domain.alignment = envelope.alignment;
29
+ if (envelope.timestamp !== undefined) domain.timestamp = envelope.timestamp;
30
+ if (envelope.executionProvenance !== undefined) {
31
+ domain.executionProvenance = envelope.executionProvenance;
32
+ }
33
+
34
+ return domain;
35
+ };
36
+
37
+ /**
38
+ * Signature domain: what each Ed25519 envelope signature covers — excludes
39
+ * the signatures array and the TSA token (timestamp is reduced to
40
+ * { claimed, tsaUrl } so a later TSA attestation does not invalidate the
41
+ * instance signature). Includes executionProvenance when present (ADR-0002).
42
+ */
43
+ export const buildSignatureDomain = (envelope) => {
44
+ const domain = {
45
+ tsp: envelope.tsp,
46
+ content: envelope.content,
47
+ process: envelope.process,
48
+ ledger: { id: envelope.ledger.id, prevHash: envelope.ledger.prevHash },
49
+ };
50
+
51
+ if (envelope.declaration !== undefined) domain.declaration = envelope.declaration;
52
+ if (envelope.alignment !== undefined) domain.alignment = envelope.alignment;
53
+ if (envelope.timestamp !== undefined) {
54
+ domain.timestamp = {
55
+ claimed: envelope.timestamp.claimed,
56
+ tsaUrl: envelope.timestamp.tsaUrl,
57
+ };
58
+ }
59
+ if (envelope.executionProvenance !== undefined) {
60
+ domain.executionProvenance = envelope.executionProvenance;
61
+ }
62
+
63
+ return domain;
64
+ };
package/src/hash.js ADDED
@@ -0,0 +1,8 @@
1
+ const encoder = new TextEncoder();
2
+
3
+ const bytesToHex = (bytes) => [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');
4
+
5
+ export const sha256Hex = async (input) => {
6
+ const digest = await crypto.subtle.digest('SHA-256', encoder.encode(input));
7
+ return bytesToHex(new Uint8Array(digest));
8
+ };
package/src/index.js ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * tsp-verify -- JavaScript port of the TSP reference verifier core.
3
+ *
4
+ * Normative authority is Lexi-TSP/tsp-spec (ADR-0008): this port is conformant
5
+ * because it reproduces the spec's fixture verdicts, not because it is trusted.
6
+ * Run `npm run conformance` to prove it on your machine. Verification only:
7
+ * holds no keys, signs nothing. Zero dependencies (Node >= 20 Web Crypto).
8
+ */
9
+ export { canonicalize } from './canonical.js';
10
+ export { sha256Hex } from './hash.js';
11
+ export { validateTrustEnvelopeShape } from './schema.js';
12
+ export { validateTrustManifest } from './manifest.js';
13
+ export { verifyLocal } from './verify-local.js';
14
+ export { validateLicenseBundleShape } from './license-schema.js';
15
+ export { verifyLicense } from './verify-license.js';
@@ -0,0 +1,24 @@
1
+ /**
2
+ * TSP License Artifact v1 — signing-domain construction (SINGLE SOURCE).
3
+ *
4
+ * Mirrors core/domains.js for the envelope: the license and issuer-credential
5
+ * signing domains are defined exactly once so the offline issuer/ceremony
6
+ * signer and verify_license() cannot diverge. ADR-0010: a license is a SIBLING
7
+ * artifact that reuses the TSP cryptographic substrate (canonicalization,
8
+ * SHA-256, Ed25519, signing-domain discipline) and nothing of the
9
+ * TrustEnvelope semantics. This module does NOT touch the envelope domains.
10
+ *
11
+ * The license body and the issuer-credential body are CLOSED allowlists
12
+ * (see license-schema.js). The signature therefore covers the ENTIRE
13
+ * validated body object — there are no excluded fields (unlike the envelope,
14
+ * whose signatures[] and TSA token are excluded) because each signature lives
15
+ * OUTSIDE the body, in the bundle. Consequence, load-bearing: schema
16
+ * validation MUST run before signature verification, so an injected unknown
17
+ * field is rejected structurally rather than riding along unsigned.
18
+ */
19
+
20
+ /** Domain for the license signature (issuer-signed): the whole validated license body. */
21
+ export const buildLicenseSigningDomain = (license) => license;
22
+
23
+ /** Domain for the issuer-credential signature (root-signed): the whole validated credential body. */
24
+ export const buildIssuerCredentialSigningDomain = (credential) => credential;
@@ -0,0 +1,162 @@
1
+ /**
2
+ * TSP License Artifact v1 — structural / shape validation.
3
+ *
4
+ * Closed-allowlist shape validator for the `tsp.license-bundle.v1` container
5
+ * and its two signed bodies (`tsp.license.v1`, `tsp.license-issuer-credential.v1`).
6
+ * Mirrors core/schema.js discipline for the envelope: unknown fields are
7
+ * rejected, so the full body can be safely signed/verified (see license-domain.js).
8
+ *
9
+ * ADR-0010 sibling artifact — this validator is independent of
10
+ * validateTrustEnvelopeShape() and must never be merged into it.
11
+ *
12
+ * Normative authority for these shapes is the tsp-spec license-v1 fixture
13
+ * track + SHA256SUMS (ADR-0008 discipline); this is the reference validator.
14
+ */
15
+
16
+ const LICENSE_ARTIFACT = 'tsp.license.v1';
17
+ const ISSUER_CRED_ARTIFACT = 'tsp.license-issuer-credential.v1';
18
+ const BUNDLE_ARTIFACT = 'tsp.license-bundle.v1';
19
+
20
+ const dateTimePattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
21
+ const editions = new Set(['trial', 'pro', 'enterprise']);
22
+ const PRIVATE_JWK_PARAMETERS = ['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'k'];
23
+
24
+ const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
25
+ const isString = (v) => typeof v === 'string';
26
+
27
+ const hasOnly = (value, path, allowed, errors) => {
28
+ const allowedSet = new Set(allowed);
29
+ for (const key of Object.keys(value)) {
30
+ if (!allowedSet.has(key)) errors.push(`${path}.${key} is not allowed`);
31
+ }
32
+ };
33
+
34
+ const recordAt = (parent, key, path, errors) => {
35
+ const v = parent[key];
36
+ if (!isRecord(v)) { errors.push(`${path}.${key} must be an object`); return undefined; }
37
+ return v;
38
+ };
39
+
40
+ const stringAt = (parent, key, path, errors) => {
41
+ const v = parent[key];
42
+ if (!isString(v) || v.length === 0) { errors.push(`${path}.${key} must be a non-empty string`); return undefined; }
43
+ return v;
44
+ };
45
+
46
+ const dateTimeAt = (parent, key, path, errors) => {
47
+ const v = stringAt(parent, key, path, errors);
48
+ if (v !== undefined && (!dateTimePattern.test(v) || Number.isNaN(Date.parse(v)))) {
49
+ errors.push(`${path}.${key} must be an ISO-8601 date-time string`);
50
+ }
51
+ };
52
+
53
+ const optionalDateTimeAt = (parent, key, path, errors) => {
54
+ if (parent[key] !== undefined) dateTimeAt(parent, key, path, errors);
55
+ };
56
+
57
+ const stringArrayAt = (parent, key, path, errors, { optional = false } = {}) => {
58
+ const v = parent[key];
59
+ if (v === undefined && optional) return;
60
+ if (!Array.isArray(v)) { errors.push(`${path}.${key} must be an array`); return; }
61
+ v.forEach((entry, i) => {
62
+ if (!isString(entry)) errors.push(`${path}.${key}[${i}] must be a string`);
63
+ });
64
+ };
65
+
66
+ const ed25519PublicJwkAt = (parent, key, path, errors) => {
67
+ const jwk = parent[key];
68
+ if (!isRecord(jwk)) { errors.push(`${path}.${key} must be an object`); return; }
69
+ const p = `${path}.${key}`;
70
+ hasOnly(jwk, p, ['kty', 'crv', 'x', 'alg', 'use', 'kid', 'ext', 'key_ops'], errors);
71
+ const priv = PRIVATE_JWK_PARAMETERS.filter((k) => Object.hasOwn(jwk, k));
72
+ if (priv.length > 0) errors.push(`${p} must not contain private JWK parameter(s): ${priv.join(', ')}`);
73
+ if (jwk.kty !== 'OKP') errors.push(`${p}.kty must be OKP for Ed25519 public keys`);
74
+ if (jwk.crv !== 'Ed25519') errors.push(`${p}.crv must be Ed25519`);
75
+ if (!isString(jwk.x) || jwk.x.length === 0) errors.push(`${p}.x must be a non-empty public key value`);
76
+ if (jwk.alg !== undefined && jwk.alg !== 'Ed25519' && jwk.alg !== 'EdDSA') {
77
+ errors.push(`${p}.alg must be Ed25519 or EdDSA when present`);
78
+ }
79
+ };
80
+
81
+ const signatureBlockAt = (parent, key, path, errors) => {
82
+ const block = recordAt(parent, key, path, errors);
83
+ if (!block) return;
84
+ const p = `${path}.${key}`;
85
+ hasOnly(block, p, ['algorithm', 'signature'], errors);
86
+ const alg = stringAt(block, 'algorithm', p, errors);
87
+ if (alg !== undefined && alg !== 'ed25519') errors.push(`${p}.algorithm must be ed25519`);
88
+ stringAt(block, 'signature', p, errors);
89
+ };
90
+
91
+ const validateLicenseBody = (license, errors) => {
92
+ if (!license) return;
93
+ hasOnly(
94
+ license,
95
+ 'license',
96
+ ['artifact_type', 'license_id', 'issuer_id', 'subject', 'edition', 'modules', 'features', 'issuedAt', 'validFrom', 'validUntil', 'graceUntil'],
97
+ errors,
98
+ );
99
+ const at = stringAt(license, 'artifact_type', 'license', errors);
100
+ if (at !== undefined && at !== LICENSE_ARTIFACT) errors.push(`license.artifact_type must be "${LICENSE_ARTIFACT}"`);
101
+ stringAt(license, 'license_id', 'license', errors);
102
+ stringAt(license, 'issuer_id', 'license', errors);
103
+
104
+ const subject = recordAt(license, 'subject', 'license', errors);
105
+ if (subject) {
106
+ hasOnly(subject, 'license.subject', ['origin', 'allowedOrigins', 'organization'], errors);
107
+ stringAt(subject, 'origin', 'license.subject', errors);
108
+ stringAt(subject, 'organization', 'license.subject', errors);
109
+ stringArrayAt(subject, 'allowedOrigins', 'license.subject', errors, { optional: true });
110
+ }
111
+
112
+ const edition = stringAt(license, 'edition', 'license', errors);
113
+ if (edition !== undefined && !editions.has(edition)) {
114
+ errors.push('license.edition must be trial, pro, or enterprise');
115
+ }
116
+ stringArrayAt(license, 'modules', 'license', errors);
117
+ stringArrayAt(license, 'features', 'license', errors, { optional: true });
118
+ dateTimeAt(license, 'issuedAt', 'license', errors);
119
+ dateTimeAt(license, 'validFrom', 'license', errors);
120
+ dateTimeAt(license, 'validUntil', 'license', errors);
121
+ optionalDateTimeAt(license, 'graceUntil', 'license', errors);
122
+ };
123
+
124
+ const validateIssuerCredential = (issuerCredential, errors) => {
125
+ if (!issuerCredential) return;
126
+ hasOnly(issuerCredential, 'issuerCredential', ['credential', 'rootSignature'], errors);
127
+
128
+ const cred = recordAt(issuerCredential, 'credential', 'issuerCredential', errors);
129
+ if (cred) {
130
+ hasOnly(cred, 'issuerCredential.credential', ['artifact_type', 'issuer_id', 'issuerPublicKey', 'validFrom', 'validUntil', 'rootKeyId'], errors);
131
+ const at = stringAt(cred, 'artifact_type', 'issuerCredential.credential', errors);
132
+ if (at !== undefined && at !== ISSUER_CRED_ARTIFACT) {
133
+ errors.push(`issuerCredential.credential.artifact_type must be "${ISSUER_CRED_ARTIFACT}"`);
134
+ }
135
+ stringAt(cred, 'issuer_id', 'issuerCredential.credential', errors);
136
+ ed25519PublicJwkAt(cred, 'issuerPublicKey', 'issuerCredential.credential', errors);
137
+ dateTimeAt(cred, 'validFrom', 'issuerCredential.credential', errors);
138
+ dateTimeAt(cred, 'validUntil', 'issuerCredential.credential', errors);
139
+ stringAt(cred, 'rootKeyId', 'issuerCredential.credential', errors);
140
+ }
141
+
142
+ signatureBlockAt(issuerCredential, 'rootSignature', 'issuerCredential', errors);
143
+ };
144
+
145
+ export const validateLicenseBundleShape = (value) => {
146
+ const errors = [];
147
+ if (!isRecord(value)) return ['bundle must be an object'];
148
+
149
+ hasOnly(value, 'bundle', ['artifact_type', 'license', 'licenseSignature', 'issuerCredential'], errors);
150
+ const at = stringAt(value, 'artifact_type', 'bundle', errors);
151
+ if (at !== undefined && at !== BUNDLE_ARTIFACT) errors.push(`bundle.artifact_type must be "${BUNDLE_ARTIFACT}"`);
152
+
153
+ validateLicenseBody(recordAt(value, 'license', 'bundle', errors), errors);
154
+ signatureBlockAt(value, 'licenseSignature', 'bundle', errors);
155
+ validateIssuerCredential(recordAt(value, 'issuerCredential', 'bundle', errors), errors);
156
+
157
+ return errors;
158
+ };
159
+
160
+ export const LICENSE_ARTIFACT_TYPE = LICENSE_ARTIFACT;
161
+ export const ISSUER_CREDENTIAL_ARTIFACT_TYPE = ISSUER_CRED_ARTIFACT;
162
+ export const LICENSE_BUNDLE_ARTIFACT_TYPE = BUNDLE_ARTIFACT;