Authenticate KDPika Licensing notification bytes with the complete Node.js verifier.
What you will learn
- Install and execute this exact sample.
- Verify raw bytes, event metadata and the pinned environment.
- Identify the boundary between authentication and durable business processing.
Prerequisites
- Node.js 22 or newer; no packages.
- The notification source archive, extracted locally.
- The signature contract and a private Sandbox test secret.
Prepare a request
- Work inside the extracted webhooks directory, which contains contract.json.
- Set KDP_WEBHOOK_SECRET through your private process environment.
- Set KDP_WEBHOOK_ENVIRONMENT to sandbox.
- Use Python 3.11+ to create a fresh private synthetic request.
python3 make-test.py events/test-ping.json private/request-1
Expected output: Created private test request files. Use a new directory for each generated request; existing files are not overwritten. The helper signs a captured synthetic body, not a real payment or license authorization. Keep contract.json in place: it supplies the shared event list, 300-second receiver freshness policy and 1 MiB receiver body cap.
Build and run
node verify.mjs private/request-1/body.json private/request-1/headers.json
Expected result: exit 0 with verified=true, event_id=evt_ffa11b785e0ede73d9e69801, event=test.ping and environment=sandbox. Property order is not significant. This source was executed in the recorded macOS contract suite; native Windows and Linux execution are not claimed.
Complete source
// Notification authenticity, not license validity. Node 22+, no dependencies.
// Run: KDP_WEBHOOK_SECRET=YOUR_WEBHOOK_SECRET KDP_WEBHOOK_ENVIRONMENT=SANDBOX node verify.mjs body.json headers.json
// Expected: verified=true JSON; invalid input prints verified=false and exits 1.
import {createHmac, timingSafeEqual} from 'node:crypto';
import {openSync, readSync, closeSync, readFileSync} from 'node:fs';
import {fileURLToPath} from 'node:url';
const contract=JSON.parse(readFileSync(new URL('./contract.json',import.meta.url),'utf8'));
const decode=bytes=>new TextDecoder('utf-8',{fatal:true}).decode(bytes);
function bounded(path,limit){const fd=openSync(path,'r');try{const out=Buffer.alloc(limit+1);let length=0,read;while(length<out.length&&(read=readSync(fd,out,length,out.length-length,null))>0)length+=read;if(length>limit)throw Error('Oversized input');return out.subarray(0,length);}finally{closeSync(fd);}}
export function verify(body,headers,secret,environment,now){
if(!secret||!contract.environments.includes(environment)||body.length>contract.body_limit)throw Error('Invalid configuration or body size');
const signature=headers?.['x-lmp-signature'];
if(typeof signature!=='string')throw Error('Missing signature');
const match=/^t=([1-9][0-9]{0,10}),v1=([0-9a-f]{64})$/.exec(signature);
if(!match||match[0]!==signature||Math.abs(now-Number(match[1]))>contract.tolerance_seconds)throw Error('Invalid or stale signature');
const expected=createHmac('sha256',secret).update(match[1]+'.','ascii').update(body).digest();
if(!timingSafeEqual(expected,Buffer.from(match[2],'hex')))throw Error('Signature mismatch');
const event=JSON.parse(decode(body));
if(!event||typeof event!=='object'||Array.isArray(event)||typeof event.id!=='string'||!/^evt_[A-Za-z0-9_-]{1,100}$(?![\s\S])/.test(event.id))throw Error('Invalid event');
if(!contract.events.includes(event.event)||event.environment!==environment||event.id!==headers['x-lmp-event-id']||event.event!==headers['x-lmp-event'])throw Error('Event metadata mismatch');
if(!event.data||typeof event.data!=='object'||Array.isArray(event.data)||typeof event.created_at!=='string'||event.created_at.length===0)throw Error('Invalid envelope');
return event;
}
if(process.argv[1]===fileURLToPath(import.meta.url)){
try{
if(process.argv.length!==4)throw Error('Two file paths required');
const body=bounded(process.argv[2],contract.body_limit),headers=JSON.parse(decode(bounded(process.argv[3],32768)));
const event=verify(body,headers,process.env.KDP_WEBHOOK_SECRET||'',(process.env.KDP_WEBHOOK_ENVIRONMENT||'').toLowerCase(),Math.floor(Date.now()/1000));
console.log(JSON.stringify({verified:true,event_id:event.id,event:event.event,environment:event.environment}));
}catch{console.log('{"verified":false}');process.exitCode=1;}
}
Connect to an HTTP adapter
- Read a bounded raw HTTP body before JSON middleware changes it.
- Reject duplicate signature, event-ID and event-name header fields.
- Normalize header names to lowercase without changing their values.
- Pass the exact raw body, headers, configured endpoint secret and expected environment to the verifier.
- Atomically persist the verified event ID and work item before sending a 2xx response.
Expected result: only authenticated recent notifications reach your inbox. The CLI tool does not start an HTTP listener, save deduplication records, call licensing APIs, send email or unlock an application. Use the local inbox example to test the durable acknowledgement boundary.
Expected result
All captured event types pass when signed with the right current secret and pinned environment. Changed raw bytes, a wrong secret, stale/future attempt timestamp, malformed envelope or wrong environment print exactly {"verified":false} and exit 1. The shared suite exercises positive events, negative input and size boundaries against the exact file above.
Common mistakes
- Reading contract.json from a different working directory or copying only one source without its companion files.
- Re-encoding JSON before HMAC verification.
- Reusing an expired test signature instead of generating a current one.
- Assuming successful authentication deduplicates an additive renewal.
Security notes
Never print the secret or full signature in logs. Use the endpoint's plaintext HMAC secret, not a developer API key or an Ed25519 public key. A verified notification is not an authoritative license-validity response. Timestamp filtering does not stop duplicate delivery inside its window; use a durable authenticated event-ID ledger and an independent business-operation key.
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| verified=false for an unchanged fixture | Timestamp expired, wrong secret or wrong environment | Regenerate the private request using the intended Sandbox configuration |
| Companion file cannot be found | Working directory or extraction incomplete | Restore the complete source archive and work inside webhooks |
| The same ID verifies again | Verifier only authenticates bytes | Commit a unique inbox record before applying an effect |
Next steps
Run the local HTTP, replay and storage-failure tests.