Files
Shade/scripts/vault-live-kotlin.ts

108 lines
5.0 KiB
TypeScript
Raw Normal View History

/**
* Live cross-check of the Kotlin vault client against the real TS routes.
*
* bun run scripts/vault-live-kotlin.ts
*
* Serves `createVaultRoutes` (memory store) on a free local port, pushes a
* few files with the TS client — one compressed, one multi-part, one PNG —
* then runs the gated `VaultLiveTest` in android/ with `SHADE_VAULT_LIVE_SPEC`
* set. That test reads every file back from Kotlin and edits the vault
* (adds two files, removes one). This script then reads the Kotlin-written
* version back with the TS client, checks every byte and that untouched
* entries kept their objects, and finally edits on top of it from TS.
*
* Vectors pin the format byte for byte; this pins the conversation — real
* HTTP, real signature checks, real SEQ handling — which no vector can.
*/
import { createHash, randomBytes } from 'node:crypto';
import { mkdtemp, readFile, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { SubtleCryptoProvider } from '../packages/shade-crypto-web/src/index.js';
import { createVaultRoutes, MemoryVaultStore } from '../packages/shade-vault/src/server.js';
import { HttpVaultTransport } from '../packages/shade-vault/src/http-transport.js';
import { VaultClient, deriveVaultKeys } from '../packages/shade-vault/src/client.js';
const sha256 = (b: Uint8Array) => createHash('sha256').update(b).digest('hex');
const enc = (s: string) => new TextEncoder().encode(s);
function check(cond: unknown, what: string): asserts cond {
if (!cond) throw new Error(`live cross-check failed: ${what}`);
}
const crypto = new SubtleCryptoProvider();
const routes = createVaultRoutes(new MemoryVaultStore(), crypto);
const server = Bun.serve({ port: 0, hostname: '127.0.0.1', fetch: (req) => routes.fetch(req) });
const url = `http://127.0.0.1:${server.port}`;
try {
const masterKey = new Uint8Array(randomBytes(32));
const app = 'kotlin-live';
const keys = await deriveVaultKeys(masterKey, app);
const client = new VaultClient(crypto, keys, new HttpVaultTransport(url));
const files = [
{ path: 'hello.txt', bytes: enc('hei fra TS\n') },
{ path: '.scaffold/plan.md', bytes: enc('# Plan\n' + '- [ ] noe å gjøre\n'.repeat(300)), mode: '644' },
{ path: 'big.bin', bytes: new Uint8Array(randomBytes(9 * 1024 * 1024)) }, // 3 parts at 4 MiB
{ path: 'pic.png', bytes: new Uint8Array([0x89, 0x50, 0x4e, 0x47, ...randomBytes(2000)]) },
];
const pushed = await client.push(files, Date.now(), 'from TS');
console.log(`TS pushed seq ${pushed.seq} (${pushed.uploaded} objects) to ${url}`);
const before = await client.manifest();
const dir = await mkdtemp(join(tmpdir(), 'shade-vault-live-'));
const specPath = join(dir, 'spec.json');
const kotlinOut = join(dir, 'kotlin-out.json');
await writeFile(
specPath,
JSON.stringify({
url,
masterKey: Buffer.from(masterKey).toString('hex'),
app,
files: Object.fromEntries(files.map((f) => [f.path, sha256(f.bytes)])),
kotlinOut,
}),
);
const androidDir = resolve(import.meta.dir, '../android');
const gradle = Bun.spawn(
['./gradlew', ':shade-android:test', '--tests', 'no.zyon.shade.VaultLiveTest', '--console=plain'],
{ cwd: androidDir, env: { ...process.env, SHADE_VAULT_LIVE_SPEC: specPath }, stdout: 'inherit', stderr: 'inherit' },
);
check((await gradle.exited) === 0, 'Kotlin VaultLiveTest failed');
const out = JSON.parse(await readFile(kotlinOut, 'utf8')) as {
seq: number;
removed: string;
files: Record<string, string>;
};
const after = await client.pull();
check(after.manifest.seq === out.seq, `head is ${after.manifest.seq}, Kotlin committed ${out.seq}`);
check(!after.files.has(out.removed), `${out.removed} should be gone`);
for (const [path, digest] of Object.entries(out.files)) {
check(after.files.has(path), `${path} missing`);
check(sha256(after.files.get(path)!) === digest, `${path} bytes differ`);
}
for (const f of files.filter((f) => f.path !== out.removed)) {
check(sha256(after.files.get(f.path)!) === sha256(f.bytes), `${f.path} changed`);
const was = before.entries.find((e) => e.path === f.path)!;
const now = after.manifest.entries.find((e) => e.path === f.path)!;
check(JSON.stringify(was) === JSON.stringify(now), `${f.path} entry was rewritten`);
}
const kotlinBig = after.manifest.entries.find((e) => e.path === 'from-kotlin/big.bin')!;
check((kotlinBig.parts?.length ?? 0) === 2, 'Kotlin big.bin should be 2 parts');
check(
after.manifest.entries.find((e) => e.path === 'from-kotlin/note.md')?.enc === 'deflate-raw',
'Kotlin note.md should be compressed',
);
// And TS can keep editing on top of a Kotlin-written head.
const ts = await client.edit(() => ({ put: [{ path: 'from-ts.txt', bytes: enc('ok') }] }), Date.now());
check(ts.committed && ts.seq === out.seq + 1, 'TS edit on top of Kotlin head');
console.log(
`LIVE OK — TS→Kotlin read ${files.length} files; Kotlin edit seq ${out.seq} read back by TS; TS edit seq ${ts.seq}`,
);
} finally {
server.stop(true);
}