Skip to content

Reference source · 0.1.0-dev.11

adversarial.ts

tests/helpers/adversarial.ts · Download original file

import { encapsulate,createHash,hkdfSync,createCipheriv,randomBytes,sign } from 'node:crypto';
import type { Identity,Credential,PublicIdentity } from '../../src/identity.ts';
import { publicKey } from '../../src/identity.ts';
import { seal } from '../../src/envelope.ts';
import { b64,unb64,jsonBytes,frame } from '../../src/core.ts';
// Test-only corpus producer: valid cryptographic authentication of deliberately invalid headers.
export function signedMalformed(sender:Identity,credential:Credential,recipient:PublicIdentity,now:number,changes:Record<string,any>,duplicate=false){
 const original=seal({status:'ok'},sender,credential,recipient,now,null);const header={...JSON.parse(unb64(original.protected).toString()),...changes};let text=JSON.stringify(header);if(duplicate)text=text.replace('"v":"0.1"','"v":"0.1","v":"0.1"');
 const protectedValue=b64(Buffer.from(text)),{sharedKey,ciphertext:kem}=encapsulate(publicKey(recipient.encryptionKey,'encryption')),nonce=randomBytes(12),aad=frame(Buffer.from('OPRP-ENVELOPE-0.1'),Buffer.from(protectedValue),kem,nonce);
 const key=Buffer.from(hkdfSync('sha512',sharedKey,createHash('sha512').update(aad).digest(),Buffer.from('OPRP-0.1/payload-key'),32));try{const cipher=createCipheriv('aes-256-gcm',key,nonce);cipher.setAAD(aad);const ciphertext=Buffer.concat([cipher.update(jsonBytes({status:'ok'})),cipher.final()]),tag=cipher.getAuthTag();return {...original,protected:protectedValue,kem:b64(kem),nonce:b64(nonce),ciphertext:b64(ciphertext),tag:b64(tag),signature:b64(sign(null,frame(aad,ciphertext,tag),sender.signingPrivate))};}finally{key.fill(0);sharedKey.fill(0);}
}
export const malformedHeaders=(now:number)=>[
 {sender:'urn:oprp:other-sender'}, {messageId:'invalid message id'}, {issuedAt:now+.5,expiresAt:now+120.5},
 {issuedAt:now,expiresAt:now+121}, {issuedAt:now-121,expiresAt:now-1}, {recipient:'urn:oprp:wrong-recipient'},
 {suite:'unsupported-classical-suite'}, {v:'0.2'}, {extra:'unexpected'},
];