mdip-agent-kit 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/README.md +37 -4
  2. package/llms.txt +1 -1
  3. package/package.json +3 -2
  4. package/src/index.js +38 -2
  5. package/vectors/README.md +6 -1
  6. package/vectors/decrypt-openssl.sh +44 -0
  7. package/vectors/expiry-cases.txt +20 -0
  8. package/vectors/make-mdip-fixture-2.js +88 -0
  9. package/vectors/mdip-challenge-2/SHA256SUMS +18 -0
  10. package/vectors/mdip-challenge-2/challenge.message.bin +1 -0
  11. package/vectors/mdip-challenge-2/challenge.op.json +21 -0
  12. package/vectors/mdip-challenge-2/challenge.sig.der +0 -0
  13. package/vectors/mdip-challenge-2/challenge.signed-op.bin +1 -0
  14. package/vectors/mdip-challenge-2/dids.json +6 -0
  15. package/vectors/mdip-challenge-2/responder-agent.message.bin +1 -0
  16. package/vectors/mdip-challenge-2/responder-agent.op.json +21 -0
  17. package/vectors/mdip-challenge-2/responder-agent.pub.pem +4 -0
  18. package/vectors/mdip-challenge-2/responder-agent.sig.der +0 -0
  19. package/vectors/mdip-challenge-2/responder-agent.signed-op.bin +1 -0
  20. package/vectors/mdip-challenge-2/response.cipher_receiver.bin +0 -0
  21. package/vectors/mdip-challenge-2/response.message.bin +1 -0
  22. package/vectors/mdip-challenge-2/response.op.json +27 -0
  23. package/vectors/mdip-challenge-2/response.plaintext.json +1 -0
  24. package/vectors/mdip-challenge-2/response.sig.der +1 -0
  25. package/vectors/mdip-challenge-2/response.signed-op.bin +1 -0
  26. package/vectors/mdip-challenge-2/test-verifier.json +21 -0
  27. package/vectors/mdip-challenge-2/verifier-agent.PUBLIC-TEST-KEY.priv.pem +5 -0
  28. package/vectors/mdip-challenge-2/verifier-agent.message.bin +1 -0
  29. package/vectors/mdip-challenge-2/verifier-agent.op.json +21 -0
  30. package/vectors/mdip-challenge-2/verifier-agent.pub.pem +4 -0
  31. package/vectors/mdip-challenge-2/verifier-agent.sig.der +1 -0
  32. package/vectors/mdip-challenge-2/verifier-agent.signed-op.bin +1 -0
  33. package/vectors/mdip-challenge-2/verify-response.json +13 -0
  34. package/vectors/verify-openssl.sh +60 -0
  35. package/vectors/verify-with-kit.js +26 -0
package/README.md CHANGED
@@ -13,7 +13,7 @@ Give your AI agent its own **decentralized identity** (`did:mdip`) on the public
13
13
 
14
14
  > Install: `npm install mdip-agent-kit` · run: `npx mdip-agent-kit <command>`
15
15
  >
16
- > Status: early (0.1.2). Not affiliated with SELF or Keychain. License MIT (see `LICENSE`; can be changed).
16
+ > Status: early (0.1.4: vector checks parse JSON with jq and compare expiry as epoch ms; 0.1.3 added the offline challenge↔response binding vector + strict-expiry check). Not affiliated with SELF or Keychain. License MIT (see `LICENSE`; can be changed).
17
17
 
18
18
  ## Why
19
19
 
@@ -158,9 +158,9 @@ each vector ships the exact canonical bytes (`*.message.bin`), the signature re-
158
158
 
159
159
  ```bash
160
160
  # fetch the published files: a plain tarball download, nothing is installed or executed
161
- curl -sL https://registry.npmjs.org/mdip-agent-kit/-/mdip-agent-kit-0.1.2.tgz | tar xz
161
+ curl -sL https://registry.npmjs.org/mdip-agent-kit/-/mdip-agent-kit-0.1.3.tgz | tar xz
162
162
  cd package/vectors
163
- (cd kav-1 && sha256sum -c SHA256SUMS) && (cd mdip-challenge-1 && sha256sum -c SHA256SUMS) # all OK
163
+ for d in kav-1 mdip-challenge-1 mdip-challenge-2; do (cd $d && sha256sum -c SHA256SUMS); done # all OK
164
164
 
165
165
  # A. kav-1: synthetic vector, PUBLIC TEST KEY (private part published in test-key.json on purpose)
166
166
  openssl dgst -sha256 -r kav-1/message.bin
@@ -180,6 +180,21 @@ for p in verifier-agent:verifier-agent challenge:verifier-agent responder-agent:
180
180
  done
181
181
  # Verified OK x4 (exit 0 each)
182
182
 
183
+ # C. mdip-challenge-2 (new in 0.1.3, thanks @homies): offline challenge <-> response BINDING.
184
+ # The verifier is a PUBLIC TEST identity, so anyone can decrypt the response it received.
185
+ d=mdip-challenge-2
186
+ openssl pkey -in $d/verifier-agent.PUBLIC-TEST-KEY.priv.pem -pubout | cmp - $d/verifier-agent.pub.pem # same key
187
+ bash decrypt-openssl.sh $d/verifier-agent.PUBLIC-TEST-KEY.priv.pem $d/responder-agent.pub.pem $d/response.cipher_receiver.bin
188
+ # {"response":{"challenge":"did:mdip:...","credentials":[],...,"match":true,"responseNonce":"..."}}
189
+ # the "challenge" value must equal dids.json "challenge"; verify-openssl.sh checks that, plus:
190
+ # - response.cipher_receiver.bin is exactly cipher_receiver inside the SIGNED response op
191
+ # - every DID == did:mdip:z + base58btc(01 8004 1220 || sha256(<name>.signed-op.bin)) (DID is the op hash)
192
+ # - challenge controller == verifier DID; response controller == encrypted.sender == responder DID
193
+ # - a flipped ciphertext byte fails the Poly1305 tag
194
+
195
+ # D. strict expiry: response.validUntil <= challenge.validUntil. Equal is allowed, 1 ms later is not.
196
+ cat expiry-cases.txt # the table; verify-openssl.sh and verify-with-kit.js both run it
197
+
183
198
  # or all of the above in one go (bash + openssl only):
184
199
  bash verify-openssl.sh # last line: ALL VECTORS OK, exit 0
185
200
  ```
@@ -205,8 +220,26 @@ bash verify-openssl.sh # last line: ALL VECTORS OK, exit 0
205
220
  the challenge `controller` is the verifier DID; the response `controller` and `data.encrypted.sender`
206
221
  are the responder DID; the response `mdip.validUntil` ≤ the challenge's (expiry, capped by this kit).
207
222
  The response payload (`challenge` DID, `responseNonce`, `match`) is **encrypted to the verifier**,
208
- so only the verifier can check it; `verify-response.json` is what the verifier saw. These DIDs were short-lived (1 h), so they may no longer resolve. The fixture is for
223
+ so only the verifier can check it; `verify-response.json` is what the verifier saw (see C for an offline-checkable version). These DIDs were short-lived (1 h), so they may no longer resolve. The fixture is for
209
224
  offline checks.
225
+ - **C (`mdip-challenge-2`, 0.1.3)** closes the gap @homies found in B: there the binding sat in
226
+ ciphertext only the verifier could open. Here the verifier is a **PUBLIC TEST identity**: its wallet
227
+ mnemonic is derived from a published label (`test-verifier.json`) and its agent private key is
228
+ shipped as `verifier-agent.PUBLIC-TEST-KEY.priv.pem`. `decrypt-openssl.sh` decrypts the response
229
+ with stock OpenSSL only. MDIP's wire format (`@mdip/cipher` 2.2.0): key = first 32 bytes of the
230
+ compressed secp256k1 ECDH point (parity byte + 31 bytes of X), blob = `nonce(24) || ct || tag(16)`,
231
+ XChaCha20-Poly1305, no AAD. HChaCha20 is computed from one raw `openssl enc -chacha20` block and the
232
+ tag with `openssl mac POLY1305`. So an offline stranger can check, from signed bytes only: the verifier
233
+ signed challenge X, the responder signed a response whose plaintext says `"challenge": X`, and each
234
+ DID string is the hash of its op. Real verifiers keep their key private, so in production only the
235
+ verifier can make this check. The vector proves the format and the kit's binding logic, not a stranger's
236
+ view of a live exchange.
237
+ - **D (strict expiry)**: the intended rule is that a response **expires no later than** its challenge
238
+ (`response.validUntil <= challenge.validUntil`). Equal is valid because `respond` caps at exactly the
239
+ challenge expiry, which is why B and C show equal timestamps to the millisecond. One ms later is
240
+ rejected, and so is a missing response expiry when the challenge has one. Since 0.1.3,
241
+ `agent.verifyResponse()` / `mdip-agent verify-response` enforce this, plus "neither already expired",
242
+ and return `expiry: { ok, reason }` with `match: false` on failure (exported as `checkResponseExpiry`).
210
243
  - **Not covered offline:** DID resolution, key rotation and revocation. `verifyResponse` re-resolves the
211
244
  challenge and each presented credential **at verify time** and ignores deactivated or revoked ones.
212
245
  That needs a gatekeeper. Check it with the kit (`npm test`) or your own MDIP node.
package/llms.txt CHANGED
@@ -9,7 +9,7 @@
9
9
  - [examples/purchase-authorization.js](examples/purchase-authorization.js): accept and check a human-issued purchase credential
10
10
  - [vectors/README.md](vectors/README.md): known-answer vectors (stock OpenSSL, no install)
11
11
 
12
- - [README.md#known-answer-vectors-verify-with-stock-openssl-no-install](README.md): install-free known-answer vectors (secp256k1 / sha256(JCS)); files in vectors/, run `bash vectors/verify-openssl.sh`
12
+ - [README.md#known-answer-vectors-verify-with-stock-openssl-no-install](README.md): install-free known-answer vectors (secp256k1 / sha256(JCS)); files in vectors/, run `bash vectors/verify-openssl.sh`; 0.1.3 adds mdip-challenge-2 (offline challenge<->response binding via a PUBLIC TEST verifier key, stock-OpenSSL decrypt) and a strict-expiry table
13
13
 
14
14
  ## Key facts
15
15
  - Install: `npm install mdip-agent-kit`; CLI: `npx mdip-agent-kit init --profile-name "Name"`; config via MDIP_HOME, MDIP_GATEKEEPER_URL, MDIP_AGENT_NAME
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "mdip-agent-kit",
3
- "version": "0.1.2",
4
- "description": "Give any AI agent its own MDIP (did:mdip) identity on the SELF / Keychain hyperswarm network: keymaster wallet, DID, SELF Public Profile molecule, backups, challenges and delegated-authority credentials.",
3
+ "version": "0.1.4",
4
+ "description": "Give any AI agent its own MDIP (did:mdip) identity on the SELF (https://selfid.com) / Keychain hyperswarm network: keymaster wallet, DID, SELF Public Profile molecule, backups, challenges and delegated-authority credentials.",
5
+ "homepage": "https://selfid.com",
5
6
  "type": "module",
6
7
  "license": "MIT",
7
8
  "bin": {
package/src/index.js CHANGED
@@ -85,6 +85,31 @@ export async function createKeymaster({ gatekeeperUrl, walletDir, passphrase, re
85
85
  * Open (or create, with create:true) this agent's identity.
86
86
  * Returns an Agent with helpers for signing, challenges, credentials and backups.
87
87
  */
88
+ /**
89
+ * Strict-expiry rule for challenge responses (intended semantics, fixtures in vectors/expiry-cases.txt):
90
+ * a response must expire NO LATER than its challenge (response.validUntil <= challenge.validUntil; equal is
91
+ * allowed because respond caps at exactly the challenge's expiry). If the challenge has a validUntil the
92
+ * response must have one too. With `now` (ms), both must also still be in the future.
93
+ * @returns {{ok: boolean, reason?: string}}
94
+ */
95
+ export function checkResponseExpiry(challengeValidUntil, responseValidUntil, now) {
96
+ // a timestamp without Z or an offset would be read in the verifier's local zone: reject it (fail closed)
97
+ const zoned = (t) => /(Z|[+-]\d{2}:?\d{2})$/.test(String(t));
98
+ if (challengeValidUntil && !zoned(challengeValidUntil)) return { ok: false, reason: 'challenge validUntil has no timezone' };
99
+ if (responseValidUntil && !zoned(responseValidUntil)) return { ok: false, reason: 'response validUntil has no timezone' };
100
+ const c = challengeValidUntil ? Date.parse(challengeValidUntil) : NaN;
101
+ const r = responseValidUntil ? Date.parse(responseValidUntil) : NaN;
102
+ if (challengeValidUntil && !Number.isFinite(c)) return { ok: false, reason: 'challenge validUntil unparseable' };
103
+ if (responseValidUntil && !Number.isFinite(r)) return { ok: false, reason: 'response validUntil unparseable' };
104
+ if (Number.isFinite(c) && !Number.isFinite(r)) return { ok: false, reason: 'response has no validUntil but challenge does' };
105
+ if (Number.isFinite(c) && r > c) return { ok: false, reason: `response validUntil ${responseValidUntil} is later than challenge validUntil ${challengeValidUntil}` };
106
+ if (now !== undefined) {
107
+ if (Number.isFinite(c) && c <= now) return { ok: false, reason: `challenge expired at ${challengeValidUntil}` };
108
+ if (Number.isFinite(r) && r <= now) return { ok: false, reason: `response expired at ${responseValidUntil}` };
109
+ }
110
+ return { ok: true };
111
+ }
112
+
88
113
  export async function openAgent(opts = {}) {
89
114
  const cfg = loadConfig(opts);
90
115
  ensurePrivateDir(cfg.home);
@@ -169,8 +194,19 @@ export class Agent {
169
194
  }
170
195
  return new Date(until).toISOString();
171
196
  }
172
- /** Verify a response DID to a challenge you created. Result has .match, .responder, .vps... */
173
- verifyResponse(responseDid, options = {}) { return this.keymaster.verifyResponse(responseDid, options); }
197
+ /**
198
+ * Verify a response DID to a challenge you created. Result has .match, .responder, .vps...
199
+ * Since 0.1.3 also enforces strict expiry (see checkResponseExpiry): a response that outlives its
200
+ * challenge, or either one already expired, gives match:false with .expiry.reason set.
201
+ */
202
+ async verifyResponse(responseDid, options = {}) {
203
+ const result = await this.keymaster.verifyResponse(responseDid, options);
204
+ const [respDoc, chDoc] = await Promise.all([this.keymaster.resolveDID(responseDid), this.keymaster.resolveDID(result.challenge)]);
205
+ const expiry = checkResponseExpiry(chDoc?.mdip?.validUntil, respDoc?.mdip?.validUntil, Date.now());
206
+ result.expiry = expiry;
207
+ if (!expiry.ok) result.match = false;
208
+ return result;
209
+ }
174
210
 
175
211
  // ---- credentials -----------------------------------------------------------------------
176
212
  /** Accept a credential issued to this agent (e.g. a purchase authorization from a SELF app). */
package/vectors/README.md CHANGED
@@ -7,9 +7,14 @@ main README under "Known-answer vectors (verify with stock OpenSSL, no install)"
7
7
  |---|---|
8
8
  | `kav-1/` | Synthetic vector: public test key, non-empty JCS payload, compact + DER signature, tampered negative case |
9
9
  | `mdip-challenge-1/` | Real MDIP create operations for verifier agent, responder agent, challenge and response, plus the verifier's decrypted `verifyResponse` result |
10
+ | `mdip-challenge-2/` | Real challenge -> response whose **verifier is a PUBLIC TEST identity** (mnemonic + private key published), so the encrypted response can be decrypted offline and its `challenge` field checked against the challenge DID. Also `*.signed-op.bin` so each DID can be recomputed from its op. Suggested by @homies |
11
+ | `expiry-cases.txt` | Strict-expiry table: response.validUntil must be <= challenge.validUntil (equal allowed, +1 ms rejected) |
12
+ | `decrypt-openssl.sh` | Stock-OpenSSL decrypt of an MDIP encrypted message (secp256k1 ECDH + XChaCha20-Poly1305, tag checked) |
10
13
  | `verify-openssl.sh` | Install-free check (bash, sha256sum, openssl). Prints `ALL VECTORS OK` and exits 0 |
11
14
  | `verify-with-kit.js` | Same checks via `@mdip/cipher` (needs `npm install`) plus the JSON binding fields |
12
15
  | `generate.js` | Regenerates `kav-1/` deterministically |
13
16
  | `make-mdip-fixture.js` | Re-captures `mdip-challenge-1/` against a gatekeeper (publishes throwaway DIDs) |
17
+ | `make-mdip-fixture-2.js` | Re-captures `mdip-challenge-2/` (publishes throwaway DIDs; verifier from the published label mnemonic) |
14
18
 
15
- No real secrets are in here. `kav-1/test-key.json` is a test key that is published on purpose.
19
+ No real secrets are in here. `kav-1/test-key.json`, `mdip-challenge-2/test-verifier.json` and
20
+ `mdip-challenge-2/verifier-agent.PUBLIC-TEST-KEY.priv.pem` are test keys published on purpose. Never use them.
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env bash
2
+ # Offline decrypt of an MDIP encrypted message with stock OpenSSL (no npm, no network).
3
+ # MDIP (@mdip/cipher 2.2.0 encryptMessage) wire format, as implemented by the kit's dependency:
4
+ # S = secp256k1 ECDH(receiver priv, sender pub), as a COMPRESSED point (33 bytes: 02|03 || X)
5
+ # key = S[0:32] (the parity byte + the first 31 bytes of X; OpenSSL -derive gives X only,
6
+ # so we try prefix 02 and 03 and keep the one whose Poly1305 tag verifies)
7
+ # blob = base64url-decode(cipher_receiver) = nonce(24) || ciphertext || tag(16)
8
+ # cipher = XChaCha20-Poly1305(key, nonce), no AAD. XChaCha = HChaCha20 subkey + IETF ChaCha20-Poly1305
9
+ # with nonce 00000000||nonce[16:24]. HChaCha20 is recovered from one raw ChaCha20 block
10
+ # (keystream minus the initial state words 0-3 and 12-15).
11
+ # Usage: decrypt-openssl.sh <receiver-priv.pem> <sender-pub.pem> <blob.bin> -> plaintext on stdout
12
+ # Exit 0 only if the Poly1305 tag verifies.
13
+ set -euo pipefail
14
+ priv=$1 pub=$2 blob=$3
15
+ hex() { od -An -v -tx1 | tr -d ' \n'; }
16
+ unhex() { printf "$(printf '%s' "$1" | sed 's/../\\x&/g')"; }
17
+ le32() { local h=$1; echo $((16#${h:6:2}${h:4:2}${h:2:2}${h:0:2})); }
18
+ tole32(){ printf '%02x%02x%02x%02x' $(($1&255)) $((($1>>8)&255)) $((($1>>16)&255)) $((($1>>24)&255)); }
19
+ le64() { local n=$1 o= i; for i in 0 1 2 3 4 5 6 7; do o+=$(printf '%02x' $(((n>>(8*i))&255))); done; echo "$o"; }
20
+ ks() { head -c "$3" /dev/zero | openssl enc -chacha20 -K "$1" -iv "$2" | hex; } # raw keystream
21
+
22
+ B=$(hex < "$blob"); N=${B:0:48}; CT=${B:48:$((${#B}-48-32))}; TAG=${B: -32}
23
+ X=$(openssl pkeyutl -derive -inkey "$priv" -peerkey "$pub" | hex)
24
+ tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
25
+ unhex "$CT" > "$tmp/ct"
26
+ for prefix in 02 03; do
27
+ key=$prefix${X:0:62}
28
+ # HChaCha20(key, nonce[0:16])
29
+ K=$(ks "$key" "${N:0:32}" 64); sub=
30
+ sigma=(1634760805 857760878 2036477234 1797285236)
31
+ for i in 0 1 2 3; do sub+=$(tole32 $(( ($(le32 ${K:$((8*i)):8}) - ${sigma[$i]}) & 0xffffffff ))); done
32
+ for i in 0 1 2 3; do sub+=$(tole32 $(( ($(le32 ${K:$((8*(12+i))):8}) - $(le32 ${N:$((8*i)):8})) & 0xffffffff ))); done
33
+ n12=00000000${N:32:16}
34
+ polykey=$(ks "$sub" "00000000$n12" 32)
35
+ pad=$(( (16 - ${#CT}/2 % 16) % 16 ))
36
+ { cat "$tmp/ct"; head -c $pad /dev/zero; unhex "$(le64 0)$(le64 $((${#CT}/2)))"; } > "$tmp/macdata"
37
+ t=$(openssl mac -macopt hexkey:"$polykey" -in "$tmp/macdata" POLY1305 | tr 'A-F' 'a-f')
38
+ if [ "$t" = "$TAG" ]; then
39
+ openssl enc -chacha20 -K "$sub" -iv "01000000$n12" < "$tmp/ct"
40
+ exit 0
41
+ fi
42
+ done
43
+ echo "decrypt-openssl.sh: Poly1305 tag did not verify (wrong key or tampered ciphertext)" >&2
44
+ exit 1
@@ -0,0 +1,20 @@
1
+ # Strict-expiry rule (intended semantics, enforced by mdip-agent-kit >= 0.1.3 verifyResponse):
2
+ # a response MUST expire no later than the challenge it answers: response.validUntil <= challenge.validUntil
3
+ # equality is ALLOWED (the kit caps a response's expiry at exactly the challenge's validUntil);
4
+ # one millisecond later is REJECTED. A missing response validUntil is REJECTED when the challenge has one.
5
+ # Separately, at verify time both must still be in the future (now < validUntil); that needs a clock, not a vector.
6
+ # Timestamps are ISO-8601 (MDIP writes UTC with ms). Since 0.1.4 they are compared as epoch ms, not strings,
7
+ # so a missing fractional part or a +00:00 offset still compares correctly; a timestamp with NO zone is rejected.
8
+ # challenge.validUntil response.validUntil expected
9
+ 2026-10-26T16:41:19.930Z 2026-10-26T16:41:19.930Z accept equal (mdip-challenge-1/-2 are this case)
10
+ 2026-10-26T16:41:19.930Z 2026-10-26T16:41:19.929Z accept 1 ms earlier
11
+ 2026-10-26T16:41:19.930Z 2026-10-19T16:41:19.930Z accept a week earlier
12
+ 2026-10-26T16:41:19.930Z 2026-10-26T16:41:19.931Z reject 1 ms later
13
+ 2026-10-26T16:41:19.930Z 2026-10-26T17:41:19.930Z reject 1 h later (keymaster's raw default, uncapped)
14
+ 2026-10-26T16:41:19.930Z 2027-01-01T00:00:00.000Z reject next year
15
+ 2026-10-26T16:41:19.930Z - reject response has no validUntil
16
+ - 2026-10-26T16:41:19.930Z accept challenge has no validUntil (nothing to cap)
17
+ 2026-10-26T16:41:19.930Z 2026-10-26T16:41:19Z accept response without ms (0.930 s earlier)
18
+ 2026-10-26T16:41:19.930Z 2026-10-26T16:41:20Z reject response without ms, 70 ms later
19
+ 2026-10-26T16:41:19.930Z 2026-10-26T09:41:19.930-07:00 accept same instant written with an offset
20
+ 2026-10-26T16:41:19.930Z 2026-10-26T16:41:19.930 reject response with no timezone (fail closed)
@@ -0,0 +1,88 @@
1
+ #!/usr/bin/env node
2
+ // Captures vectors/mdip-challenge-2/: a REAL challenge -> response where the VERIFIER is a PUBLIC TEST
3
+ // IDENTITY (its wallet mnemonic and agent private key are published on purpose), so anyone can decrypt
4
+ // the response offline and check the challenge <-> response binding without running this kit.
5
+ // Suggested by @homies on connectthebots.app (/book/1227): in mdip-challenge-1 the binding lived only
6
+ // inside ciphertext encrypted to a private verifier key.
7
+ // Usage: MDIP_GATEKEEPER_URL=http://localhost:4224 node vectors/make-mdip-fixture-2.js
8
+ // NOTE: publishes throwaway DIDs (two agents, one 1-hour challenge, one response) to the registry.
9
+ import fs from 'node:fs';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+ import crypto from 'node:crypto';
13
+ import { fileURLToPath } from 'node:url';
14
+ import * as bip39 from 'bip39';
15
+ import CipherNode from '@mdip/cipher/node';
16
+ import { openAgent, waitForDid } from '../src/index.js';
17
+
18
+ const out = path.join(path.dirname(fileURLToPath(import.meta.url)), 'mdip-challenge-2');
19
+ fs.rmSync(out, { recursive: true, force: true });
20
+ fs.mkdirSync(out, { recursive: true });
21
+ const cipher = new CipherNode();
22
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'kav2-fixture-'));
23
+ const w = (f, data) => fs.writeFileSync(path.join(out, f), data);
24
+ const der = hex => {
25
+ 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]); };
26
+ const body = Buffer.concat([int(Buffer.from(hex.slice(0, 64), 'hex')), int(Buffer.from(hex.slice(64), 'hex'))]);
27
+ return Buffer.concat([Buffer.from([0x30, body.length]), body]);
28
+ };
29
+ // PUBLIC TEST VERIFIER. Mnemonic derived from a published label; anyone can re-derive it. Never use it.
30
+ const LABEL = 'mdip-agent-kit mdip-challenge-2 PUBLIC TEST VERIFIER - never use for anything real';
31
+ const mnemonic = bip39.entropyToMnemonic(crypto.createHash('sha256').update(LABEL, 'utf8').digest().subarray(0, 16));
32
+ try {
33
+ const verifier = await openAgent({ home: path.join(tmp, 'v'), name: 'kav2-public-test-verifier', create: true, mnemonic });
34
+ const responder = await openAgent({ home: path.join(tmp, 'r'), name: 'kav2-responder', create: true });
35
+ const vkp = await verifier.keymaster.fetchKeyPair();
36
+ const challengeDid = await verifier.createChallenge({});
37
+ await waitForDid(verifier.keymaster, challengeDid);
38
+ const responseDid = await responder.respondToChallenge(challengeDid); // validUntil capped at challenge's
39
+ await waitForDid(verifier.keymaster, responseDid);
40
+ const result = await verifier.verifyResponse(responseDid);
41
+ if (!result.match) throw new Error('verifyResponse did not match');
42
+
43
+ const names = { 'verifier-agent': verifier.did, 'responder-agent': responder.did, challenge: challengeDid, response: responseDid };
44
+ const exported = await verifier.keymaster.gatekeeper.exportDIDs(Object.values(names));
45
+ const ops = {};
46
+ Object.keys(names).forEach((k, i) => { ops[k] = exported[i][0].operation; });
47
+ if (JSON.stringify(ops['verifier-agent'].publicJwk) !== JSON.stringify(vkp.publicJwk)) throw new Error('verifier key mismatch');
48
+ for (const k of ['verifier-agent', 'responder-agent'])
49
+ w(`${k}.pub.pem`, crypto.createPublicKey({ key: { ...ops[k].publicJwk }, format: 'jwk' }).export({ type: 'spki', format: 'pem' }));
50
+ const priv = crypto.createPrivateKey({ key: { ...vkp.privateJwk }, format: 'jwk' });
51
+ w('verifier-agent.PUBLIC-TEST-KEY.priv.pem', priv.export({ type: 'pkcs8', format: 'pem' }));
52
+ w('test-verifier.json', JSON.stringify({
53
+ WARNING: 'PUBLIC TEST VERIFIER - wallet mnemonic and private key are published on purpose; never use them',
54
+ label: LABEL, mnemonicEntropy: 'first 16 bytes of sha256(label)', mnemonic,
55
+ derivationPath: "m/44'/0'/0'/0/0", did: verifier.did, publicJwk: vkp.publicJwk, privateJwk: vkp.privateJwk,
56
+ }, null, 2) + '\n');
57
+
58
+ const sums = [];
59
+ for (const [k, op] of Object.entries(ops)) {
60
+ const copy = JSON.parse(JSON.stringify(op)); delete copy.signature;
61
+ const msg = cipher.canonicalizeJSON(copy);
62
+ const hash = cipher.hashMessage(msg);
63
+ if (hash !== op.signature.hash) throw new Error(`${k}: hash mismatch`);
64
+ const signerKey = op.mdip.type === 'agent' ? op.publicJwk : ops[op.controller === verifier.did ? 'verifier-agent' : 'responder-agent'].publicJwk;
65
+ if (!cipher.verifySig(hash, op.signature.value, signerKey)) throw new Error(`${k}: sig fails`);
66
+ const full = cipher.canonicalizeJSON(op); // DID suffix = CIDv1(dag-json, sha256(JCS(signed op)))
67
+ w(`${k}.op.json`, JSON.stringify(op, null, 2) + '\n');
68
+ w(`${k}.message.bin`, msg);
69
+ w(`${k}.sig.der`, der(op.signature.value));
70
+ w(`${k}.signed-op.bin`, full);
71
+ sums.push(`${k}.message.bin`, `${k}.sig.der`, `${k}.signed-op.bin`);
72
+ }
73
+ // The response ciphertext the verifier received, and the plaintext it decrypts to (exact bytes).
74
+ const ct = ops.response.data.encrypted.cipher_receiver;
75
+ w('response.cipher_receiver.bin', Buffer.from(ct, 'base64url'));
76
+ const plaintext = cipher.decryptMessage(ops['responder-agent'].publicJwk, vkp.privateJwk, ct);
77
+ w('response.plaintext.json', plaintext);
78
+ if (JSON.parse(plaintext).response.challenge !== challengeDid) throw new Error('binding mismatch');
79
+ sums.push('response.cipher_receiver.bin', 'response.plaintext.json');
80
+ w('dids.json', JSON.stringify(names, null, 2) + '\n');
81
+ w('verify-response.json', JSON.stringify(result, null, 2) + '\n');
82
+ sums.push('verifier-agent.pub.pem', 'responder-agent.pub.pem', 'verifier-agent.PUBLIC-TEST-KEY.priv.pem', 'dids.json');
83
+ w('SHA256SUMS', sums.map(f => crypto.createHash('sha256').update(fs.readFileSync(path.join(out, f))).digest('hex') + ' ' + f).join('\n') + '\n');
84
+ console.log(JSON.stringify({ out, names, match: result.match, plaintext }, null, 2));
85
+ } finally {
86
+ fs.rmSync(tmp, { recursive: true, force: true });
87
+ }
88
+ process.exit(0);
@@ -0,0 +1,18 @@
1
+ 304f8e61072bd53f8c6077c17a8130fb4c5c32b7df03df4877927840f47fa286 verifier-agent.message.bin
2
+ aeedc84dd1d5d3b4ea44b3e26b651bcb37bae0547a4bb8dd0ff59e86caadddd9 verifier-agent.sig.der
3
+ 79b787f6d17ded13dbdd2354facad9e1130f7540f282c95feb9642c7f0c62259 verifier-agent.signed-op.bin
4
+ 8dd03638585ae9879f90443387231f079686539fdf23202fd77f8e9c64cebab1 responder-agent.message.bin
5
+ fd93ceb9990037595ee673873e1f3a73e4c735b8fff28d7f452b1bd7cf3d4f34 responder-agent.sig.der
6
+ b4b75dd4c2eaafdc25efbf3ca91b125bca7fb443e4097bf643edb719c012a345 responder-agent.signed-op.bin
7
+ a297b228dde5b31d82fc73a231db08c3bcb4da52cbe08098d1e582494f7c9908 challenge.message.bin
8
+ 9e75039393498b4c5fc6bff43a53141bb78e948c75c545e7b5ad0fcc5c44f6ee challenge.sig.der
9
+ 121891ebf0134e0d0b9a767df3f0367db8734612ea0199c6fe844788996653da challenge.signed-op.bin
10
+ 819ef6b2dae2d7400172be292a77aa1588257fd5f7be5e1f085a0b9ac0c89189 response.message.bin
11
+ 07b099b003d0fda5a415dcb36771dc09117144487b139c10f2667f7d467f8deb response.sig.der
12
+ b5ad2a12c5da722e08f9ad60c33344d444d53897a8c519c88b7b4a720fdd10f9 response.signed-op.bin
13
+ 1a3a67024f5847fe23ac569a5c1db89e70d7f2c39c8a4e5ef4b4450b32561f84 response.cipher_receiver.bin
14
+ 77f446a04c092117a90f95e53d0c2c51b7251db162bac31b70922b76f7681456 response.plaintext.json
15
+ f10c6a188f1c6b8117249327f96c3f00ee98e5859869e5e54cf29e8473412c83 verifier-agent.pub.pem
16
+ 232b067381d813d51472e84b9ffc09b39157f3813f7e85f7d562133f85d37596 responder-agent.pub.pem
17
+ af390f2d2ede2a07b4ec5ff35c1d27e0bf2f5fbd855b00e8e84da83e020dd87f verifier-agent.PUBLIC-TEST-KEY.priv.pem
18
+ 07ef1db1ee18d26a3e00a09dddf42843b64ea3400bc3d68b006ee8238a425189 dids.json
@@ -0,0 +1 @@
1
+ {"controller":"did:mdip:z3v8AuabH5z2RyBFCP8KzhS98jSL8Y62JPfis8EJiBo6io6QoRA","created":"2026-10-26T16:52:16.041Z","data":{"challenge":{}},"mdip":{"prefix":"did:mdip","registry":"hyperswarm","type":"asset","validUntil":"2026-10-26T17:52:16.038Z","version":1},"type":"create"}
@@ -0,0 +1,21 @@
1
+ {
2
+ "type": "create",
3
+ "created": "2026-10-26T16:52:16.041Z",
4
+ "mdip": {
5
+ "version": 1,
6
+ "type": "asset",
7
+ "registry": "hyperswarm",
8
+ "validUntil": "2026-10-26T17:52:16.038Z",
9
+ "prefix": "did:mdip"
10
+ },
11
+ "controller": "did:mdip:z3v8AuabH5z2RyBFCP8KzhS98jSL8Y62JPfis8EJiBo6io6QoRA",
12
+ "data": {
13
+ "challenge": {}
14
+ },
15
+ "signature": {
16
+ "signer": "did:mdip:z3v8AuabH5z2RyBFCP8KzhS98jSL8Y62JPfis8EJiBo6io6QoRA",
17
+ "signed": "2026-10-26T16:52:16.045Z",
18
+ "hash": "a297b228dde5b31d82fc73a231db08c3bcb4da52cbe08098d1e582494f7c9908",
19
+ "value": "e03ab72983791ae4e888e01433977bc37cd08e13ca0e138b10067c32fa19b23268190eff9296001734b3261b4bede40bb0c285c396126a8510f2219163947750"
20
+ }
21
+ }
@@ -0,0 +1 @@
1
+ {"controller":"did:mdip:z3v8AuabH5z2RyBFCP8KzhS98jSL8Y62JPfis8EJiBo6io6QoRA","created":"2026-10-26T16:52:16.041Z","data":{"challenge":{}},"mdip":{"prefix":"did:mdip","registry":"hyperswarm","type":"asset","validUntil":"2026-10-26T17:52:16.038Z","version":1},"signature":{"hash":"a297b228dde5b31d82fc73a231db08c3bcb4da52cbe08098d1e582494f7c9908","signed":"2026-10-26T16:52:16.045Z","signer":"did:mdip:z3v8AuabH5z2RyBFCP8KzhS98jSL8Y62JPfis8EJiBo6io6QoRA","value":"e03ab72983791ae4e888e01433977bc37cd08e13ca0e138b10067c32fa19b23268190eff9296001734b3261b4bede40bb0c285c396126a8510f2219163947750"},"type":"create"}
@@ -0,0 +1,6 @@
1
+ {
2
+ "verifier-agent": "did:mdip:z3v8AuabH5z2RyBFCP8KzhS98jSL8Y62JPfis8EJiBo6io6QoRA",
3
+ "responder-agent": "did:mdip:z3v8AuafFPtizoWoRCuV71sNVen1MUCrFuvfFNjhrYmasfnEFy6",
4
+ "challenge": "did:mdip:z3v8AuaUJbQT6UJRU58Bv8wWKZWCijUQwgej1cNjgoExXZLpeAM",
5
+ "response": "did:mdip:z3v8AuafK9H3bXz1apseJCAyp24v2Joh1kYAzdDVBCwzjfaAwAY"
6
+ }
@@ -0,0 +1 @@
1
+ {"created":"2026-10-26T16:52:15.961Z","mdip":{"prefix":"did:mdip","registry":"hyperswarm","type":"agent","version":1},"publicJwk":{"crv":"secp256k1","kty":"EC","x":"8pjNHCsnPMrvIaPpahoe3i24dI6HW1dUNVMRPKpOUHo","y":"K_GcL32twYMH3Wt9ppOraKQJVxwzvuITcVTHhkAAo_k"},"type":"create"}
@@ -0,0 +1,21 @@
1
+ {
2
+ "type": "create",
3
+ "created": "2026-10-26T16:52:15.961Z",
4
+ "mdip": {
5
+ "version": 1,
6
+ "type": "agent",
7
+ "registry": "hyperswarm",
8
+ "prefix": "did:mdip"
9
+ },
10
+ "publicJwk": {
11
+ "kty": "EC",
12
+ "crv": "secp256k1",
13
+ "x": "8pjNHCsnPMrvIaPpahoe3i24dI6HW1dUNVMRPKpOUHo",
14
+ "y": "K_GcL32twYMH3Wt9ppOraKQJVxwzvuITcVTHhkAAo_k"
15
+ },
16
+ "signature": {
17
+ "signed": "2026-10-26T16:52:15.962Z",
18
+ "hash": "8dd03638585ae9879f90443387231f079686539fdf23202fd77f8e9c64cebab1",
19
+ "value": "b4b9fc978e4241368cf1a0cfc87d917c4c79ebcd3bb1dfc79bed3493f28bcc381987fbf8e58bea2a95c399d2a0c771d5825f043441aadeb54ba617dcb55e1566"
20
+ }
21
+ }
@@ -0,0 +1,4 @@
1
+ -----BEGIN PUBLIC KEY-----
2
+ MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAE8pjNHCsnPMrvIaPpahoe3i24dI6HW1dU
3
+ NVMRPKpOUHor8Zwvfa3Bgwfda32mk6topAlXHDO+4hNxVMeGQACj+Q==
4
+ -----END PUBLIC KEY-----
@@ -0,0 +1 @@
1
+ {"created":"2026-10-26T16:52:15.961Z","mdip":{"prefix":"did:mdip","registry":"hyperswarm","type":"agent","version":1},"publicJwk":{"crv":"secp256k1","kty":"EC","x":"8pjNHCsnPMrvIaPpahoe3i24dI6HW1dUNVMRPKpOUHo","y":"K_GcL32twYMH3Wt9ppOraKQJVxwzvuITcVTHhkAAo_k"},"signature":{"hash":"8dd03638585ae9879f90443387231f079686539fdf23202fd77f8e9c64cebab1","signed":"2026-10-26T16:52:15.962Z","value":"b4b9fc978e4241368cf1a0cfc87d917c4c79ebcd3bb1dfc79bed3493f28bcc381987fbf8e58bea2a95c399d2a0c771d5825f043441aadeb54ba617dcb55e1566"},"type":"create"}
@@ -0,0 +1 @@
1
+ {"controller":"did:mdip:z3v8AuafFPtizoWoRCuV71sNVen1MUCrFuvfFNjhrYmasfnEFy6","created":"2026-10-26T16:52:16.076Z","data":{"encrypted":{"cipher_hash":null,"cipher_receiver":"uiMHA9AAA9MOHHuXMnFZ-HNCzTrJDJm1VuXvaNO9R97FmZ-v3qvDjNOoYAi1oGOhn2krsd00ZAMmvPoiOWqf1Ows3yMO2tcE1kednFQoIUVg7gC25kjScsa-CfzgeDJk3GI0IlRA7XnG_C0-jPdiyGzBA_RNA_MrFWNhQP6k_ayJdmqdAophEUInX4x5EDHp7s2G5GTPjRPswH7nN9e2Nxf13ioSXd2X7gT7iDBPcWQNU-8jVWgMz4E7Xd7bMxJZeIVwHyDudnuUKbxL_DNunypedW7YMpIAnhBoMdRG5V8eODPr72-vDiz2uzPAELOyIm_ehw0RDgqAeg","cipher_sender":"ySZI62MoVA63_QzxGd483KUvme_JvD6MI1nHTsht3lqfSj-LP_XMzhago2c8ZqTJEMOAC3zqLvN77LidCeqFRJSlXEgn8hv0qW2nXEzfbCe2pA_0yNKHZ6_Lz2z9Z31fLrc8V2Y4fEOj38XMUS_UML3WVYiJTaLWvyCbB0JEoNEkXCg6xaa8jSu6mvVVevpu088BpFjx2SmYpGBQWNIrWyYyQ_L9Qde-o31zn0lXHe9HFXfO52d7cq6b1H81Bu3xwsA3qxylMKo15OEGca3EKV8C45fKVrB61MMccnkJmWgwEPJ6p5-beFnXsmlM94gMedd4U7mCayO2CQ","created":"2026-10-26T16:52:16.074Z","sender":"did:mdip:z3v8AuafFPtizoWoRCuV71sNVen1MUCrFuvfFNjhrYmasfnEFy6"}},"mdip":{"prefix":"did:mdip","registry":"hyperswarm","type":"asset","validUntil":"2026-10-26T17:52:16.038Z","version":1},"type":"create"}
@@ -0,0 +1,27 @@
1
+ {
2
+ "type": "create",
3
+ "created": "2026-10-26T16:52:16.076Z",
4
+ "mdip": {
5
+ "version": 1,
6
+ "type": "asset",
7
+ "registry": "hyperswarm",
8
+ "validUntil": "2026-10-26T17:52:16.038Z",
9
+ "prefix": "did:mdip"
10
+ },
11
+ "controller": "did:mdip:z3v8AuafFPtizoWoRCuV71sNVen1MUCrFuvfFNjhrYmasfnEFy6",
12
+ "data": {
13
+ "encrypted": {
14
+ "sender": "did:mdip:z3v8AuafFPtizoWoRCuV71sNVen1MUCrFuvfFNjhrYmasfnEFy6",
15
+ "created": "2026-10-26T16:52:16.074Z",
16
+ "cipher_hash": null,
17
+ "cipher_sender": "ySZI62MoVA63_QzxGd483KUvme_JvD6MI1nHTsht3lqfSj-LP_XMzhago2c8ZqTJEMOAC3zqLvN77LidCeqFRJSlXEgn8hv0qW2nXEzfbCe2pA_0yNKHZ6_Lz2z9Z31fLrc8V2Y4fEOj38XMUS_UML3WVYiJTaLWvyCbB0JEoNEkXCg6xaa8jSu6mvVVevpu088BpFjx2SmYpGBQWNIrWyYyQ_L9Qde-o31zn0lXHe9HFXfO52d7cq6b1H81Bu3xwsA3qxylMKo15OEGca3EKV8C45fKVrB61MMccnkJmWgwEPJ6p5-beFnXsmlM94gMedd4U7mCayO2CQ",
18
+ "cipher_receiver": "uiMHA9AAA9MOHHuXMnFZ-HNCzTrJDJm1VuXvaNO9R97FmZ-v3qvDjNOoYAi1oGOhn2krsd00ZAMmvPoiOWqf1Ows3yMO2tcE1kednFQoIUVg7gC25kjScsa-CfzgeDJk3GI0IlRA7XnG_C0-jPdiyGzBA_RNA_MrFWNhQP6k_ayJdmqdAophEUInX4x5EDHp7s2G5GTPjRPswH7nN9e2Nxf13ioSXd2X7gT7iDBPcWQNU-8jVWgMz4E7Xd7bMxJZeIVwHyDudnuUKbxL_DNunypedW7YMpIAnhBoMdRG5V8eODPr72-vDiz2uzPAELOyIm_ehw0RDgqAeg"
19
+ }
20
+ },
21
+ "signature": {
22
+ "signer": "did:mdip:z3v8AuafFPtizoWoRCuV71sNVen1MUCrFuvfFNjhrYmasfnEFy6",
23
+ "signed": "2026-10-26T16:52:16.080Z",
24
+ "hash": "819ef6b2dae2d7400172be292a77aa1588257fd5f7be5e1f085a0b9ac0c89189",
25
+ "value": "174cb39fe81cdd7f3e48f9d54a3b3bda126f9e4734e3369ad9c62460493ec0b213bc86ebd91e7fe3e739fe307d266d38d0578335c39896d538e03ba4660d6dc2"
26
+ }
27
+ }
@@ -0,0 +1 @@
1
+ {"response":{"challenge":"did:mdip:z3v8AuaUJbQT6UJRU58Bv8wWKZWCijUQwgej1cNjgoExXZLpeAM","credentials":[],"requested":0,"fulfilled":0,"match":true,"responseNonce":"ux7adN66ROY2r76oL-nlwCLGhw-lAKTrQL0Bem1FWGfA"}}
@@ -0,0 +1 @@
1
+ 0D L����>H��J;;�o�G4�6���$`I>�� ������9�0}&m8�W�5��8�;�f
@@ -0,0 +1 @@
1
+ {"controller":"did:mdip:z3v8AuafFPtizoWoRCuV71sNVen1MUCrFuvfFNjhrYmasfnEFy6","created":"2026-10-26T16:52:16.076Z","data":{"encrypted":{"cipher_hash":null,"cipher_receiver":"uiMHA9AAA9MOHHuXMnFZ-HNCzTrJDJm1VuXvaNO9R97FmZ-v3qvDjNOoYAi1oGOhn2krsd00ZAMmvPoiOWqf1Ows3yMO2tcE1kednFQoIUVg7gC25kjScsa-CfzgeDJk3GI0IlRA7XnG_C0-jPdiyGzBA_RNA_MrFWNhQP6k_ayJdmqdAophEUInX4x5EDHp7s2G5GTPjRPswH7nN9e2Nxf13ioSXd2X7gT7iDBPcWQNU-8jVWgMz4E7Xd7bMxJZeIVwHyDudnuUKbxL_DNunypedW7YMpIAnhBoMdRG5V8eODPr72-vDiz2uzPAELOyIm_ehw0RDgqAeg","cipher_sender":"ySZI62MoVA63_QzxGd483KUvme_JvD6MI1nHTsht3lqfSj-LP_XMzhago2c8ZqTJEMOAC3zqLvN77LidCeqFRJSlXEgn8hv0qW2nXEzfbCe2pA_0yNKHZ6_Lz2z9Z31fLrc8V2Y4fEOj38XMUS_UML3WVYiJTaLWvyCbB0JEoNEkXCg6xaa8jSu6mvVVevpu088BpFjx2SmYpGBQWNIrWyYyQ_L9Qde-o31zn0lXHe9HFXfO52d7cq6b1H81Bu3xwsA3qxylMKo15OEGca3EKV8C45fKVrB61MMccnkJmWgwEPJ6p5-beFnXsmlM94gMedd4U7mCayO2CQ","created":"2026-10-26T16:52:16.074Z","sender":"did:mdip:z3v8AuafFPtizoWoRCuV71sNVen1MUCrFuvfFNjhrYmasfnEFy6"}},"mdip":{"prefix":"did:mdip","registry":"hyperswarm","type":"asset","validUntil":"2026-10-26T17:52:16.038Z","version":1},"signature":{"hash":"819ef6b2dae2d7400172be292a77aa1588257fd5f7be5e1f085a0b9ac0c89189","signed":"2026-10-26T16:52:16.080Z","signer":"did:mdip:z3v8AuafFPtizoWoRCuV71sNVen1MUCrFuvfFNjhrYmasfnEFy6","value":"174cb39fe81cdd7f3e48f9d54a3b3bda126f9e4734e3369ad9c62460493ec0b213bc86ebd91e7fe3e739fe307d266d38d0578335c39896d538e03ba4660d6dc2"},"type":"create"}
@@ -0,0 +1,21 @@
1
+ {
2
+ "WARNING": "PUBLIC TEST VERIFIER - wallet mnemonic and private key are published on purpose; never use them",
3
+ "label": "mdip-agent-kit mdip-challenge-2 PUBLIC TEST VERIFIER - never use for anything real",
4
+ "mnemonicEntropy": "first 16 bytes of sha256(label)",
5
+ "mnemonic": "two sugar fold avoid decrease tape quiz enter suspect spring friend ensure",
6
+ "derivationPath": "m/44'/0'/0'/0/0",
7
+ "did": "did:mdip:z3v8AuabH5z2RyBFCP8KzhS98jSL8Y62JPfis8EJiBo6io6QoRA",
8
+ "publicJwk": {
9
+ "kty": "EC",
10
+ "crv": "secp256k1",
11
+ "x": "bX9BWDIW4h1PY9G4HW9oHdcbtn1497wT8Sn5I7pUYFU",
12
+ "y": "rOgfOT0uSEnru8NPqXEF621htZn8LayC35uN4lmOOe0"
13
+ },
14
+ "privateJwk": {
15
+ "kty": "EC",
16
+ "crv": "secp256k1",
17
+ "x": "bX9BWDIW4h1PY9G4HW9oHdcbtn1497wT8Sn5I7pUYFU",
18
+ "y": "rOgfOT0uSEnru8NPqXEF621htZn8LayC35uN4lmOOe0",
19
+ "d": "DHF4kSOAUJgtlziC5guj0_Op1aKqKH3NdVLsvTXTKto"
20
+ }
21
+ }
@@ -0,0 +1,5 @@
1
+ -----BEGIN PRIVATE KEY-----
2
+ MIGEAgEAMBAGByqGSM49AgEGBSuBBAAKBG0wawIBAQQgDHF4kSOAUJgtlziC5guj
3
+ 0/Op1aKqKH3NdVLsvTXTKtqhRANCAARtf0FYMhbiHU9j0bgdb2gd1xu2fXj3vBPx
4
+ KfkjulRgVazoHzk9LkhJ67vDT6lxBettYbWZ/C2sgt+bjeJZjjnt
5
+ -----END PRIVATE KEY-----
@@ -0,0 +1 @@
1
+ {"created":"2026-10-26T16:52:15.731Z","mdip":{"prefix":"did:mdip","registry":"hyperswarm","type":"agent","version":1},"publicJwk":{"crv":"secp256k1","kty":"EC","x":"bX9BWDIW4h1PY9G4HW9oHdcbtn1497wT8Sn5I7pUYFU","y":"rOgfOT0uSEnru8NPqXEF621htZn8LayC35uN4lmOOe0"},"type":"create"}
@@ -0,0 +1,21 @@
1
+ {
2
+ "type": "create",
3
+ "created": "2026-10-26T16:52:15.731Z",
4
+ "mdip": {
5
+ "version": 1,
6
+ "type": "agent",
7
+ "registry": "hyperswarm",
8
+ "prefix": "did:mdip"
9
+ },
10
+ "publicJwk": {
11
+ "kty": "EC",
12
+ "crv": "secp256k1",
13
+ "x": "bX9BWDIW4h1PY9G4HW9oHdcbtn1497wT8Sn5I7pUYFU",
14
+ "y": "rOgfOT0uSEnru8NPqXEF621htZn8LayC35uN4lmOOe0"
15
+ },
16
+ "signature": {
17
+ "signed": "2026-10-26T16:52:15.735Z",
18
+ "hash": "304f8e61072bd53f8c6077c17a8130fb4c5c32b7df03df4877927840f47fa286",
19
+ "value": "652ab286c3820c1da4a10b9a0785ea83564a49afa29867d99c819bd5d69580f7114b7c3219bed17e9bbefd08f8bbd32fc0ccf27e98590643dc67068c4d449316"
20
+ }
21
+ }
@@ -0,0 +1,4 @@
1
+ -----BEGIN PUBLIC KEY-----
2
+ MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEbX9BWDIW4h1PY9G4HW9oHdcbtn1497wT
3
+ 8Sn5I7pUYFWs6B85PS5ISeu7w0+pcQXrbWG1mfwtrILfm43iWY457Q==
4
+ -----END PUBLIC KEY-----
@@ -0,0 +1 @@
1
+ 0D e*�� �� ���VJI���gٜ���֕�� K|2��~������/���~�YC�g�MD�
@@ -0,0 +1 @@
1
+ {"created":"2026-10-26T16:52:15.731Z","mdip":{"prefix":"did:mdip","registry":"hyperswarm","type":"agent","version":1},"publicJwk":{"crv":"secp256k1","kty":"EC","x":"bX9BWDIW4h1PY9G4HW9oHdcbtn1497wT8Sn5I7pUYFU","y":"rOgfOT0uSEnru8NPqXEF621htZn8LayC35uN4lmOOe0"},"signature":{"hash":"304f8e61072bd53f8c6077c17a8130fb4c5c32b7df03df4877927840f47fa286","signed":"2026-10-26T16:52:15.735Z","value":"652ab286c3820c1da4a10b9a0785ea83564a49afa29867d99c819bd5d69580f7114b7c3219bed17e9bbefd08f8bbd32fc0ccf27e98590643dc67068c4d449316"},"type":"create"}
@@ -0,0 +1,13 @@
1
+ {
2
+ "challenge": "did:mdip:z3v8AuaUJbQT6UJRU58Bv8wWKZWCijUQwgej1cNjgoExXZLpeAM",
3
+ "credentials": [],
4
+ "requested": 0,
5
+ "fulfilled": 0,
6
+ "match": true,
7
+ "responseNonce": "ux7adN66ROY2r76oL-nlwCLGhw-lAKTrQL0Bem1FWGfA",
8
+ "vps": [],
9
+ "responder": "did:mdip:z3v8AuafFPtizoWoRCuV71sNVen1MUCrFuvfFNjhrYmasfnEFy6",
10
+ "expiry": {
11
+ "ok": true
12
+ }
13
+ }
@@ -25,4 +25,64 @@ done
25
25
  v mdip-challenge-1/verifier-agent.pub.pem mdip-challenge-1/response.sig.der mdip-challenge-1/response.message.bin \
26
26
  && bad "response verified under verifier key (must not)" || ok "response NOT valid under verifier key"
27
27
 
28
+ echo "== mdip-challenge-2: offline challenge <-> response binding (PUBLIC TEST verifier key; thanks @homies)"
29
+ d=mdip-challenge-2
30
+ ( cd $d && sha256sum -c --quiet SHA256SUMS ) && ok "mdip-challenge-2 SHA256SUMS" || bad "mdip-challenge-2 SHA256SUMS"
31
+ for k in verifier-agent:verifier-agent challenge:verifier-agent responder-agent:responder-agent response:responder-agent; do
32
+ op=${k%%:*}; key=${k##*:}
33
+ v "$d/$key.pub.pem" "$d/$op.sig.der" "$d/$op.message.bin" && ok "$op op signed by $key key" || bad "$op op signature"
34
+ done
35
+ # 1. each DID string IS the hash of its signed create op: did:mdip:z<base58btc(01 8004 1220 || sha256(JCS(op)))>
36
+ b58hex() { local A=123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz s=$1 b=() i j c x; local -i carry
37
+ for ((i=0;i<${#s};i++)); do x=${A%%"${s:i:1}"*}; carry=${#x}
38
+ for ((j=${#b[@]}-1;j>=0;j--)); do carry+=$((b[j]*58)); b[j]=$((carry&255)); carry=$((carry>>8)); done
39
+ while ((carry)); do b=($((carry&255)) "${b[@]}"); carry=$((carry>>8)); done; done
40
+ for c in "${b[@]}"; do printf %02x "$c"; done; }
41
+ did() { sed -n "s/.*\"$1\": \"\\(did:mdip:[^\"]*\\)\".*/\\1/p" $d/dids.json; }
42
+ jget() { sed -n "s/.*\"$1\":\"\\([^\"]*\\)\".*/\\1/p" "$2" | head -1; }
43
+ for k in verifier-agent challenge responder-agent response; do
44
+ sfx=$(did $k); sfx=${sfx#did:mdip:z}
45
+ [ "$(b58hex "$sfx")" = "0180041220$(openssl dgst -sha256 -r $d/$k.signed-op.bin | cut -d' ' -f1)" ] \
46
+ && ok "$k DID == CID(sha256(signed-op.bin))" || bad "$k DID does not match its op"
47
+ done
48
+ # 2. the private test key really is the verifier agent's key
49
+ [ "$(openssl pkey -in $d/verifier-agent.PUBLIC-TEST-KEY.priv.pem -pubout 2>/dev/null)" = "$(cat $d/verifier-agent.pub.pem)" ] \
50
+ && ok "published private test key matches verifier-agent.pub.pem" || bad "test key mismatch"
51
+ # 3. controllers: challenge by verifier, response by responder (fields read from the signed bytes)
52
+ [ "$(jget controller $d/challenge.message.bin)" = "$(did verifier-agent)" ] && ok "challenge controller == verifier DID" || bad "challenge controller"
53
+ [ "$(jget controller $d/response.message.bin)" = "$(did responder-agent)" ] && [ "$(jget sender $d/response.message.bin)" = "$(did responder-agent)" ] \
54
+ && ok "response controller == encrypted.sender == responder DID" || bad "response controller/sender"
55
+ # 4. decrypt the signed response ciphertext with the PUBLIC TEST verifier key (ECDH + XChaCha20-Poly1305)
56
+ [ "$(jget cipher_receiver $d/response.message.bin)" = "$(openssl base64 -A < $d/response.cipher_receiver.bin | tr '+/' '-_' | tr -d '=')" ] \
57
+ && ok "response.cipher_receiver.bin == cipher_receiver in the signed response op" || bad "ciphertext not from signed op"
58
+ pt=$(bash decrypt-openssl.sh $d/verifier-agent.PUBLIC-TEST-KEY.priv.pem $d/responder-agent.pub.pem $d/response.cipher_receiver.bin) \
59
+ && ok "response decrypts, Poly1305 tag OK" || bad "response decrypt"
60
+ [ "$pt" = "$(cat $d/response.plaintext.json)" ] && ok "decrypted bytes == response.plaintext.json" || bad "plaintext mismatch"
61
+ # 5. THE BINDING: the signed+encrypted response names this challenge DID
62
+ # parse as JSON (key order independent) when jq exists; the anchored sed is only a no-jq fallback
63
+ if command -v jq >/dev/null; then bound=$(printf %s "$pt" | jq -r '.response.challenge // empty'); else
64
+ echo " (no jq: falling back to anchored sed; install jq for an encoder-independent parse)"
65
+ bound=$(printf %s "$pt" | sed -n 's/^{"response":{"challenge":"\(did:mdip:[^"]*\)".*/\1/p'); fi
66
+ [ -n "$bound" ] && [ "$bound" = "$(did challenge)" ] \
67
+ && ok "BINDING: decrypted response.challenge == challenge DID" || bad "BINDING: response does not answer this challenge"
68
+ printf %s "$pt" | grep -q '"match":true' && printf %s "$pt" | grep -q '"responseNonce":"[^"]\+"' && ok "response match=true, has responseNonce" || bad "response fields"
69
+ # negative: one flipped ciphertext byte must fail the tag
70
+ tmpc=$(mktemp); cp $d/response.cipher_receiver.bin "$tmpc"; printf '\xff' | dd of="$tmpc" bs=1 seek=30 conv=notrunc 2>/dev/null
71
+ bash decrypt-openssl.sh $d/verifier-agent.PUBLIC-TEST-KEY.priv.pem $d/responder-agent.pub.pem "$tmpc" >/dev/null 2>&1 \
72
+ && bad "tampered ciphertext decrypted (must not)" || ok "tampered ciphertext rejected (tag)"; rm -f "$tmpc"
73
+
74
+ echo "== strict expiry: response.validUntil <= challenge.validUntil (equal allowed, 1 ms later rejected)"
75
+ # compare as epoch ms, not strings: accepts with/without fractional seconds; a timestamp with no Z/offset is rejected (fail closed)
76
+ tms() { [[ "$1" =~ (Z|[+-][0-9]{2}:?[0-9]{2})$ ]] || return 1; date -u -d "$1" +%s%3N 2>/dev/null; }
77
+ expiry_ok() { [ "$1" = - ] && return 0; [ "$2" = - ] && return 1; local c r; c=$(tms "$1") && r=$(tms "$2") || return 1; [ "$r" -le "$c" ]; }
78
+ for dd in mdip-challenge-1 mdip-challenge-2; do
79
+ c=$(jget validUntil $dd/challenge.message.bin); r=$(jget validUntil $dd/response.message.bin)
80
+ expiry_ok "$c" "$r" && ok "$dd response $r <= challenge $c$([ "$r" = "$c" ] && echo ' (equal: allowed)')" || bad "$dd expiry"
81
+ done
82
+ while read -r c r want note; do
83
+ case "$c" in ''|\#*) continue;; esac
84
+ expiry_ok "$c" "$r" && got=accept || got=reject
85
+ [ "$got" = "$want" ] && ok "expiry case: $note -> $got" || bad "expiry case: $note -> $got (want $want)"
86
+ done < expiry-cases.txt
87
+
28
88
  [ $fail = 0 ] && echo "ALL VECTORS OK" || { echo "VECTORS FAILED"; exit 1; }
@@ -7,6 +7,7 @@ import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import CipherNode from '@mdip/cipher/node';
10
+ import { checkResponseExpiry } from '../src/index.js';
10
11
 
11
12
  const dir = path.dirname(fileURLToPath(import.meta.url));
12
13
  const c = new CipherNode();
@@ -41,5 +42,30 @@ check(ch.controller === dids['verifier-agent'], 'challenge controller == verifie
41
42
  check(re.controller === dids['responder-agent'] && re.data.encrypted.sender === re.controller, 'response controller == encrypted.sender == responder DID');
42
43
  check(Date.parse(re.mdip.validUntil) <= Date.parse(ch.mdip.validUntil), 'response validUntil <= challenge validUntil (expiry)');
43
44
  check(vr.challenge === dids.challenge && vr.responder === dids['responder-agent'] && vr.match === true && !!vr.responseNonce, 'decrypted response names the challenge DID, responder, match=true, has responseNonce');
45
+
46
+ // mdip-challenge-2: PUBLIC TEST verifier key -> decrypt the response and check the binding offline
47
+ {
48
+ const d = 'mdip-challenge-2';
49
+ const dids2 = js(`${d}/dids.json`), o2 = k => js(`${d}/${k}.op.json`), tv = js(`${d}/test-verifier.json`);
50
+ const ch2 = o2('challenge'), re2 = o2('response'), resp = o2('responder-agent'), ver = o2('verifier-agent');
51
+ check(JSON.stringify(tv.publicJwk) === JSON.stringify(ver.publicJwk) && tv.did === dids2['verifier-agent'], `${d} test-verifier.json key == verifier-agent op key`);
52
+ for (const k of ['verifier-agent', 'challenge', 'responder-agent', 'response']) {
53
+ const o = o2(k);
54
+ 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.verifySig(o.signature.hash, o.signature.value, o.mdip.type === 'agent' ? o.publicJwk : (o.controller === dids2['verifier-agent'] ? ver : resp).publicJwk), `${d} ${k} signature`);
56
+ }
57
+ const pt = c.decryptMessage(resp.publicJwk, tv.privateJwk, re2.data.encrypted.cipher_receiver);
58
+ check(pt === rd(`${d}/response.plaintext.json`), `${d} @mdip/cipher decrypt == response.plaintext.json`);
59
+ check(JSON.parse(pt).response.challenge === dids2.challenge, `${d} BINDING: response.challenge == challenge DID`);
60
+ check(ch2.controller === dids2['verifier-agent'] && re2.controller === dids2['responder-agent'], `${d} controllers`);
61
+ check(checkResponseExpiry(ch2.mdip.validUntil, re2.mdip.validUntil).ok, `${d} strict expiry (response <= challenge)`);
62
+ }
63
+ // strict-expiry cases (same table verify-openssl.sh uses)
64
+ for (const line of rd('expiry-cases.txt').split('\n')) {
65
+ if (!line.trim() || line.startsWith('#')) continue;
66
+ const [cv, rv, want, ...note] = line.trim().split(/\s+/);
67
+ const got = checkResponseExpiry(cv === '-' ? undefined : cv, rv === '-' ? undefined : rv).ok ? 'accept' : 'reject';
68
+ check(got === want, `expiry case: ${note.join(' ')} -> ${got}`);
69
+ }
44
70
  console.log(fail ? 'VECTORS FAILED' : 'ALL VECTORS OK');
45
71
  process.exit(fail);