@cloakapi/conformance 0.0.0-stage → 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.
- package/LICENSE +202 -0
- package/NOTICE +9 -0
- package/README.md +128 -2
- package/THIRD-PARTY-NOTICES.md +9 -0
- package/TRADEMARKS.md +23 -0
- package/badge/attestation.js +47 -0
- package/badge/badge.html +40 -0
- package/badge/make-variants.mjs +40 -0
- package/badge/verified-by-cloakapi-dark.svg +16 -0
- package/badge/verified-by-cloakapi-light.svg +16 -0
- package/badge/verified-by-cloakapi.svg +43 -0
- package/bin/cloakapi-conformance.js +150 -0
- package/fixtures/chain-broken.json +74 -0
- package/fixtures/chain-pass.json +74 -0
- package/fixtures/countersigned-forged.json +52 -0
- package/fixtures/countersigned-pass.json +52 -0
- package/fixtures/engine-hashes-unpublished.json +8 -0
- package/fixtures/engine-hashes.json +10 -0
- package/fixtures/jwks.json +13 -0
- package/fixtures/receipt-bad-token-hash.json +36 -0
- package/fixtures/receipt-future-engine.json +36 -0
- package/fixtures/receipt-no-egress-claim.json +35 -0
- package/fixtures/receipt-pass.json +36 -0
- package/fixtures/receipt-raw-pii.json +36 -0
- package/fixtures/receipt-spoofed-hash.json +36 -0
- package/fixtures/receipt-stale-engine.json +36 -0
- package/fixtures/receipt-tampered.json +36 -0
- package/package.json +56 -4
- package/src/checks.js +570 -0
- package/src/index.js +120 -0
- package/vendor/cloakapi-verify.d.ts +121 -0
- package/vendor/cloakapi-verify.js +1350 -0
- package/vendor/strict-json.js +143 -0
|
@@ -0,0 +1,1350 @@
|
|
|
1
|
+
import { parseStrictJson } from './strict-json.js';
|
|
2
|
+
export { parseStrictJson };
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @cloakapi/verify-widget — end-user "verify this session" widget.
|
|
6
|
+
*
|
|
7
|
+
* A tiny, DEPENDENCY-FREE, CSP-SAFE embeddable that lets the END USERS of any
|
|
8
|
+
* third-party app built on CloakAPI independently check that tokenisation
|
|
9
|
+
* actually happened and the receipts are cryptographically valid — shifting
|
|
10
|
+
* the residual "third-party correctness" question (ADR-0014 §5 #6) from
|
|
11
|
+
* "trust the builder" to "the end user can verify it themselves".
|
|
12
|
+
*
|
|
13
|
+
* WHY THIS FILE HAS NO EXTERNAL RUNTIME DEPENDENCIES
|
|
14
|
+
* ----------------------------
|
|
15
|
+
* The crypto is done entirely with the browser's native WebCrypto
|
|
16
|
+
* (`crypto.subtle`, ECDSA-P256 + SHA-256) plus a hand-rolled RFC-8785 (JCS)
|
|
17
|
+
* canonicaliser. That is a deliberate re-use of the SAME algorithm as the
|
|
18
|
+
* portal receipt-verifier / `@cloakapi/open-receipt` reference impl (JCS →
|
|
19
|
+
* SHA-256 → P-256 raw r||s), re-expressed with zero npm dependencies so the
|
|
20
|
+
* file drops into ANY page (script tag / web component) under a strict CSP
|
|
21
|
+
* with no bundler, no `eval`, no inline handlers. The signature scheme and the
|
|
22
|
+
* canonical bytes are byte-identical to the signer — this file was validated
|
|
23
|
+
* against the real signed fixture `open_receipt_v3_vector.json`.
|
|
24
|
+
*
|
|
25
|
+
* TWO WAYS TO USE IT
|
|
26
|
+
* ------------------
|
|
27
|
+
* 1. Web component (one tag):
|
|
28
|
+
* <script type="module" src="https://cdn.example/cloakapi-verify.js"></script>
|
|
29
|
+
* <cloakapi-verify jti="01J..." theme="auto"></cloakapi-verify>
|
|
30
|
+
* 2. Programmatic API:
|
|
31
|
+
* import { verifyReceipt } from 'https://cdn.example/cloakapi-verify.js';
|
|
32
|
+
* const verdict = await verifyReceipt(receiptOrCountersignedResult);
|
|
33
|
+
*
|
|
34
|
+
* The element auto-registers itself as <cloakapi-verify> when loaded in a DOM.
|
|
35
|
+
* Importing the module in Node (for unit tests) only pulls the pure crypto —
|
|
36
|
+
* the custom-element registration is guarded and never runs headless.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
/* eslint-disable no-bitwise */
|
|
40
|
+
|
|
41
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
42
|
+
// 1. Canonicalisation — RFC 8785 JSON Canonical Form (JCS).
|
|
43
|
+
// Byte-identical to @cloakapi/open-receipt `canon.ts` and the Rust/PHP
|
|
44
|
+
// signers. Pure; no dependencies.
|
|
45
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
46
|
+
|
|
47
|
+
/** @param {unknown} value @returns {string} */
|
|
48
|
+
export function canonicaliseToString(value) {
|
|
49
|
+
if (value === null) return 'null';
|
|
50
|
+
if (typeof value === 'boolean') return value ? 'true' : 'false';
|
|
51
|
+
if (typeof value === 'number') {
|
|
52
|
+
if (!Number.isFinite(value)) throw new Error('Cannot canonicalise a non-finite number');
|
|
53
|
+
return JSON.stringify(value);
|
|
54
|
+
}
|
|
55
|
+
if (typeof value === 'string') return canonicalString(value);
|
|
56
|
+
if (Array.isArray(value)) return '[' + value.map(canonicaliseToString).join(',') + ']';
|
|
57
|
+
if (typeof value === 'object') {
|
|
58
|
+
const keys = Object.keys(value).sort();
|
|
59
|
+
const pairs = keys.map((k) => canonicalString(k) + ':' + canonicaliseToString(value[k]));
|
|
60
|
+
return '{' + pairs.join(',') + '}';
|
|
61
|
+
}
|
|
62
|
+
throw new Error('Cannot canonicalise value of type ' + typeof value);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** @param {unknown} value @returns {Uint8Array} */
|
|
66
|
+
export function canonicalise(value) {
|
|
67
|
+
return new TextEncoder().encode(canonicaliseToString(value));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** @param {string} s */
|
|
71
|
+
function canonicalString(s) {
|
|
72
|
+
let out = '"';
|
|
73
|
+
for (const ch of s) {
|
|
74
|
+
const cp = ch.codePointAt(0);
|
|
75
|
+
if (cp === 0x22) out += '\\"';
|
|
76
|
+
else if (cp === 0x5c) out += '\\\\';
|
|
77
|
+
else if (cp === 0x08) out += '\\b';
|
|
78
|
+
else if (cp === 0x09) out += '\\t';
|
|
79
|
+
else if (cp === 0x0a) out += '\\n';
|
|
80
|
+
else if (cp === 0x0c) out += '\\f';
|
|
81
|
+
else if (cp === 0x0d) out += '\\r';
|
|
82
|
+
else if (cp < 0x20) out += '\\u' + cp.toString(16).padStart(4, '0');
|
|
83
|
+
else out += ch;
|
|
84
|
+
}
|
|
85
|
+
return out + '"';
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
89
|
+
// 2. Low-level crypto helpers (WebCrypto only).
|
|
90
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
91
|
+
|
|
92
|
+
/** hex → Uint8Array */
|
|
93
|
+
function hexToBytes(hex) {
|
|
94
|
+
if (typeof hex !== 'string' || hex.length % 2 !== 0) return null;
|
|
95
|
+
const out = new Uint8Array(hex.length / 2);
|
|
96
|
+
for (let i = 0; i < out.length; i++) {
|
|
97
|
+
const b = parseInt(hex.substr(i * 2, 2), 16);
|
|
98
|
+
if (Number.isNaN(b)) return null;
|
|
99
|
+
out[i] = b;
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Uint8Array → lowercase hex */
|
|
105
|
+
function bytesToHex(bytes) {
|
|
106
|
+
let s = '';
|
|
107
|
+
for (const b of bytes) s += b.toString(16).padStart(2, '0');
|
|
108
|
+
return s;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** base64 / base64url → Uint8Array (tolerant of both alphabets + missing pad) */
|
|
112
|
+
function b64AnyToBytes(s) {
|
|
113
|
+
if (typeof s !== 'string') return null;
|
|
114
|
+
const norm = s.replace(/-/g, '+').replace(/_/g, '/');
|
|
115
|
+
const pad = (4 - (norm.length % 4)) % 4;
|
|
116
|
+
try {
|
|
117
|
+
const bin = atob(norm + '='.repeat(pad));
|
|
118
|
+
const out = new Uint8Array(bin.length);
|
|
119
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
120
|
+
return out;
|
|
121
|
+
} catch {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function bytesToB64url(bytes) {
|
|
127
|
+
let bin = '';
|
|
128
|
+
for (const b of bytes) bin += String.fromCharCode(b);
|
|
129
|
+
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Import an uncompressed hex P-256 public key (0x04 || X || Y, 130 hex chars). */
|
|
133
|
+
async function importHexP256(pubHex) {
|
|
134
|
+
const raw = hexToBytes(pubHex);
|
|
135
|
+
if (!raw || raw.length !== 65 || raw[0] !== 0x04) return null;
|
|
136
|
+
const x = bytesToB64url(raw.slice(1, 33));
|
|
137
|
+
const y = bytesToB64url(raw.slice(33, 65));
|
|
138
|
+
return crypto.subtle.importKey(
|
|
139
|
+
'jwk',
|
|
140
|
+
{ kty: 'EC', crv: 'P-256', x, y, ext: true },
|
|
141
|
+
{ name: 'ECDSA', namedCurve: 'P-256' },
|
|
142
|
+
false,
|
|
143
|
+
['verify'],
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Import a P-256 JWK ({x,y} base64url) for verification. */
|
|
148
|
+
async function importJwkP256(jwk) {
|
|
149
|
+
return crypto.subtle.importKey(
|
|
150
|
+
'jwk',
|
|
151
|
+
{ kty: 'EC', crv: 'P-256', x: jwk.x, y: jwk.y, ext: true },
|
|
152
|
+
{ name: 'ECDSA', namedCurve: 'P-256' },
|
|
153
|
+
false,
|
|
154
|
+
['verify'],
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** SHA-256 hex of the JCS-canonical bytes of a value (incl. any `sig`). */
|
|
159
|
+
export async function receiptHash(signed) {
|
|
160
|
+
const digest = await crypto.subtle.digest('SHA-256', canonicalise(signed));
|
|
161
|
+
return bytesToHex(new Uint8Array(digest));
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
165
|
+
// 3. Receipt-shape helpers.
|
|
166
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
167
|
+
|
|
168
|
+
/** @param {any} env attester (device) public key from a v3 self-contained envelope */
|
|
169
|
+
function attesterKeyOf(env) {
|
|
170
|
+
const att = env && env.claims && env.claims['v3-attestation'];
|
|
171
|
+
return att && typeof att.attester_public_key === 'string' ? att.attester_public_key : null;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function isObjectRecord(value) {
|
|
175
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function isNonemptyString(value) {
|
|
179
|
+
return typeof value === 'string' && value.trim().length > 0;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function isSha256Hex(value) {
|
|
183
|
+
return typeof value === 'string' && /^[0-9a-f]{64}$/i.test(value);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// SHA-256 of the empty string: the "hash of the empty set" some producers write
|
|
187
|
+
// when they commit no token binding (browser portal, extension with no matches).
|
|
188
|
+
const EMPTY_SET_SHA256 = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
|
|
189
|
+
|
|
190
|
+
// `token_binding_hmac` is a required member, but the spec does not say it must be
|
|
191
|
+
// non-empty. Producers that commit no binding write "" (cloakup, starter kit) and
|
|
192
|
+
// receipts in that shape verified with SDK <= 1.4.0. An empty value is a format
|
|
193
|
+
// the verifier accepts and a claim it never credits: see unverifiedV3Fields.
|
|
194
|
+
function isTokenBindingValue(value) {
|
|
195
|
+
return value === '' || isNonemptyString(value);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function hasNoTokenBinding(value) {
|
|
199
|
+
return value === '' || (typeof value === 'string' && value.toLowerCase() === EMPTY_SET_SHA256);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function isLegacyDeviceReceipt(env) {
|
|
203
|
+
return env.typ === 'cloak-device-receipt'
|
|
204
|
+
&& !Object.prototype.hasOwnProperty.call(env, 'v')
|
|
205
|
+
&& !Object.prototype.hasOwnProperty.call(env, 'alg')
|
|
206
|
+
&& !Object.prototype.hasOwnProperty.call(env, 'iss')
|
|
207
|
+
&& !Object.prototype.hasOwnProperty.call(env, 'sub')
|
|
208
|
+
&& !Object.prototype.hasOwnProperty.call(env, 'chain')
|
|
209
|
+
&& !Object.prototype.hasOwnProperty.call(env, 'kid');
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function validateV3ReceiptSchema(receipt) {
|
|
213
|
+
const invalid = [];
|
|
214
|
+
if (!isObjectRecord(receipt)) return ['receipt'];
|
|
215
|
+
if (receipt.v !== 'v3') invalid.push('receipt.v');
|
|
216
|
+
if (receipt.alg !== 'ecdsa-p256-sha256') invalid.push('receipt.alg');
|
|
217
|
+
for (const field of ['kid', 'iss', 'sub', 'jti', 'sig']) {
|
|
218
|
+
if (!isNonemptyString(receipt[field])) invalid.push(`receipt.${field}`);
|
|
219
|
+
}
|
|
220
|
+
if (!Number.isSafeInteger(receipt.iat) || receipt.iat < 0) invalid.push('receipt.iat');
|
|
221
|
+
for (const field of ['nbf', 'exp']) {
|
|
222
|
+
if (Object.prototype.hasOwnProperty.call(receipt, field)
|
|
223
|
+
&& (!Number.isSafeInteger(receipt[field]) || receipt[field] < 0)) {
|
|
224
|
+
invalid.push(`receipt.${field}`);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (!isObjectRecord(receipt.chain)) {
|
|
229
|
+
invalid.push('receipt.chain');
|
|
230
|
+
} else {
|
|
231
|
+
if (!isNonemptyString(receipt.chain.chain_id)) invalid.push('receipt.chain.chain_id');
|
|
232
|
+
if (!Number.isSafeInteger(receipt.chain.seq) || receipt.chain.seq < 0) invalid.push('receipt.chain.seq');
|
|
233
|
+
if (receipt.chain.prev_hash !== null && !isSha256Hex(receipt.chain.prev_hash)) {
|
|
234
|
+
invalid.push('receipt.chain.prev_hash');
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
let attestation = null;
|
|
239
|
+
if (!isObjectRecord(receipt.claims)) {
|
|
240
|
+
invalid.push('receipt.claims');
|
|
241
|
+
} else if (!isObjectRecord(receipt.claims['v3-attestation'])) {
|
|
242
|
+
invalid.push('receipt.claims.v3-attestation');
|
|
243
|
+
} else {
|
|
244
|
+
attestation = receipt.claims['v3-attestation'];
|
|
245
|
+
}
|
|
246
|
+
if (attestation) {
|
|
247
|
+
for (const field of ['tier', 'engine_ruleset_version', 'privacy_tier']) {
|
|
248
|
+
if (!isNonemptyString(attestation[field])) invalid.push(`receipt.claims.v3-attestation.${field}`);
|
|
249
|
+
}
|
|
250
|
+
for (const field of ['tokenised_body_hash', 'engine_binary_hash']) {
|
|
251
|
+
if (!isNonemptyString(attestation[field])) invalid.push(`receipt.claims.v3-attestation.${field}`);
|
|
252
|
+
}
|
|
253
|
+
if (!isTokenBindingValue(attestation.token_binding_hmac)) {
|
|
254
|
+
invalid.push('receipt.claims.v3-attestation.token_binding_hmac');
|
|
255
|
+
}
|
|
256
|
+
if (typeof attestation.no_raw_pii_egress !== 'boolean') {
|
|
257
|
+
invalid.push('receipt.claims.v3-attestation.no_raw_pii_egress');
|
|
258
|
+
}
|
|
259
|
+
if (!Array.isArray(attestation.detector_categories)
|
|
260
|
+
|| !attestation.detector_categories.every(isNonemptyString)) {
|
|
261
|
+
invalid.push('receipt.claims.v3-attestation.detector_categories');
|
|
262
|
+
}
|
|
263
|
+
if (typeof attestation.genuine_engine !== 'boolean') {
|
|
264
|
+
invalid.push('receipt.claims.v3-attestation.genuine_engine');
|
|
265
|
+
}
|
|
266
|
+
if (!isObjectRecord(attestation.anchoring)) invalid.push('receipt.claims.v3-attestation.anchoring');
|
|
267
|
+
if (typeof attestation.attester_public_key !== 'string'
|
|
268
|
+
|| !/^04[0-9a-f]{128}$/i.test(attestation.attester_public_key)) {
|
|
269
|
+
invalid.push('receipt.claims.v3-attestation.attester_public_key');
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return invalid;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function unverifiedV3Fields(receipt) {
|
|
276
|
+
const fields = [];
|
|
277
|
+
const knownReceipt = ['v', 'alg', 'kid', 'iss', 'sub', 'iat', 'jti', 'chain', 'claims', 'sig', 'nbf', 'exp'];
|
|
278
|
+
for (const key of Object.keys(receipt)) {
|
|
279
|
+
if (!knownReceipt.includes(key)) fields.push(`receipt.${key}: signed, semantics not checked`);
|
|
280
|
+
}
|
|
281
|
+
if (isObjectRecord(receipt.chain)) {
|
|
282
|
+
for (const key of Object.keys(receipt.chain)) {
|
|
283
|
+
if (!['chain_id', 'seq', 'prev_hash'].includes(key)) {
|
|
284
|
+
fields.push(`receipt.chain.${key}: signed, semantics not checked`);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (isObjectRecord(receipt.claims)) {
|
|
289
|
+
for (const key of Object.keys(receipt.claims)) {
|
|
290
|
+
if (key !== 'v3-attestation') fields.push(`receipt.claims.${key}: signed, semantics not checked`);
|
|
291
|
+
}
|
|
292
|
+
const attestation = receipt.claims['v3-attestation'];
|
|
293
|
+
if (isObjectRecord(attestation)) {
|
|
294
|
+
const knownAttestation = [
|
|
295
|
+
'tier', 'no_raw_pii_egress', 'tokenised_body_hash', 'detector_categories',
|
|
296
|
+
'engine_ruleset_version', 'engine_binary_hash', 'genuine_engine', 'privacy_tier',
|
|
297
|
+
'token_binding_hmac', 'anchoring', 'attester_public_key', 'self_check',
|
|
298
|
+
'client_destination', 'compliance_pack',
|
|
299
|
+
];
|
|
300
|
+
for (const key of Object.keys(attestation)) {
|
|
301
|
+
if (!knownAttestation.includes(key)) {
|
|
302
|
+
fields.push(`receipt.claims.v3-attestation.${key}: signed, semantics not checked`);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
if (hasNoTokenBinding(attestation.token_binding_hmac)) {
|
|
306
|
+
fields.push('receipt.claims.v3-attestation.token_binding_hmac: empty, no token binding committed');
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return fields.sort();
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Is this a gateway countersign RESULT rather than a bare envelope? */
|
|
314
|
+
export function isCountersignedResult(obj) {
|
|
315
|
+
// Recognise incomplete wrappers too, so verifyReceipt can report the
|
|
316
|
+
// malformed field instead of treating the whole object as a bare receipt.
|
|
317
|
+
return isObjectRecord(obj) && isObjectRecord(obj.receipt);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
321
|
+
// 4. Core verification.
|
|
322
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Verify a single self-contained v3 device receipt OFFLINE, using the public
|
|
326
|
+
* key embedded inside the signed envelope (tamper-evident: the key is inside
|
|
327
|
+
* the signed bytes). No network, no account.
|
|
328
|
+
* @returns {Promise<{ok:boolean, reason:string}>}
|
|
329
|
+
*/
|
|
330
|
+
export async function verifyDeviceReceipt(env) {
|
|
331
|
+
if (!isObjectRecord(env)) {
|
|
332
|
+
return { ok: false, reason: 'not a signed receipt' };
|
|
333
|
+
}
|
|
334
|
+
const legacy = isLegacyDeviceReceipt(env);
|
|
335
|
+
if (!legacy) {
|
|
336
|
+
const invalid = validateV3ReceiptSchema(env);
|
|
337
|
+
if (invalid.length) {
|
|
338
|
+
return { ok: false, reason: 'Invalid receipt format: required receipt information is missing or malformed.' };
|
|
339
|
+
}
|
|
340
|
+
} else if (typeof env.sig !== 'string') {
|
|
341
|
+
return { ok: false, reason: 'not a signed receipt' };
|
|
342
|
+
}
|
|
343
|
+
const pubHex = attesterKeyOf(env);
|
|
344
|
+
if (!pubHex) {
|
|
345
|
+
return { ok: false, reason: 'no embedded public key — cannot verify offline' };
|
|
346
|
+
}
|
|
347
|
+
const { sig, ...receipt } = env;
|
|
348
|
+
const sigBytes = b64AnyToBytes(sig);
|
|
349
|
+
if (!sigBytes || sigBytes.length !== 64) {
|
|
350
|
+
return { ok: false, reason: 'malformed signature (expected 64-byte raw r||s)' };
|
|
351
|
+
}
|
|
352
|
+
let key;
|
|
353
|
+
try { key = await importHexP256(pubHex); }
|
|
354
|
+
catch { return { ok: false, reason: 'malformed public key' }; }
|
|
355
|
+
if (!key) return { ok: false, reason: 'malformed public key' };
|
|
356
|
+
let ok = false;
|
|
357
|
+
try {
|
|
358
|
+
ok = await crypto.subtle.verify(
|
|
359
|
+
{ name: 'ECDSA', hash: 'SHA-256' },
|
|
360
|
+
key,
|
|
361
|
+
sigBytes,
|
|
362
|
+
canonicalise(receipt),
|
|
363
|
+
);
|
|
364
|
+
} catch {
|
|
365
|
+
ok = false;
|
|
366
|
+
}
|
|
367
|
+
const unverifiedFields = !legacy && ok ? unverifiedV3Fields(env) : [];
|
|
368
|
+
const extensionNote = unverifiedFields.length
|
|
369
|
+
? '; signed fields not semantically checked: ' + unverifiedFields.join(', ')
|
|
370
|
+
: '';
|
|
371
|
+
return {
|
|
372
|
+
ok,
|
|
373
|
+
reason: ok ? 'signature valid' + extensionNote : 'signature mismatch — receipt was altered',
|
|
374
|
+
...(unverifiedFields.length ? { unverifiedFields } : {}),
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Verify the gateway COUNTERSIGNATURE (raw r||s base64 over the JCS bytes of
|
|
380
|
+
* the countersignature minus its own signature carriers) against the JWKS.
|
|
381
|
+
* @returns {Promise<[boolean, string|null, string?]>} [verified, kid, rejection reason]
|
|
382
|
+
*/
|
|
383
|
+
export async function verifyGatewaySignature(cs, jwksJson, receiptContext) {
|
|
384
|
+
const kid = cs && typeof cs.kid === 'string' ? cs.kid : null;
|
|
385
|
+
const sigB64 = cs && typeof cs.signature === 'string' ? cs.signature : null;
|
|
386
|
+
const clientPublicKeyHex = isObjectRecord(receiptContext) ? attesterKeyOf(receiptContext) : null;
|
|
387
|
+
if (typeof clientPublicKeyHex !== 'string' || !/^04[0-9a-f]{128}$/i.test(clientPublicKeyHex)) {
|
|
388
|
+
return [false, kid, 'cannot verify without receipt context'];
|
|
389
|
+
}
|
|
390
|
+
if (!kid || !sigB64) return [false, kid];
|
|
391
|
+
if (cs.v !== 'v3-countersign' || !isSha256Hex(cs.receipt_hash)) return [false, kid];
|
|
392
|
+
const signedFields = cs && Array.isArray(cs.signed_fields) ? cs.signed_fields : null;
|
|
393
|
+
if (!signedFields || !signedFields.includes('receipt_hash')
|
|
394
|
+
|| !signedFields.every(isNonemptyString)
|
|
395
|
+
|| !['v', 'kid', 'receipt_hash', 'timestamp'].every((field) => signedFields.includes(field))
|
|
396
|
+
|| signedFields.some((field) => field === 'signature' || field === 'signed_fields'
|
|
397
|
+
|| !Object.prototype.hasOwnProperty.call(cs, field))) {
|
|
398
|
+
return [false, kid];
|
|
399
|
+
}
|
|
400
|
+
if (kid && isPortalKid(kid)) {
|
|
401
|
+
return [false, kid, 'countersignature key is a self-attested portal key, not a gateway witness'];
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
let keys;
|
|
405
|
+
try {
|
|
406
|
+
keys = parseStrictJson(jwksJson).keys || [];
|
|
407
|
+
} catch {
|
|
408
|
+
return [false, kid];
|
|
409
|
+
}
|
|
410
|
+
if (!Array.isArray(keys)) return [false, kid];
|
|
411
|
+
const matches = keys.filter((k) => k && k.kid === kid);
|
|
412
|
+
if (matches.some((jwk) => jwkIsClientKey(jwk, clientPublicKeyHex))) {
|
|
413
|
+
return [false, kid, 'countersignature key is a self-attested portal key, not a gateway witness'];
|
|
414
|
+
}
|
|
415
|
+
if (matches.length !== 1) return [false, kid];
|
|
416
|
+
const jwk = matches[0];
|
|
417
|
+
if (jwk.kty !== 'EC' || jwk.crv !== 'P-256') return [false, kid];
|
|
418
|
+
if (!jwk.x || !jwk.y) return [false, kid];
|
|
419
|
+
const portalKeys = keys.filter((k) => k && typeof k.kid === 'string' && isPortalKid(k.kid) && k.kty === 'EC' && k.crv === 'P-256');
|
|
420
|
+
if (portalKeys.some((portalKey) => jwkHasSamePublicKey(jwk, portalKey))) {
|
|
421
|
+
return [false, kid, 'countersignature key is a self-attested portal key, not a gateway witness'];
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
const sig = b64AnyToBytes(sigB64);
|
|
425
|
+
if (!sig || sig.length !== 64) return [false, kid];
|
|
426
|
+
|
|
427
|
+
const toSign = Object.create(null);
|
|
428
|
+
for (const field of signedFields) {
|
|
429
|
+
if (!Object.prototype.hasOwnProperty.call(cs, field)) return [false, kid];
|
|
430
|
+
toSign[field] = cs[field];
|
|
431
|
+
}
|
|
432
|
+
try {
|
|
433
|
+
const key = await importJwkP256(jwk);
|
|
434
|
+
const ok = await crypto.subtle.verify(
|
|
435
|
+
{ name: 'ECDSA', hash: 'SHA-256' },
|
|
436
|
+
key,
|
|
437
|
+
sig,
|
|
438
|
+
canonicalise(toSign),
|
|
439
|
+
);
|
|
440
|
+
return [ok, kid];
|
|
441
|
+
} catch {
|
|
442
|
+
return [false, kid];
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function jwkIsClientKey(jwk, clientPublicKeyHex) {
|
|
447
|
+
if (typeof clientPublicKeyHex !== 'string' || !/^04[0-9a-f]{128}$/i.test(clientPublicKeyHex)) return false;
|
|
448
|
+
const x = b64AnyToBytes(jwk.x);
|
|
449
|
+
const y = b64AnyToBytes(jwk.y);
|
|
450
|
+
if (!x || !y || x.length !== 32 || y.length !== 32) return false;
|
|
451
|
+
for (let i = 0; i < 32; i++) {
|
|
452
|
+
if (x[i] !== parseInt(clientPublicKeyHex.slice(2 + i * 2, 4 + i * 2), 16)
|
|
453
|
+
|| y[i] !== parseInt(clientPublicKeyHex.slice(66 + i * 2, 68 + i * 2), 16)) return false;
|
|
454
|
+
}
|
|
455
|
+
return true;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function jwkHasSamePublicKey(left, right) {
|
|
459
|
+
const leftX = b64AnyToBytes(left && left.x);
|
|
460
|
+
const leftY = b64AnyToBytes(left && left.y);
|
|
461
|
+
const rightX = b64AnyToBytes(right && right.x);
|
|
462
|
+
const rightY = b64AnyToBytes(right && right.y);
|
|
463
|
+
if (!leftX || !leftY || !rightX || !rightY
|
|
464
|
+
|| leftX.length !== 32 || leftY.length !== 32
|
|
465
|
+
|| rightX.length !== 32 || rightY.length !== 32) return false;
|
|
466
|
+
for (let i = 0; i < 32; i++) {
|
|
467
|
+
if (leftX[i] !== rightX[i] || leftY[i] !== rightY[i]) return false;
|
|
468
|
+
}
|
|
469
|
+
return true;
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function isPortalKid(kid) {
|
|
473
|
+
// Gateway key ids are plain printable ASCII. Anything else (spaces, zero-width or other
|
|
474
|
+
// format characters, non-ASCII) cannot be a gateway witness id and is treated like a
|
|
475
|
+
// portal key id; the prefix check is ASCII case-insensitive after NFKC.
|
|
476
|
+
if (/[^\x21-\x7e]/.test(kid)) return true;
|
|
477
|
+
return /^portal-/i.test(kid.normalize('NFKC'));
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* Full two-party verification of a countersigned result (device sig + gateway
|
|
482
|
+
* countersignature + hash-binding). Mirrors the portal `verify-countersigned`.
|
|
483
|
+
* @returns {Promise<{deviceVerified:boolean, gatewayVerified:boolean, hashBound:boolean, tier:string, gatewayKid:string|null, error?:string}>}
|
|
484
|
+
*/
|
|
485
|
+
export async function verifyCountersigned(result, jwksJson) {
|
|
486
|
+
const entry = isObjectRecord(result) ? result : {};
|
|
487
|
+
const inner = isObjectRecord(entry.receipt) ? entry.receipt : {};
|
|
488
|
+
const cs = isObjectRecord(entry.countersignature) ? entry.countersignature : {};
|
|
489
|
+
const device = await verifyDeviceReceipt(inner);
|
|
490
|
+
const schemaValid = !/^invalid receipt format:/i.test(device.reason);
|
|
491
|
+
const deviceVerified = device.ok && schemaValid;
|
|
492
|
+
|
|
493
|
+
let witnessStatus = 'unverified';
|
|
494
|
+
const witnessVersion = typeof cs.v === 'string' ? cs.v.replace(/[^\x20-\x7e]/g, '?').slice(0, 64) : null;
|
|
495
|
+
let witnessError;
|
|
496
|
+
const signedFields = Array.isArray(cs.signed_fields) ? cs.signed_fields : null;
|
|
497
|
+
const invalidWitnessSchema = !schemaValid || !isObjectRecord(entry.countersignature) || cs.v !== 'v3-countersign'
|
|
498
|
+
? false
|
|
499
|
+
: !isNonemptyString(cs.kid)
|
|
500
|
+
|| !isSha256Hex(cs.receipt_hash)
|
|
501
|
+
|| !isNonemptyString(cs.timestamp)
|
|
502
|
+
|| !isNonemptyString(cs.signature)
|
|
503
|
+
|| !signedFields
|
|
504
|
+
|| !signedFields.every(isNonemptyString)
|
|
505
|
+
|| !['v', 'kid', 'receipt_hash', 'timestamp'].every((field) => signedFields.includes(field))
|
|
506
|
+
|| signedFields.some((field) => field === 'signature' || field === 'signed_fields'
|
|
507
|
+
|| !Object.prototype.hasOwnProperty.call(cs, field))
|
|
508
|
+
|| !isSha256Hex(entry.receipt_hash);
|
|
509
|
+
if (!schemaValid) {
|
|
510
|
+
witnessStatus = 'invalid-format';
|
|
511
|
+
witnessError = 'The receipt format is incomplete or malformed; the gateway confirmation could not be checked.';
|
|
512
|
+
} else if (!isObjectRecord(entry.countersignature)) {
|
|
513
|
+
witnessStatus = 'missing';
|
|
514
|
+
witnessError = 'No gateway confirmation was found.';
|
|
515
|
+
} else if (cs.v !== 'v3-countersign') {
|
|
516
|
+
witnessStatus = isNonemptyString(cs.v) ? 'unsupported-version' : 'invalid-format';
|
|
517
|
+
witnessError = isNonemptyString(cs.v)
|
|
518
|
+
? 'This receipt uses an unsupported gateway confirmation format (' + (witnessVersion || 'unknown') + ').'
|
|
519
|
+
: 'The gateway confirmation is incomplete or malformed.';
|
|
520
|
+
} else if (invalidWitnessSchema) {
|
|
521
|
+
witnessStatus = 'invalid-format';
|
|
522
|
+
witnessError = 'The gateway confirmation is incomplete or malformed.';
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
let gatewayVerified = false;
|
|
526
|
+
let gatewayKid = null;
|
|
527
|
+
let gatewayError;
|
|
528
|
+
if (jwksJson && schemaValid && witnessStatus === 'unverified') {
|
|
529
|
+
[gatewayVerified, gatewayKid, gatewayError] = await verifyGatewaySignature(
|
|
530
|
+
cs, jwksJson, inner,
|
|
531
|
+
);
|
|
532
|
+
} else {
|
|
533
|
+
gatewayKid = typeof cs.kid === 'string' ? cs.kid : null;
|
|
534
|
+
}
|
|
535
|
+
let hashBound = false;
|
|
536
|
+
try {
|
|
537
|
+
if (!schemaValid || !isSha256Hex(cs.receipt_hash) || !isSha256Hex(entry.receipt_hash)) {
|
|
538
|
+
throw new Error('invalid receipt or witness hash');
|
|
539
|
+
}
|
|
540
|
+
const computed = await receiptHash(inner);
|
|
541
|
+
hashBound = computed.toLowerCase() === cs.receipt_hash.toLowerCase()
|
|
542
|
+
&& computed.toLowerCase() === entry.receipt_hash.toLowerCase();
|
|
543
|
+
} catch {
|
|
544
|
+
hashBound = false;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
const tier =
|
|
548
|
+
deviceVerified && gatewayVerified && hashBound
|
|
549
|
+
? 'gateway-countersigned'
|
|
550
|
+
: deviceVerified
|
|
551
|
+
? 'beacon-anchored'
|
|
552
|
+
: 'unverified';
|
|
553
|
+
|
|
554
|
+
const unknownFields = [];
|
|
555
|
+
if (schemaValid && device.ok) unknownFields.push(...(device.unverifiedFields || []));
|
|
556
|
+
for (const key of Object.keys(entry)) {
|
|
557
|
+
if (!['receipt', 'countersignature', 'receipt_hash'].includes(key)) {
|
|
558
|
+
unknownFields.push(`entry.${key}: unsigned, not checked`);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
const knownCs = ['v', 'kid', 'receipt_hash', 'timestamp', 'request_id', 'provider', 'model', 'signature', 'signed_fields'];
|
|
562
|
+
for (const key of Object.keys(cs)) {
|
|
563
|
+
if (!knownCs.includes(key)) {
|
|
564
|
+
const status = Array.isArray(cs.signed_fields) && cs.signed_fields.includes(key)
|
|
565
|
+
? 'signed, semantics not checked'
|
|
566
|
+
: 'unsigned, not checked';
|
|
567
|
+
unknownFields.push(`countersignature.${key}: ${status}`);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
unknownFields.sort();
|
|
571
|
+
if (schemaValid && witnessStatus === 'unverified') {
|
|
572
|
+
if (gatewayVerified && hashBound) witnessStatus = 'verified';
|
|
573
|
+
else witnessError = gatewayError === 'countersignature key is a self-attested portal key, not a gateway witness'
|
|
574
|
+
? "The receipt's own key cannot confirm a gateway signature."
|
|
575
|
+
: gatewayError || (jwksJson
|
|
576
|
+
? 'The gateway confirmation could not be verified with the available key.'
|
|
577
|
+
: 'No gateway key was available to check the confirmation.');
|
|
578
|
+
}
|
|
579
|
+
const error = !device.ok ? device.reason : gatewayError;
|
|
580
|
+
return {
|
|
581
|
+
deviceVerified, gatewayVerified, hashBound, tier, gatewayKid, schemaValid,
|
|
582
|
+
witnessStatus, witnessVersion,
|
|
583
|
+
...(witnessError ? { witnessError } : {}),
|
|
584
|
+
...(error ? { error } : {}),
|
|
585
|
+
...(unknownFields.length ? { unverifiedFields: unknownFields } : {}),
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* Verify an ORDERED array of self-contained device receipts as a hash chain:
|
|
591
|
+
* each `chain.prev_hash` must equal the SHA-256 of the previous canonical
|
|
592
|
+
* receipt, `chain.seq` must be monotonic, and every signature must verify.
|
|
593
|
+
* @returns {Promise<{ok:boolean, index?:number, reason?:string}>}
|
|
594
|
+
*/
|
|
595
|
+
export async function verifyChain(receipts) {
|
|
596
|
+
// Zero receipts verified nothing. An empty list used to return ok:true,
|
|
597
|
+
// and verifyReceipt then rendered a signature check as passed.
|
|
598
|
+
if (!Array.isArray(receipts) || receipts.length === 0) {
|
|
599
|
+
return { ok: false, index: 0, reason: 'no receipts to verify' };
|
|
600
|
+
}
|
|
601
|
+
let prevHash = null;
|
|
602
|
+
for (let i = 0; i < receipts.length; i++) {
|
|
603
|
+
const signed = receipts[i];
|
|
604
|
+
if (!signed || typeof signed !== 'object' || Array.isArray(signed)) {
|
|
605
|
+
return { ok: false, index: i, reason: 'chain entry is not a receipt object' };
|
|
606
|
+
}
|
|
607
|
+
if (!signed.chain || typeof signed.chain !== 'object' || Array.isArray(signed.chain)) {
|
|
608
|
+
return { ok: false, index: i, reason: 'chain metadata is missing or malformed' };
|
|
609
|
+
}
|
|
610
|
+
const expected = prevHash;
|
|
611
|
+
const actual = signed.chain.prev_hash;
|
|
612
|
+
if (actual !== expected) {
|
|
613
|
+
return {
|
|
614
|
+
ok: false,
|
|
615
|
+
index: i,
|
|
616
|
+
reason: 'chain break: prev_hash expected ' + JSON.stringify(expected) + ', got ' + JSON.stringify(actual),
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
if (!Number.isSafeInteger(signed.chain.seq) || signed.chain.seq !== i) {
|
|
620
|
+
return { ok: false, index: i, reason: 'chain break: non-monotonic seq (expected ' + i + ', got ' + signed.chain.seq + ')' };
|
|
621
|
+
}
|
|
622
|
+
const r = await verifyDeviceReceipt(signed);
|
|
623
|
+
if (!r.ok) return { ok: false, index: i, reason: r.reason };
|
|
624
|
+
prevHash = await receiptHash(signed);
|
|
625
|
+
}
|
|
626
|
+
return { ok: true };
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
630
|
+
// 5. Consumer-friendly verdict — the whole point: plain language for a
|
|
631
|
+
// non-technical person.
|
|
632
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* Map span-type codes → plain-language labels for the STAND-IN that was used.
|
|
636
|
+
*
|
|
637
|
+
* ⛔⛔ THIS IS THE SURROGATE CLASS, NOT "WHAT WE FOUND". `detector_categories`
|
|
638
|
+
* is built as `[...new Set(spans.map((s) => s.type))]` — and `s.type` is the
|
|
639
|
+
* class that CHOSE the placeholder, so a person name the model labelled `ORG`
|
|
640
|
+
* is carried here as `ORG` and rendered "Organisation names".
|
|
641
|
+
*
|
|
642
|
+
* Measured 2026-09-14 over gauntlet batch-03 on the product path
|
|
643
|
+
* (`goal-run/F-BEVIS/HZ-KVITTERING-PERSON-RAN-2026-09-14.md` §2.2): **3 of 44
|
|
644
|
+
* PERSON gold spans** got a non-PERSON class, identically in both contexts —
|
|
645
|
+
* `Kvitbrekke` → ORG, `Áilu Sárrit` → ORG/LOC, `Torbjørg` → LOC (surrogate
|
|
646
|
+
* `Ålesund`, a real Norwegian town). Read as a finding list, the receipt then
|
|
647
|
+
* tells the customer "Organisation names" about their own name.
|
|
648
|
+
*
|
|
649
|
+
* ⛔ The FIELD NAME cannot be fixed, and that is a measurement, not a
|
|
650
|
+
* preference: `detector_categories` is a REQUIRED field of the published
|
|
651
|
+
* OpenReceipt spec (`repo/packages/openreceipt-site/spec/extensions.md:49`),
|
|
652
|
+
* it sits INSIDE the JCS-canonicalised, SIGNED `v3-attestation`, and 63 tracked
|
|
653
|
+
* files across 8 SDK languages carry it with golden cross-impl vectors in five.
|
|
654
|
+
* Renaming it to `surrogate_categories` would invalidate every one of those
|
|
655
|
+
* signatures and break a published spec. So the honesty has to live in the
|
|
656
|
+
* LABELS and in the sentence that renders them — this block and `greenVerdict`.
|
|
657
|
+
*
|
|
658
|
+
* ⛔ EVERY code `ReviewSpanType` can emit must have an entry. Measured before
|
|
659
|
+
* this change: 4 of the 13 emittable codes had none, so `humaniseCode()` showed
|
|
660
|
+
* the customer the raw wire tokens "Loc", "Govid", "Id" and "Other".
|
|
661
|
+
*/
|
|
662
|
+
const CATEGORY_LABELS = {
|
|
663
|
+
EMAIL: 'Email addresses',
|
|
664
|
+
PHONE: 'Phone numbers',
|
|
665
|
+
CREDIT_CARD: 'Card numbers',
|
|
666
|
+
SSN: 'Social-security / national ID numbers',
|
|
667
|
+
NATIONAL_ID: 'National ID numbers',
|
|
668
|
+
IBAN: 'Bank account (IBAN) numbers',
|
|
669
|
+
BANK_ACCOUNT: 'Bank account numbers',
|
|
670
|
+
ADDRESS: 'Postal addresses',
|
|
671
|
+
NAME: 'Names',
|
|
672
|
+
PERSON: 'Names',
|
|
673
|
+
DOB: 'Dates of birth',
|
|
674
|
+
DATE_OF_BIRTH: 'Dates of birth',
|
|
675
|
+
IP: 'IP addresses',
|
|
676
|
+
IP_ADDRESS: 'IP addresses',
|
|
677
|
+
PASSPORT: 'Passport numbers',
|
|
678
|
+
DRIVER_LICENSE: 'Driver-licence numbers',
|
|
679
|
+
API_KEY: 'API keys / secrets',
|
|
680
|
+
SECRET: 'Secrets',
|
|
681
|
+
MRN: 'Medical record numbers',
|
|
682
|
+
HEALTH: 'Health information',
|
|
683
|
+
LOCATION: 'Locations',
|
|
684
|
+
ORG: 'Organisation names',
|
|
685
|
+
// ⛔ The four `ReviewSpanType` codes that had NO label until 2026-09-14. The
|
|
686
|
+
// fallback `humaniseCode()` rendered them "Loc", "Govid", "Id", "Other" —
|
|
687
|
+
// raw wire tokens shown to a non-technical reader.
|
|
688
|
+
LOC: 'Places',
|
|
689
|
+
GOVID: 'Government ID numbers',
|
|
690
|
+
ID: 'Identifiers',
|
|
691
|
+
OTHER: 'Other sensitive details',
|
|
692
|
+
};
|
|
693
|
+
|
|
694
|
+
/**
|
|
695
|
+
* Codes → labels. EXPORTED so the mapping can be tested exhaustively against
|
|
696
|
+
* the emitting union rather than through a signed fixture — the same reason
|
|
697
|
+
* `safetyClassifierStatus` is exported. A guard that cannot reach its
|
|
698
|
+
* measurement object reports clean without having measured.
|
|
699
|
+
*
|
|
700
|
+
* ⛔ The labels name the STAND-IN, not the finding. See CATEGORY_LABELS.
|
|
701
|
+
*/
|
|
702
|
+
export function friendlyCategories(codes) {
|
|
703
|
+
if (!Array.isArray(codes)) return [];
|
|
704
|
+
return codes.map((c) => CATEGORY_LABELS[c] || humaniseCode(c));
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
function humaniseCode(c) {
|
|
708
|
+
return String(c)
|
|
709
|
+
.toLowerCase()
|
|
710
|
+
.replace(/_/g, ' ')
|
|
711
|
+
.replace(/\b\w/g, (m) => m.toUpperCase());
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/**
|
|
715
|
+
* Verify ANY supported input and return a consumer verdict object suitable for
|
|
716
|
+
* direct rendering. Accepts: a bare v3 device envelope, a countersigned
|
|
717
|
+
* result, or an array (chain).
|
|
718
|
+
*
|
|
719
|
+
* @param {object|Array} input
|
|
720
|
+
* @param {{ jwksJson?: string|null, verifyLink?: string }} [opts]
|
|
721
|
+
* @returns {Promise<Verdict>}
|
|
722
|
+
*/
|
|
723
|
+
export async function verifyReceipt(input, opts = {}) {
|
|
724
|
+
const verifyLink = opts.verifyLink || 'https://signedreceipts.org';
|
|
725
|
+
try {
|
|
726
|
+
// Chain of receipts.
|
|
727
|
+
if (Array.isArray(input)) {
|
|
728
|
+
const res = await verifyChain(input);
|
|
729
|
+
const last = input[input.length - 1] || {};
|
|
730
|
+
const att = (last.claims && last.claims['v3-attestation']) || {};
|
|
731
|
+
if (res.ok) {
|
|
732
|
+
return greenVerdict(att, 'device-verified', input.length, verifyLink, last);
|
|
733
|
+
}
|
|
734
|
+
return redVerdict('This conversation history could not be verified.', res.reason, verifyLink);
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
// Gateway countersigned result.
|
|
738
|
+
if (isCountersignedResult(input)) {
|
|
739
|
+
const cs = await verifyCountersigned(input, opts.jwksJson ?? null);
|
|
740
|
+
const att = (input.receipt.claims && input.receipt.claims['v3-attestation']) || {};
|
|
741
|
+
if (cs.schemaValid && cs.deviceVerified) {
|
|
742
|
+
const v = greenVerdict(att, cs.tier, 1, verifyLink, input.receipt);
|
|
743
|
+
v.gatewayVerified = cs.gatewayVerified;
|
|
744
|
+
v.hashBound = cs.hashBound;
|
|
745
|
+
v.witnessStatus = cs.witnessStatus;
|
|
746
|
+
v.witnessVersion = cs.witnessVersion;
|
|
747
|
+
v.witnessError = cs.witnessError;
|
|
748
|
+
if (cs.unverifiedFields && cs.unverifiedFields.length) {
|
|
749
|
+
v.checks.push({
|
|
750
|
+
label: 'Extension fields',
|
|
751
|
+
status: 'skip',
|
|
752
|
+
detail: 'Not semantically checked: ' + cs.unverifiedFields.join(', '),
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
v.checks.push({
|
|
756
|
+
label: 'Gateway confirmation',
|
|
757
|
+
status: cs.witnessStatus === 'verified' ? 'ok' : 'skip',
|
|
758
|
+
detail: cs.witnessStatus === 'verified'
|
|
759
|
+
? 'The gateway confirmation was verified against the available key.'
|
|
760
|
+
: cs.witnessError || 'The gateway confirmation could not be verified.',
|
|
761
|
+
});
|
|
762
|
+
v.checks.push({
|
|
763
|
+
label: 'Receipt hash',
|
|
764
|
+
status: cs.witnessStatus === 'verified' && cs.hashBound ? 'ok' : 'skip',
|
|
765
|
+
detail: cs.witnessStatus === 'verified' && cs.hashBound
|
|
766
|
+
? 'The gateway confirmation covers this receipt hash.'
|
|
767
|
+
: 'The gateway confirmation and receipt hash could not both be verified.',
|
|
768
|
+
});
|
|
769
|
+
return v;
|
|
770
|
+
}
|
|
771
|
+
return redVerdict(
|
|
772
|
+
'We could not confirm your data was protected.',
|
|
773
|
+
cs.error || 'The device signature on this receipt did not verify.',
|
|
774
|
+
verifyLink,
|
|
775
|
+
);
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
// Bare device envelope.
|
|
779
|
+
if (input && typeof input === 'object') {
|
|
780
|
+
const res = await verifyDeviceReceipt(input);
|
|
781
|
+
const att = (input.claims && input.claims['v3-attestation']) || {};
|
|
782
|
+
if (res.ok) {
|
|
783
|
+
// ⛔ K16 / sak 86, 2026-08-06 — HER STOD `att.tier || 'device-verified'`.
|
|
784
|
+
//
|
|
785
|
+
// `att` er `claims['v3-attestation']`, eit felt AVSENDAREN SKRIV SJØLV.
|
|
786
|
+
// Ei bar konvolutt som sa `tier: 'gateway-countersigned'` fekk difor
|
|
787
|
+
// merkelappen «Gateway-countersigned (strongest)» utan at nokon gateway
|
|
788
|
+
// hadde sett henne og utan at nokon JWKS blei henta.
|
|
789
|
+
//
|
|
790
|
+
// ⚠ DENNE FILA ER EIN AV **TRE** KJELDEKOPIAR av same widget:
|
|
791
|
+
// repo/packages/cloakapi-verify-widget/src/cloakapi-verify.js
|
|
792
|
+
// repo/packages/cloakapi-conformance/vendor/cloakapi-verify.js
|
|
793
|
+
// repo/sdk/typescript/src/browser/verify/cloakapi-verify.js
|
|
794
|
+
// Eg retta den fyrste, bygde portalen på nytt — og defekten stod
|
|
795
|
+
// framleis i bundlen. Det var kopi nummer tre som blei bundla.
|
|
796
|
+
// R63 i reinaste form: tre implementasjonar av éin definisjon.
|
|
797
|
+
//
|
|
798
|
+
// På denne stien er nøyaktig éin ting verifisert: ein einings-signatur
|
|
799
|
+
// mot ein nøkkel som ligg INNI konvolutten. Ingen JWKS, ingen
|
|
800
|
+
// motsignatur, ingen hash-binding. Då ER nivået `device-verified`.
|
|
801
|
+
const verdict = greenVerdict(att, 'device-verified', 1, verifyLink, input);
|
|
802
|
+
if (res.unverifiedFields && res.unverifiedFields.length) {
|
|
803
|
+
verdict.checks.push({
|
|
804
|
+
label: 'Extension fields',
|
|
805
|
+
status: 'skip',
|
|
806
|
+
detail: 'Not semantically checked: ' + res.unverifiedFields.join(', '),
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
return verdict;
|
|
810
|
+
}
|
|
811
|
+
return redVerdict('We could not confirm your data was protected.', res.reason, verifyLink);
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
return redVerdict('Nothing to verify.', 'No receipt was supplied to the widget.', verifyLink);
|
|
815
|
+
} catch (err) {
|
|
816
|
+
return redVerdict(
|
|
817
|
+
'Verification could not run.',
|
|
818
|
+
'Unexpected error while verifying the receipt.',
|
|
819
|
+
verifyLink,
|
|
820
|
+
);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
function greenVerdict(att, tier, count, verifyLink, envelope) {
|
|
825
|
+
const hidden = friendlyCategories(att.detector_categories);
|
|
826
|
+
const destination = typeof att.client_destination === 'string' ? att.client_destination : null;
|
|
827
|
+
const jti = envelope && typeof envelope.jti === 'string' ? envelope.jti : null;
|
|
828
|
+
const noEgress = att.no_raw_pii_egress === true;
|
|
829
|
+
const checks = [
|
|
830
|
+
{
|
|
831
|
+
label: 'On-device signature',
|
|
832
|
+
status: 'ok',
|
|
833
|
+
detail: 'This receipt was signed on your device and the signature checks out — it has not been altered since.',
|
|
834
|
+
},
|
|
835
|
+
{
|
|
836
|
+
label: 'Sensitive data hidden before sending',
|
|
837
|
+
status: noEgress ? 'ok' : 'unknown',
|
|
838
|
+
detail: !noEgress
|
|
839
|
+
? 'This receipt does not attest to hiding sensitive data before sending, so we cannot confirm it here.'
|
|
840
|
+
: hidden.length
|
|
841
|
+
? 'Replaced with stand-in values before anything left this device: ' +
|
|
842
|
+
hidden.join(', ') +
|
|
843
|
+
'. That names the kind of stand-in used, not what the engine decided each detail was.'
|
|
844
|
+
: 'This receipt attests that on-device protection ran for this send; it does not prove every value was detected.',
|
|
845
|
+
},
|
|
846
|
+
];
|
|
847
|
+
if (count > 1) {
|
|
848
|
+
checks.push({
|
|
849
|
+
label: 'Unbroken history',
|
|
850
|
+
status: 'ok',
|
|
851
|
+
detail: 'All ' + count + ' receipts in this session form an unbroken, tamper-evident chain.',
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
return {
|
|
855
|
+
ok: true,
|
|
856
|
+
status: 'partial',
|
|
857
|
+
tier,
|
|
858
|
+
headline: 'Receipt signature verified — redaction claim is not an egress measurement',
|
|
859
|
+
detail:
|
|
860
|
+
'The signature confirms this receipt has not changed. It does not prove what request bytes reached a provider.',
|
|
861
|
+
hidden,
|
|
862
|
+
destination,
|
|
863
|
+
jti,
|
|
864
|
+
reasons: [],
|
|
865
|
+
checks,
|
|
866
|
+
verifyLink,
|
|
867
|
+
tierLabel: tierLabel(tier),
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
function redVerdict(headline, reason, verifyLink) {
|
|
872
|
+
return {
|
|
873
|
+
ok: false,
|
|
874
|
+
status: 'failed',
|
|
875
|
+
tier: 'unverified',
|
|
876
|
+
headline: headline,
|
|
877
|
+
detail:
|
|
878
|
+
'This means we could NOT prove your sensitive data was hidden before it was sent. Do not rely on this receipt — contact the app’s provider.',
|
|
879
|
+
hidden: [],
|
|
880
|
+
destination: null,
|
|
881
|
+
jti: null,
|
|
882
|
+
reasons: [reason],
|
|
883
|
+
checks: [
|
|
884
|
+
{ label: 'Cryptographic check', status: 'fail', detail: reason },
|
|
885
|
+
],
|
|
886
|
+
verifyLink,
|
|
887
|
+
tierLabel: 'Not verified',
|
|
888
|
+
};
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
function tierLabel(tier) {
|
|
892
|
+
switch (tier) {
|
|
893
|
+
case 'gateway-countersigned':
|
|
894
|
+
return 'Gateway-countersigned (strongest)';
|
|
895
|
+
case 'beacon-anchored':
|
|
896
|
+
return 'On-device verified + anchored';
|
|
897
|
+
case 'local-only':
|
|
898
|
+
return 'On-device verified';
|
|
899
|
+
default:
|
|
900
|
+
return 'On-device verified';
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
905
|
+
// 6. Data loading (public verify path + JWKS — no account).
|
|
906
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
907
|
+
|
|
908
|
+
/** Fetch a receipt by a UUID-shaped opaque JTI from the fixed gateway. */
|
|
909
|
+
export async function fetchReceiptByJti(jti) {
|
|
910
|
+
if (typeof jti !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(jti)) {
|
|
911
|
+
throw new Error('receipt identifier is invalid');
|
|
912
|
+
}
|
|
913
|
+
const res = await fetch('https://api.cloakapi.io/api/v1/receipts/by-jti/' + jti, {
|
|
914
|
+
headers: { accept: 'application/json' },
|
|
915
|
+
credentials: 'omit',
|
|
916
|
+
signal: AbortSignal.timeout(12000),
|
|
917
|
+
}).catch(() => { throw new Error('receipt lookup failed'); });
|
|
918
|
+
if (!res.ok) throw new Error('No receipt found for that ID (HTTP ' + res.status + ').');
|
|
919
|
+
const data = parseStrictJson(await res.text());
|
|
920
|
+
return data && data.receipt ? data.receipt : data;
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
/** Fetch JWKS from the fixed gateway origin. Null on failure. */
|
|
924
|
+
export async function fetchJwks() {
|
|
925
|
+
try {
|
|
926
|
+
const res = await fetch('https://api.cloakapi.io/.well-known/jwks.json', {
|
|
927
|
+
signal: AbortSignal.timeout(6000), credentials: 'omit',
|
|
928
|
+
});
|
|
929
|
+
if (res.ok) return await res.text();
|
|
930
|
+
} catch {
|
|
931
|
+
/* offline — caller may pass a cached copy */
|
|
932
|
+
}
|
|
933
|
+
return null;
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
937
|
+
// 7. The web component: <cloakapi-verify>
|
|
938
|
+
// CSP-safe (no inline scripts/handlers/styles; constructable stylesheet in
|
|
939
|
+
// a shadow root), theme-able (CSS custom properties + `theme` attr), and a
|
|
940
|
+
// one-tag embed for builders.
|
|
941
|
+
// ─────────────────────────────────────────────────────────────────────────
|
|
942
|
+
|
|
943
|
+
const WIDGET_CSS = `
|
|
944
|
+
:host{
|
|
945
|
+
--cv-radius: 14px;
|
|
946
|
+
--cv-font: system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
|
|
947
|
+
--cv-bg: #ffffff;
|
|
948
|
+
--cv-fg: #10233b;
|
|
949
|
+
--cv-muted: #5b6b7f;
|
|
950
|
+
--cv-border: #e2e8f0;
|
|
951
|
+
--cv-ok: #0f9d58;
|
|
952
|
+
--cv-ok-bg: #e9f8ef;
|
|
953
|
+
--cv-ok-border: #b7e6c7;
|
|
954
|
+
--cv-fail: #d23f36;
|
|
955
|
+
--cv-fail-bg: #fdecea;
|
|
956
|
+
--cv-fail-border: #f6c3bf;
|
|
957
|
+
--cv-accent: #1c6ff0;
|
|
958
|
+
--cv-shadow: 0 1px 3px rgba(16,35,59,.08), 0 6px 24px rgba(16,35,59,.06);
|
|
959
|
+
display:block;
|
|
960
|
+
max-width:520px;
|
|
961
|
+
font-family:var(--cv-font);
|
|
962
|
+
color:var(--cv-fg);
|
|
963
|
+
-webkit-font-smoothing:antialiased;
|
|
964
|
+
}
|
|
965
|
+
:host([theme="dark"]){
|
|
966
|
+
--cv-bg:#0f1826; --cv-fg:#e8eef7; --cv-muted:#9db0c6; --cv-border:#25344a;
|
|
967
|
+
--cv-ok:#4ecb83; --cv-ok-bg:#12261b; --cv-ok-border:#1f4c33;
|
|
968
|
+
--cv-fail:#ff7a70; --cv-fail-bg:#2a1513; --cv-fail-border:#5a2320;
|
|
969
|
+
--cv-accent:#5fa0ff; --cv-shadow:0 1px 3px rgba(0,0,0,.4);
|
|
970
|
+
}
|
|
971
|
+
*{box-sizing:border-box}
|
|
972
|
+
.card{
|
|
973
|
+
background:var(--cv-bg); border:1px solid var(--cv-border);
|
|
974
|
+
border-radius:var(--cv-radius); box-shadow:var(--cv-shadow);
|
|
975
|
+
padding:18px 18px 16px; overflow:hidden;
|
|
976
|
+
}
|
|
977
|
+
.card.ok{border-color:var(--cv-ok-border)}
|
|
978
|
+
.card.fail{border-color:var(--cv-fail-border)}
|
|
979
|
+
.head{display:flex;gap:12px;align-items:flex-start}
|
|
980
|
+
.badge{
|
|
981
|
+
flex:0 0 auto;width:38px;height:38px;border-radius:50%;
|
|
982
|
+
display:flex;align-items:center;justify-content:center;
|
|
983
|
+
font-size:20px;font-weight:700;line-height:1;color:#fff;
|
|
984
|
+
}
|
|
985
|
+
.ok .badge{background:var(--cv-ok)}
|
|
986
|
+
.fail .badge{background:var(--cv-fail)}
|
|
987
|
+
.loading .badge{background:var(--cv-muted)}
|
|
988
|
+
.htext{flex:1;min-width:0}
|
|
989
|
+
.headline{font-size:15.5px;font-weight:650;line-height:1.3;margin:2px 0 3px}
|
|
990
|
+
.ok .headline{color:var(--cv-ok)}
|
|
991
|
+
.fail .headline{color:var(--cv-fail)}
|
|
992
|
+
.detail{font-size:13px;line-height:1.5;color:var(--cv-muted);margin:0}
|
|
993
|
+
.tier{
|
|
994
|
+
display:inline-block;margin-top:9px;font-size:11px;font-weight:600;
|
|
995
|
+
letter-spacing:.02em;padding:3px 9px;border-radius:999px;
|
|
996
|
+
background:var(--cv-ok-bg);color:var(--cv-ok);border:1px solid var(--cv-ok-border);
|
|
997
|
+
}
|
|
998
|
+
.fail .tier{background:var(--cv-fail-bg);color:var(--cv-fail);border-color:var(--cv-fail-border)}
|
|
999
|
+
.hidden-box{
|
|
1000
|
+
margin-top:13px;background:var(--cv-ok-bg);border:1px solid var(--cv-ok-border);
|
|
1001
|
+
border-radius:10px;padding:11px 12px;
|
|
1002
|
+
}
|
|
1003
|
+
.hidden-box h4{margin:0 0 6px;font-size:12px;font-weight:650;color:var(--cv-fg);text-transform:none}
|
|
1004
|
+
.chips{display:flex;flex-wrap:wrap;gap:6px}
|
|
1005
|
+
.chip{font-size:11.5px;background:var(--cv-bg);border:1px solid var(--cv-ok-border);
|
|
1006
|
+
color:var(--cv-fg);border-radius:7px;padding:3px 8px}
|
|
1007
|
+
details{margin-top:12px;border-top:1px solid var(--cv-border);padding-top:10px}
|
|
1008
|
+
summary{cursor:pointer;font-size:12.5px;font-weight:600;color:var(--cv-accent);
|
|
1009
|
+
list-style:none;user-select:none}
|
|
1010
|
+
summary::-webkit-details-marker{display:none}
|
|
1011
|
+
summary::before{content:"› ";display:inline-block;transition:transform .15s}
|
|
1012
|
+
details[open] summary::before{content:"⌄ "}
|
|
1013
|
+
.checks{list-style:none;margin:10px 0 0;padding:0}
|
|
1014
|
+
.checks li{display:flex;gap:8px;font-size:12px;line-height:1.45;margin-bottom:9px;color:var(--cv-muted)}
|
|
1015
|
+
.checks .mk{flex:0 0 auto;font-weight:700}
|
|
1016
|
+
.checks .ok .mk,.mk.ok{color:var(--cv-ok)}
|
|
1017
|
+
.mk.fail{color:var(--cv-fail)}
|
|
1018
|
+
.mk.skip{color:var(--cv-muted)}
|
|
1019
|
+
.checks b{color:var(--cv-fg);font-weight:600}
|
|
1020
|
+
.foot{margin-top:13px;display:flex;flex-wrap:wrap;gap:10px;align-items:center;
|
|
1021
|
+
font-size:11.5px;color:var(--cv-muted)}
|
|
1022
|
+
.foot a{color:var(--cv-accent);text-decoration:none;font-weight:600}
|
|
1023
|
+
.foot a:hover{text-decoration:underline}
|
|
1024
|
+
.foot button.act{background:none;border:0;padding:0;margin:0;cursor:pointer;
|
|
1025
|
+
color:var(--cv-accent);font:inherit;font-size:11.5px;font-weight:600;line-height:1.4}
|
|
1026
|
+
.foot button.act:hover{text-decoration:underline}
|
|
1027
|
+
.jti{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:10.5px;
|
|
1028
|
+
color:var(--cv-muted);word-break:break-all}
|
|
1029
|
+
.spinner{width:16px;height:16px;border:2px solid var(--cv-border);
|
|
1030
|
+
border-top-color:var(--cv-accent);border-radius:50%;animation:cv-spin .7s linear infinite}
|
|
1031
|
+
@keyframes cv-spin{to{transform:rotate(360deg)}}
|
|
1032
|
+
@media (prefers-reduced-motion:reduce){.spinner{animation:none}}
|
|
1033
|
+
`;
|
|
1034
|
+
|
|
1035
|
+
function h(tag, attrs, children) {
|
|
1036
|
+
const el = document.createElement(tag);
|
|
1037
|
+
if (attrs) {
|
|
1038
|
+
for (const [k, v] of Object.entries(attrs)) {
|
|
1039
|
+
if (v == null) continue;
|
|
1040
|
+
if (k === 'class') el.className = v;
|
|
1041
|
+
else if (k === 'text') el.textContent = v;
|
|
1042
|
+
else el.setAttribute(k, v);
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
if (children) for (const c of children) if (c) el.appendChild(c);
|
|
1046
|
+
return el;
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
// Guard: only register the element in a real DOM (skips Node unit tests).
|
|
1050
|
+
if (typeof window !== 'undefined' && typeof HTMLElement !== 'undefined' && window.customElements) {
|
|
1051
|
+
let sheet = null;
|
|
1052
|
+
try {
|
|
1053
|
+
sheet = new CSSStyleSheet();
|
|
1054
|
+
sheet.replaceSync(WIDGET_CSS);
|
|
1055
|
+
} catch {
|
|
1056
|
+
sheet = null; // very old engine — fall back to <style>
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
class CloakapiVerify extends HTMLElement {
|
|
1060
|
+
static get observedAttributes() {
|
|
1061
|
+
return ['jti', 'theme'];
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
constructor() {
|
|
1065
|
+
super();
|
|
1066
|
+
this._root = this.attachShadow({ mode: 'open' });
|
|
1067
|
+
if (sheet) this._root.adoptedStyleSheets = [sheet];
|
|
1068
|
+
else {
|
|
1069
|
+
const st = document.createElement('style');
|
|
1070
|
+
st.textContent = WIDGET_CSS;
|
|
1071
|
+
this._root.appendChild(st);
|
|
1072
|
+
}
|
|
1073
|
+
this._mount = document.createElement('div');
|
|
1074
|
+
this._root.appendChild(this._mount);
|
|
1075
|
+
this._receipts = null; // programmatic override
|
|
1076
|
+
this._rawJson = null;
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
/** Programmatic API: set receipt(s) directly (fully offline). */
|
|
1080
|
+
set receipt(value) {
|
|
1081
|
+
this.setReceipts(value);
|
|
1082
|
+
}
|
|
1083
|
+
set receipts(value) {
|
|
1084
|
+
this.setReceipts(value);
|
|
1085
|
+
}
|
|
1086
|
+
setReceipts(value) {
|
|
1087
|
+
if (typeof value === 'string' || value instanceof Uint8Array) {
|
|
1088
|
+
this._rawJson = value;
|
|
1089
|
+
this._receipts = null;
|
|
1090
|
+
} else {
|
|
1091
|
+
this._rawJson = null;
|
|
1092
|
+
this._receipts = value;
|
|
1093
|
+
}
|
|
1094
|
+
this._run();
|
|
1095
|
+
}
|
|
1096
|
+
setReceiptJson(raw) {
|
|
1097
|
+
this._rawJson = raw;
|
|
1098
|
+
this._receipts = null;
|
|
1099
|
+
this._run();
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
connectedCallback() {
|
|
1103
|
+
this._run();
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
attributeChangedCallback() {
|
|
1107
|
+
if (this.isConnected) this._run();
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
async _load() {
|
|
1111
|
+
// Priority: programmatic → inline <script type=application/json> → opaque jti.
|
|
1112
|
+
if (this._rawJson != null) return parseStrictJson(rawJsonText(this._rawJson));
|
|
1113
|
+
if (this._receipts != null) return this._receipts;
|
|
1114
|
+
|
|
1115
|
+
const inline = this.querySelector('script[type="application/json"]');
|
|
1116
|
+
if (inline && inline.textContent && inline.textContent.trim()) {
|
|
1117
|
+
return parseStrictJson(inline.textContent);
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
const jti = this.getAttribute('jti');
|
|
1121
|
+
if (jti) return fetchReceiptByJti(jti.trim());
|
|
1122
|
+
|
|
1123
|
+
return null;
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
async _run() {
|
|
1127
|
+
const runId = (this._runId || 0) + 1;
|
|
1128
|
+
this._runId = runId;
|
|
1129
|
+
this._renderLoading();
|
|
1130
|
+
try {
|
|
1131
|
+
const inlineNode = this.querySelector('script[type="application/json"]');
|
|
1132
|
+
const rawInput = this._rawJson ?? (this._receipts == null && inlineNode && inlineNode.textContent && inlineNode.textContent.trim()
|
|
1133
|
+
? inlineNode.textContent
|
|
1134
|
+
: null);
|
|
1135
|
+
const input = await this._load();
|
|
1136
|
+
if (runId !== this._runId) return;
|
|
1137
|
+
this._lastInput = input; // #137-A: keep the actual receipt for view/download
|
|
1138
|
+
if (input == null) {
|
|
1139
|
+
this._renderError('No receipt to verify', 'Add an opaque jti="…" or an inline receipt to this widget.');
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
const verifyLink = this.getAttribute('verify-link') || 'https://signedreceipts.org';
|
|
1143
|
+
|
|
1144
|
+
// Only fetch JWKS when we actually have a countersigned result.
|
|
1145
|
+
let jwksJson = null;
|
|
1146
|
+
if (isCountersignedResult(input) && this.getAttribute('offline') == null) {
|
|
1147
|
+
jwksJson = await fetchJwks();
|
|
1148
|
+
}
|
|
1149
|
+
if (runId !== this._runId) return;
|
|
1150
|
+
const verdict = rawInput != null
|
|
1151
|
+
? await verifyReceiptJson(rawInput, { jwksJson, verifyLink })
|
|
1152
|
+
: await verifyReceipt(input, { jwksJson, verifyLink });
|
|
1153
|
+
if (runId !== this._runId) return;
|
|
1154
|
+
this._renderVerdict(verdict);
|
|
1155
|
+
this.dispatchEvent(new CustomEvent('cloakapi-verify', { detail: verdict, bubbles: true }));
|
|
1156
|
+
} catch (err) {
|
|
1157
|
+
if (runId !== this._runId) return;
|
|
1158
|
+
this._renderError('Verification could not run', 'Unexpected error while verifying the receipt.');
|
|
1159
|
+
this.dispatchEvent(
|
|
1160
|
+
new CustomEvent('cloakapi-verify', {
|
|
1161
|
+
detail: { ok: false, status: 'error', reasons: ['Unexpected error while verifying the receipt.'] },
|
|
1162
|
+
bubbles: true,
|
|
1163
|
+
}),
|
|
1164
|
+
);
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
_clear() {
|
|
1169
|
+
this._mount.textContent = '';
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
_renderLoading() {
|
|
1173
|
+
this._clear();
|
|
1174
|
+
const card = h('div', { class: 'card loading' }, [
|
|
1175
|
+
h('div', { class: 'head' }, [
|
|
1176
|
+
h('div', { class: 'badge' }, [h('div', { class: 'spinner' })]),
|
|
1177
|
+
h('div', { class: 'htext' }, [
|
|
1178
|
+
h('p', { class: 'headline', text: 'Checking your privacy receipt…' }),
|
|
1179
|
+
h('p', { class: 'detail', text: 'Verifying the cryptographic proof here in your browser.' }),
|
|
1180
|
+
]),
|
|
1181
|
+
]),
|
|
1182
|
+
]);
|
|
1183
|
+
this._mount.appendChild(card);
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
_renderError(headline, detail) {
|
|
1187
|
+
this._clear();
|
|
1188
|
+
const card = h('div', { class: 'card fail' }, [
|
|
1189
|
+
h('div', { class: 'head' }, [
|
|
1190
|
+
h('div', { class: 'badge', text: '!' }),
|
|
1191
|
+
h('div', { class: 'htext' }, [
|
|
1192
|
+
h('p', { class: 'headline', text: headline }),
|
|
1193
|
+
h('p', { class: 'detail', text: detail }),
|
|
1194
|
+
]),
|
|
1195
|
+
]),
|
|
1196
|
+
]);
|
|
1197
|
+
this._mount.appendChild(card);
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
_renderVerdict(v) {
|
|
1201
|
+
this._clear();
|
|
1202
|
+
const ok = v.ok;
|
|
1203
|
+
const card = h('div', { class: 'card ' + (ok ? 'ok' : 'fail') });
|
|
1204
|
+
|
|
1205
|
+
const head = h('div', { class: 'head' }, [
|
|
1206
|
+
h('div', { class: 'badge', text: ok ? '✓' : '✕' }),
|
|
1207
|
+
h('div', { class: 'htext' }, [
|
|
1208
|
+
h('p', { class: 'headline', text: v.headline }),
|
|
1209
|
+
h('p', { class: 'detail', text: v.detail }),
|
|
1210
|
+
v.tierLabel ? h('span', { class: 'tier', text: v.tierLabel }) : null,
|
|
1211
|
+
]),
|
|
1212
|
+
]);
|
|
1213
|
+
card.appendChild(head);
|
|
1214
|
+
|
|
1215
|
+
if (ok && v.hidden && v.hidden.length) {
|
|
1216
|
+
const box = h('div', { class: 'hidden-box' }, [
|
|
1217
|
+
// ⛔ NARROWED 2026-09-14 (rad 32). Was "What was hidden before sending",
|
|
1218
|
+
// which frames the chips as the detector's FINDINGS. They are the
|
|
1219
|
+
// classes that picked each STAND-IN, and 3 of 44 measured person
|
|
1220
|
+
// names carried a non-PERSON class (see CATEGORY_LABELS).
|
|
1221
|
+
h('h4', { text: 'Kinds of stand-in used before sending' }),
|
|
1222
|
+
h('div', { class: 'chips' }, v.hidden.map((x) => h('span', { class: 'chip', text: x }))),
|
|
1223
|
+
]);
|
|
1224
|
+
card.appendChild(box);
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
// How we know (the crypto checks) — expandable, plain language.
|
|
1228
|
+
const det = h('details');
|
|
1229
|
+
det.appendChild(h('summary', { text: ok ? 'How we know this' : 'Why this failed' }));
|
|
1230
|
+
const list = h('ul', { class: 'checks' });
|
|
1231
|
+
for (const c of v.checks || []) {
|
|
1232
|
+
const mk = c.status === 'ok' ? '✓' : c.status === 'fail' ? '✕' : '–';
|
|
1233
|
+
list.appendChild(
|
|
1234
|
+
h('li', {}, [
|
|
1235
|
+
h('span', { class: 'mk ' + c.status, text: mk }),
|
|
1236
|
+
h('span', {}, [h('b', { text: c.label + ': ' }), document.createTextNode(c.detail)]),
|
|
1237
|
+
]),
|
|
1238
|
+
);
|
|
1239
|
+
}
|
|
1240
|
+
det.appendChild(list);
|
|
1241
|
+
card.appendChild(det);
|
|
1242
|
+
|
|
1243
|
+
const foot = h('div', { class: 'foot' });
|
|
1244
|
+
|
|
1245
|
+
// #137-A: link to THE ACTUAL receipt just verified — open/download the real
|
|
1246
|
+
// signed artefact — not only the spec homepage. Honest per-receipt permalink:
|
|
1247
|
+
// if the widget was pointed at a resolvable public receipt (opaque jti),
|
|
1248
|
+
// also surface that stable link; otherwise the portable JSON IS the artefact.
|
|
1249
|
+
if (this._lastInput != null) {
|
|
1250
|
+
const viewBtn = h('button', { class: 'act', type: 'button', text: 'View this receipt' });
|
|
1251
|
+
viewBtn.addEventListener('click', () => this._openReceipt());
|
|
1252
|
+
foot.appendChild(viewBtn);
|
|
1253
|
+
const dlBtn = h('button', { class: 'act', type: 'button', text: 'Download (.json)' });
|
|
1254
|
+
dlBtn.addEventListener('click', () => this._downloadReceipt());
|
|
1255
|
+
foot.appendChild(dlBtn);
|
|
1256
|
+
}
|
|
1257
|
+
const permalink = this._receiptPermalink();
|
|
1258
|
+
if (permalink) {
|
|
1259
|
+
foot.appendChild(
|
|
1260
|
+
h('a', { class: 'act', href: permalink, target: '_blank', rel: 'noopener noreferrer', text: 'Permalink ↗' }),
|
|
1261
|
+
);
|
|
1262
|
+
}
|
|
1263
|
+
const link = h('a', {
|
|
1264
|
+
href: v.verifyLink || 'https://signedreceipts.org',
|
|
1265
|
+
target: '_blank',
|
|
1266
|
+
rel: 'noopener noreferrer',
|
|
1267
|
+
text: 'About signed receipts ↗',
|
|
1268
|
+
});
|
|
1269
|
+
foot.appendChild(link);
|
|
1270
|
+
if (v.jti) foot.appendChild(h('span', { class: 'jti', text: 'Receipt ' + v.jti }));
|
|
1271
|
+
card.appendChild(foot);
|
|
1272
|
+
|
|
1273
|
+
this._mount.appendChild(card);
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
// ── #137-A helpers: the actual receipt as a portable, honest artefact. ──
|
|
1277
|
+
_jtiOf(x) {
|
|
1278
|
+
if (!x || typeof x !== 'object') return null;
|
|
1279
|
+
if (Array.isArray(x)) return this._jtiOf(x[x.length - 1]);
|
|
1280
|
+
if (x.receipt) return this._jtiOf(x.receipt);
|
|
1281
|
+
return typeof x.jti === 'string' ? x.jti : null;
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
_receiptBlobUrl() {
|
|
1285
|
+
const data = JSON.stringify(this._lastInput, null, 2);
|
|
1286
|
+
return URL.createObjectURL(new Blob([data], { type: 'application/json' }));
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
_openReceipt() {
|
|
1290
|
+
try {
|
|
1291
|
+
const url = this._receiptBlobUrl();
|
|
1292
|
+
window.open(url, '_blank', 'noopener');
|
|
1293
|
+
setTimeout(() => URL.revokeObjectURL(url), 10000);
|
|
1294
|
+
} catch (_) {
|
|
1295
|
+
this._downloadReceipt();
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
_downloadReceipt() {
|
|
1300
|
+
try {
|
|
1301
|
+
const url = this._receiptBlobUrl();
|
|
1302
|
+
const jti = this._jtiOf(this._lastInput);
|
|
1303
|
+
const a = document.createElement('a');
|
|
1304
|
+
a.href = url;
|
|
1305
|
+
a.download = 'cloakapi-receipt-' + (jti || 'signed') + '.json';
|
|
1306
|
+
document.body.appendChild(a);
|
|
1307
|
+
a.click();
|
|
1308
|
+
a.remove();
|
|
1309
|
+
setTimeout(() => URL.revokeObjectURL(url), 5000);
|
|
1310
|
+
} catch (_) {
|
|
1311
|
+
/* no-op */
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
/** A stable public permalink for THIS receipt when it came from an opaque
|
|
1316
|
+
* UUID on the fixed public receipts API.
|
|
1317
|
+
* Returns null for purely local/inline receipts (honest: no fake link). */
|
|
1318
|
+
_receiptPermalink() {
|
|
1319
|
+
const fromServer = this.getAttribute('jti');
|
|
1320
|
+
const jti = fromServer || this._jtiOf(this._lastInput);
|
|
1321
|
+
if (jti && fromServer && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(jti)) {
|
|
1322
|
+
return 'https://api.cloakapi.io/api/v1/receipts/by-jti/' + jti;
|
|
1323
|
+
}
|
|
1324
|
+
return null;
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
if (!window.customElements.get('cloakapi-verify')) {
|
|
1329
|
+
window.customElements.define('cloakapi-verify', CloakapiVerify);
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
/** Verify raw JSON while rejecting duplicate keys and lossy values before object parsing. */
|
|
1334
|
+
export async function verifyCountersignedJson(raw, jwksJson) {
|
|
1335
|
+
const text = rawJsonText(raw);
|
|
1336
|
+
return verifyCountersigned(parseStrictJson(text), jwksJson);
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
/** Verify JSON text without discarding duplicate keys or lossy numeric/string values first. */
|
|
1340
|
+
export async function verifyReceiptJson(raw, opts = {}) {
|
|
1341
|
+
const text = rawJsonText(raw);
|
|
1342
|
+
return verifyReceipt(parseStrictJson(text), opts);
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
function rawJsonText(raw) {
|
|
1346
|
+
if (typeof raw === 'string') return raw;
|
|
1347
|
+
if (!(raw instanceof Uint8Array)) throw new TypeError('JSON input must be text or UTF-8 bytes');
|
|
1348
|
+
if (raw.byteLength > 8 * 1024 * 1024) throw new SyntaxError('JSON input is too large');
|
|
1349
|
+
return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(raw);
|
|
1350
|
+
}
|