mdip-agent-kit 0.1.3 → 0.1.5
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/AGENTS.md +4 -3
- package/CHANGELOG.md +86 -0
- package/README.md +130 -29
- package/bin/mdip-agent.js +55 -16
- package/examples/agent-handshake.js +6 -4
- package/examples/purchase-authorization.js +5 -2
- package/llms.txt +4 -1
- package/package.json +6 -3
- package/src/index.js +209 -49
- package/test/api-security.mjs +130 -0
- package/test/e2e.sh +68 -0
- package/test/vectors-negative.sh +232 -0
- package/vectors/README.md +15 -4
- package/vectors/decrypt-openssl.sh +11 -2
- package/vectors/expiry-cases.txt +64 -15
- package/vectors/generate.js +9 -4
- package/vectors/kav-1/SHA256SUMS +7 -3
- package/vectors/kav-1/payload.json +3 -3
- package/vectors/kav-1/signed.json +6 -6
- package/vectors/kav-1/test-key.json +7 -7
- package/vectors/make-mdip-fixture-2.js +13 -11
- package/vectors/make-mdip-fixture.js +12 -7
- package/vectors/mdip-challenge-1/SHA256SUMS +15 -5
- package/vectors/mdip-challenge-1/challenge.op.json +11 -11
- package/vectors/mdip-challenge-1/challenge.signed-op.bin +1 -0
- package/vectors/mdip-challenge-1/dids.json +3 -3
- package/vectors/mdip-challenge-1/responder-agent.op.json +7 -7
- package/vectors/mdip-challenge-1/responder-agent.signed-op.bin +1 -0
- package/vectors/mdip-challenge-1/response.op.json +15 -15
- package/vectors/mdip-challenge-1/response.signed-op.bin +1 -0
- package/vectors/mdip-challenge-1/verifier-agent.op.json +7 -7
- package/vectors/mdip-challenge-1/verifier-agent.signed-op.bin +1 -0
- package/vectors/mdip-challenge-1/verify-response.json +3 -3
- package/vectors/mdip-challenge-2/SHA256SUMS +17 -11
- package/vectors/mdip-challenge-2/challenge.op.json +11 -11
- package/vectors/mdip-challenge-2/dids.json +3 -3
- package/vectors/mdip-challenge-2/responder-agent.op.json +7 -7
- package/vectors/mdip-challenge-2/response.op.json +15 -15
- package/vectors/mdip-challenge-2/test-verifier.json +9 -9
- package/vectors/mdip-challenge-2/verifier-agent.op.json +7 -7
- package/vectors/mdip-challenge-2/verify-response.json +6 -6
- package/vectors/verify-openssl.sh +269 -40
- package/vectors/verify-with-kit.js +207 -10
|
@@ -4,10 +4,14 @@
|
|
|
4
4
|
// and verifies each signature. Also checks the MDIP binding fields of the challenge fixture.
|
|
5
5
|
// Usage: node vectors/verify-with-kit.js (after npm install; no network)
|
|
6
6
|
import fs from 'node:fs';
|
|
7
|
+
import crypto from 'node:crypto';
|
|
7
8
|
import path from 'node:path';
|
|
8
9
|
import { fileURLToPath } from 'node:url';
|
|
9
10
|
import CipherNode from '@mdip/cipher/node';
|
|
10
|
-
import {
|
|
11
|
+
import { createRequire } from 'node:module';
|
|
12
|
+
import { checkResponseExpiry, parseTimestampNs } from '../src/index.js';
|
|
13
|
+
// bip39 is @mdip/cipher's own dependency: resolve it from there (works with hoisted and non-hoisted installs)
|
|
14
|
+
const bip39 = createRequire(import.meta.resolve('@mdip/cipher/node'))('bip39');
|
|
11
15
|
|
|
12
16
|
const dir = path.dirname(fileURLToPath(import.meta.url));
|
|
13
17
|
const c = new CipherNode();
|
|
@@ -15,7 +19,66 @@ const rd = f => fs.readFileSync(path.join(dir, f), 'utf8');
|
|
|
15
19
|
const js = f => JSON.parse(rd(f));
|
|
16
20
|
let fail = 0;
|
|
17
21
|
const check = (cond, msg) => { console.log(`${cond ? 'ok ' : 'FAIL'} ${msg}`); if (!cond) fail = 1; };
|
|
22
|
+
// did:mdip:z + base58btc(CIDv1, codec json 0x0200, sha2-256: 01 8004 1220 || sha256(bytes))
|
|
23
|
+
const didFromOp = (bytes) => {
|
|
24
|
+
const buf = Buffer.concat([Buffer.from('0180041220', 'hex'), crypto.createHash('sha256').update(bytes).digest()]);
|
|
25
|
+
const A = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
|
|
26
|
+
let n = BigInt('0x' + buf.toString('hex')), s = '';
|
|
27
|
+
while (n > 0n) { s = A[Number(n % 58n)] + s; n /= 58n; }
|
|
28
|
+
return 'did:mdip:z' + s;
|
|
29
|
+
};
|
|
18
30
|
const unsigned = o => { const x = JSON.parse(JSON.stringify(o)); delete x.signature; return x; };
|
|
31
|
+
// PINNED known answers (same constants as verify-openssl.sh and the README): a vector dir regenerated
|
|
32
|
+
// wholesale would otherwise be self-consistent. Each DID is the hash of its signed op.
|
|
33
|
+
const PIN = {
|
|
34
|
+
kav1Label: 'mdip-agent-kit kav-1 PUBLIC TEST KEY - never use for anything real',
|
|
35
|
+
kav1MsgSha256: '4d4523d99bebdd70689f67a80e865349848f520d19ab9537403e56a280dcf64b',
|
|
36
|
+
kav1Signer: 'did:example:kav-1-signer', kav1Signed: '2026-10-26T00:00:00.000Z',
|
|
37
|
+
kav1TamperedSha256: '17bb3f553bd7a600ad5585015f59c770278b599921eb52b9bfd51e16aa4de476',
|
|
38
|
+
ch1Nonce: 'ui6M_7_U7KqOgZVTTk4k0uxGnr6mz5J9G40vOle7JyQQ', // recorded by the verifier; not re-derivable (private key)
|
|
39
|
+
ch2Label: 'mdip-agent-kit mdip-challenge-2 PUBLIC TEST VERIFIER - never use for anything real',
|
|
40
|
+
kav1Sig: '2b61bc63136caf5dbbdfee80d6717d57df09555be0f6c1b0158adc70feb0363c2067a7017b2b52fd92fd0e980650118bf5d4e07bc88ee8527f04f6404a37b4d1',
|
|
41
|
+
'mdip-challenge-1': {
|
|
42
|
+
'verifier-agent': 'did:mdip:z3v8AuafKYqAKRVQVArS7VX399DWXp6AqUofefLxE84Ksi5FKjx',
|
|
43
|
+
'responder-agent': 'did:mdip:z3v8AuaTpa2sv416LhYnLLghNPBiqiByPhgPCMyJDvh3nEWX1AQ',
|
|
44
|
+
challenge: 'did:mdip:z3v8AuabdK9jyaLmHoWNumjBkU7wTZSUZJTBepL9QQZEqXMxCgq',
|
|
45
|
+
response: 'did:mdip:z3v8AuaXWLRpxX5228cexKgnxhnME9pAf8QtQqG9ZJccEe6VRMz',
|
|
46
|
+
},
|
|
47
|
+
'mdip-challenge-2': {
|
|
48
|
+
'verifier-agent': 'did:mdip:z3v8AuabH5z2RyBFCP8KzhS98jSL8Y62JPfis8EJiBo6io6QoRA',
|
|
49
|
+
'responder-agent': 'did:mdip:z3v8AuafFPtizoWoRCuV71sNVen1MUCrFuvfFNjhrYmasfnEFy6',
|
|
50
|
+
challenge: 'did:mdip:z3v8AuaUJbQT6UJRU58Bv8wWKZWCijUQwgej1cNjgoExXZLpeAM',
|
|
51
|
+
response: 'did:mdip:z3v8AuafK9H3bXz1apseJCAyp24v2Joh1kYAzdDVBCwzjfaAwAY',
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
const sha256 = b => crypto.createHash('sha256').update(b).digest('hex');
|
|
55
|
+
const bin = f => fs.readFileSync(path.join(dir, f));
|
|
56
|
+
// strict DER ECDSA-Sig-Value -> compact r||s hex; null unless it re-encodes to the exact same bytes
|
|
57
|
+
const derToCompact = der => {
|
|
58
|
+
const int = b => { let i = 0; while (i < b.length - 1 && b[i] === 0) i++; b = b.subarray(i); if (b[0] & 0x80) b = Buffer.concat([Buffer.from([0]), b]); return Buffer.concat([Buffer.from([0x02, b.length]), b]); };
|
|
59
|
+
try {
|
|
60
|
+
if (der[0] !== 0x30 || der[1] !== der.length - 2 || der[2] !== 0x02) return null;
|
|
61
|
+
const rl = der[3], r = der.subarray(4, 4 + rl); if (der[4 + rl] !== 0x02) return null;
|
|
62
|
+
const sl = der[5 + rl], sv = der.subarray(6 + rl, 6 + rl + sl);
|
|
63
|
+
const hex = b => { const h = Buffer.from(b).toString('hex').replace(/^(00)+/, ''); return h.length > 64 ? null : h.padStart(64, '0'); };
|
|
64
|
+
const rh = hex(r), sh = hex(sv); if (!rh || !sh) return null;
|
|
65
|
+
const body = Buffer.concat([int(Buffer.from(rh, 'hex')), int(Buffer.from(sh, 'hex'))]);
|
|
66
|
+
return Buffer.concat([Buffer.from([0x30, body.length]), body]).equals(der) ? rh + sh : null;
|
|
67
|
+
} catch { return null; }
|
|
68
|
+
};
|
|
69
|
+
// low-S: MDIP (@noble/secp256k1) rejects s > n/2; OpenSSL accepts both (r,s) and (r,n-s)
|
|
70
|
+
const lowS = compact => /^[0-9a-f]{128}$/.test(compact) && BigInt('0x' + compact.slice(64)) <= 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0n;
|
|
71
|
+
// MDIP signature block: exactly hash, signed, [signer,] value; strict hex and a strict RFC 3339 `signed`
|
|
72
|
+
const sigShape = (sig, withSigner) => !!sig && JSON.stringify(Object.keys(sig).sort()) === JSON.stringify(withSigner ? ['hash', 'signed', 'signer', 'value'] : ['hash', 'signed', 'value'])
|
|
73
|
+
&& /^[0-9a-f]{64}$/.test(sig.hash) && /^[0-9a-f]{128}$/.test(sig.value) && parseTimestampNs(sig.signed) !== null
|
|
74
|
+
&& (!withSigner || typeof sig.signer === 'string');
|
|
75
|
+
// fixture invariant: created <= signature.signed <= created + 60 s (MDIP does not sign signature.signed; see README)
|
|
76
|
+
const signedOk = o => { const a = parseTimestampNs(o.created), b = parseTimestampNs(o.signature?.signed); return a !== null && b !== null && b >= a && b - a <= 60000000000n; };
|
|
77
|
+
const sameKeys = (o, keys) => JSON.stringify(Object.keys(o).sort()) === JSON.stringify(keys);
|
|
78
|
+
const DIDNAMES = ['challenge', 'responder-agent', 'response', 'verifier-agent'];
|
|
79
|
+
// verify-response.json: what verifyResponse() returned; every field pinned (exact key order and values)
|
|
80
|
+
const vrExact = (v, d, nonce, extra) => JSON.stringify(v) === JSON.stringify({ challenge: d.challenge, credentials: [], ...extra, fulfilled: 0, match: true, requested: 0, responder: d['responder-agent'], responseNonce: nonce, vps: [] });
|
|
81
|
+
const pemJwk = f => crypto.createPublicKey(rd(f)).export({ format: 'jwk' });
|
|
19
82
|
|
|
20
83
|
// kav-1
|
|
21
84
|
const signed = js('kav-1/signed.json');
|
|
@@ -24,6 +87,27 @@ check(c.canonicalizeJSON(unsigned(signed)) === rd('kav-1/message.bin'), 'kav-1 m
|
|
|
24
87
|
check(c.hashJSON(unsigned(signed)) === signed.signature.hash, 'kav-1 signature.hash == sha256(JCS)');
|
|
25
88
|
check(c.verifySig(signed.signature.hash, signed.signature.value, key), 'kav-1 verifySig');
|
|
26
89
|
check(rd('kav-1/signature.hex').trim() === signed.signature.value, 'kav-1 signature.hex == signature.value');
|
|
90
|
+
check(derToCompact(bin('kav-1/signature.der')) === signed.signature.value && lowS(signed.signature.value), 'kav-1 signature.der (strict DER) == signature.value, low-S');
|
|
91
|
+
{
|
|
92
|
+
const pj = pemJwk('kav-1/pub.pem'), tk = js('kav-1/test-key.json');
|
|
93
|
+
const d = crypto.createHash('sha256').update(PIN.kav1Label, 'utf8').digest();
|
|
94
|
+
const derived = crypto.createPrivateKey({ key: { kty: 'EC', crv: 'secp256k1', d: d.toString('base64url'), x: key.x, y: key.y }, format: 'jwk' });
|
|
95
|
+
const dpub = crypto.createPublicKey(derived).export({ format: 'jwk' });
|
|
96
|
+
check(tk.label === PIN.kav1Label && tk.privateKeyHex === d.toString('hex') && tk.privateJwk.d === d.toString('base64url')
|
|
97
|
+
&& dpub.x === key.x && dpub.y === key.y && pj.x === key.x && pj.y === key.y,
|
|
98
|
+
'kav-1 PINNED: test key == sha256(published label); pub.pem == test-key.json publicJwk');
|
|
99
|
+
check(sha256(bin('kav-1/message.bin')) === PIN.kav1MsgSha256 && rd('kav-1/message.sha256').trim() === PIN.kav1MsgSha256 && signed.signature.value === PIN.kav1Sig,
|
|
100
|
+
'kav-1 PINNED: message sha256 and signature match the published known answers');
|
|
101
|
+
check(c.canonicalizeJSON(js('kav-1/payload.json')) === rd('kav-1/message.bin'), 'kav-1 message.bin == JCS(payload.json)');
|
|
102
|
+
check(sigShape(signed.signature, true) && signed.signature.signer === 'did:example:kav-1-signer', 'kav-1 signed.json signature block shape');
|
|
103
|
+
const g = c.generateJwk(new Uint8Array(d)), same = (a, b) => sameKeys(a, Object.keys(b).sort()) && Object.keys(a).every(f => a[f] === b[f]);
|
|
104
|
+
check(sameKeys(tk, ['WARNING', 'label', 'privateJwk', 'privateKeyHex', 'publicJwk']) && same(g.privateJwk, tk.privateJwk) && same(g.publicJwk, tk.publicJwk) && same(tk.publicJwk, key),
|
|
105
|
+
'kav-1 test-key.json is exactly that key (private + public JWK, no extra fields)');
|
|
106
|
+
const m = bin('kav-1/message.bin'), t = bin('kav-1/message-tampered.bin');
|
|
107
|
+
check(m.length === t.length && [...m].filter((b, i) => b !== t[i]).length === 1
|
|
108
|
+
&& !crypto.verify('sha256', t, { key: crypto.createPublicKey(rd('kav-1/pub.pem')), dsaEncoding: 'der' }, bin('kav-1/signature.der')),
|
|
109
|
+
'kav-1 message-tampered.bin: exactly one byte changed, signature rejects it');
|
|
110
|
+
}
|
|
27
111
|
|
|
28
112
|
// mdip-challenge-1
|
|
29
113
|
const dids = js('mdip-challenge-1/dids.json');
|
|
@@ -36,12 +120,24 @@ for (const k of ['verifier-agent', 'challenge', 'responder-agent', 'response'])
|
|
|
36
120
|
// agent create ops are self-signed with their own publicJwk (no signer DID yet); assets by their controller
|
|
37
121
|
const signer = o.mdip.type === 'agent' ? (k === 'verifier-agent' ? dids['verifier-agent'] : dids['responder-agent']) : o.controller;
|
|
38
122
|
check(c.verifySig(o.signature.hash, o.signature.value, o.mdip.type === 'agent' ? o.publicJwk : keys[signer]), `${k} signed by ${signer === dids['verifier-agent'] ? 'verifier' : 'responder'} key`);
|
|
123
|
+
check(derToCompact(bin(`mdip-challenge-1/${k}.sig.der`)) === o.signature.value && lowS(o.signature.value), `${k} sig.der (strict DER) == signature.value, low-S`);
|
|
124
|
+
check(c.canonicalizeJSON(o) === rd(`mdip-challenge-1/${k}.signed-op.bin`), `${k} signed-op.bin == JCS(op)`);
|
|
125
|
+
check(dids[k] === PIN['mdip-challenge-1'][k] && dids[k] === didFromOp(c.canonicalizeJSON(o)), `${k} DID == CID(sha256(JCS(signed op))) == PINNED`);
|
|
126
|
+
check(sigShape(o.signature, o.mdip.type !== 'agent') && (o.mdip.type === 'agent' || o.signature.signer === o.controller), `${k} signature block shape, signer == controller`);
|
|
127
|
+
check(signedOk(o), `${k} created <= signature.signed <= created + 60 s`);
|
|
128
|
+
}
|
|
129
|
+
for (const k of ['verifier-agent', 'responder-agent']) {
|
|
130
|
+
const jwk = pemJwk(`mdip-challenge-1/${k}.pub.pem`);
|
|
131
|
+
check(jwk.x === op(k).publicJwk.x && jwk.y === op(k).publicJwk.y, `${k}.pub.pem == publicJwk in its op`);
|
|
39
132
|
}
|
|
133
|
+
check(sameKeys(dids, DIDNAMES), 'mdip-challenge-1 dids.json has exactly the four names');
|
|
40
134
|
const ch = op('challenge'), re = op('response'), vr = js('mdip-challenge-1/verify-response.json');
|
|
41
135
|
check(ch.controller === dids['verifier-agent'], 'challenge controller == verifier DID (binds verifier)');
|
|
42
136
|
check(re.controller === dids['responder-agent'] && re.data.encrypted.sender === re.controller, 'response controller == encrypted.sender == responder DID');
|
|
43
|
-
check(
|
|
44
|
-
|
|
137
|
+
check(checkResponseExpiry(ch.mdip.validUntil, re.mdip.validUntil).ok, 'response validUntil <= challenge validUntil + 2 h (expiry)');
|
|
138
|
+
// verify-response.json is what the verifier recorded; the payload is encrypted to a private key, so this is
|
|
139
|
+
// NOT an offline proof of the binding (mdip-challenge-2 is). It only checks the recorded result is consistent.
|
|
140
|
+
check(typeof vr.responseNonce === 'string' && /^[A-Za-z0-9_-]+$/.test(vr.responseNonce) && vrExact(vr, dids, vr.responseNonce, {}), 'recorded verify-response.json is consistent and exact (challenge, responder, match=true, responseNonce; not re-derivable offline)');
|
|
45
141
|
|
|
46
142
|
// mdip-challenge-2: PUBLIC TEST verifier key -> decrypt the response and check the binding offline
|
|
47
143
|
{
|
|
@@ -49,23 +145,124 @@ check(vr.challenge === dids.challenge && vr.responder === dids['responder-agent'
|
|
|
49
145
|
const dids2 = js(`${d}/dids.json`), o2 = k => js(`${d}/${k}.op.json`), tv = js(`${d}/test-verifier.json`);
|
|
50
146
|
const ch2 = o2('challenge'), re2 = o2('response'), resp = o2('responder-agent'), ver = o2('verifier-agent');
|
|
51
147
|
check(JSON.stringify(tv.publicJwk) === JSON.stringify(ver.publicJwk) && tv.did === dids2['verifier-agent'], `${d} test-verifier.json key == verifier-agent op key`);
|
|
148
|
+
{
|
|
149
|
+
const pk = crypto.createPrivateKey(rd(`${d}/verifier-agent.PUBLIC-TEST-KEY.priv.pem`)).export({ format: 'jwk' });
|
|
150
|
+
check(pk.d === tv.privateJwk.d && pk.x === ver.publicJwk.x && pk.y === ver.publicJwk.y && tv.privateJwk.x === pk.x && tv.privateJwk.y === pk.y,
|
|
151
|
+
`${d} PUBLIC-TEST-KEY.priv.pem == test-verifier.json privateJwk == verifier-agent op key`);
|
|
152
|
+
// the published label -> mnemonic -> HD key -> the verifier's key (anyone can re-derive the PUBLIC TEST wallet)
|
|
153
|
+
const m = bip39.entropyToMnemonic(crypto.createHash('sha256').update(tv.label, 'utf8').digest().subarray(0, 16));
|
|
154
|
+
const kp = c.generateJwk(c.generateHDKey(tv.mnemonic).derive(tv.derivationPath).privateKey);
|
|
155
|
+
check(m === tv.mnemonic && tv.derivationPath === "m/44'/0'/0'/0/0" && ['x', 'y', 'd'].every(f => kp.privateJwk[f] === tv.privateJwk[f] && pk[f] === tv.privateJwk[f])
|
|
156
|
+
&& sameKeys(tv, ['WARNING', 'derivationPath', 'did', 'label', 'mnemonic', 'mnemonicEntropy', 'privateJwk', 'publicJwk']) && tv.mnemonicEntropy === 'first 16 bytes of sha256(label)',
|
|
157
|
+
`${d} test-verifier.json: label -> mnemonic -> m/44'/0'/0'/0/0 == verifier key == .priv.pem`);
|
|
158
|
+
}
|
|
159
|
+
check(sameKeys(dids2, DIDNAMES), `${d} dids.json has exactly the four names`);
|
|
52
160
|
for (const k of ['verifier-agent', 'challenge', 'responder-agent', 'response']) {
|
|
53
161
|
const o = o2(k);
|
|
54
162
|
check(c.canonicalizeJSON(unsigned(o)) === rd(`${d}/${k}.message.bin`) && c.canonicalizeJSON(o) === rd(`${d}/${k}.signed-op.bin`), `${d} ${k} JCS bytes`);
|
|
55
|
-
check(c.
|
|
163
|
+
check(c.hashJSON(unsigned(o)) === o.signature.hash, `${d} ${k} signature.hash == sha256(JCS(op minus signature))`);
|
|
164
|
+
const expectSigner = k === 'challenge' ? dids2['verifier-agent'] : k === 'response' ? dids2['responder-agent'] : undefined;
|
|
165
|
+
check(o.signature.signer === expectSigner && (expectSigner === undefined || o.controller === expectSigner), `${d} ${k} signer == controller (${expectSigner ? 'asset' : 'self-signed agent'})`);
|
|
166
|
+
check(c.verifySig(o.signature.hash, o.signature.value, o.mdip.type === 'agent' ? o.publicJwk : (expectSigner === dids2['verifier-agent'] ? ver : resp).publicJwk), `${d} ${k} signature`);
|
|
167
|
+
check(dids2[k] === PIN[d][k] && dids2[k] === didFromOp(c.canonicalizeJSON(o)), `${d} ${k} DID == CID(sha256(JCS(signed op))) == PINNED`);
|
|
168
|
+
check(derToCompact(bin(`${d}/${k}.sig.der`)) === o.signature.value && lowS(o.signature.value), `${d} ${k} sig.der (strict DER) == signature.value, low-S`);
|
|
169
|
+
check(sigShape(o.signature, !!expectSigner), `${d} ${k} signature block shape`);
|
|
170
|
+
check(signedOk(o), `${d} ${k} created <= signature.signed <= created + 60 s`);
|
|
171
|
+
}
|
|
172
|
+
for (const k of ['verifier-agent', 'responder-agent']) {
|
|
173
|
+
const jwk = crypto.createPublicKey(rd(`${d}/${k}.pub.pem`)).export({ format: 'jwk' });
|
|
174
|
+
check(jwk.x === o2(k).publicJwk.x && jwk.y === o2(k).publicJwk.y, `${d} ${k}.pub.pem == publicJwk in its op`);
|
|
56
175
|
}
|
|
176
|
+
check(fs.readFileSync(path.join(dir, `${d}/response.cipher_receiver.bin`)).toString('base64url') === re2.data.encrypted.cipher_receiver, `${d} response.cipher_receiver.bin == signed op's cipher_receiver`);
|
|
57
177
|
const pt = c.decryptMessage(resp.publicJwk, tv.privateJwk, re2.data.encrypted.cipher_receiver);
|
|
58
178
|
check(pt === rd(`${d}/response.plaintext.json`), `${d} @mdip/cipher decrypt == response.plaintext.json`);
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
check(
|
|
179
|
+
// exact shape keymaster writes: one "challenge" key, so no JSON parser can read a different binding
|
|
180
|
+
const PTRE = /^\{"response":\{"challenge":"did:mdip:z[1-9A-HJ-NP-Za-km-z]+","credentials":\[\],"requested":0,"fulfilled":0,"match":true,"responseNonce":"[A-Za-z0-9_-]+"\}\}$/;
|
|
181
|
+
check(PTRE.test(pt) && JSON.parse(pt).response.challenge === dids2.challenge, `${d} BINDING: response.challenge == challenge DID (exact plaintext shape, one challenge key)`);
|
|
182
|
+
check(ch2.controller === dids2['verifier-agent'] && re2.controller === dids2['responder-agent'] && re2.data.encrypted.sender === re2.controller, `${d} controllers, encrypted.sender`);
|
|
183
|
+
const vr2 = js(`${d}/verify-response.json`);
|
|
184
|
+
check(vrExact(vr2, dids2, JSON.parse(pt).response.responseNonce, { expiry: { ok: true } }), `${d} verify-response.json agrees with the decrypted response (exact)`);
|
|
185
|
+
check(checkResponseExpiry(ch2.mdip.validUntil, re2.mdip.validUntil).ok, `${d} expiry (response <= challenge + 2 h)`);
|
|
62
186
|
}
|
|
63
|
-
// strict
|
|
187
|
+
// Every byte of every vector dir: strict SHA256SUMS (same rules as verify-openssl.sh's sumcheck), the .json
|
|
188
|
+
// files in the exact layout the generators write (JCS key order, 2-space indent, one trailing newline), each
|
|
189
|
+
// PEM a single canonical block, and every human-readable file equal to what the signed/derived bytes say.
|
|
190
|
+
{
|
|
191
|
+
const sortKeys = v => Array.isArray(v) ? v.map(sortKeys) : v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map(k => [k, sortKeys(v[k])])) : v;
|
|
192
|
+
for (const d of ['kav-1', 'mdip-challenge-1', 'mdip-challenge-2']) {
|
|
193
|
+
const lines = rd(`${d}/SHA256SUMS`).split('\n'), last = lines.pop();
|
|
194
|
+
const listed = new Map(), entries = fs.readdirSync(path.join(dir, d)).filter(f => f !== 'SHA256SUMS');
|
|
195
|
+
let okSums = last === '' && lines.length > 0;
|
|
196
|
+
for (const l of lines) {
|
|
197
|
+
const m = /^([0-9a-f]{64}) [ *]([A-Za-z0-9][A-Za-z0-9._-]*)$/.exec(l);
|
|
198
|
+
if (!m || m[2] === 'SHA256SUMS' || listed.has(m[2])) { okSums = false; continue; }
|
|
199
|
+
listed.set(m[2], m[1]);
|
|
200
|
+
}
|
|
201
|
+
for (const f of entries) {
|
|
202
|
+
const st = fs.lstatSync(path.join(dir, d, f));
|
|
203
|
+
if (!st.isFile() || listed.get(f) !== sha256(bin(`${d}/${f}`))) okSums = false;
|
|
204
|
+
}
|
|
205
|
+
check(okSums && listed.size === entries.length, `${d} SHA256SUMS strict: every entry (dotfiles too) a listed, matching regular file, nothing extra`);
|
|
206
|
+
for (const f of entries.filter(f => f.endsWith('.json') && f !== 'response.plaintext.json')) { // plaintext: exact decrypted bytes, checked below
|
|
207
|
+
check(rd(`${d}/${f}`) === JSON.stringify(sortKeys(js(`${d}/${f}`)), null, 2) + '\n', `${d} ${f} in generator layout (JCS key order, 2-space indent)`);
|
|
208
|
+
}
|
|
209
|
+
for (const f of entries.filter(f => f.endsWith('.pem'))) {
|
|
210
|
+
const priv = f.endsWith('.priv.pem'), k = priv ? crypto.createPrivateKey(rd(`${d}/${f}`)) : crypto.createPublicKey(rd(`${d}/${f}`));
|
|
211
|
+
check(k.export(priv ? { type: 'pkcs8', format: 'pem' } : { type: 'spki', format: 'pem' }) === rd(`${d}/${f}`), `${d} ${f} is one canonical PEM block`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const sgn = js('kav-1/signed.json'), tk = js('kav-1/test-key.json');
|
|
215
|
+
check(JSON.stringify(sgn) === JSON.stringify(sortKeys({ ...js('kav-1/payload.json'), signature: { hash: PIN.kav1MsgSha256, signed: PIN.kav1Signed, signer: PIN.kav1Signer, value: PIN.kav1Sig } })),
|
|
216
|
+
'kav-1 signed.json == payload.json + PINNED signature {hash, signed, signer, value}, nothing else');
|
|
217
|
+
check(tk.WARNING === 'PUBLIC TEST KEY - private part is published on purpose; never use it' && JSON.stringify(Object.keys(tk)) === '["WARNING","label","privateJwk","privateKeyHex","publicJwk"]'
|
|
218
|
+
&& JSON.stringify(tk.publicJwk) === JSON.stringify({ crv: 'secp256k1', kty: 'EC', x: tk.publicJwk.x, y: tk.publicJwk.y })
|
|
219
|
+
&& JSON.stringify(tk.privateJwk) === JSON.stringify({ crv: 'secp256k1', d: tk.privateJwk.d, kty: 'EC', x: tk.publicJwk.x, y: tk.publicJwk.y }), 'kav-1 test-key.json has exactly the expected members (WARNING pinned)');
|
|
220
|
+
check(rd('kav-1/message.sha256') === PIN.kav1MsgSha256 + '\n' && rd('kav-1/signature.hex') === PIN.kav1Sig + '\n' && sha256(bin('kav-1/message-tampered.bin')) === PIN.kav1TamperedSha256,
|
|
221
|
+
'kav-1 message.sha256 / signature.hex exact bytes; message-tampered.bin PINNED');
|
|
222
|
+
for (const d of ['mdip-challenge-1', 'mdip-challenge-2']) {
|
|
223
|
+
check(JSON.stringify(js(`${d}/dids.json`)) === JSON.stringify(sortKeys(PIN[d])), `${d} dids.json == the 4 pinned DIDs, nothing else`);
|
|
224
|
+
}
|
|
225
|
+
const vr1 = { challenge: PIN['mdip-challenge-1'].challenge, credentials: [], fulfilled: 0, match: true, requested: 0, responder: PIN['mdip-challenge-1']['responder-agent'], responseNonce: PIN.ch1Nonce, vps: [] };
|
|
226
|
+
check(JSON.stringify(js('mdip-challenge-1/verify-response.json')) === JSON.stringify(vr1), 'mdip-challenge-1 verify-response.json == recorded result exactly (pinned nonce)');
|
|
227
|
+
const d = 'mdip-challenge-2', pt = rd(`${d}/response.plaintext.json`), nonce = JSON.parse(pt).response?.responseNonce;
|
|
228
|
+
check(typeof nonce === 'string' && /^[A-Za-z0-9_-]+$/.test(nonce)
|
|
229
|
+
&& pt === JSON.stringify({ response: { challenge: PIN[d].challenge, credentials: [], requested: 0, fulfilled: 0, match: true, responseNonce: nonce } }),
|
|
230
|
+
`${d} plaintext is exactly {response:{challenge, credentials:[], requested 0, fulfilled 0, match true, responseNonce}} (no extra or duplicate member)`);
|
|
231
|
+
const vr2 = { challenge: PIN[d].challenge, credentials: [], expiry: { ok: true }, fulfilled: 0, match: true, requested: 0, responder: PIN[d]['responder-agent'], responseNonce: nonce, vps: [] };
|
|
232
|
+
check(JSON.stringify(js(`${d}/verify-response.json`)) === JSON.stringify(vr2), `${d} verify-response.json == decrypted response + responder, exactly`);
|
|
233
|
+
// the PUBLIC TEST verifier wallet: label -> bip39 entropy -> mnemonic -> HD key at derivationPath -> the verifier DID's key
|
|
234
|
+
const tv = js(`${d}/test-verifier.json`);
|
|
235
|
+
const mn = bip39.entropyToMnemonic(crypto.createHash('sha256').update(PIN.ch2Label, 'utf8').digest().subarray(0, 16));
|
|
236
|
+
const kp = c.generateJwk(c.generateHDKey(mn).derive("m/44'/0'/0'/0/0").privateKey);
|
|
237
|
+
const ver = js(`${d}/verifier-agent.op.json`).publicJwk;
|
|
238
|
+
check(tv.WARNING === 'PUBLIC TEST VERIFIER - wallet mnemonic and private key are published on purpose; never use them' && tv.label === PIN.ch2Label && tv.mnemonicEntropy === 'first 16 bytes of sha256(label)' && tv.mnemonic === mn && tv.derivationPath === "m/44'/0'/0'/0/0"
|
|
239
|
+
&& tv.did === PIN[d]['verifier-agent'] && JSON.stringify(tv.privateJwk) === JSON.stringify(sortKeys(kp.privateJwk)) && JSON.stringify(tv.publicJwk) === JSON.stringify(sortKeys(kp.publicJwk))
|
|
240
|
+
&& kp.publicJwk.x === ver.x && kp.publicJwk.y === ver.y
|
|
241
|
+
&& JSON.stringify(Object.keys(tv)) === '["WARNING","derivationPath","did","label","mnemonic","mnemonicEntropy","privateJwk","publicJwk"]',
|
|
242
|
+
`${d} test-verifier.json: bip39(sha256(label)[0:16]) == mnemonic -> ${tv.derivationPath} key == privateJwk == verifier-agent op key`);
|
|
243
|
+
}
|
|
244
|
+
// expiry cases (same table verify-openssl.sh uses; columns separated by "|")
|
|
245
|
+
let rows = 0;
|
|
64
246
|
for (const line of rd('expiry-cases.txt').split('\n')) {
|
|
65
247
|
if (!line.trim() || line.startsWith('#')) continue;
|
|
66
|
-
const [cv, rv, want,
|
|
248
|
+
const [cv, rv, want, note] = line.split('|').map(x => x.trim());
|
|
67
249
|
const got = checkResponseExpiry(cv === '-' ? undefined : cv, rv === '-' ? undefined : rv).ok ? 'accept' : 'reject';
|
|
68
|
-
check(got === want, `expiry case: ${note
|
|
250
|
+
check(got === want, `expiry case: ${note} -> ${got}`); rows++;
|
|
251
|
+
}
|
|
252
|
+
check(rows > 0, `expiry table: all ${rows} rows run`);
|
|
253
|
+
// "neither already expired" (the `now` argument, epoch ms); not in the table because it depends on the clock
|
|
254
|
+
{
|
|
255
|
+
const C = '2026-10-26T17:52:16.038Z', R = '2026-10-26T17:52:16.000Z', t = Date.parse(R);
|
|
256
|
+
check(checkResponseExpiry(C, R, t - 1).ok, 'now: both still valid 1 ms before the response expires -> accept');
|
|
257
|
+
check(!checkResponseExpiry(C, R, t).ok, 'now: response expiring exactly now -> reject');
|
|
258
|
+
check(!checkResponseExpiry(C, C, Date.parse(C) + 1).ok, 'now: challenge already expired -> reject');
|
|
259
|
+
// stock keymaster skew: response expires 4.2 s AFTER the challenge (both defaults are +1 h)
|
|
260
|
+
const S = '2026-10-26T17:52:20.238Z';
|
|
261
|
+
check(checkResponseExpiry(C, S, Date.parse(C) - 1).ok, 'now: stock keymaster response 4.2 s past the challenge, both still valid -> accept');
|
|
262
|
+
check(!checkResponseExpiry(C, S, Date.parse(C)).ok, 'now: stock keymaster response outlives its challenge, challenge expired -> reject');
|
|
263
|
+
check(!checkResponseExpiry(C, S, Date.parse(C) + 1000).ok, 'now: inside the response\'s extra seconds but after the challenge expired -> reject');
|
|
264
|
+
check(!checkResponseExpiry(C, '2099-01-01T00:00:00Z', Date.parse(C) - 1).ok, 'now: far-future response (2099) -> reject even though both unexpired');
|
|
265
|
+
check(!checkResponseExpiry(C, R, NaN).ok && !checkResponseExpiry(C, R, 'soon').ok, 'now: non-numeric now -> reject (fail closed)');
|
|
69
266
|
}
|
|
70
267
|
console.log(fail ? 'VECTORS FAILED' : 'ALL VECTORS OK');
|
|
71
268
|
process.exit(fail);
|