-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmachine.html
More file actions
318 lines (304 loc) · 15.1 KB
/
Copy pathmachine.html
File metadata and controls
318 lines (304 loc) · 15.1 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>The Python Machine - pyproc</title>
<link rel="icon" href="../assets/logo.svg">
<meta name="theme-color" content="#0a0f1c">
<link rel="stylesheet" href="demo.css">
<script type="module" src="siteChrome.js"></script>
</head>
<body>
<div class="wrap">
<header class="site">
<a class="logo" href="../"><img class="logoMark" src="../assets/logo.svg" width="22" height="22" alt=""> <span><span class="py">py</span>proc</span></a>
<nav>
<a href="agentSandbox.html">Agent</a>
<a href="machine.html" class="on">Machine</a>
<a href="serverDev.html">Server</a>
<a href="speedLab.html">Speed</a>
<a href="terminal.html">Terminal</a>
<a href="processOs.html">Process OS</a>
<a href="basic.html">Basics</a>
</nav>
<sns-links></sns-links>
</header>
<h1>A computer that never turns off</h1>
<p class="lead">This page is a Python machine. Close the tab and it hibernates as a few MB;
reopen and it wakes exactly where it was, variables and files intact. Export the whole
running computer as a signed <span class="ok">.pymachine</span> file and open it only when
its public key is trusted.</p>
<div class="panel">
<div class="status" id="st">Booting...</div>
<div class="row" style="margin:.6rem 0 .2rem">
<span class="badge ok">state survives the tab</span>
<span class="badge info">/home/web is a real disk (OPFS)</span>
<span class="badge">resume.py reopens SQLite</span>
<span class="badge">WebCrypto signature on export</span>
<span class="badge">trusted public-key import</span>
</div>
<div class="dim" id="keyFp" style="font-size:.86rem"></div>
</div>
<div class="panel">
<p class="dim" style="margin:0 0 .5rem">Try it: run this, then close the tab and come back. The counter and the file keep counting.</p>
<textarea id="code" rows="4" spellcheck="false">n = globals().get('n', 0) + 1
appDb.execute('insert into resumeEvent(reason, n) values (?, ?)', ('run', n))
appDb.commit()
resumeEvents = appDb.execute('select count(*) from resumeEvent').fetchone()[0]
open('/home/web/visits.txt', 'a').write(f'visit {n}\n')
print('counter:', n, '| lines in visits.txt:', len(open('/home/web/visits.txt').readlines()), '| resume events:', resumeEvents)</textarea>
<div class="row">
<button id="run">Run</button>
<button id="sleep" class="ghost">Sleep now (manual save)</button>
<button id="cast" class="ghost">Cast signed copy</button>
<button id="exp" class="ghost">Export signed .pymachine</button>
<button id="imp" class="ghost">Open signed machine file</button>
<input id="file" type="file" accept=".pymachine" style="display:none">
</div>
<div class="term" id="out"></div>
</div>
<footer class="site">Chromium/Edge. Source: <a href="https://github.com/eddmpython/pyproc">github.com/eddmpython/pyproc</a> · <a href="https://www.npmjs.com/package/pyproc">npm install pyproc</a></footer>
</div>
<script type="module">
import { boot, open } from "../index.js";
const st = document.getElementById("st"), out = document.getElementById("out"), keyFp = document.getElementById("keyFp");
const print = (t) => { out.textContent += t + "\n"; };
// 예제 실행 게이트(?gate): 부팅+실행 완주를 보고. 사람이 열면 no-op.
const params = new URLSearchParams(location.search);
const gateMode = params.has("gate");
const INDEX = params.get("indexURL") ? new URL(params.get("indexURL"), location.href).href : undefined;
const gateReport = (ok) => { if (!gateMode) return; fetch("/gateReport", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ok: !!ok, checks: [{ name: document.title, pass: !!ok, info: (st.textContent + " | " + keyFp.textContent + " | " + out.textContent).slice(-220) }] }) }).catch(() => {}); };
const q = (value) => JSON.stringify(value);
const resumeSrc = [
"import os, sqlite3",
"os.makedirs('/home/web', exist_ok=True)",
"resumeReasonSeen = pyprocResumeReason",
"appDbPath = '/home/web/app.db'",
"appDb = sqlite3.connect(appDbPath)",
"appDb.execute('create table if not exists resumeEvent(reason text, n integer)')",
"appDb.execute('insert into resumeEvent(reason, n) values (?, ?)', (resumeReasonSeen, globals().get('n', 0)))",
"appDb.commit()",
"resumeEvents = appDb.execute('select count(*) from resumeEvent').fetchone()[0]",
].join("\n");
const opfs = await navigator.storage.getDirectory();
const stateDir = await opfs.getDirectoryHandle("pyMachineState", { create: true });
const homeDir = await opfs.getDirectoryHandle("pyMachineHome", { create: true });
const keyStoreName = "pyprocMachineDemo";
// .pymachine 서명 키: WebCrypto ECDSA P-256. history.export({ signingKey })와
// open(blob, { trustedPublicKeys })가 소비하는 표준 형태(CryptoKeyPair / 공개 JWK)다.
// 지문은 정규화 JWK(kty, crv, x, y 순서)의 sha256 주소로, 라이브러리 신뢰 지문 규약과 같다.
const KEY_ALG = { name: "ECDSA", namedCurve: "P-256" };
const createSigningKeys = () => crypto.subtle.generateKey(KEY_ALG, true, ["sign", "verify"]);
async function exportPublicJwk(keys) {
const jwk = await crypto.subtle.exportKey("jwk", keys.publicKey);
return { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y };
}
async function fingerprintPublicJwk(jwk) {
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(jwk))));
return "sha256:" + [...digest].map((b) => b.toString(16).padStart(2, "0")).join("");
}
const reqAsPromise = (req) => new Promise((resolve, reject) => {
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
const openKeyDb = () => new Promise((resolve, reject) => {
const req = indexedDB.open(keyStoreName, 1);
req.onupgradeneeded = () => req.result.createObjectStore("keys");
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
async function loadMachineKeys() {
try {
const db = await openKeyDb();
const tx = db.transaction("keys", "readonly");
const stored = await reqAsPromise(tx.objectStore("keys").get("machine"));
db.close();
if (stored && stored.privateKey && stored.publicKey) return stored;
} catch (e) {}
const keys = await createSigningKeys();
try {
const db = await openKeyDb();
const tx = db.transaction("keys", "readwrite");
tx.objectStore("keys").put(keys, "machine");
await new Promise((res, rej) => { tx.oncomplete = res; tx.onerror = () => rej(tx.error); });
db.close();
} catch (e) {}
return keys;
}
const machineKeys = await loadMachineKeys();
const trustedPublicKey = await exportPublicJwk(machineKeys);
const trustedKeyFp = await fingerprintPublicJwk(trustedPublicKey);
const trustedKeyShort = trustedKeyFp.slice("sha256:".length, "sha256:".length + 16);
keyFp.textContent = `trusted signer: ${trustedKeyShort}. Unsigned or unknown-signer machine files are rejected before any state touches the heap.`;
async function clearDirectory(dir) {
for await (const [name, handle] of dir.entries()) {
await dir.removeEntry(name, { recursive: handle.kind === "directory" });
}
}
async function copyHomeToOpfs(m, srcPath, dstDir) {
await clearDirectory(dstDir);
const copyDir = async (path, dir) => {
for (const name of m.fs.readdir(path)) {
const full = `${path.replace(/\/+$/, "")}/${name}`;
const stat = m.fs.stat(full);
if (stat.isDir) {
const child = await dir.getDirectoryHandle(name, { create: true });
await copyDir(full, child);
} else if (stat.isFile) {
const data = m.fs.readFile(full);
const w = await (await dir.getFileHandle(name, { create: true })).createWritable();
await w.write(data);
await w.close();
}
}
};
await copyDir(srcPath, dstDir);
}
function clearMachineDir(m, path) {
for (const name of m.fs.readdir(path)) {
const full = `${path.replace(/\/+$/, "")}/${name}`;
const stat = m.fs.stat(full);
if (stat.isDir) {
clearMachineDir(m, full);
m.fs.rmdir(full);
} else if (stat.isFile) {
m.fs.unlink(full);
}
}
}
// resume: 이전 hibernate 저장이 있으면 open({ dir, name })이 같은 매니페스트 리플레이 +
// 델타 적용으로 그 자리에서 깨어난다. 없으면(첫 방문) 결정적 리플레이 부팅으로 시작한다
// (history.save/export는 결정 부팅에서만 성립한다). 저장 유무는 이 데모가 hibernate 성공
// 직후 남기는 마커 파일로 판단한다: 저장 포맷 내부(파일 이름)에 결합하지 않고, 첫 방문에
// 실패할 open 부팅(버려질 커널 하나)을 만들지 않기 위해서다.
const SAVE_MARKER = "machine.saved";
const hasSave = await stateDir.getFileHandle(SAVE_MARKER).then(() => true, () => false);
const markSaved = async () => {
const w = await (await stateDir.getFileHandle(SAVE_MARKER, { create: true })).createWritable();
await w.write("1");
await w.close();
};
let machine = null;
let resumeReason = "fresh.boot";
if (hasSave) {
try {
machine = await open({ dir: stateDir, name: "machine" }, { manifest: { indexURL: INDEX } });
st.textContent = "Awake: previous session revived from its heap delta. This computer never turned off.";
resumeReason = "session.load";
} catch (e) {
machine = null; // 저장이 깨졌거나 매니페스트가 어긋나면 새로 시작한다(아래 fresh boot)
}
}
if (!machine) {
machine = await boot({ deterministic: true, indexURL: INDEX });
st.textContent = "Fresh boot (first visit). Make some state, then close the tab and come back.";
}
let home = await machine.runtime.mountHome(homeDir);
async function ensureResumeHook() {
machine.runtime.setGlobal("_pmResumeSrc", resumeSrc);
machine.run([
"import os",
"os.makedirs('/home/web', exist_ok=True)",
"if not os.path.exists('/home/web/resume.py'):",
" open('/home/web/resume.py', 'w').write(_pmResumeSrc)",
].join("\n"));
}
function resumeMachine(reason, init = machine.runtime.enableInit()) {
const r = init.resume(reason);
if (r.resume) print(`resume.py: reopened appDb (${reason}, events=${machine.run("resumeEvents")}).`);
return r;
}
await ensureResumeHook();
// OS의 init: /home/web/boot.py가 있으면 부팅마다 저절로 돈다(rc.local). cron.py는 60초 틱.
const init = machine.runtime.enableInit();
const ran = init.install();
if (ran.boot) print("init: ran /home/web/boot.py");
resumeMachine(resumeReason, init);
const runCode = async () => {
const code = document.getElementById("code").value;
machine.runtime.setGlobal("_pmSrc", code);
const r = await machine.runAsync(
"import io, contextlib\n_buf = io.StringIO()\n" +
"with contextlib.redirect_stdout(_buf), contextlib.redirect_stderr(_buf):\n" +
" exec(_pmSrc, globals())\n_buf.getvalue()"
);
return r ? String(r).trimEnd() : "";
};
const hibernate = async () => {
const r = await machine.history.save(stateDir, "machine");
await home.sync();
await markSaved();
return r;
};
const exportSignedImage = async () => {
await home.sync();
return machine.history.export({ signingKey: machineKeys, includeHome: true });
};
const switchToSignedImage = async (blob) => {
const next = await open(blob, { trustedPublicKeys: [trustedPublicKey], requireSignature: true });
await copyHomeToOpfs(next, "/home/web", homeDir);
clearMachineDir(next, "/home/web");
machine = next;
home = await machine.runtime.mountHome(homeDir);
await ensureResumeHook();
resumeMachine("openMachine");
st.textContent = `Switched to a signed machine verified by key ${trustedKeyShort}.`;
return next;
};
const castSigned = async () => {
const blob = await exportSignedImage();
await switchToSignedImage(blob);
print(`Cast complete: signed .pymachine verified (${(blob.size / 1048576).toFixed(1)}MB).`);
return blob;
};
if (gateMode) {
try {
const r = await runCode();
print(r);
const blob = await castSigned();
const stateOk = machine.run("n >= 1") === true;
const fileOk = String(machine.run("open('/home/web/visits.txt').read()")).includes("visit");
const resumeOk = machine.run("resumeReasonSeen == 'openMachine' and appDb.execute('select count(*) from resumeEvent').fetchone()[0] >= 3") === true;
const trustUiOk = keyFp.textContent.includes("trusted signer:") && keyFp.textContent.includes("rejected");
gateReport(r.includes("counter") && blob.size > 0 && stateOk && fileOk && resumeOk && trustUiOk && st.textContent.includes("verified"));
} catch (e) { print(String(e).slice(-160)); gateReport(false); }
}
// 수명주기: 탭이 사라질 때 자동 hibernate
addEventListener("pagehide", () => { hibernate(); });
document.addEventListener("visibilitychange", () => { if (document.visibilityState === "hidden") hibernate(); });
document.getElementById("run").onclick = async () => {
try { print(await runCode()); }
catch (e) { print(String(e).split("\n").slice(-3).join("\n")); }
};
document.getElementById("sleep").onclick = async () => {
const r = await hibernate();
print(`Hibernated: ${r.pages} pages / ${r.mb}MB delta written to OPFS.`);
};
document.getElementById("cast").onclick = async () => {
try { await castSigned(); }
catch (e) { print(String(e).split("\n").slice(-3).join("\n")); }
};
document.getElementById("exp").onclick = async () => {
const blob = await exportSignedImage();
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = "computer.pymachine";
a.click();
print(`Exported signed computer.pymachine (${(blob.size / 1048576).toFixed(1)}MB, key ${trustedKeyShort}). That file IS this computer.`);
};
document.getElementById("imp").onclick = () => document.getElementById("file").click();
document.getElementById("file").onchange = async (e) => {
const f = e.target.files[0]; if (!f) return;
st.textContent = "Booting the imported computer...";
try {
await switchToSignedImage(f);
print("open() done: signature verified, the sender's exact state is alive here.");
} catch (err) {
st.textContent = "Import rejected.";
print(`Rejected machine file: ${String(err).slice(-220)}`);
}
};
</script>
</body>
</html>