@zanii/vc 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,159 @@
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 Derivative
95
+ 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; and
103
+
104
+ (d) If the Work includes a "NOTICE" text file as part of its
105
+ distribution, then any Derivative Works that You distribute must
106
+ include a readable copy of the attribution notices contained
107
+ within such NOTICE file.
108
+
109
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
110
+ any Contribution intentionally submitted for inclusion in the Work
111
+ by You to the Licensor shall be under the terms and conditions of
112
+ this License, without any additional terms or conditions.
113
+
114
+ 6. Trademarks. This License does not grant permission to use the trade
115
+ names, trademarks, service marks, or product names of the Licensor,
116
+ except as required for reasonable and customary use in describing the
117
+ origin of the Work and reproducing the content of the NOTICE file.
118
+
119
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed
120
+ to in writing, Licensor provides the Work (and each Contributor
121
+ provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES
122
+ OR CONDITIONS OF ANY KIND, either express or implied, including,
123
+ without limitation, any warranties or conditions of TITLE,
124
+ NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
125
+
126
+ 8. Limitation of Liability. In no event and under no legal theory,
127
+ whether in tort (including negligence), contract, or otherwise,
128
+ unless required by applicable law (such as deliberate and grossly
129
+ negligent acts) or agreed to in writing, shall any Contributor be
130
+ liable to You for damages, including any direct, indirect, special,
131
+ incidental, or consequential damages of any character arising as a
132
+ result of this License or out of the use or inability to use the
133
+ Work.
134
+
135
+ 9. Accepting Warranty or Additional Liability. While redistributing
136
+ the Work or Derivative Works thereof, You may choose to offer,
137
+ and charge a fee for, acceptance of support, warranty, indemnity,
138
+ or other liability obligations and/or rights consistent with this
139
+ License. However, in accepting such obligations, You may act only
140
+ on Your own behalf and on Your sole responsibility, not on behalf
141
+ of any other Contributor, and only if You agree to indemnify,
142
+ defend, and hold each Contributor harmless for any liability
143
+ incurred by, or claims asserted against, such Contributor.
144
+
145
+ END OF TERMS AND CONDITIONS
146
+
147
+ Copyright 2026 Zanii
148
+
149
+ Licensed under the Apache License, Version 2.0 (the "License");
150
+ you may not use this file except in compliance with the License.
151
+ You may obtain a copy of the License at
152
+
153
+ http://www.apache.org/licenses/LICENSE-2.0
154
+
155
+ Unless required by applicable law or agreed to in writing, software
156
+ distributed under the License is distributed on an "AS IS" BASIS,
157
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
158
+ See the License for the specific language governing permissions and
159
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,54 @@
1
+ # @zanii/vc
2
+
3
+ The **W3C Verifiable Credentials 2.0 bridge** — and it is not cosmetic. Zanii already
4
+ signs with did:key + Ed25519 over JCS, which is *exactly* the W3C Data Integrity
5
+ cryptosuite **`eddsa-jcs-2022`**. So `toVC` emits spec-conformant VCs with genuine
6
+ `DataIntegrityProof`s that a standards wallet can verify with no Zanii code at all —
7
+ and `verifyVC` verifies any did:key `eddsa-jcs-2022` VC from anyone.
8
+
9
+ ```sh
10
+ npm install @zanii/vc @zanii/core @zanii/credentials @zanii/cv
11
+ ```
12
+
13
+ ```ts
14
+ import { toVC, cvToVC, signVC, verifyVC } from '@zanii/vc';
15
+
16
+ // a university exports a Zanii diploma credential as a W3C VC (same issuer key):
17
+ const vc = toVC(zaniiCredential, issuerPrivateKey, { created: now });
18
+ // → { "@context": ["https://www.w3.org/ns/credentials/v2"],
19
+ // type: ["VerifiableCredential", "ZaniiCredential"],
20
+ // issuer: "did:key:z6Mk…", validFrom, validUntil,
21
+ // credentialSubject: { id: holderDid, scope, claim, issuerDomain },
22
+ // proof: { type: "DataIntegrityProof", cryptosuite: "eddsa-jcs-2022", proofValue: "z…" } }
23
+
24
+ // an agent exports its CV as a self-issued VC:
25
+ const cvVc = cvToVC(signedCv, agentPrivateKey, { created: now });
26
+
27
+ // verify anyone's did:key eddsa-jcs-2022 VC:
28
+ const r = verifyVC(vc, { at: now }); // window checked only when `at` is passed
29
+ r.ok; r.issuer;
30
+
31
+ // or sign your own custom VC types with the generic engine:
32
+ signVC({ '@context': [...], type: ['VerifiableCredential'], issuer, credentialSubject }, keypair, { created });
33
+ ```
34
+
35
+ Python: `from zanii.vc import to_vc, cv_to_vc, verify_vc, ...` — **byte-identical**:
36
+ the same credential + key + timestamp produces the exact same VC (proofValue included)
37
+ in both languages, locked by parity vectors.
38
+
39
+ ## Guardrails
40
+
41
+ - `toVC`/`cvToVC` **verify the Zanii artifact first** — a forged credential or altered
42
+ CV is refused, so the bridge can never launder a broken artifact into a
43
+ valid-looking VC.
44
+ - `verifyVC` is deterministic: the validity window is checked only against an explicit
45
+ `at`, never a hidden "now".
46
+
47
+ ## The limit, stated up front
48
+
49
+ This bridges the **format, not the trust model.** A VC produced here proves what the
50
+ Zanii artifact proved — no more. Revocation with its explicit freshness window, the
51
+ domain-bound issuer root-of-trust, and ledger-backed history remain Zanii-side checks
52
+ (`@zanii/credentials`, `@zanii/kya`); W3C StatusList is deliberately not implemented —
53
+ mapping it would claim a liveness this bridge cannot provide. And `verifyVC` checks
54
+ the proof, not the issuer's institutional identity — say what it does, never more.
@@ -0,0 +1,68 @@
1
+ import type { Credential } from '@zanii/credentials';
2
+ import { type AgentCV } from '@zanii/cv';
3
+ export declare const VC_CONTEXT = "https://www.w3.org/ns/credentials/v2";
4
+ export declare const CRYPTOSUITE = "eddsa-jcs-2022";
5
+ export interface DataIntegrityProof {
6
+ type: 'DataIntegrityProof';
7
+ cryptosuite: typeof CRYPTOSUITE;
8
+ created: string;
9
+ /** `did:key:z6Mk…#z6Mk…` — the did:key with its multikey fragment. */
10
+ verificationMethod: string;
11
+ proofPurpose: 'assertionMethod';
12
+ /** Multibase base58btc (`z…`) of the Ed25519 signature. */
13
+ proofValue: string;
14
+ }
15
+ export interface VerifiableCredential {
16
+ '@context': string[];
17
+ type: string[];
18
+ issuer: string;
19
+ validFrom?: string;
20
+ validUntil?: string;
21
+ credentialSubject: Record<string, unknown>;
22
+ proof?: DataIntegrityProof;
23
+ [k: string]: unknown;
24
+ }
25
+ /** The verification method a did:key controls: the DID plus its own multikey fragment. */
26
+ export declare function verificationMethodOf(did: string): string;
27
+ /**
28
+ * Sign any VC-shaped document with a did:key per `eddsa-jcs-2022`. The generic proof
29
+ * engine — the mappers below use it, and you can too for custom VC types.
30
+ */
31
+ export declare function signVC(unsecured: Omit<VerifiableCredential, 'proof'>, signer: {
32
+ did: string;
33
+ privateKey: Uint8Array;
34
+ }, opts: {
35
+ created: string;
36
+ }): VerifiableCredential;
37
+ export interface VCCheck {
38
+ ok: boolean;
39
+ reasons: string[];
40
+ /** The issuer DID whose key produced the proof (when it verified). */
41
+ issuer: string | null;
42
+ }
43
+ /**
44
+ * Verify a did:key `eddsa-jcs-2022` VC — any issuer, not just Zanii's. Checks the
45
+ * DataIntegrityProof and that the verification method belongs to the stated issuer.
46
+ * Pass `at` to also check the `validFrom`/`validUntil` window (deliberately not
47
+ * defaulted to "now" — verification stays deterministic).
48
+ */
49
+ export declare function verifyVC(vc: VerifiableCredential | undefined, opts?: {
50
+ at?: string;
51
+ }): VCCheck;
52
+ /**
53
+ * Export a `@zanii/credentials` credential as a W3C VC, re-issued by the SAME issuer
54
+ * key. The Zanii signature is verified first — an invalid credential is refused, so
55
+ * the bridge can never launder a forged artifact into a valid-looking VC. (Revocation
56
+ * and issuer-domain resolution are deliberately NOT checked here — acceptance-time
57
+ * checks belong to the verifier via `@zanii/credentials`; the bridge only re-encodes.)
58
+ */
59
+ export declare function toVC(credential: Credential, issuerPrivateKey: Uint8Array, opts: {
60
+ created: string;
61
+ }): VerifiableCredential;
62
+ /** Export an AgentCV as a self-issued VC — the agent attests its own assembled view. */
63
+ export declare function cvToVC(cv: AgentCV, agentPrivateKey: Uint8Array, opts: {
64
+ created: string;
65
+ }): VerifiableCredential;
66
+ /** Decode helper for tests/interop: raw signature bytes from a multibase proofValue. */
67
+ export declare function proofSignatureBytes(proofValue: string):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AE,GACxB,oBAAoB,CAuBtB;AAED,MAAM,WAAW,OAAO;IACtB,EAAE,EAAE,OAAO,CAAC;IACZ,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,sEAAsE;IACtE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB;AAED;;;;;GAKG;AACH,wBAAgB,QAAQ,CAAC,EAAE,EAAE,oBAAoB,GAAG,SAAS,EAAE,IAAI,GAAE;IAAE,EAAE,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,OAAO,CA+ClG;AAeD;;;;;;GAMG;AACH,wBAAgB,IAAI,CAClB,UAAU,EAAE,UAAU,EACtB,gBAAgB,EAAE,UAAU,EAC5B,IAAI,EAAE;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,GACxB,oBAAoB,CAwBtB;AAED,wFAAwF;AACxF,wBAAgB,MAAM,CAAC,EAAE,EAAE,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,IAAI,EAAE;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,oBAAoB,CAuBhH;AAED,wFAAwF;AACxF,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,GAAG,UAAU,CAGlE"}
package/dist/index.js ADDED
@@ -0,0 +1,217 @@
1
+ /**
2
+ * @zanii/vc — the W3C Verifiable Credentials 2.0 bridge.
3
+ *
4
+ * Governments, universities, and wallets increasingly speak the W3C VC data model.
5
+ * Zanii doesn't need a new trust stack to meet them: Zanii already signs with
6
+ * **did:key + Ed25519 over JCS**, which is *exactly* the W3C Data Integrity
7
+ * cryptosuite **`eddsa-jcs-2022`**. So this bridge is not cosmetic — `toVC` emits
8
+ * spec-conformant VCs with genuine `DataIntegrityProof`s a standards wallet can
9
+ * verify, and `verifyVC` verifies any did:key `eddsa-jcs-2022` VC from anyone.
10
+ *
11
+ * Two mappers over one proof engine:
12
+ * - `toVC(credential, issuerKey)` — a `@zanii/credentials` credential (diploma,
13
+ * licence), re-issued as a VC **by the same issuer key** (the Zanii signature is
14
+ * verified first; an invalid credential is refused).
15
+ * - `cvToVC(cv, agentKey)` — an AgentCV as a self-issued VC (the agent attests its
16
+ * own assembled view, exactly like `signCV`).
17
+ *
18
+ * ## The limit, stated up front
19
+ *
20
+ * This bridges the **format, not the trust model.** A VC produced here proves what
21
+ * the Zanii artifact proved — no more. Revocation with an explicit freshness window,
22
+ * the domain-bound issuer root-of-trust, and ledger-backed history remain Zanii-side
23
+ * checks (`@zanii/credentials` `verifyCredential`, `resolveIssuer`); W3C-native
24
+ * status mechanisms (StatusList) are deliberately not implemented — mapping them
25
+ * would claim a liveness this bridge cannot provide. And `verifyVC` checks the
26
+ * proof and (optionally) the validity window — it does NOT resolve issuers or check
27
+ * revocation; say what it does, never more.
28
+ */
29
+ import { ed25519 } from '@noble/curves/ed25519';
30
+ import { sha256 } from '@noble/hashes/sha256';
31
+ import { hexToBytes } from '@noble/hashes/utils';
32
+ import { base58 } from '@scure/base';
33
+ import { canonicalBytes, publicKeyFromDid } from '@zanii/core';
34
+ import { verifyCV } from '@zanii/cv';
35
+ export const VC_CONTEXT = 'https://www.w3.org/ns/credentials/v2';
36
+ export const CRYPTOSUITE = 'eddsa-jcs-2022';
37
+ /** The verification method a did:key controls: the DID plus its own multikey fragment. */
38
+ export function verificationMethodOf(did) {
39
+ return `${did}#${did.slice('did:key:'.length)}`;
40
+ }
41
+ /**
42
+ * `eddsa-jcs-2022` hash step: sha256(JCS(proof options)) || sha256(JCS(document
43
+ * without proof)) — 64 bytes, which the Ed25519 key signs.
44
+ */
45
+ function hashData(doc, proofOptions) {
46
+ const { proof: _omit, ...unsecured } = doc;
47
+ const configHash = sha256(canonicalBytes(proofOptions));
48
+ const docHash = sha256(canonicalBytes(unsecured));
49
+ const out = new Uint8Array(64);
50
+ out.set(configHash, 0);
51
+ out.set(docHash, 32);
52
+ return out;
53
+ }
54
+ /**
55
+ * Sign any VC-shaped document with a did:key per `eddsa-jcs-2022`. The generic proof
56
+ * engine — the mappers below use it, and you can too for custom VC types.
57
+ */
58
+ export function signVC(unsecured, signer, opts) {
59
+ if (!Array.isArray(unsecured['@context']) || unsecured['@context'][0] !== VC_CONTEXT) {
60
+ throw new Error(`@context must start with ${VC_CONTEXT}`);
61
+ }
62
+ if (Number.isNaN(Date.parse(opts.created)))
63
+ throw new Error('created must be an ISO timestamp');
64
+ const proofOptions = {
65
+ '@context': unsecured['@context'],
66
+ type: 'DataIntegrityProof',
67
+ cryptosuite: CRYPTOSUITE,
68
+ created: opts.created,
69
+ verificationMethod: verificationMethodOf(signer.did),
70
+ proofPurpose: 'assertionMethod',
71
+ };
72
+ const sig = ed25519.sign(hashData(unsecured, proofOptions), signer.privateKey);
73
+ const proof = {
74
+ type: 'DataIntegrityProof',
75
+ cryptosuite: CRYPTOSUITE,
76
+ created: opts.created,
77
+ verificationMethod: proofOptions['verificationMethod'],
78
+ proofPurpose: 'assertionMethod',
79
+ proofValue: `z${base58.encode(sig)}`,
80
+ };
81
+ return { ...unsecured, proof };
82
+ }
83
+ /**
84
+ * Verify a did:key `eddsa-jcs-2022` VC — any issuer, not just Zanii's. Checks the
85
+ * DataIntegrityProof and that the verification method belongs to the stated issuer.
86
+ * Pass `at` to also check the `validFrom`/`validUntil` window (deliberately not
87
+ * defaulted to "now" — verification stays deterministic).
88
+ */
89
+ export function verifyVC(vc, opts = {}) {
90
+ const reasons = [];
91
+ const v = vc ?? {};
92
+ if (!Array.isArray(v['@context']) || v['@context'][0] !== VC_CONTEXT)
93
+ reasons.push(`@context must start with ${VC_CONTEXT}`);
94
+ if (!Array.isArray(v.type) || !v.type.includes('VerifiableCredential'))
95
+ reasons.push('type must include VerifiableCredential');
96
+ if (typeof v.issuer !== 'string' || !v.issuer.startsWith('did:key:'))
97
+ reasons.push('issuer must be a did:key (this bridge verifies did:key VCs only)');
98
+ const p = v.proof;
99
+ if (!p || p.type !== 'DataIntegrityProof' || p.cryptosuite !== CRYPTOSUITE) {
100
+ reasons.push(`proof must be a DataIntegrityProof with cryptosuite ${CRYPTOSUITE}`);
101
+ }
102
+ if (reasons.length > 0)
103
+ return { ok: false, reasons, issuer: null };
104
+ const proof = p;
105
+ if (proof.verificationMethod !== verificationMethodOf(v.issuer)) {
106
+ reasons.push('verificationMethod does not belong to the stated issuer');
107
+ }
108
+ const pub = publicKeyFromDid(v.issuer);
109
+ if (!pub)
110
+ reasons.push('issuer did:key does not decode to an Ed25519 key');
111
+ let sig = null;
112
+ if (typeof proof.proofValue === 'string' && proof.proofValue.startsWith('z')) {
113
+ try {
114
+ sig = base58.decode(proof.proofValue.slice(1));
115
+ }
116
+ catch {
117
+ sig = null;
118
+ }
119
+ }
120
+ if (!sig)
121
+ reasons.push('proofValue is not multibase base58btc');
122
+ if (reasons.length === 0 && pub && sig) {
123
+ const { proofValue: _omit, ...proofOptions } = proof;
124
+ const data = hashData(v, { '@context': v['@context'], ...proofOptions });
125
+ let valid = false;
126
+ try {
127
+ valid = ed25519.verify(sig, data, pub);
128
+ }
129
+ catch {
130
+ valid = false;
131
+ }
132
+ if (!valid)
133
+ reasons.push('proof does not verify — the VC was altered or signed by another key');
134
+ }
135
+ if (opts.at !== undefined && reasons.length === 0) {
136
+ const at = Date.parse(opts.at);
137
+ if (Number.isNaN(at))
138
+ reasons.push('at must be an ISO timestamp');
139
+ else {
140
+ if (typeof v.validFrom === 'string' && at < Date.parse(v.validFrom))
141
+ reasons.push(`not yet valid at ${opts.at}`);
142
+ if (typeof v.validUntil === 'string' && at > Date.parse(v.validUntil))
143
+ reasons.push(`expired at ${opts.at}`);
144
+ }
145
+ }
146
+ return { ok: reasons.length === 0, reasons, issuer: reasons.length === 0 ? v.issuer : null };
147
+ }
148
+ /** The Zanii credential signature convention: `ed25519:<hex>` over the JCS bytes minus `sig`. */
149
+ function zaniiSigValid(obj, signerDid) {
150
+ const pub = publicKeyFromDid(signerDid);
151
+ const hex = typeof obj.sig === 'string' && obj.sig.startsWith('ed25519:') ? obj.sig.slice(8) : '';
152
+ if (!pub || !/^[0-9a-f]{128}$/.test(hex))
153
+ return false;
154
+ const { sig: _omit, ...unsigned } = obj;
155
+ try {
156
+ return ed25519.verify(hexToBytes(hex), canonicalBytes(unsigned), pub);
157
+ }
158
+ catch {
159
+ return false;
160
+ }
161
+ }
162
+ /**
163
+ * Export a `@zanii/credentials` credential as a W3C VC, re-issued by the SAME issuer
164
+ * key. The Zanii signature is verified first — an invalid credential is refused, so
165
+ * the bridge can never launder a forged artifact into a valid-looking VC. (Revocation
166
+ * and issuer-domain resolution are deliberately NOT checked here — acceptance-time
167
+ * checks belong to the verifier via `@zanii/credentials`; the bridge only re-encodes.)
168
+ */
169
+ export function toVC(credential, issuerPrivateKey, opts) {
170
+ if (credential?.v !== 1 || credential.type !== 'credential' || !credential.issuer || !credential.holder) {
171
+ throw new Error('refusing to bridge: not a Zanii credential (v1)');
172
+ }
173
+ if (!zaniiSigValid(credential, credential.issuer)) {
174
+ throw new Error('refusing to bridge an invalid credential: bad issuer signature');
175
+ }
176
+ return signVC({
177
+ '@context': [VC_CONTEXT],
178
+ type: ['VerifiableCredential', 'ZaniiCredential'],
179
+ issuer: credential.issuer,
180
+ validFrom: credential.issued_at,
181
+ validUntil: credential.exp,
182
+ credentialSubject: {
183
+ id: credential.holder,
184
+ scope: credential.scope,
185
+ claim: credential.claim,
186
+ issuerDomain: credential.issuer_domain,
187
+ },
188
+ }, { did: credential.issuer, privateKey: issuerPrivateKey }, opts);
189
+ }
190
+ /** Export an AgentCV as a self-issued VC — the agent attests its own assembled view. */
191
+ export function cvToVC(cv, agentPrivateKey, opts) {
192
+ const check = verifyCV(cv);
193
+ if (!check.ok || check.signed === false) {
194
+ throw new Error(`refusing to bridge an invalid CV: ${[...check.reasons].join('; ') || 'bad signature'}`);
195
+ }
196
+ return signVC({
197
+ '@context': [VC_CONTEXT],
198
+ type: ['VerifiableCredential', 'ZaniiAgentCV'],
199
+ issuer: cv.did,
200
+ validFrom: cv.generated_at,
201
+ credentialSubject: {
202
+ id: cv.did,
203
+ summary: cv.summary,
204
+ work: cv.work,
205
+ authority: cv.authority,
206
+ benchmarks: cv.benchmarks,
207
+ skills: cv.skills,
208
+ },
209
+ }, { did: cv.did, privateKey: agentPrivateKey }, opts);
210
+ }
211
+ /** Decode helper for tests/interop: raw signature bytes from a multibase proofValue. */
212
+ export function proofSignatureBytes(proofValue) {
213
+ if (!proofValue.startsWith('z'))
214
+ throw new Error('not multibase base58btc');
215
+ return base58.decode(proofValue.slice(1));
216
+ }
217
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/D,OAAO,EAAE,QAAQ,EAAgB,MAAM,WAAW,CAAC;AAEnD,MAAM,CAAC,MAAM,UAAU,GAAG,sCAAsC,CAAC;AACjE,MAAM,CAAC,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAwB5C,0FAA0F;AAC1F,MAAM,UAAU,oBAAoB,CAAC,GAAW;IAC9C,OAAO,GAAG,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC;AAClD,CAAC;AAED;;;GAGG;AACH,SAAS,QAAQ,CAAC,GAA4B,EAAE,YAAqC;IACnF,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,SAAS,EAAE,GAAG,GAAG,CAAC;IAC3C,MAAM,UAAU,GAAG,MAAM,CAAC,cAAc,CAAC,YAAY,CAAC,CAAC,CAAC;IACxD,MAAM,OAAO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CAAC,yBAAyB,CAAC,CAAC;IAC5E,OAAO,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;AAC5C,CAAC"}
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@zanii/vc",
3
+ "version": "0.1.0",
4
+ "description": "W3C Verifiable Credentials 2.0 bridge - export Zanii credentials and AgentCVs as spec-conformant VCs with genuine eddsa-jcs-2022 DataIntegrityProofs (Zanii already speaks did:key + Ed25519 + JCS, which IS that cryptosuite), and verify any did:key eddsa-jcs-2022 VC from anyone. Bridges the format, not the trust model: revocation freshness and domain binding remain Zanii-side checks.",
5
+ "license": "Apache-2.0",
6
+ "homepage": "https://ledger.zanii.agency",
7
+ "type": "module",
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "src",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "engines": {
26
+ "node": ">=18"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^26.1.0",
30
+ "typescript": "^5.8.2",
31
+ "vitest": "^3.0.9"
32
+ },
33
+ "dependencies": {
34
+ "@noble/curves": "^1.8.1",
35
+ "@noble/hashes": "^1.7.1",
36
+ "@scure/base": "^1.2.1",
37
+ "@zanii/core": "0.4.0",
38
+ "@zanii/cv": "0.1.0",
39
+ "@zanii/credentials": "0.1.0"
40
+ },
41
+ "scripts": {
42
+ "build": "tsc -p tsconfig.build.json",
43
+ "test": "vitest run",
44
+ "typecheck": "tsc --noEmit"
45
+ }
46
+ }
package/src/index.ts ADDED
@@ -0,0 +1,256 @@
1
+ /**
2
+ * @zanii/vc — the W3C Verifiable Credentials 2.0 bridge.
3
+ *
4
+ * Governments, universities, and wallets increasingly speak the W3C VC data model.
5
+ * Zanii doesn't need a new trust stack to meet them: Zanii already signs with
6
+ * **did:key + Ed25519 over JCS**, which is *exactly* the W3C Data Integrity
7
+ * cryptosuite **`eddsa-jcs-2022`**. So this bridge is not cosmetic — `toVC` emits
8
+ * spec-conformant VCs with genuine `DataIntegrityProof`s a standards wallet can
9
+ * verify, and `verifyVC` verifies any did:key `eddsa-jcs-2022` VC from anyone.
10
+ *
11
+ * Two mappers over one proof engine:
12
+ * - `toVC(credential, issuerKey)` — a `@zanii/credentials` credential (diploma,
13
+ * licence), re-issued as a VC **by the same issuer key** (the Zanii signature is
14
+ * verified first; an invalid credential is refused).
15
+ * - `cvToVC(cv, agentKey)` — an AgentCV as a self-issued VC (the agent attests its
16
+ * own assembled view, exactly like `signCV`).
17
+ *
18
+ * ## The limit, stated up front
19
+ *
20
+ * This bridges the **format, not the trust model.** A VC produced here proves what
21
+ * the Zanii artifact proved — no more. Revocation with an explicit freshness window,
22
+ * the domain-bound issuer root-of-trust, and ledger-backed history remain Zanii-side
23
+ * checks (`@zanii/credentials` `verifyCredential`, `resolveIssuer`); W3C-native
24
+ * status mechanisms (StatusList) are deliberately not implemented — mapping them
25
+ * would claim a liveness this bridge cannot provide. And `verifyVC` checks the
26
+ * proof and (optionally) the validity window — it does NOT resolve issuers or check
27
+ * revocation; say what it does, never more.
28
+ */
29
+ import { ed25519 } from '@noble/curves/ed25519';
30
+ import { sha256 } from '@noble/hashes/sha256';
31
+ import { hexToBytes } from '@noble/hashes/utils';
32
+ import { base58 } from '@scure/base';
33
+ import { canonicalBytes, publicKeyFromDid } from '@zanii/core';
34
+ import type { Credential } from '@zanii/credentials';
35
+ import { verifyCV, type AgentCV } from '@zanii/cv';
36
+
37
+ export const VC_CONTEXT = 'https://www.w3.org/ns/credentials/v2';
38
+ export const CRYPTOSUITE = 'eddsa-jcs-2022';
39
+
40
+ export interface DataIntegrityProof {
41
+ type: 'DataIntegrityProof';
42
+ cryptosuite: typeof CRYPTOSUITE;
43
+ created: string;
44
+ /** `did:key:z6Mk…#z6Mk…` — the did:key with its multikey fragment. */
45
+ verificationMethod: string;
46
+ proofPurpose: 'assertionMethod';
47
+ /** Multibase base58btc (`z…`) of the Ed25519 signature. */
48
+ proofValue: string;
49
+ }
50
+
51
+ export interface VerifiableCredential {
52
+ '@context': string[];
53
+ type: string[];
54
+ issuer: string;
55
+ validFrom?: string;
56
+ validUntil?: string;
57
+ credentialSubject: Record<string, unknown>;
58
+ proof?: DataIntegrityProof;
59
+ [k: string]: unknown;
60
+ }
61
+
62
+ /** The verification method a did:key controls: the DID plus its own multikey fragment. */
63
+ export function verificationMethodOf(did: string): string {
64
+ return `${did}#${did.slice('did:key:'.length)}`;
65
+ }
66
+
67
+ /**
68
+ * `eddsa-jcs-2022` hash step: sha256(JCS(proof options)) || sha256(JCS(document
69
+ * without proof)) — 64 bytes, which the Ed25519 key signs.
70
+ */
71
+ function hashData(doc: Record<string, unknown>, proofOptions: Record<string, unknown>): Uint8Array {
72
+ const { proof: _omit, ...unsecured } = doc;
73
+ const configHash = sha256(canonicalBytes(proofOptions));
74
+ const docHash = sha256(canonicalBytes(unsecured));
75
+ const out = new Uint8Array(64);
76
+ out.set(configHash, 0);
77
+ out.set(docHash, 32);
78
+ return out;
79
+ }
80
+
81
+ /**
82
+ * Sign any VC-shaped document with a did:key per `eddsa-jcs-2022`. The generic proof
83
+ * engine — the mappers below use it, and you can too for custom VC types.
84
+ */
85
+ export function signVC(
86
+ unsecured: Omit<VerifiableCredential, 'proof'>,
87
+ signer: { did: string; privateKey: Uint8Array },
88
+ opts: { created: string },
89
+ ): VerifiableCredential {
90
+ if (!Array.isArray(unsecured['@context']) || unsecured['@context'][0] !== VC_CONTEXT) {
91
+ throw new Error(`@context must start with ${VC_CONTEXT}`);
92
+ }
93
+ if (Number.isNaN(Date.parse(opts.created))) throw new Error('created must be an ISO timestamp');
94
+ const proofOptions: Record<string, unknown> = {
95
+ '@context': unsecured['@context'],
96
+ type: 'DataIntegrityProof',
97
+ cryptosuite: CRYPTOSUITE,
98
+ created: opts.created,
99
+ verificationMethod: verificationMethodOf(signer.did),
100
+ proofPurpose: 'assertionMethod',
101
+ };
102
+ const sig = ed25519.sign(hashData(unsecured as Record<string, unknown>, proofOptions), signer.privateKey);
103
+ const proof: DataIntegrityProof = {
104
+ type: 'DataIntegrityProof',
105
+ cryptosuite: CRYPTOSUITE,
106
+ created: opts.created,
107
+ verificationMethod: proofOptions['verificationMethod'] as string,
108
+ proofPurpose: 'assertionMethod',
109
+ proofValue: `z${base58.encode(sig)}`,
110
+ };
111
+ return { ...unsecured, proof } as VerifiableCredential;
112
+ }
113
+
114
+ export interface VCCheck {
115
+ ok: boolean;
116
+ reasons: string[];
117
+ /** The issuer DID whose key produced the proof (when it verified). */
118
+ issuer: string | null;
119
+ }
120
+
121
+ /**
122
+ * Verify a did:key `eddsa-jcs-2022` VC — any issuer, not just Zanii's. Checks the
123
+ * DataIntegrityProof and that the verification method belongs to the stated issuer.
124
+ * Pass `at` to also check the `validFrom`/`validUntil` window (deliberately not
125
+ * defaulted to "now" — verification stays deterministic).
126
+ */
127
+ export function verifyVC(vc: VerifiableCredential | undefined, opts: { at?: string } = {}): VCCheck {
128
+ const reasons: string[] = [];
129
+ const v = vc ?? ({} as VerifiableCredential);
130
+ if (!Array.isArray(v['@context']) || v['@context'][0] !== VC_CONTEXT) reasons.push(`@context must start with ${VC_CONTEXT}`);
131
+ if (!Array.isArray(v.type) || !v.type.includes('VerifiableCredential')) reasons.push('type must include VerifiableCredential');
132
+ if (typeof v.issuer !== 'string' || !v.issuer.startsWith('did:key:')) reasons.push('issuer must be a did:key (this bridge verifies did:key VCs only)');
133
+ const p = v.proof;
134
+ if (!p || p.type !== 'DataIntegrityProof' || p.cryptosuite !== CRYPTOSUITE) {
135
+ reasons.push(`proof must be a DataIntegrityProof with cryptosuite ${CRYPTOSUITE}`);
136
+ }
137
+ if (reasons.length > 0) return { ok: false, reasons, issuer: null };
138
+
139
+ const proof = p as DataIntegrityProof;
140
+ if (proof.verificationMethod !== verificationMethodOf(v.issuer)) {
141
+ reasons.push('verificationMethod does not belong to the stated issuer');
142
+ }
143
+ const pub = publicKeyFromDid(v.issuer);
144
+ if (!pub) reasons.push('issuer did:key does not decode to an Ed25519 key');
145
+ let sig: Uint8Array | null = null;
146
+ if (typeof proof.proofValue === 'string' && proof.proofValue.startsWith('z')) {
147
+ try {
148
+ sig = base58.decode(proof.proofValue.slice(1));
149
+ } catch {
150
+ sig = null;
151
+ }
152
+ }
153
+ if (!sig) reasons.push('proofValue is not multibase base58btc');
154
+ if (reasons.length === 0 && pub && sig) {
155
+ const { proofValue: _omit, ...proofOptions } = proof;
156
+ const data = hashData(v as unknown as Record<string, unknown>, { '@context': v['@context'], ...proofOptions });
157
+ let valid = false;
158
+ try {
159
+ valid = ed25519.verify(sig, data, pub);
160
+ } catch {
161
+ valid = false;
162
+ }
163
+ if (!valid) reasons.push('proof does not verify — the VC was altered or signed by another key');
164
+ }
165
+ if (opts.at !== undefined && reasons.length === 0) {
166
+ const at = Date.parse(opts.at);
167
+ if (Number.isNaN(at)) reasons.push('at must be an ISO timestamp');
168
+ else {
169
+ if (typeof v.validFrom === 'string' && at < Date.parse(v.validFrom)) reasons.push(`not yet valid at ${opts.at}`);
170
+ if (typeof v.validUntil === 'string' && at > Date.parse(v.validUntil)) reasons.push(`expired at ${opts.at}`);
171
+ }
172
+ }
173
+ return { ok: reasons.length === 0, reasons, issuer: reasons.length === 0 ? v.issuer : null };
174
+ }
175
+
176
+ /** The Zanii credential signature convention: `ed25519:<hex>` over the JCS bytes minus `sig`. */
177
+ function zaniiSigValid(obj: Record<string, unknown> & { sig?: string }, signerDid: string): boolean {
178
+ const pub = publicKeyFromDid(signerDid);
179
+ const hex = typeof obj.sig === 'string' && obj.sig.startsWith('ed25519:') ? obj.sig.slice(8) : '';
180
+ if (!pub || !/^[0-9a-f]{128}$/.test(hex)) return false;
181
+ const { sig: _omit, ...unsigned } = obj;
182
+ try {
183
+ return ed25519.verify(hexToBytes(hex), canonicalBytes(unsigned), pub);
184
+ } catch {
185
+ return false;
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Export a `@zanii/credentials` credential as a W3C VC, re-issued by the SAME issuer
191
+ * key. The Zanii signature is verified first — an invalid credential is refused, so
192
+ * the bridge can never launder a forged artifact into a valid-looking VC. (Revocation
193
+ * and issuer-domain resolution are deliberately NOT checked here — acceptance-time
194
+ * checks belong to the verifier via `@zanii/credentials`; the bridge only re-encodes.)
195
+ */
196
+ export function toVC(
197
+ credential: Credential,
198
+ issuerPrivateKey: Uint8Array,
199
+ opts: { created: string },
200
+ ): VerifiableCredential {
201
+ if (credential?.v !== 1 || credential.type !== 'credential' || !credential.issuer || !credential.holder) {
202
+ throw new Error('refusing to bridge: not a Zanii credential (v1)');
203
+ }
204
+ if (!zaniiSigValid(credential as unknown as Record<string, unknown> & { sig?: string }, credential.issuer)) {
205
+ throw new Error('refusing to bridge an invalid credential: bad issuer signature');
206
+ }
207
+ return signVC(
208
+ {
209
+ '@context': [VC_CONTEXT],
210
+ type: ['VerifiableCredential', 'ZaniiCredential'],
211
+ issuer: credential.issuer,
212
+ validFrom: credential.issued_at,
213
+ validUntil: credential.exp,
214
+ credentialSubject: {
215
+ id: credential.holder,
216
+ scope: credential.scope,
217
+ claim: credential.claim,
218
+ issuerDomain: credential.issuer_domain,
219
+ },
220
+ },
221
+ { did: credential.issuer, privateKey: issuerPrivateKey },
222
+ opts,
223
+ );
224
+ }
225
+
226
+ /** Export an AgentCV as a self-issued VC — the agent attests its own assembled view. */
227
+ export function cvToVC(cv: AgentCV, agentPrivateKey: Uint8Array, opts: { created: string }): VerifiableCredential {
228
+ const check = verifyCV(cv);
229
+ if (!check.ok || check.signed === false) {
230
+ throw new Error(`refusing to bridge an invalid CV: ${[...check.reasons].join('; ') || 'bad signature'}`);
231
+ }
232
+ return signVC(
233
+ {
234
+ '@context': [VC_CONTEXT],
235
+ type: ['VerifiableCredential', 'ZaniiAgentCV'],
236
+ issuer: cv.did,
237
+ validFrom: cv.generated_at,
238
+ credentialSubject: {
239
+ id: cv.did,
240
+ summary: cv.summary as unknown as Record<string, unknown>,
241
+ work: cv.work,
242
+ authority: cv.authority,
243
+ benchmarks: cv.benchmarks,
244
+ skills: cv.skills,
245
+ },
246
+ },
247
+ { did: cv.did, privateKey: agentPrivateKey },
248
+ opts,
249
+ );
250
+ }
251
+
252
+ /** Decode helper for tests/interop: raw signature bytes from a multibase proofValue. */
253
+ export function proofSignatureBytes(proofValue: string): Uint8Array {
254
+ if (!proofValue.startsWith('z')) throw new Error('not multibase base58btc');
255
+ return base58.decode(proofValue.slice(1));
256
+ }