-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmake_encrypted_example.mjs
More file actions
142 lines (119 loc) · 4.98 KB
/
Copy pathmake_encrypted_example.mjs
File metadata and controls
142 lines (119 loc) · 4.98 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
#!/usr/bin/env node
// Generates a pre-encrypted example notebook.
// Usage: node make_encrypted_example.mjs
//
// Reads the example def, encrypts it with a known passphrase,
// outputs the encrypted HTML + recovery key sidecar.
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { webcrypto } from 'crypto';
import { gzipSync } from 'zlib';
// Ensure crypto.subtle is available
if (!globalThis.crypto?.subtle) {
Object.defineProperty(globalThis, 'crypto', { value: webcrypto, configurable: true });
}
const __dirname = dirname(fileURLToPath(import.meta.url));
// Import crypto functions
const {
cryptoEnable,
cryptoBuildBlock,
cryptoDisable,
} = await import('./src/js/crypto.js');
// ── Parse the def file (same logic as gen_examples.js) ──
function parseDef(text) {
const lines = text.split('\n');
let title = 'untitled';
let settings = { theme: 'dark', fontSize: 13, width: '860' };
const cells = [];
let currentCell = null;
for (const line of lines) {
if (line.startsWith('/// ')) {
const directive = line.slice(4);
if (currentCell) {
currentCell.code = currentCell.code.replace(/^\n/, '').replace(/\n$/, '');
cells.push(currentCell);
currentCell = null;
}
if (directive === 'auditable') continue;
else if (directive.startsWith('title: ')) title = directive.slice(7);
else if (directive.startsWith('settings: ')) settings = JSON.parse(directive.slice(10));
else {
const parts = directive.split(' ');
currentCell = { type: parts[0] };
if (parts.includes('collapsed')) currentCell.collapsed = true;
currentCell.code = '';
}
} else if (currentCell) {
currentCell.code += (currentCell.code ? '\n' : '') + line;
}
}
if (currentCell) {
currentCell.code = currentCell.code.replace(/^\n/, '').replace(/\n$/, '');
cells.push(currentCell);
}
return { title, settings, cells };
}
// ── Modules encoding (same as save.js) ──
function encodeModules(obj) {
const b64 = Buffer.from(JSON.stringify(obj), 'utf8').toString('base64');
return b64.replace(/.{1,76}/g, '$&\n').trimEnd();
}
// ── Main ──
const PASSPHRASE = 'auditable';
// Parse the def
const defPath = join(__dirname, 'examples', 'defs', 'basics', 'example_encrypted.txt');
const defText = readFileSync(defPath, 'utf8');
const notebook = parseDef(defText);
// Enable encryption and get recovery key
const recoveryHex = await cryptoEnable(PASSPHRASE);
// Build encrypted payload
const payload = {
data: notebook.cells,
settings: notebook.settings,
modules: null,
fs: null,
title: notebook.title,
};
const cryptoBlock = await cryptoBuildBlock(payload);
// Read auditable.html base
const basePath = join(__dirname, 'auditable.html');
if (!existsSync(basePath)) {
console.error('auditable.html not found — run `node build.js` first');
process.exit(1);
}
let html = readFileSync(basePath, 'utf8');
// Set title to encrypted
html = html.replace(
'<title>Auditable</title>',
'<title>Auditable \u2014 Encrypted</title>'
);
// Insert CRYPTO block and compress runtime
const cryptoComment = '<!-- encrypted notebook data: passphrase required to access cells, settings, and modules -->\n<!--AUDITABLE-CRYPTO\n' + JSON.stringify(cryptoBlock) + '\nAUDITABLE-CRYPTO-->';
// Compress runtime (same as make_example.js compressRuntimeNode)
const scriptMatch = html.match(/<script>([\s\S]*?)<\/script>/);
if (!scriptMatch) { console.error('Could not find <script> in auditable.html'); process.exit(1); }
const scriptContent = scriptMatch[1].trim();
const compressed = gzipSync(Buffer.from(scriptContent, 'utf8'));
const b64 = compressed.toString('base64').replace(/.{1,76}/g, '$&\n');
const loader =
'(function(){var me=document.scripts[document.scripts.length-1];(async function(){' +
"var b=document.getElementById('_rt').textContent.replace(/\\\\s/g,'');" +
'var d=Uint8Array.from(atob(b),function(c){return c.charCodeAt(0)});' +
"var s=await new Response(new Blob([d]).stream().pipeThrough(new DecompressionStream('gzip'))).text();" +
"me.textContent=s;document.getElementById('_rt').remove();" +
'(0,eval)(s)})()})()';
const compressedBlock = `<script type="text/plain" id="_rt">\n${b64}</script>\n<script>\n${loader}\n</script>`;
html = html.replace(/\n<script>[\s\S]*?<\/script>/, () => '\n' + cryptoComment + '\n\n' + compressedBlock);
// Write output
const outDir = join(__dirname, 'examples', 'basics');
if (!existsSync(outDir)) mkdirSync(outDir, { recursive: true });
const outName = `example_encrypted_password-is-${PASSPHRASE}`;
const htmlPath = join(outDir, outName + '.html');
const recoveryPath = join(outDir, outName + '.recovery.txt');
writeFileSync(htmlPath, html);
writeFileSync(recoveryPath, recoveryHex + '\n');
const kb = (html.length / 1024).toFixed(1);
console.log(` ${outName}.html (${kb} KB) [encrypted, passphrase: "${PASSPHRASE}"]`);
console.log(` ${outName}.recovery.txt`);
cryptoDisable();