// Signs every request with the workspace secret key (see API authentication).
// Canonical request: X-Timestamp + "." + METHOD + path + ("?" + query, if any) + raw body.
// The timestamp is taken when you press Send, so every send is signed anew.
const rfc3986 = (value) =>
encodeURIComponent(value).replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());
const apiKey = pm.variables.get('apiKey');
const secretKey = pm.variables.get('secretKey');
if (!apiKey || !secretKey) {
throw new Error('Set the apiKey and secretKey variables of the ProofAge collection first.');
}
pm.request.headers.upsert({ key: 'X-API-Key', value: apiKey });
const timestamp = String(Math.floor(Date.now() / 1000));
const body = pm.request.body;
if (body && body.mode === 'formdata') {
// A media upload is signed over its fields and the SHA-256 of each file, which a
// pre-request script cannot read: upload media with a server SDK instead.
console.warn('ProofAge: media uploads cannot be signed from Postman.');
} else {
// The sandbox has no URL class: take the path of baseUrl (for example /v1) by hand.
const basePath = pm.variables.replaceIn('{{baseUrl}}').replace(/^[a-z]+:\/\/[^/]+/i, '').replace(/\/$/, '');
const path = basePath + pm.variables.replaceIn(pm.request.url.getPath());
const query = pm.request.url.query
.filter((param) => !param.disabled)
.map((param) => [pm.variables.replaceIn(param.key), pm.variables.replaceIn(param.value ?? '')])
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
.map(([key, value]) => rfc3986(key) + '=' + rfc3986(value))
.join('&');
const raw = body && body.mode === 'raw' ? pm.variables.replaceIn(body.raw) : '';
const canonical = timestamp + '.' + pm.request.method + path + (query ? '?' + query : '') + raw;
const signature = CryptoJS.HmacSHA256(canonical, secretKey).toString(CryptoJS.enc.Hex);
pm.request.headers.upsert({ key: 'X-Timestamp', value: timestamp });
pm.request.headers.upsert({ key: 'X-HMAC-Signature', value: signature });
// The two create calls take an Idempotency-Key: a new one per send. To retry a create
// without making a second one, copy the key from the Console and send it again yourself.
if (pm.request.method === 'POST' && /\/(verifications|webhook-subscriptions)$/.test(path)) {
const existing = pm.request.headers.get('Idempotency-Key');
if (!existing) {
pm.request.headers.upsert({ key: 'Idempotency-Key', value: pm.variables.replaceIn('{{$guid}}') });
}
}
}