-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproof.html
More file actions
691 lines (607 loc) · 21.3 KB
/
proof.html
File metadata and controls
691 lines (607 loc) · 21.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Provable - View Proof</title>
<meta name="description" content="View and verify any Provable proof">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link id="ui-stylesheet" rel="stylesheet" href="https://cdn.jsdelivr.net/npm/provable-sdk-ui@0.0.6/dist/browser/style.css">
<style>
body {
margin: 0;
padding: 24px;
font-family: 'Roboto Condensed', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: #f5f6f7;
color: #2b2d2e;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.header {
margin-bottom: 24px;
}
.header h1 {
margin: 0 0 8px;
font-size: 1.5rem;
color: #2b2d2e;
}
.header p {
margin: 0;
color: #6b6d6e;
font-size: 0.9rem;
}
.upload-area {
background: white;
border: 2px dashed #d4d6d7;
border-radius: 8px;
padding: 48px 24px;
text-align: center;
transition: border-color 200ms;
}
.upload-area.drag-over {
border-color: #6b7176;
background: rgba(107, 113, 118, 0.05);
}
.upload-area p {
margin: 0 0 16px;
color: #6b6d6e;
}
.upload-button {
appearance: none;
background: #6b7176;
color: white;
border: none;
border-radius: 6px;
padding: 10px 20px;
font-size: 0.9rem;
cursor: pointer;
transition: background 200ms;
}
.upload-button:hover {
background: #4a4d4e;
}
.viewer-wrapper {
background: white;
border: 1px solid #d4d6d7;
border-radius: 8px;
padding: 24px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.error-message {
color: #dc2626;
background: #fee2e2;
border: 1px solid #fecaca;
border-radius: 4px;
padding: 12px;
margin-bottom: 16px;
font-size: 0.9rem;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Provable Proof Viewer</h1>
<p id="page-url">Loading...</p>
</div>
<div id="error-container"></div>
<div id="upload-area" class="upload-area">
<p>Drag & drop a Provable proof JSON file here or</p>
<button id="upload-button" class="upload-button">Choose File</button>
<input type="file" id="file-input" accept=".json,application/json" hidden>
</div>
<div id="viewer-wrapper" class="viewer-wrapper" hidden>
<div id="proof-root"></div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/js-sha3@0.9.3/build/sha3.min.js"></script>
<script>
const pageUrlElement = document.getElementById('page-url');
const uploadArea = document.getElementById('upload-area');
const viewerWrapper = document.getElementById('viewer-wrapper');
const proofRoot = document.getElementById('proof-root');
const uploadButton = document.getElementById('upload-button');
const fileInput = document.getElementById('file-input');
const errorContainer = document.getElementById('error-container');
let unmountViewer = null;
const uiParams = new URLSearchParams(window.location.search);
const uiMode = uiParams.get('ui');
const uiVersion = uiParams.get('ui_version') || '0.0.6';
const uiBaseOverride = uiParams.get('ui_base');
const uiBundleBase = uiMode === 'local'
? (uiBaseOverride || 'http://localhost:8080').replace(/\/+$/, '')
: `https://cdn.jsdelivr.net/npm/provable-sdk-ui@${encodeURIComponent(uiVersion)}/dist/browser`;
function loadExternalScript(src) {
return new Promise((resolve, reject) => {
const existingScript = document.querySelector(`script[data-ui-bundle-src="${src}"]`);
if (existingScript) {
resolve();
return;
}
const script = document.createElement('script');
script.src = src;
script.async = true;
script.dataset.uiBundleSrc = src;
script.onload = () => resolve();
script.onerror = () => reject(new Error(`Failed to load UI bundle from ${src}`));
document.head.appendChild(script);
});
}
async function ensureUiBundleLoaded() {
const stylesheet = document.getElementById('ui-stylesheet');
if (stylesheet && stylesheet instanceof HTMLLinkElement) {
stylesheet.href = `${uiBundleBase}/style.css`;
}
if (window.ProvableSdkUi && typeof window.ProvableSdkUi.mountProofViewer === 'function') {
return true;
}
await loadExternalScript(`${uiBundleBase}/provable-sdk-ui.iife.js`);
return !!(window.ProvableSdkUi && typeof window.ProvableSdkUi.mountProofViewer === 'function');
}
function setError(message) {
errorContainer.innerHTML = `<div class="error-message">${message}</div>`;
}
function clearError() {
errorContainer.innerHTML = '';
}
function isRecord(value) {
return typeof value === 'object' && value !== null;
}
function readPath(root, path) {
let current = root;
for (const segment of path) {
if (!isRecord(current) || !(segment in current)) {
return undefined;
}
current = current[segment];
}
return current;
}
function firstString(...values) {
for (const value of values) {
if (typeof value === 'string' && value.length > 0) {
return value;
}
}
return undefined;
}
function decodeHexString(value) {
if (!value || typeof value !== 'string') return undefined;
const normalized = value.startsWith('0x') ? value.slice(2) : value;
if (normalized.length === 0 || normalized.length % 2 !== 0) return undefined;
if (!/^[0-9a-fA-F]+$/.test(normalized)) return undefined;
const bytes = new Uint8Array(normalized.length / 2);
for (let i = 0; i < normalized.length; i += 2) {
bytes[i / 2] = Number.parseInt(normalized.slice(i, i + 2), 16);
}
return new TextDecoder().decode(bytes);
}
function decodeBase64ToBytes(value) {
if (typeof value !== 'string') return undefined;
const normalized = value.trim();
if (!normalized || normalized.length % 4 !== 0) return undefined;
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(normalized)) return undefined;
try {
const binary = atob(normalized);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i += 1) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
} catch {
return undefined;
}
}
function normalizeHashAlgorithm(value) {
if (typeof value !== 'string') return 'sha256';
const normalized = value.toLowerCase().replace(/_/g, '').replace(/-/g, '');
return normalized === 'keccak256' ? 'keccak256' : 'sha256';
}
function toDataTypeLabel(value) {
if (!value) return undefined;
const decoded = decodeHexString(value) || value;
return decoded.replace(/\u0000+$/g, '');
}
function uniqueStrings(values) {
const result = [];
const seen = new Set();
for (const value of values) {
if (!value || seen.has(value)) continue;
seen.add(value);
result.push(value);
}
return result;
}
function extractTopLevelDataJson(jsonText) {
const marker = '"data"';
const markerIndex = jsonText.indexOf(marker);
if (markerIndex < 0) return undefined;
const colon = jsonText.indexOf(':', markerIndex + marker.length);
if (colon < 0) return undefined;
let i = colon + 1;
while (i < jsonText.length && /\s/.test(jsonText[i])) i += 1;
if (i >= jsonText.length) return undefined;
const first = jsonText[i];
if (first === '"') {
let escaped = false;
let j = i + 1;
while (j < jsonText.length) {
const ch = jsonText[j];
if (escaped) {
escaped = false;
} else if (ch === '\\') {
escaped = true;
} else if (ch === '"') {
return jsonText.slice(i, j + 1);
}
j += 1;
}
return undefined;
}
if (first === '{' || first === '[') {
const stack = [first];
let inString = false;
let escaped = false;
let j = i + 1;
while (j < jsonText.length) {
const ch = jsonText[j];
if (inString) {
if (escaped) escaped = false;
else if (ch === '\\') escaped = true;
else if (ch === '"') inString = false;
j += 1;
continue;
}
if (ch === '"') {
inString = true;
j += 1;
continue;
}
if (ch === '{' || ch === '[') stack.push(ch);
if (ch === '}' || ch === ']') {
stack.pop();
if (stack.length === 0) return jsonText.slice(i, j + 1);
}
j += 1;
}
}
let j = i;
while (j < jsonText.length && jsonText[j] !== ',' && jsonText[j] !== '}') j += 1;
return jsonText.slice(i, j).trim();
}
async function sha256Hex(bytes) {
const hashBuffer = await crypto.subtle.digest('SHA-256', bytes);
return Array.from(new Uint8Array(hashBuffer)).map(b => b.toString(16).padStart(2, '0')).join('');
}
function bytesToHex(bytes) {
return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
}
function createEnvelopeAdapter(rawEnvelope, rawDataJson) {
const data = rawEnvelope.data;
const kayros = rawEnvelope.kayros || {};
function hasTimestampResponse() {
return readPath(kayros, ['timestamp', 'response']) !== undefined;
}
function isV0() {
return readPath(kayros, ['data', 'data_item_hex']) !== undefined
|| readPath(kayros, ['data', 'computed_hash_hex']) !== undefined
|| readPath(kayros, ['success']) !== undefined;
}
function getTimestampResponse() {
return readPath(kayros, ['timestamp', 'response']);
}
function getRegisterResponse() {
const response = getTimestampResponse();
return readPath(response, ['response']) || response;
}
function getDataHash() {
if (hasTimestampResponse()) {
return firstString(
readPath(kayros, ['hash']),
readPath(getRegisterResponse(), ['data_item_hex']),
readPath(getRegisterResponse(), ['data', 'data_item_hex']),
readPath(getTimestampResponse(), ['data', 'data_item_hex']),
readPath(kayros, ['data', 'data_item_hex'])
);
}
return firstString(
readPath(kayros, ['hash']),
readPath(kayros, ['data', 'data_item_hex']),
readPath(kayros, ['timestamp', 'response', 'data', 'data_item_hex'])
);
}
function getDataType() {
const raw = firstString(
readPath(getRegisterResponse(), ['data_type']),
readPath(getRegisterResponse(), ['data', 'data_type']),
readPath(getTimestampResponse(), ['data', 'data_type']),
readPath(kayros, ['data', 'data_type']),
readPath(kayros, ['data_type'])
);
if (raw) return raw;
const hex = firstString(
readPath(getRegisterResponse(), ['data_type_hex']),
readPath(getRegisterResponse(), ['data', 'data_type_hex']),
readPath(getTimestampResponse(), ['data', 'data_type_hex']),
readPath(kayros, ['data', 'data_type_hex']),
readPath(kayros, ['data_type_hex'])
);
if (!hex) return undefined;
return decodeHexString(hex) || hex;
}
function getDataTypeLabel() {
return toDataTypeLabel(getDataType());
}
function getDataTypeLookupCandidates() {
const raw = firstString(
readPath(getRegisterResponse(), ['data_type']),
readPath(getRegisterResponse(), ['data', 'data_type']),
readPath(getTimestampResponse(), ['data', 'data_type']),
readPath(kayros, ['data', 'data_type']),
readPath(kayros, ['data_type'])
);
const decodedRaw = raw ? decodeHexString(raw) : undefined;
const type = getDataType();
const decodedType = type ? decodeHexString(type) : undefined;
const label = getDataTypeLabel();
return uniqueStrings([raw, decodedRaw, type, decodedType, label]);
}
function getKayrosHash() {
return firstString(
readPath(getTimestampResponse(), ['data', 'computed_hash_hex']),
readPath(getRegisterResponse(), ['data', 'computed_hash_hex']),
readPath(getRegisterResponse(), ['computed_hash_hex']),
readPath(getRegisterResponse(), ['hash']),
readPath(kayros, ['data', 'computed_hash_hex'])
);
}
function getTimeUUID() {
return firstString(
readPath(getRegisterResponse(), ['data', 'timeuuid_hex']),
readPath(getRegisterResponse(), ['timeuuid_hex']),
readPath(getRegisterResponse(), ['data', 'timeuuid']),
readPath(getRegisterResponse(), ['timeuuid']),
readPath(getTimestampResponse(), ['data', 'timeuuid_hex']),
readPath(getTimestampResponse(), ['data', 'timeuuid']),
readPath(kayros, ['data', 'timeuuid_hex'])
);
}
function getHashAlgorithm() {
return normalizeHashAlgorithm(readPath(kayros, ['hashAlgorithm']));
}
function getUtf8Bytes(value) {
return new TextEncoder().encode(value);
}
function getObjectBytes() {
if (typeof rawDataJson === 'string') {
return getUtf8Bytes(rawDataJson);
}
return getUtf8Bytes(JSON.stringify(data));
}
function getData() {
if (typeof data !== 'string') {
return getObjectBytes();
}
const base64Bytes = decodeBase64ToBytes(data);
if (isV0() && base64Bytes) {
return base64Bytes;
}
return getUtf8Bytes(data);
}
function getByteCandidates() {
const candidates = [];
const seen = new Set();
function add(bytes) {
if (!bytes) return;
const key = bytesToHex(bytes);
if (seen.has(key)) return;
seen.add(key);
candidates.push(bytes);
}
if (typeof data === 'string') {
const utf8Bytes = getUtf8Bytes(data);
const base64Bytes = decodeBase64ToBytes(data);
if (isV0()) {
add(base64Bytes);
add(utf8Bytes);
} else {
add(utf8Bytes);
add(base64Bytes);
}
return candidates;
}
if (typeof rawDataJson === 'string') {
add(getUtf8Bytes(rawDataJson));
}
add(getUtf8Bytes(JSON.stringify(data)));
return candidates;
}
async function computeDataHash() {
const preferred = getHashAlgorithm();
const alternate = preferred === 'keccak256' ? 'sha256' : 'keccak256';
const expected = getDataHash() ? getDataHash().toLowerCase() : undefined;
async function digest(bytes, algorithm) {
if (algorithm === 'keccak256') {
if (typeof window.keccak256 !== 'function') {
throw new Error('keccak256 helper not available');
}
return window.keccak256(bytes);
}
return sha256Hex(bytes);
}
const candidates = getByteCandidates();
if (expected) {
for (const bytes of candidates) {
const preferredHash = await digest(bytes, preferred);
if (preferredHash === expected) return preferredHash;
const alternateHash = await digest(bytes, alternate);
if (alternateHash === expected) return alternateHash;
}
}
return digest(getData(), preferred);
}
return {
data,
kayros,
getDataHash,
getDataType,
getDataTypeLabel,
getDataTypeLookupCandidates,
getKayrosHash,
getTimeUUID,
getHashAlgorithm,
isV0,
getData,
computeDataHash
};
}
function isEnvelope(value) {
return isRecord(value) && 'data' in value && 'kayros' in value;
}
function unmountExistingViewer() {
if (typeof unmountViewer === 'function') {
unmountViewer();
}
unmountViewer = null;
proofRoot.innerHTML = '';
}
function getDisplayedSource(envelope) {
if (!envelope || !isRecord(envelope.data)) {
return 'Proof loaded';
}
return envelope.data.pageUrl || envelope.data.url || readPath(envelope.data, ['meta', 'url']) || 'Proof loaded';
}
function renderEnvelope(envelope, rawText) {
if (!window.ProvableSdkUi || typeof window.ProvableSdkUi.mountProofViewer !== 'function') {
setError('provable-sdk-ui browser bundle did not load.');
return;
}
clearError();
unmountExistingViewer();
const rawDataJson = typeof rawText === 'string' ? extractTopLevelDataJson(rawText) : undefined;
const adapter = createEnvelopeAdapter(envelope, rawDataJson);
uploadArea.hidden = true;
viewerWrapper.hidden = false;
pageUrlElement.textContent = getDisplayedSource(envelope);
unmountViewer = window.ProvableSdkUi.mountProofViewer(proofRoot, {
envelope: adapter,
theme: 'light',
showRemoteRecord: true
});
}
async function parseJsonText(text) {
const parsed = JSON.parse(text);
if (!isEnvelope(parsed)) {
throw new Error('Invalid proof JSON. Expected an envelope with { data, kayros }.');
}
return { parsed, text };
}
async function loadFromUrl(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch proof URL (${response.status})`);
}
const text = await response.text();
const { parsed } = await parseJsonText(text);
renderEnvelope(parsed, text);
}
async function loadFromBase64(dataParam) {
let decoded;
try {
decoded = decodeURIComponent(escape(atob(dataParam)));
} catch {
decoded = atob(dataParam);
}
const { parsed } = await parseJsonText(decoded);
renderEnvelope(parsed, decoded);
}
function loadFromFile(file) {
const reader = new FileReader();
reader.onload = async (event) => {
try {
const text = String(event.target && event.target.result ? event.target.result : '');
const { parsed } = await parseJsonText(text);
renderEnvelope(parsed, text);
} catch (error) {
setError(error instanceof Error ? error.message : String(error));
}
};
reader.onerror = () => setError('Failed to read selected file.');
reader.readAsText(file);
}
async function init() {
try {
const bundleReady = await ensureUiBundleLoaded();
if (!bundleReady) {
throw new Error('provable-sdk-ui browser bundle did not load.');
}
} catch (error) {
uploadArea.hidden = false;
viewerWrapper.hidden = true;
pageUrlElement.textContent = 'Failed to load proof viewer UI';
setError(error instanceof Error ? error.message : String(error));
return;
}
const params = new URLSearchParams(window.location.search);
const urlParam = params.get('url');
const dataParam = params.get('data');
if (urlParam) {
try {
await loadFromUrl(urlParam);
return;
} catch (error) {
uploadArea.hidden = false;
viewerWrapper.hidden = true;
pageUrlElement.textContent = 'Failed to load proof from URL';
setError(error instanceof Error ? error.message : String(error));
return;
}
}
if (dataParam) {
try {
await loadFromBase64(dataParam);
return;
} catch (error) {
uploadArea.hidden = false;
viewerWrapper.hidden = true;
pageUrlElement.textContent = 'Failed to load proof from data';
setError(error instanceof Error ? error.message : String(error));
return;
}
}
uploadArea.hidden = false;
viewerWrapper.hidden = true;
pageUrlElement.textContent = 'Upload a proof file to view';
}
uploadArea.addEventListener('dragover', (event) => {
event.preventDefault();
uploadArea.classList.add('drag-over');
});
uploadArea.addEventListener('dragleave', () => {
uploadArea.classList.remove('drag-over');
});
uploadArea.addEventListener('drop', (event) => {
event.preventDefault();
uploadArea.classList.remove('drag-over');
const file = event.dataTransfer && event.dataTransfer.files ? event.dataTransfer.files[0] : null;
if (file) {
loadFromFile(file);
}
});
uploadButton.addEventListener('click', () => {
fileInput.click();
});
fileInput.addEventListener('change', () => {
const file = fileInput.files && fileInput.files[0] ? fileInput.files[0] : null;
if (file) {
loadFromFile(file);
}
});
init();
</script>
</body>
</html>