Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Storage Node8 * File : server/src/crypto.ts9 * Description : Fragment encryption (AES-256-GCM, convergent under the10 * cluster master key), transfer tickets, device signature11 * checks.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 { createCipheriv, createDecipheriv, createHash, createHmac, createPublicKey, timingSafeEqual, verify as cryptoVerify, randomBytes } from "node:crypto";4647export const sha256hex = (b: Buffer | string) => createHash("sha256").update(b).digest("hex");48const hmac = (key: Buffer, ...parts: (Buffer | string)[]) => { const h = createHmac("sha256", key); for (const p of parts) h.update(p); return h.digest(); };4950// A fragment is AES-256-GCM(ciphertext) || tag(16). Key and nonce derive from the master key and the SHA-256 of the plaintext51// chunk, so identical chunks give identical fragments (deduplication) while nothing can be derived without the master key.52// Each (key, nonce) pair encrypts exactly one plaintext, which is the condition for GCM safety.53export function encryptChunk(master: Buffer, plain: Buffer): { fragment: Buffer; id: string; plainSha: string } {54 const plainSha = sha256hex(plain);55 const key = hmac(master, "msf1-key", plainSha);56 const nonce = hmac(master, "msf1-nonce", plainSha).subarray(0, 12);57 const c = createCipheriv("aes-256-gcm", key, nonce);58 const fragment = Buffer.concat([c.update(plain), c.final(), c.getAuthTag()]);59 return { fragment, id: sha256hex(fragment), plainSha };60}6162export function decryptFragment(master: Buffer, fragment: Buffer, plainSha: string): Buffer {63 const key = hmac(master, "msf1-key", plainSha);64 const nonce = hmac(master, "msf1-nonce", plainSha).subarray(0, 12);65 const d = createDecipheriv("aes-256-gcm", key, nonce);66 d.setAuthTag(fragment.subarray(fragment.length - 16));67 const plain = Buffer.concat([d.update(fragment.subarray(0, fragment.length - 16)), d.final()]);68 if (sha256hex(plain) !== plainSha) throw new Error("plaintext digest mismatch");69 return plain;70}7172// Transfer ticket: lets one device move one fragment in one direction until it expires. Carried in the URL so that73// background transfers started hours later by iOS still authenticate; it only ever exposes an opaque encrypted fragment.74export function makeTicket(key: Buffer, deviceId: string, op: string, fragmentId: string, taskId: string, exp: number): string {75 return `${exp}.${hmac(key, `${deviceId}|${op}|${fragmentId}|${taskId}|${exp}`).toString("base64url")}`;76}77export function checkTicket(key: Buffer, ticket: string, deviceId: string, op: string, fragmentId: string, taskId: string, nowS: number): boolean {78 const [expS, mac] = ticket.split(".");79 const exp = Number(expS);80 if (!mac || !Number.isFinite(exp) || exp < nowS) return false;81 const want = hmac(key, `${deviceId}|${op}|${fragmentId}|${taskId}|${exp}`);82 const got = Buffer.from(mac, "base64url");83 return got.length === want.length && timingSafeEqual(got, want);84}8586const P256_SPKI_PREFIX = Buffer.from("3059301306072a8648ce3d020106082a8648ce3d030107034200", "hex");87export function validPublicKey(b64: string): boolean {88 const raw = Buffer.from(b64, "base64");89 if (raw.length !== 65 || raw[0] !== 4) return false;90 try { createPublicKey({ key: Buffer.concat([P256_SPKI_PREFIX, raw]), format: "der", type: "spki" }); return true; } catch { return false; }91}92export function verifySignature(pubkeyB64: string, message: string, signatureB64: string): boolean {93 try {94 const key = createPublicKey({ key: Buffer.concat([P256_SPKI_PREFIX, Buffer.from(pubkeyB64, "base64")]), format: "der", type: "spki" });95 return cryptoVerify("sha256", Buffer.from(message), { key, dsaEncoding: "der" }, Buffer.from(signatureB64, "base64"));96 } catch { return false; }97}98export function canonicalRequest(method: string, pathAndQuery: string, timestamp: string, nonce: string, bodySha: string): string {99 return `MSP1\n${method.toUpperCase()}\n${pathAndQuery}\n${timestamp}\n${nonce}\n${bodySha}`;100}101102export const possessionProof = (nonceHex: string, fragment: Buffer) => createHash("sha256").update(Buffer.from(nonceHex, "hex")).update(fragment).digest("hex");103export const randomId = (bytes = 12) => randomBytes(bytes).toString("hex");104export function safeEqualHex(a: string, b: string): boolean {105 const x = Buffer.from(a, "hex"), y = Buffer.from(b, "hex");106 return x.length === y.length && x.length > 0 && timingSafeEqual(x, y);107}108const B32 = "ABCDEFGHJKMNPQRSTVWXYZ23456789"; // no I, L, O, U, 0, 1109export function pairingCode(): string {110 const b = randomBytes(12);111 let s = "";112 for (let i = 0; i < 12; i++) s += B32[b[i] % B32.length];113 return `${s.slice(0, 4)}-${s.slice(4, 8)}-${s.slice(8, 12)}`;114}115export const normalizeCode = (c: string) => c.toUpperCase().replace(/[^A-Z0-9]/g, "");116