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.
Files changed (43) hide show
  1. package/AGENTS.md +4 -3
  2. package/CHANGELOG.md +86 -0
  3. package/README.md +130 -29
  4. package/bin/mdip-agent.js +55 -16
  5. package/examples/agent-handshake.js +6 -4
  6. package/examples/purchase-authorization.js +5 -2
  7. package/llms.txt +4 -1
  8. package/package.json +6 -3
  9. package/src/index.js +209 -49
  10. package/test/api-security.mjs +130 -0
  11. package/test/e2e.sh +68 -0
  12. package/test/vectors-negative.sh +232 -0
  13. package/vectors/README.md +15 -4
  14. package/vectors/decrypt-openssl.sh +11 -2
  15. package/vectors/expiry-cases.txt +64 -15
  16. package/vectors/generate.js +9 -4
  17. package/vectors/kav-1/SHA256SUMS +7 -3
  18. package/vectors/kav-1/payload.json +3 -3
  19. package/vectors/kav-1/signed.json +6 -6
  20. package/vectors/kav-1/test-key.json +7 -7
  21. package/vectors/make-mdip-fixture-2.js +13 -11
  22. package/vectors/make-mdip-fixture.js +12 -7
  23. package/vectors/mdip-challenge-1/SHA256SUMS +15 -5
  24. package/vectors/mdip-challenge-1/challenge.op.json +11 -11
  25. package/vectors/mdip-challenge-1/challenge.signed-op.bin +1 -0
  26. package/vectors/mdip-challenge-1/dids.json +3 -3
  27. package/vectors/mdip-challenge-1/responder-agent.op.json +7 -7
  28. package/vectors/mdip-challenge-1/responder-agent.signed-op.bin +1 -0
  29. package/vectors/mdip-challenge-1/response.op.json +15 -15
  30. package/vectors/mdip-challenge-1/response.signed-op.bin +1 -0
  31. package/vectors/mdip-challenge-1/verifier-agent.op.json +7 -7
  32. package/vectors/mdip-challenge-1/verifier-agent.signed-op.bin +1 -0
  33. package/vectors/mdip-challenge-1/verify-response.json +3 -3
  34. package/vectors/mdip-challenge-2/SHA256SUMS +17 -11
  35. package/vectors/mdip-challenge-2/challenge.op.json +11 -11
  36. package/vectors/mdip-challenge-2/dids.json +3 -3
  37. package/vectors/mdip-challenge-2/responder-agent.op.json +7 -7
  38. package/vectors/mdip-challenge-2/response.op.json +15 -15
  39. package/vectors/mdip-challenge-2/test-verifier.json +9 -9
  40. package/vectors/mdip-challenge-2/verifier-agent.op.json +7 -7
  41. package/vectors/mdip-challenge-2/verify-response.json +6 -6
  42. package/vectors/verify-openssl.sh +269 -40
  43. package/vectors/verify-with-kit.js +207 -10
package/src/index.js CHANGED
@@ -73,39 +73,121 @@ export async function waitForDid(keymaster, did, { timeoutMs = 60000, intervalMs
73
73
  }
74
74
 
75
75
  /** Build a Keymaster bound to a wallet directory and passphrase. Low-level; prefer openAgent(). */
76
- export async function createKeymaster({ gatekeeperUrl, walletDir, passphrase, registry = DEFAULTS.registry, didPrefix = DEFAULTS.didPrefix, wait = true }) {
76
+ export async function createKeymaster({ gatekeeperUrl, walletDir, passphrase, registry = DEFAULTS.registry, didPrefix = DEFAULTS.didPrefix, wait = true, waitSeconds = 60 }) {
77
77
  const gatekeeper = new GatekeeperClient();
78
- await gatekeeper.connect({ url: gatekeeperUrl, waitUntilReady: wait, intervalSeconds: 3, chatty: false });
78
+ // Bounded wait (the client's own default retries forever, so a down gatekeeper would hang the agent).
79
+ const intervalSeconds = 3, maxRetries = Math.max(1, Math.ceil(Number(waitSeconds) / intervalSeconds) || 1);
80
+ await gatekeeper.connect({ url: gatekeeperUrl, waitUntilReady: wait, intervalSeconds, maxRetries, chatty: false });
81
+ if (wait && !(await gatekeeper.isReady())) {
82
+ throw new Error(`Gatekeeper at ${gatekeeperUrl} not ready after ${waitSeconds}s (is it running? see scripts/run-local-node.sh)`);
83
+ }
79
84
  ensurePrivateDir(walletDir);
80
85
  const wallet = new WalletJson('wallet.json', walletDir);
81
86
  return new Keymaster({ gatekeeper, wallet, cipher: new CipherNode(), defaultRegistry: registry, didPrefix, passphrase });
82
87
  }
83
88
 
84
89
  /**
85
- * Open (or create, with create:true) this agent's identity.
86
- * Returns an Agent with helpers for signing, challenges, credentials and backups.
90
+ * Strict RFC 3339 timestamp -> exact epoch nanoseconds (BigInt), or null if not accepted (fail closed).
91
+ * Accepted: YYYY-MM-DDTHH:MM:SS[.1-9 digits](Z|+hh:mm|-hh:mm), uppercase T and Z, a real calendar date,
92
+ * hour 00-23, minute/second 00-59, offset hours 00-23. Rejected: lowercase t/z, a space separator,
93
+ * no zone, +hhmm without colon, leap second :60, 24:00, Feb 30, expanded years, RFC 2822 dates, etc.
94
+ * Same grammar and arithmetic as tns() in vectors/verify-openssl.sh, so both give identical verdicts.
95
+ */
96
+ export function parseTimestampNs(t) {
97
+ const m = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|([+-])(\d{2}):(\d{2}))$/.exec(typeof t === 'string' ? t : '');
98
+ if (!m) return null;
99
+ const [Y, M, D, h, mi, s] = m.slice(1, 7).map(Number);
100
+ const dim = [31, (Y % 4 === 0 && Y % 100 !== 0) || Y % 400 === 0 ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
101
+ if (M < 1 || M > 12 || D < 1 || D > dim[M - 1] || h > 23 || mi > 59 || s > 59) return null;
102
+ let off = 0;
103
+ if (m[8] !== 'Z') {
104
+ const oh = Number(m[10]), om = Number(m[11]);
105
+ if (oh > 23 || om > 59) return null;
106
+ off = (m[9] === '-' ? -1 : 1) * (oh * 3600 + om * 60);
107
+ }
108
+ // days since 1970-01-01 (proleptic Gregorian, H. Hinnant's days_from_civil); not Date.UTC, which maps years 0-99 to 19xx
109
+ const y = M <= 2 ? Y - 1 : Y, era = Math.floor(y / 400), yoe = y - era * 400;
110
+ const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + Math.floor((153 * (M + (M > 2 ? -3 : 9)) + 2) / 5) + D - 1;
111
+ const sec = BigInt(era * 146097 + doe - 719468) * 86400n + BigInt(h * 3600 + mi * 60 + s - off);
112
+ return sec * 1000000000n + BigInt((m[7] || '').padEnd(9, '0'));
113
+ }
114
+
115
+ // epoch-ms `now` -> ns BigInt, or null if not a finite number / Date (fail closed: null, '', true would coerce to 0/1)
116
+ function nowToNs(now) {
117
+ const ms = now instanceof Date ? now.getTime() : (typeof now === 'number' || typeof now === 'bigint') ? Number(now) : NaN;
118
+ return Number.isFinite(ms) ? BigInt(Math.floor(ms)) * 1000000n : null;
119
+ }
120
+
121
+ /** Latest instant toISOString() still writes as a 4-digit year (later years become +0YYYYY, which RFC 3339 rejects). */
122
+ const MAX_ISO_MS = Date.UTC(9999, 11, 31, 23, 59, 59, 999);
123
+
124
+ /**
125
+ * Validity window check for a credential (VC or presented VP) at `now` (epoch ms, default Date.now()).
126
+ * validFrom/validUntil are optional but, when present, must be strict RFC 3339 (fail closed).
127
+ * @returns {{ok: boolean, reason?: string}}
87
128
  */
129
+ export function checkCredentialValidity(vc, now = Date.now()) {
130
+ const n = nowToNs(now);
131
+ if (n === null) return { ok: false, reason: 'now is not a finite epoch-ms number (fail closed)' };
132
+ const present = (t) => t !== undefined && t !== null && t !== '';
133
+ if (present(vc?.validUntil)) {
134
+ const u = parseTimestampNs(vc.validUntil);
135
+ if (u === null) return { ok: false, reason: `credential validUntil ${JSON.stringify(vc.validUntil)} is not a strict RFC 3339 timestamp (fail closed)` };
136
+ if (u <= n) return { ok: false, reason: `credential expired at ${vc.validUntil}` };
137
+ }
138
+ if (present(vc?.validFrom)) {
139
+ const f = parseTimestampNs(vc.validFrom);
140
+ if (f === null) return { ok: false, reason: `credential validFrom ${JSON.stringify(vc.validFrom)} is not a strict RFC 3339 timestamp (fail closed)` };
141
+ if (f > n) return { ok: false, reason: `credential not valid until ${vc.validFrom}` };
142
+ }
143
+ return { ok: true };
144
+ }
145
+
88
146
  /**
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.
147
+ * How much later than its challenge a response may expire. Stock @mdip/keymaster (2.2.0) gives a challenge
148
+ * validUntil = createdAt + 1 h and a response validUntil = respondedAt + 1 h by default, so an uncapped
149
+ * stock response normally expires a few seconds to (at most) 1 h after the challenge it answers. keymaster adds
150
+ * that hour with local-time setHours(+1), which is 2 real hours across a DST fall-back, so the bound is 2 h.
151
+ * Page wallets, Snaps and other stock-keymaster responders therefore interoperate; this kit's own respond
152
+ * still caps at exactly the challenge's validUntil.
153
+ */
154
+ export const RESPONSE_EXPIRY_SKEW_MS = 2 * 60 * 60 * 1000;
155
+ const RESPONSE_EXPIRY_SKEW_NS = BigInt(RESPONSE_EXPIRY_SKEW_MS) * 1000000n;
156
+
157
+ /**
158
+ * Expiry rule for challenge responses (intended semantics, fixtures in vectors/expiry-cases.txt):
159
+ * - with `now` (epoch ms number or Date), the challenge AND the response must both still be valid at `now`
160
+ * (validUntil strictly in the future); this is what decides whether a response is accepted in time.
161
+ * Any other `now` (null, '', a string, NaN) fails closed;
162
+ * - a response may expire after its challenge by at most RESPONSE_EXPIRY_SKEW_MS (2 h):
163
+ * response.validUntil <= challenge.validUntil + 2 h. This accepts stock keymaster responses (validUntil
164
+ * ~ a few seconds to 1 h after the challenge's) and rejects far-future ones (e.g. 2099, next year);
165
+ * - if the challenge has a validUntil the response must have one too.
166
+ * Responders should still cap at the challenge's validUntil (this kit's respond does). Timestamps must pass
167
+ * parseTimestampNs (strict RFC 3339, compared exactly to the nanosecond; anything else is rejected).
93
168
  * @returns {{ok: boolean, reason?: string}}
94
169
  */
95
170
  export function checkResponseExpiry(challengeValidUntil, responseValidUntil, now) {
96
- const c = challengeValidUntil ? Date.parse(challengeValidUntil) : NaN;
97
- const r = responseValidUntil ? Date.parse(responseValidUntil) : NaN;
98
- if (challengeValidUntil && !Number.isFinite(c)) return { ok: false, reason: 'challenge validUntil unparseable' };
99
- if (responseValidUntil && !Number.isFinite(r)) return { ok: false, reason: 'response validUntil unparseable' };
100
- if (Number.isFinite(c) && !Number.isFinite(r)) return { ok: false, reason: 'response has no validUntil but challenge does' };
101
- if (Number.isFinite(c) && r > c) return { ok: false, reason: `response validUntil ${responseValidUntil} is later than challenge validUntil ${challengeValidUntil}` };
171
+ const present = (t) => t !== undefined && t !== null && t !== '';
172
+ const c = present(challengeValidUntil) ? parseTimestampNs(challengeValidUntil) : undefined;
173
+ const r = present(responseValidUntil) ? parseTimestampNs(responseValidUntil) : undefined;
174
+ if (c === null) return { ok: false, reason: `challenge validUntil ${JSON.stringify(challengeValidUntil)} is not a strict RFC 3339 timestamp with Z or +hh:mm (fail closed)` };
175
+ if (r === null) return { ok: false, reason: `response validUntil ${JSON.stringify(responseValidUntil)} is not a strict RFC 3339 timestamp with Z or +hh:mm (fail closed)` };
176
+ if (c !== undefined && r === undefined) return { ok: false, reason: 'response has no validUntil but challenge does' };
177
+ if (c !== undefined && r > c + RESPONSE_EXPIRY_SKEW_NS) return { ok: false, reason: `response validUntil ${responseValidUntil} is more than 2 h later than challenge validUntil ${challengeValidUntil}` };
102
178
  if (now !== undefined) {
103
- if (Number.isFinite(c) && c <= now) return { ok: false, reason: `challenge expired at ${challengeValidUntil}` };
104
- if (Number.isFinite(r) && r <= now) return { ok: false, reason: `response expired at ${responseValidUntil}` };
179
+ const n = nowToNs(now);
180
+ if (n === null) return { ok: false, reason: 'now is not a finite epoch-ms number or Date (fail closed)' };
181
+ if (c !== undefined && c <= n) return { ok: false, reason: `challenge expired at ${challengeValidUntil}` };
182
+ if (r !== undefined && r <= n) return { ok: false, reason: `response expired at ${responseValidUntil}` };
105
183
  }
106
184
  return { ok: true };
107
185
  }
108
186
 
187
+ /**
188
+ * Open (or create, with create:true) this agent's identity.
189
+ * Returns an Agent with helpers for signing, challenges, credentials and backups.
190
+ */
109
191
  export async function openAgent(opts = {}) {
110
192
  const cfg = loadConfig(opts);
111
193
  ensurePrivateDir(cfg.home);
@@ -118,12 +200,17 @@ export async function openAgent(opts = {}) {
118
200
  writeSecret(cfg.paths.passphrase, crypto.randomBytes(32).toString('base64url'));
119
201
  }
120
202
  const passphrase = fs.readFileSync(cfg.paths.passphrase, 'utf8').trim();
121
- const keymaster = await createKeymaster({ gatekeeperUrl: cfg.gatekeeperUrl, walletDir: cfg.home, passphrase, registry: cfg.registry, didPrefix: cfg.didPrefix });
203
+ const keymaster = await createKeymaster({ gatekeeperUrl: cfg.gatekeeperUrl, walletDir: cfg.home, passphrase, registry: cfg.registry, didPrefix: cfg.didPrefix, ...(opts.waitSeconds !== undefined ? { waitSeconds: opts.waitSeconds } : {}) });
122
204
 
123
205
  if (!exists) {
124
206
  await keymaster.newWallet(opts.mnemonic || undefined, false);
125
207
  fs.chmodSync(cfg.paths.wallet, 0o600);
126
208
  }
209
+ // Save the recovery phrase before any network step, so a gatekeeper error or timeout below
210
+ // can never leave a wallet whose phrase was not written down.
211
+ if (!fs.existsSync(cfg.paths.recoveryPhrase)) {
212
+ writeSecret(cfg.paths.recoveryPhrase, (await keymaster.decryptMnemonic()).trim() + '\n');
213
+ }
127
214
  let ids = await keymaster.listIds();
128
215
  if (!ids.includes(cfg.name)) {
129
216
  if (!opts.create) throw new Error(`Identity "${cfg.name}" not in wallet (have: ${ids.join(', ') || 'none'})`);
@@ -135,9 +222,6 @@ export async function openAgent(opts = {}) {
135
222
  await waitForDid(keymaster, (await keymaster.fetchIdInfo(cfg.name)).did);
136
223
  await keymaster.setCurrentId(cfg.name);
137
224
  const did = (await keymaster.fetchIdInfo(cfg.name)).did;
138
- if (!fs.existsSync(cfg.paths.recoveryPhrase)) {
139
- writeSecret(cfg.paths.recoveryPhrase, (await keymaster.decryptMnemonic()).trim() + '\n');
140
- }
141
225
  writeState(cfg, { name: cfg.name, did, gatekeeperUrl: cfg.gatekeeperUrl, registry: cfg.registry });
142
226
  return new Agent(cfg, keymaster, did);
143
227
  }
@@ -157,50 +241,110 @@ export class Agent {
157
241
  // ---- signing -------------------------------------------------------------------------
158
242
  /** Sign any JSON object with this agent's DID key (adds a `signature` block). */
159
243
  sign(obj) { return this.keymaster.addSignature(obj); }
160
- /** Verify a signed JSON object; resolves the signer DID on the network. */
244
+ /**
245
+ * Verify a signed JSON object; resolves the signer DID on the network. Returns a boolean only:
246
+ * `true` means SOME DID signed it, namely `signed.signature.signer`. Check that it is the DID you expect.
247
+ */
161
248
  verify(signed) { return this.keymaster.verifySignature(signed); }
162
249
 
163
250
  // ---- challenges ("every interaction is an invite") ------------------------------------
164
251
  /**
165
252
  * Create a challenge DID another agent/human must answer. Optionally require credentials:
166
253
  * createChallenge({ credentials: [{ schema: SCHEMA_DID, issuers: [ISSUER_DID] }], callback })
254
+ * options.validUntil (default: 1 hour from now) must be a strict RFC 3339 timestamp in the future;
255
+ * anything else is rejected here, because no response to it could ever pass verifyResponse.
167
256
  */
168
- createChallenge(challenge = {}, options = {}) { return this.keymaster.createChallenge(challenge, options); }
169
- /** Answer someone else's challenge DID; returns a response DID to send back. */
257
+ createChallenge(challenge = {}, options = {}) {
258
+ if (options.validUntil !== undefined) {
259
+ const ns = parseTimestampNs(options.validUntil);
260
+ if (ns === null) throw new Error(`validUntil ${JSON.stringify(options.validUntil)} is not a strict RFC 3339 timestamp (e.g. 2026-01-01T00:00:00Z)`);
261
+ if (ns <= BigInt(Date.now()) * 1000000n) throw new Error(`validUntil ${options.validUntil} is not in the future`);
262
+ }
263
+ return this.keymaster.createChallenge(challenge, { ...options });
264
+ }
170
265
  /**
171
266
  * Answer someone else's challenge DID; returns a response DID to send back.
172
267
  * The response stays resolvable for `validDays` (default 7; keymaster's own default is 1 hour),
173
- * capped at the challenge's own validUntil if it has one. Pass `validUntil` to set it exactly.
268
+ * capped at the challenge's own validUntil if it has one. Pass `validUntil` to set it exactly; it must
269
+ * be strict RFC 3339, in the future and not later than the challenge's validUntil (else this throws,
270
+ * since the verifier would reject the response anyway).
271
+ * Note: the response is created even if you hold none of the requested credentials (the verifier then
272
+ * gets match:false); check findCredentials() first if that matters.
174
273
  */
175
274
  async respondToChallenge(challengeDid, options = {}) {
176
275
  const { validDays = DEFAULT_RESPONSE_VALID_DAYS, ...rest } = options;
177
- if (!rest.validUntil) rest.validUntil = await this.responseValidUntil(challengeDid, validDays);
276
+ rest.validUntil = rest.validUntil
277
+ ? await this.#checkResponseValidUntil(challengeDid, rest.validUntil)
278
+ : await this.responseValidUntil(challengeDid, validDays);
178
279
  return this.keymaster.createResponse(challengeDid, rest);
179
280
  }
180
- /** Compute a response expiry: now + validDays, capped at the challenge's validUntil. */
281
+ /** The challenge's validUntil as exact ns (BigInt), or undefined if it has none. Throws if unparseable or past. */
282
+ async #challengeValidUntilNs(challengeDid) {
283
+ const doc = await this.keymaster.resolveDID(challengeDid);
284
+ const vu = doc?.mdip?.validUntil;
285
+ if (vu === undefined || vu === null || vu === '') return undefined;
286
+ const ns = parseTimestampNs(vu);
287
+ if (ns === null) throw new Error(`challenge validUntil ${JSON.stringify(vu)} is not a strict RFC 3339 timestamp; a response could never verify`);
288
+ if (ns <= BigInt(Date.now()) * 1000000n) throw new Error(`challenge expired at ${vu}`);
289
+ return ns;
290
+ }
291
+ async #checkResponseValidUntil(challengeDid, validUntil) {
292
+ const ns = parseTimestampNs(validUntil);
293
+ if (ns === null) throw new Error(`validUntil ${JSON.stringify(validUntil)} is not a strict RFC 3339 timestamp (e.g. 2026-01-01T00:00:00Z)`);
294
+ if (ns <= BigInt(Date.now()) * 1000000n) throw new Error(`validUntil ${validUntil} is not in the future`);
295
+ const cap = await this.#challengeValidUntilNs(challengeDid);
296
+ if (cap !== undefined && ns > cap) throw new Error(`validUntil ${validUntil} is later than the challenge's validUntil; the verifier would reject it`);
297
+ return validUntil;
298
+ }
299
+ /** Compute a response expiry: now + validDays, capped at the challenge's validUntil (and at year 9999). */
181
300
  async responseValidUntil(challengeDid, validDays = DEFAULT_RESPONSE_VALID_DAYS) {
182
301
  const days = Number(validDays);
183
- if (!Number.isFinite(days) || days <= 0) throw new Error('validDays must be a positive number');
184
- let until = Date.now() + days * 24 * 60 * 60 * 1000;
185
- const doc = await this.keymaster.resolveDID(challengeDid);
186
- const cap = doc?.mdip?.validUntil ? Date.parse(doc.mdip.validUntil) : NaN;
187
- if (Number.isFinite(cap)) {
188
- if (cap <= Date.now()) throw new Error(`challenge expired at ${doc.mdip.validUntil}`);
189
- until = Math.min(until, cap);
190
- }
302
+ if (typeof validDays === 'boolean' || !Number.isFinite(days) || days <= 0) throw new Error('validDays must be a positive number');
303
+ let until = Math.min(Date.now() + days * 24 * 60 * 60 * 1000, MAX_ISO_MS);
304
+ const cap = await this.#challengeValidUntilNs(challengeDid);
305
+ if (cap !== undefined) until = Math.min(until, Number(cap / 1000000n)); // floor to ms: never later than the challenge
191
306
  return new Date(until).toISOString();
192
307
  }
193
308
  /**
194
- * Verify a response DID to a challenge you created. Result has .match, .responder, .vps...
195
- * Since 0.1.3 also enforces strict expiry (see checkResponseExpiry): a response that outlives its
196
- * challenge, or either one already expired, gives match:false with .expiry.reason set.
309
+ * Verify a response DID to a challenge you created. Result has .match, .responder, .challenge, .vps,
310
+ * plus .checks (why match is false). match is true only if ALL of these hold:
311
+ * - keymaster's own checks (decrypts to us, every requested credential presented, signatures, hashes);
312
+ * - the challenge was created by this agent (its controller is our DID);
313
+ * - options.challenge, if given, equals the response's challenge. Pass it: without it a response to
314
+ * ANY earlier challenge of yours (with the same requirements) is accepted, i.e. replayable;
315
+ * - the response was encrypted by its own controller, the reported responder (otherwise anyone could copy
316
+ * a public response into an asset they control and claim it, e.g. front-running the real responder);
317
+ * - expiry (checkResponseExpiry): challenge and response both still valid now; the response expires at
318
+ * most 2 h after the challenge (stock keymaster responses expire up to ~1 h after it; far-future rejected);
319
+ * - every presented credential's subject is the responder (otherwise anyone who has seen a credential,
320
+ * e.g. a Public Profile published with reveal:true, could present it as their own);
321
+ * - every presented credential is inside its validFrom/validUntil window (checkCredentialValidity).
322
+ * Challenge receipts are published (keymaster's default, publish:true) only after all checks pass.
197
323
  */
198
324
  async verifyResponse(responseDid, options = {}) {
199
- const result = await this.keymaster.verifyResponse(responseDid, options);
325
+ const { challenge: expectedChallenge, publish = true, ...rest } = options;
326
+ const result = await this.keymaster.verifyResponse(responseDid, { ...rest, publish: false });
327
+ const now = Date.now();
200
328
  const [respDoc, chDoc] = await Promise.all([this.keymaster.resolveDID(responseDid), this.keymaster.resolveDID(result.challenge)]);
201
- const expiry = checkResponseExpiry(chDoc?.mdip?.validUntil, respDoc?.mdip?.validUntil, Date.now());
329
+ const checks = [];
330
+ if (!result.match) checks.push('not every requested credential was validly presented');
331
+ if (chDoc?.didDocument?.controller !== this.did) checks.push(`challenge ${result.challenge} was not created by this agent`);
332
+ if (expectedChallenge !== undefined && result.challenge !== expectedChallenge) checks.push(`response answers challenge ${result.challenge}, not the expected ${expectedChallenge}`);
333
+ // keymaster decrypts with encrypted.sender's key but reports the asset's controller as responder, so anyone
334
+ // can copy a public response into an asset they control and "answer" a challenge they never decrypted
335
+ const sender = respDoc?.didDocumentData?.encrypted?.sender;
336
+ if (sender !== result.responder) checks.push(`response was encrypted by ${sender}, not by its controller ${result.responder} (a copied response)`);
337
+ const expiry = checkResponseExpiry(chDoc?.mdip?.validUntil, respDoc?.mdip?.validUntil, now);
338
+ if (!expiry.ok) checks.push(expiry.reason);
339
+ for (const vp of result.vps || []) {
340
+ if (vp?.credentialSubject?.id !== result.responder) checks.push(`presented credential is about ${vp?.credentialSubject?.id}, not the responder ${result.responder}`);
341
+ const v = checkCredentialValidity(vp, now);
342
+ if (!v.ok) checks.push(v.reason);
343
+ }
202
344
  result.expiry = expiry;
203
- if (!expiry.ok) result.match = false;
345
+ result.checks = checks;
346
+ result.match = checks.length === 0;
347
+ if (result.match && publish) await this.keymaster.publishChallengeReceipts(responseDid, { verification: result });
204
348
  return result;
205
349
  }
206
350
 
@@ -215,26 +359,40 @@ export class Agent {
215
359
  /**
216
360
  * Find held credentials (decrypted) by schema and/or issuer - e.g. check that a human's
217
361
  * DID authorized this agent to purchase: findCredentials({ schema: PURCHASE_SCHEMA, issuer: HUMAN_DID }).
218
- * Also filters out credentials whose validUntil has passed.
362
+ * Only returns credentials that are about this agent, signed by their stated issuer, not revoked, and
363
+ * inside their validFrom/validUntil window (a timestamp that is not strict RFC 3339 drops it: fail closed).
219
364
  */
220
365
  async findCredentials({ schema, issuer } = {}) {
221
366
  const found = [];
367
+ const now = Date.now();
222
368
  for (const did of await this.listCredentials()) {
223
369
  const vc = await this.getCredential(did).catch(() => null);
224
- if (!vc) continue;
370
+ if (!vc) continue; // revoked, unresolvable or not a credential
225
371
  if (schema && !vc.type?.includes(schema)) continue;
226
372
  if (issuer && vc.issuer !== issuer) continue;
227
- if (vc.validUntil && Date.parse(vc.validUntil) < Date.now()) continue;
228
- if (!(await this.keymaster.verifySignature(vc).catch(() => false))) continue;
373
+ if (vc.credentialSubject?.id !== this.did) continue;
374
+ // fail closed: an unparseable validUntil/validFrom drops the credential instead of keeping it
375
+ if (!checkCredentialValidity(vc, now).ok) continue;
376
+ // signer must BE the issuer (plain verifySignature accepts any signer)
377
+ if (!(await this.keymaster.verifyCredentialSignature(vc).catch(() => false))) continue;
229
378
  found.push({ did, ...vc });
230
379
  }
231
380
  return found;
232
381
  }
233
382
 
234
- /** Issue a credential from this agent to `subjectDid` using a schema DID. Returns credential DID. */
383
+ /**
384
+ * Issue a credential from this agent to `subjectDid` using a schema DID. Returns credential DID.
385
+ * options.validFrom / options.validUntil set the credential's own validity window; they do NOT make the
386
+ * credential DID itself ephemeral (so a holder still sees "expired", not "not found"). Other options
387
+ * (e.g. registry) go to the credential DID.
388
+ */
235
389
  async issueCredential(schemaDid, subjectDid, credential, options = {}) {
236
- const bound = await this.keymaster.bindCredential(schemaDid, subjectDid, { credential, ...options });
237
- return this.keymaster.issueCredential(bound, { registry: this.config.registry, ...options });
390
+ const { validFrom, validUntil, ...didOptions } = options;
391
+ for (const [k, t] of [['validFrom', validFrom], ['validUntil', validUntil]]) {
392
+ if (t !== undefined && parseTimestampNs(t) === null) throw new Error(`${k} ${JSON.stringify(t)} is not a strict RFC 3339 timestamp (e.g. 2026-01-01T00:00:00Z)`);
393
+ }
394
+ const bound = await this.keymaster.bindCredential(schemaDid, subjectDid, { credential, validFrom, validUntil });
395
+ return this.keymaster.issueCredential(bound, { registry: this.config.registry, ...didOptions });
238
396
  }
239
397
 
240
398
  /**
@@ -322,9 +480,11 @@ export class Agent {
322
480
 
323
481
  /** Check whether this DID (or another) is visible on SELF's public explorer. */
324
482
  async explorerStatus(did = this.did) {
325
- const res = await fetch(SELF_EXPLORER_API + did);
483
+ const res = await fetch(SELF_EXPLORER_API + encodeURIComponent(did), { signal: AbortSignal.timeout(15000) });
484
+ if (res.status === 404) return { visible: false };
485
+ if (!res.ok) throw new Error(`explorer returned HTTP ${res.status}`);
326
486
  const body = await res.json().catch(() => null);
327
- if (!body || typeof body === 'string') return { visible: false };
487
+ if (!body || typeof body !== 'object' || body.didDocument?.id !== did) return { visible: false };
328
488
  return { visible: true, version: body.didDocumentMetadata?.version, confirmed: body.didDocumentMetadata?.confirmed, manifest: Object.keys(body.didDocumentData?.manifest || {}) };
329
489
  }
330
490
  }
@@ -0,0 +1,130 @@
1
+ // Live-gatekeeper security tests for the JS API (reviewer D, 0.1.5). Each case is an attack or misuse
2
+ // that keymaster 2.2.0 alone accepts; the kit must reject it. Prints "API SECURITY OK" on success.
3
+ // Usage (from e2e.sh): MDIP_GATEKEEPER_URL=... node test/api-security.mjs
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { openAgent, waitForDid, checkResponseExpiry, checkCredentialValidity, createKeymaster, SELF_PUBLIC_PROFILE_SCHEMA as S } from '../src/index.js';
8
+
9
+ let failed = 0;
10
+ const ok = (cond, label) => { console.log(`${cond ? 'ok ' : 'FAIL'} ${label}`); if (!cond) failed++; };
11
+ const throws = async (fn, re, label) => { try { await fn(); ok(false, `${label} (did not throw)`); } catch (e) { ok(re.test(e.message), `${label}: ${e.message}`); } };
12
+
13
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'mdip-api-sec-'));
14
+ const mk = (n) => openAgent({ home: path.join(root, n), name: `mdip-kit-test-${n}`, create: true });
15
+ try {
16
+ const V = await mk('verifier'), R = await mk('responder'), Z = await mk('impostor');
17
+ const owned = async () => (await V.keymaster.fetchIdInfo()).owned?.length ?? 0;
18
+
19
+ // 1. replay across challenges: a response to challenge A must not verify as an answer to B
20
+ const A = await V.createChallenge({}), B = await V.createChallenge({});
21
+ const rA = await R.respondToChallenge(A); await waitForDid(V.keymaster, rA);
22
+ ok((await V.verifyResponse(rA, { challenge: A })).match === true, 'response verifies against its own challenge');
23
+ const rp = await V.verifyResponse(rA, { challenge: B });
24
+ ok(rp.match === false && rp.checks.some(c => /not the expected/.test(c)), 'response to A rejected when B expected (replay)');
25
+
26
+ // 2. expiry. (a) a forged far-future response (challenge + 1 day): match false AND no receipt published
27
+ const prof = await R.selfAttestPublicProfile('mdip-kit-test responder (throwaway)');
28
+ const C = await V.createChallenge({ credentials: [{ schema: S, issuers: [R.did] }] });
29
+ const cVU = (await V.resolve(C)).mdip.validUntil;
30
+ const late = await R.keymaster.createResponse(C, { validUntil: new Date(Date.parse(cVU) + 86400e3).toISOString() });
31
+ await waitForDid(V.keymaster, late);
32
+ const before = await owned();
33
+ const lr = await V.verifyResponse(late, { challenge: C });
34
+ ok(lr.match === false && lr.checks.some(c => /more than 2 h later/.test(c)) && (await owned()) === before, 'far-future response (challenge + 1 day): match false and no receipt published');
35
+ // (b) stock keymaster interop: createResponse with NO validUntil gives now + 1 h, i.e. a few seconds AFTER
36
+ // the challenge's created + 1 h. Both still valid now, so it must match (page wallets / Snaps / Homies)
37
+ await new Promise(r => setTimeout(r, 1500)); // like a real responder: answer a moment after the challenge
38
+ const stock = await R.keymaster.createResponse(C); await waitForDid(V.keymaster, stock);
39
+ const sVU = (await V.resolve(stock)).mdip.validUntil;
40
+ ok(Date.parse(sVU) > Date.parse(cVU), `stock keymaster response expires after its challenge (${sVU} > ${cVU})`);
41
+ const sv = await V.verifyResponse(stock, { challenge: C, publish: false });
42
+ ok(sv.match === true && sv.expiry.ok === true, `stock keymaster response (uncapped, +${(Date.parse(sVU) - Date.parse(cVU)) / 1000} s) accepted while both unexpired`);
43
+ const good = await R.respondToChallenge(C); await waitForDid(V.keymaster, good);
44
+ ok((await V.resolve(good)).mdip.validUntil === cVU, 'kit respond still caps at exactly the challenge validUntil');
45
+ const b2 = await owned();
46
+ ok((await V.verifyResponse(good, { challenge: C })).match === true && (await owned()) === b2 + 1, 'valid response: match true and exactly one receipt published');
47
+ // (c) true expiry: a stock response to a short challenge must NOT match once the challenge has expired,
48
+ // even though the response itself (now + 1 h) has not
49
+ const SC = await V.createChallenge({}, { validUntil: new Date(Date.now() + 6000).toISOString() });
50
+ const sr = await R.keymaster.createResponse(SC); await waitForDid(V.keymaster, sr);
51
+ ok((await V.verifyResponse(sr, { challenge: SC, publish: false })).match === true, 'stock response to a short challenge matches before the challenge expires');
52
+ await new Promise(r => setTimeout(r, 7000));
53
+ const b2c = await owned();
54
+ let srv; try { srv = await V.verifyResponse(sr, { challenge: SC }); } catch (e) { srv = { match: false, threw: e.message }; }
55
+ ok(srv.match === false && (srv.threw !== undefined || srv.checks.some(c => /challenge expired/.test(c))) && (await owned()) === b2c, `expired challenge rejected though the stock response is unexpired (${srv.threw ?? srv.checks.join('; ')})`);
56
+
57
+ // 3. impersonation: Z presents R's publicly revealed Public Profile as its own
58
+ const vcObj = (await Z.resolve(R.did)).didDocumentData.manifest[prof.credentialDid];
59
+ const vu = new Date(Date.parse(cVU) - 1000).toISOString();
60
+ const vp = await Z.keymaster.encryptMessage(JSON.stringify(vcObj), V.did, { includeHash: true, validUntil: vu });
61
+ const forged = await Z.keymaster.encryptJSON({ response: { challenge: C, credentials: [{ vc: prof.credentialDid, vp }], requested: 1, fulfilled: 1, match: true, responseNonce: 'x' } }, V.did, { validUntil: vu });
62
+ await waitForDid(V.keymaster, forged);
63
+ const fr = await V.verifyResponse(forged, { challenge: C, publish: false });
64
+ ok(fr.match === false && fr.checks.some(c => /not the responder/.test(c)), "impostor presenting someone else's credential rejected");
65
+
66
+ // 4. expired credential presented: keymaster matches it, kit must not
67
+ const shortVc = await V.issueCredential(S, R.did, { publicName: 'short-lived' }, { validUntil: new Date(Date.now() + 3000).toISOString() });
68
+ await waitForDid(R.keymaster, shortVc);
69
+ ok(await R.acceptCredential(shortVc), 'short-lived credential accepted');
70
+ ok(!(await R.resolve(shortVc)).mdip.validUntil, 'credential validUntil does not make the credential DID itself ephemeral');
71
+ await new Promise(r => setTimeout(r, 4000));
72
+ ok((await R.findCredentials({ schema: S, issuer: V.did })).length === 0, 'findCredentials drops the expired credential');
73
+ const E = await V.createChallenge({ credentials: [{ schema: S, issuers: [V.did] }] });
74
+ const er = await R.respondToChallenge(E); await waitForDid(V.keymaster, er);
75
+ const ev = await V.verifyResponse(er, { challenge: E, publish: false });
76
+ ok(ev.match === false && ev.checks.some(c => /credential expired/.test(c)), 'presenting an expired credential rejected');
77
+
78
+ // 5. challenge not created by this agent (Z's challenge, response hand-encrypted to V)
79
+ const ZC = await Z.createChallenge({});
80
+ const zr = await R.keymaster.encryptJSON({ response: { challenge: ZC, credentials: [], requested: 0, fulfilled: 0, match: true, responseNonce: 'y' } }, V.did, { validUntil: (await Z.resolve(ZC)).mdip.validUntil });
81
+ await waitForDid(V.keymaster, zr);
82
+ const zv = await V.verifyResponse(zr, { publish: false });
83
+ ok(zv.match === false && zv.checks.some(c => /not created by this agent/.test(c)), "response to someone else's challenge rejected");
84
+
85
+ // 6. API misuse fails loudly instead of creating unverifiable DIDs
86
+ await throws(() => V.createChallenge({}, { validUntil: 'Tue, 27 Oct 2026 10:00:00 GMT' }), /strict RFC 3339/, 'createChallenge rejects non-RFC 3339 validUntil');
87
+ await throws(() => V.createChallenge({}, { validUntil: '2000-01-01T00:00:00Z' }), /not in the future/, 'createChallenge rejects past validUntil');
88
+ await throws(() => R.respondToChallenge(A, { validUntil: '2099-01-01T00:00:00Z' }), /later than the challenge/, 'respondToChallenge rejects validUntil past the challenge');
89
+ await throws(() => R.respondToChallenge(A, { validUntil: '2099-01-01 00:00:00' }), /strict RFC 3339/, 'respondToChallenge rejects non-RFC 3339 validUntil');
90
+ await throws(() => R.respondToChallenge(A, { validDays: true }), /positive number/, 'validDays:true rejected');
91
+ await throws(() => V.issueCredential(S, R.did, { publicName: 'x' }, { validUntil: 'tomorrow' }), /strict RFC 3339/, 'issueCredential rejects non-RFC 3339 validUntil');
92
+ const noCap = await V.createChallenge({}, { validUntil: '9999-12-31T23:59:59.999Z' });
93
+ ok(/^9999-12-31T23:59:59\.999Z$/.test(await R.responseValidUntil(noCap, 1e9)), 'huge validDays clamps to year 9999 (stays RFC 3339)');
94
+
95
+ // 7. pure-function fail-closed edges
96
+ for (const bad of [null, '', true, '1', NaN, Infinity]) ok(!checkResponseExpiry('2099-01-01T00:00:00Z', '2099-01-01T00:00:00Z', bad).ok, `checkResponseExpiry now=${String(bad) || "''"} fails closed`);
97
+ ok(checkResponseExpiry('2099-01-01T00:00:00Z', '2099-01-01T00:00:00Z', new Date()).ok, 'checkResponseExpiry accepts now as Date');
98
+ { // stock keymaster skew vs true expiry, pure function with a fixed now
99
+ const c = '2026-10-26T16:41:19.930Z', t = Date.parse(c);
100
+ ok(checkResponseExpiry(c, '2026-10-26T16:41:24.112Z', t - 60e3).ok, 'skew: response 4.2 s after challenge, both unexpired -> ok');
101
+ ok(checkResponseExpiry(c, '2026-10-26T17:41:19.930Z', t - 60e3).ok, 'skew: response 1 h after challenge (keymaster default), both unexpired -> ok');
102
+ ok(!checkResponseExpiry(c, '2026-10-26T16:41:24.112Z', t).ok, 'skew: challenge expired exactly now -> rejected');
103
+ ok(!checkResponseExpiry(c, '2026-10-26T17:41:19.930Z', t + 1800e3).ok, 'skew: challenge expired 30 min ago, response still valid -> rejected');
104
+ ok(!checkResponseExpiry(c, '2026-10-26T16:41:19.929Z', t - 1).ok, 'response expired before now -> rejected');
105
+ ok(!checkResponseExpiry(c, '2026-10-26T18:41:19.931Z', t - 60e3).ok && !checkResponseExpiry(c, '2099-01-01T00:00:00Z', t - 60e3).ok, 'far future (2 h + 1 ms, 2099) -> rejected');
106
+ ok(!checkResponseExpiry(c, undefined, t - 60e3).ok, 'missing response validUntil when challenge has one -> rejected');
107
+ }
108
+ ok(!checkCredentialValidity({ validFrom: '2999-01-01T00:00:00Z' }).ok && !checkCredentialValidity({ validUntil: '2000-01-01T00:00:00Z' }).ok && !checkCredentialValidity({ validUntil: '2099-01-01' }).ok && checkCredentialValidity({}).ok, 'checkCredentialValidity window + strictness');
109
+
110
+ // 9. copied response (reviewer A): Z republishes R's public response asset under Z's own control. keymaster
111
+ // decrypts it with R's key (encrypted.sender) yet reports Z as responder: Z "answers" a challenge it never saw
112
+ const cc = await V.createChallenge({});
113
+ const cr = await R.respondToChallenge(cc); await waitForDid(Z.keymaster, cr);
114
+ const crDoc = await Z.resolve(cr);
115
+ const copy = await Z.keymaster.createAsset(crDoc.didDocumentData, { validUntil: crDoc.mdip.validUntil });
116
+ await waitForDid(V.keymaster, copy);
117
+ const b9 = await owned();
118
+ const cv = await V.verifyResponse(copy, { challenge: cc });
119
+ ok(cv.match === false && cv.responder === Z.did && cv.checks.some(c => /copied response/.test(c)) && (await owned()) === b9, 'copied response (controller != encrypting sender) rejected, no receipt published');
120
+ ok((await V.verifyResponse(cr, { challenge: cc, publish: false })).match === true, 'the original response still verifies');
121
+
122
+ // 8. a down gatekeeper fails fast instead of hanging forever
123
+ const t0 = Date.now();
124
+ await throws(() => createKeymaster({ gatekeeperUrl: 'http://127.0.0.1:9', walletDir: path.join(root, 'down'), passphrase: 'x', waitSeconds: 3 }), /not ready after 3s/, 'unreachable gatekeeper throws');
125
+ ok(Date.now() - t0 < 20000, 'unreachable gatekeeper fails within bounded time');
126
+ } finally {
127
+ fs.rmSync(root, { recursive: true, force: true });
128
+ }
129
+ if (failed) { console.log(`API SECURITY FAILED (${failed})`); process.exit(1); }
130
+ console.log('API SECURITY OK'); process.exit(0);
package/test/e2e.sh ADDED
@@ -0,0 +1,68 @@
1
+ #!/usr/bin/env bash
2
+ # End-to-end test against a gatekeeper. Creates ONE throwaway identity (public, clearly named) in a
3
+ # temp MDIP_HOME unless MDIP_HOME is set (a temp home is deleted afterwards; set KEEP_HOME=1 to keep it).
4
+ # Usage: MDIP_GATEKEEPER_URL=http://127.0.0.1:4224 npm test (bash 3.2+, node 22+, OpenSSL 3)
5
+ # NOTE: publishes that throwaway DID (plus its profile credential, backup and test challenges/responses)
6
+ # to the configured registry. Run it against your own node.
7
+ set -euo pipefail
8
+ cd "$(dirname "$0")/.."
9
+ export MDIP_GATEKEEPER_URL="${MDIP_GATEKEEPER_URL:-http://localhost:4224}"
10
+ export MDIP_AGENT_NAME="${MDIP_AGENT_NAME:-mdip-agent-kit-test}"
11
+ tmp=$(mktemp -d "${TMPDIR:-/tmp}/mdip-e2e.XXXXXX")
12
+ cleanup() { if [ -z "${MDIP_HOME_GIVEN:-}" ] && [ -z "${KEEP_HOME:-}" ]; then rm -rf "$tmp"; else rm -f "$tmp/out.log" "$tmp/vec.log"; fi; }
13
+ trap cleanup EXIT
14
+ [ -n "${MDIP_HOME:-}" ] && MDIP_HOME_GIVEN=1
15
+ export MDIP_HOME="${MDIP_HOME:-$tmp/home}"
16
+ LOG=$tmp/out.log; : > "$LOG"
17
+ # every CLI stdout line also goes to $LOG, which is checked for secrets at the end
18
+ A() { node bin/mdip-agent.js "$@" | tee -a "$LOG"; }
19
+ fail() { echo "FAIL $*"; exit 1; }
20
+ # offline known-answer vectors first (stock openssl + @mdip/cipher); show the output only on failure
21
+ { bash vectors/verify-openssl.sh && node vectors/verify-with-kit.js && bash test/vectors-negative.sh; } > "$tmp/vec.log" 2>&1 \
22
+ || { grep -E '^(FAIL|skip)|FAILED' "$tmp/vec.log" || tail -20 "$tmp/vec.log"; fail "vectors (run: npm run test:vectors)"; }
23
+ echo "vectors OK; home=$MDIP_HOME gatekeeper=$MDIP_GATEKEEPER_URL"
24
+ A init --profile-name "$MDIP_AGENT_NAME (throwaway test identity)"
25
+ # secrets 600, their directories 700 (node's stat: same on Linux and macOS)
26
+ mode() { node -e 'console.log((require("fs").statSync(process.argv[1]).mode & 0o777).toString(8))' "$1"; }
27
+ for d in "$MDIP_HOME" "$MDIP_HOME"/secrets "$MDIP_HOME"/backups; do [ "$(mode "$d")" = 700 ] || fail "perms $d ($(mode "$d"), want 700)"; done
28
+ for f in "$MDIP_HOME"/secrets/* "$MDIP_HOME"/wallet.json "$MDIP_HOME"/backups/*; do
29
+ [ -e "$f" ] || fail "missing $f"; [ "$(mode "$f")" = 600 ] || fail "perms $f ($(mode "$f"), want 600)"; done
30
+ echo '{"hello":"world"}' | A sign - > "$tmp/signed.json"
31
+ A verify "$tmp/signed.json" | grep -q '"valid": true' || fail "verify"
32
+ ME=$(node -e 'console.log(JSON.parse(require("fs").readFileSync(process.env.MDIP_HOME+"/state.json","utf8")).did)')
33
+ A verify "$tmp/signed.json" | grep -qF "\"signer\": \"$ME\"" || fail "verify does not report the signer"
34
+ CH=$(A challenge --schema did:mdip:z3v8AuagfG89zr9aGxfxub4wRAd15qJs6u9C5jQPgrqC1YRHF67)
35
+ R=$(A respond "$CH")
36
+ A verify-response "$R" --challenge "$CH" | grep -q '"match": true' || fail "verify-response"
37
+ A verify-response "$R" --challenge "$CH" | grep -q '"ok": true' || fail "verify-response checks" # expiry: kit respond caps at exactly the challenge's validUntil
38
+ # without --challenge the CLI must warn (stderr) that any of our challenges is accepted
39
+ A verify-response "$R" 2>&1 >/dev/null | grep -q 'no --challenge' || fail "verify-response without --challenge did not warn"
40
+ # replay: R answers CH, so it must not verify against a different challenge of ours
41
+ CH2=$(A challenge)
42
+ A verify-response "$R" --challenge "$CH2" >/dev/null 2>&1 && fail "response accepted for the wrong --challenge"
43
+ # expiry negative: a far-future response (raw keymaster, challenge + 1 day) must NOT match
44
+ R3=$(node -e 'import("./src/index.js").then(async m=>{const a=await m.openAgent();const d=await a.keymaster.resolveDID(process.argv[1]);const r=await a.keymaster.createResponse(process.argv[1],{validUntil:new Date(Date.parse(d.mdip.validUntil)+86400e3).toISOString()});await m.waitForDid(a.keymaster,r);console.log(r);process.exit(0)})' "$CH")
45
+ A verify-response "$R3" --challenge "$CH" >/dev/null 2>&1 && fail "far-future response was accepted"
46
+ { A verify-response "$R3" --challenge "$CH" 2>/dev/null || true; } | grep -q 'more than 2 h later than challenge validUntil' || fail "expiry reason missing"
47
+ # interop: a stock keymaster response (default now + 1 h, a few seconds past the challenge) must match
48
+ R4=$(node -e 'import("./src/index.js").then(async m=>{const a=await m.openAgent();const r=await a.keymaster.createResponse(process.argv[1]);await m.waitForDid(a.keymaster,r);console.log(r);process.exit(0)})' "$CH")
49
+ A verify-response "$R4" --challenge "$CH" | grep -q '"match": true' || fail "stock keymaster response (uncapped) rejected"
50
+ # response validity: capped at the challenge's validUntil (challenge default is 1h < 7d default)
51
+ VU() { A resolve "$1" | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>console.log(JSON.parse(s).mdip.validUntil))'; }
52
+ [ "$(VU "$R")" = "$(VU "$CH")" ] || fail "response validUntil not capped: $(VU "$R") vs $(VU "$CH")"
53
+ A respond "$CH" --valid-days 0 >/dev/null 2>&1 && fail "--valid-days 0 accepted"
54
+ A respond "$CH" --valid-days >/dev/null 2>&1 && fail "--valid-days without a value accepted"
55
+ R2=$(A respond "$CH" --valid-days 0.01)
56
+ T2=$(VU "$R2"); node -e 'const d=Date.parse(process.argv[1])-Date.now(); if(d<10*60e3||d>16*60e3){console.log("FAIL --valid-days 0.01 ->",process.argv[1]);process.exit(1)}' "$T2"
57
+ A verify-response "$R2" --challenge "$CH" | grep -q '"match": true' || fail "verify-response --valid-days 0.01"
58
+ # JS API attacks/misuse against the live gatekeeper (replay, impostor, expired VC, receipts, bad timestamps)
59
+ node test/api-security.mjs > "$tmp/api.log" 2>&1 || { grep FAIL "$tmp/api.log" || tail -20 "$tmp/api.log"; fail "api-security"; }
60
+ A verify-backups | grep -q '"pass": true' || fail "verify-backups"
61
+ A whoami > /dev/null
62
+ # secrets never on stdout: neither the recovery phrase nor the wallet passphrase may appear in ANY CLI output above
63
+ PHRASE=$(tr -s ' \n' ' ' < "$MDIP_HOME/secrets/recovery-phrase.txt" | sed 's/^ //; s/ $//')
64
+ PASS=$(tr -d "\n" < "$MDIP_HOME/secrets/passphrase")
65
+ [ -n "$PHRASE" ] && [ -n "$PASS" ] || fail "secrets missing"
66
+ tr -s ' \n' ' ' < "$LOG" | grep -qF "$PHRASE" && fail "recovery phrase leaked to CLI output"
67
+ grep -qF "$PASS" "$LOG" && fail "passphrase leaked to CLI output"
68
+ echo "E2E PASS: $(A whoami | grep '"did"')"