Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Storage Node8 * File : server/test/device.ts9 * Description : Test harness only: a scripted MSP/1 device (P-256 key,10 * signed requests, in-memory fragments) used by the11 * end-to-end tests.12 * Module : server13 * Repository : https://git.spboucher.ai/maclustr-storage-ios14 * Project Website : https://storage.spboucher.ai15 * Created : 2026-12-0116 * Last Modified : 2026-12-0117 *18 * Author : Simon-Pierre Boucher19 * Position : Professor of Finance20 * Institution : Université du Québec en Outaouais (UQO)21 * Organization : SP Boucher22 * Website : https://spboucher.ai23 * Git : https://git.spboucher.ai24 *25 * Preferred Contact: admin@spboucher.ai26 * Technical Contact: dev@spboucher.ai27 * Security/Admin : admin@spboucher.ai28 *29 * Copyright (c) 202630 * Simon-Pierre Boucher31 * All rights reserved where applicable. This file is governed by the32 * applicable project license, copyright notices and relevant law.33 * Existing third-party rights and notices remain unaffected.34 *35 * License : None specified (no license file in this repository)36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445import { createHash, generateKeyPairSync, randomBytes, sign, type KeyObject } from "node:crypto";4647export class TestDevice {48 base: string; name: string; id = ""; key: KeyObject; pub: string;49 fragments = new Map<string, Buffer>();50 quota = 0; accepting = true; writable = 50 * 2 ** 30;51 constructor(base: string, name: string) {52 this.base = base; this.name = name;53 const kp = generateKeyPairSync("ec", { namedCurve: "prime256v1" });54 this.key = kp.privateKey;55 this.pub = (kp.publicKey.export({ format: "der", type: "spki" }) as Buffer).subarray(26).toString("base64");56 }57 headers(method: string, path: string, body: Buffer, opts: { ts?: number; nonce?: string; key?: KeyObject; device?: string } = {}) {58 const ts = String(opts.ts ?? Math.floor(Date.now() / 1000)), nonce = opts.nonce ?? randomBytes(12).toString("base64url");59 const msg = `MSP1\n${method}\n${path}\n${ts}\n${nonce}\n${createHash("sha256").update(body).digest("hex")}`;60 return { "MSP-Device": opts.device ?? this.id, "MSP-Timestamp": ts, "MSP-Nonce": nonce, "MSP-Signature": sign("sha256", Buffer.from(msg), opts.key ?? this.key).toString("base64"), "Content-Type": "application/json" };61 }62 async post(route: string, payload: unknown, opts: Parameters<TestDevice["headers"]>[3] = {}): Promise<{ status: number; body: any }> {63 const body = Buffer.from(JSON.stringify(payload));64 const r = await fetch(this.base + "/msp/1/" + route, { method: "POST", headers: this.headers("POST", "/msp/1/" + route, body, opts), body });65 return { status: r.status, body: await r.json().catch(() => ({})) };66 }67 async pair(code: string) {68 const r = await this.post("pair", { code, public_key: this.pub, name: this.name, model: "TestDevice1,1", os_version: "test", app_version: "test" }, { device: "pair" });69 if (r.status === 200) this.id = r.body.device_id;70 return r;71 }72 used() { let n = 0; for (const f of this.fragments.values()) n += f.length; return n; }73 heartbeat(extra: Record<string, unknown> = {}) {74 return this.post("heartbeat", { state: "active", mode: "active", accepting: this.accepting, capacity: { total: 256 * 2 ** 30, free: 100 * 2 ** 30, reserve: 25 * 2 ** 30, quota: this.quota, used: this.used(), fragments: this.fragments.size, writable: this.writable },75 power: { battery: 0.8, charging: true, low_power: false }, thermal: "nominal", network: "wifi", policy: { wifi_only: true, charging_only: false, cellular: false, rate_limit_bps: 0 }, rates: { rx_bps: 0, tx_bps: 0 }, ...extra });76 }77 url(t: any, extra = "") { return `${this.base}/msp/1/fragments/${t.fragment}?d=${this.id}&t=${t.task}&k=${encodeURIComponent(t.ticket)}${extra}`; }78 proof(nonce: string, data: Buffer) { return createHash("sha256").update(Buffer.from(nonce, "hex")).update(data).digest("hex"); }7980 // Runs one work cycle. `hooks` lets a test interrupt transfers or tamper with what the device does.81 async work(hooks: { splitDownload?: boolean; splitUpload?: boolean; refuse?: boolean } = {}): Promise<any[]> {82 const w = await this.post("work", { max: 16, wait: 0, active: [] });83 if (w.status !== 200) throw new Error(`work ${w.status} ${JSON.stringify(w.body)}`);84 const results: any[] = [];85 for (const t of w.body.tasks as any[]) {86 if (t.op === "store") {87 if (hooks.refuse) { results.push({ task: t.task, ok: false, error: "quota_exceeded" }); continue; }88 let data: Buffer;89 if (hooks.splitDownload) {90 // interrupted transfer: read half, drop the connection, resume with a Range request91 const half = Math.floor(t.size / 2);92 const ac = new AbortController();93 const r1 = await fetch(this.url(t), { signal: ac.signal });94 const reader = r1.body!.getReader(); const got: Buffer[] = []; let n = 0;95 while (n < half) { const { value, done } = await reader.read(); if (done) break; got.push(Buffer.from(value)); n += value.length; }96 ac.abort();97 const first = Buffer.concat(got);98 const r2 = await fetch(this.url(t), { headers: { Range: `bytes=${first.length}-` } });99 if (r2.status !== 206) throw new Error("expected 206, got " + r2.status);100 data = Buffer.concat([first, Buffer.from(await r2.arrayBuffer())]);101 } else {102 const r = await fetch(this.url(t));103 if (r.status !== 200) { results.push({ task: t.task, ok: false, error: "download_" + r.status }); continue; }104 data = Buffer.from(await r.arrayBuffer());105 }106 if (createHash("sha256").update(data).digest("hex") !== t.fragment) { results.push({ task: t.task, ok: false, error: "corrupt_on_arrival" }); continue; }107 this.fragments.set(t.fragment, data);108 results.push({ task: t.task, ok: true, proof: this.proof(t.nonce, data) });109 } else if (t.op === "verify") {110 const data = this.fragments.get(t.fragment);111 results.push(data ? { task: t.task, ok: true, proof: this.proof(t.nonce, data) } : { task: t.task, ok: false, error: "missing" });112 } else if (t.op === "delete") {113 this.fragments.delete(t.fragment); results.push({ task: t.task, ok: true });114 } else if (t.op === "retrieve") {115 const data = this.fragments.get(t.fragment);116 if (!data) { results.push({ task: t.task, ok: false, error: "missing" }); continue; }117 if (hooks.splitUpload) {118 const half = Math.floor(data.length / 2);119 const r1 = await fetch(this.url(t), { method: "PUT", headers: { "Content-Range": `bytes 0-${half - 1}/${data.length}` }, body: data.subarray(0, half) });120 if (r1.status !== 202) throw new Error("expected 202, got " + r1.status);121 const h = await fetch(this.url(t, "&op=retrieve"), { method: "HEAD" });122 const off = Number(h.headers.get("msp-offset"));123 if (off !== half) throw new Error(`offset ${off} != ${half}`);124 const r2 = await fetch(this.url(t), { method: "PUT", headers: { "Content-Range": `bytes ${off}-${data.length - 1}/${data.length}` }, body: data.subarray(off) });125 t.uploadStatus = r2.status;126 } else {127 const r = await fetch(this.url(t), { method: "PUT", body: data });128 t.uploadStatus = r.status;129 }130 }131 }132 if (results.length) { const a = await this.post("ack", { results }); if (a.status !== 200) throw new Error("ack " + a.status); }133 return w.body.tasks;134 }135 inventory() { return this.post("inventory", { fragments: [...this.fragments.keys()] }); }136}137