π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
2of3 v0
Manav Rathi3b3d1f1a8022
diff --git a/web/apps/twoof3/eslint.config.mjs b/web/apps/twoof3/eslint.config.mjsnew file mode 100644index 0000000000..38d1479f25--- /dev/null+++ b/web/apps/twoof3/eslint.config.mjs@@ -0,0 +1,3 @@+import baseConfig from "ente-build-config/eslintrc-next-app.mjs";++export default [...baseConfig];diff --git a/web/apps/twoof3/next.config.js b/web/apps/twoof3/next.config.jsnew file mode 100644index 0000000000..511bb9d14c--- /dev/null+++ b/web/apps/twoof3/next.config.js@@ -0,0 +1,18 @@+const baseConfig = require("ente-base/next.config.base.js");++module.exports = {+ ...baseConfig,+ ...(process.env.NODE_ENV === "development" && {+ output: undefined,+ async rewrites() {+ return {+ fallback: [+ {+ source: "/:path((?!_next|images|favicon.ico).*)",+ destination: "/",+ },+ ],+ };+ },+ }),+};diff --git a/web/apps/twoof3/package.json b/web/apps/twoof3/package.jsonnew file mode 100644index 0000000000..de5ac66c11--- /dev/null+++ b/web/apps/twoof3/package.json@@ -0,0 +1,13 @@+{+ "name": "twoof3",+ "version": "0.0.0",+ "private": true,+ "dependencies": {+ "@fontsource/space-grotesk": "^5.2.10",+ "ente-base": "*",+ "nayuki-qr-code-generator": "^1.8.0"+ },+ "devDependencies": {+ "ente-build-config": "*"+ }+}diff --git a/web/apps/twoof3/public/_redirects b/web/apps/twoof3/public/_redirectsnew file mode 100644index 0000000000..4aa7faf062--- /dev/null+++ b/web/apps/twoof3/public/_redirects@@ -0,0 +1 @@+/* /index.html 200diff --git a/web/apps/twoof3/src/features/twoof3/utils/export.ts b/web/apps/twoof3/src/features/twoof3/utils/export.tsnew file mode 100644index 0000000000..9e22dd197e--- /dev/null+++ b/web/apps/twoof3/src/features/twoof3/utils/export.ts@@ -0,0 +1,586 @@+import { maxSecretBytesForEncodedShareLength, parseShare } from "./shamir";++interface ShareCardAsset {+ qrModules: { finder: boolean; x: number; y: number }[];+ qrSize: number;+ shareIndex: number;+ shareText: string;+ title: string;+}++const CARD_WIDTH = 1400;+const CARD_HEIGHT = 1840;+const CARD_RADIUS = 64;+const QR_SIZE = 860;+const APP_LINK = "2of3.ente.io";+const PRINTED_SHARE_CHARS_PER_LINE = 80;+const PRINTED_SHARE_LINE_COUNT = 4;+export const MAX_PRINTED_SHARE_LENGTH =+ PRINTED_SHARE_CHARS_PER_LINE * PRINTED_SHARE_LINE_COUNT;+export const MAX_SECRET_BYTES_FOR_PRINTED_CARD =+ maxSecretBytesForEncodedShareLength(MAX_PRINTED_SHARE_LENGTH);++const wrapCanvasText = (+ context: CanvasRenderingContext2D,+ text: string,+ maxWidth: number,+ maxLines: number,+) => {+ const words = text.trim().split(/\s+/u).filter(Boolean);+ if (words.length === 0) return [""];++ const lines: string[] = [];+ let current = "";++ for (const word of words) {+ const candidate = current ? `${current} ${word}` : word;+ if (context.measureText(candidate).width <= maxWidth) {+ current = candidate;+ continue;+ }++ if (current) lines.push(current);+ current = word;++ if (lines.length === maxLines - 1) break;+ }++ if (current && lines.length < maxLines) {+ lines.push(current);+ }++ const consumedWords = lines.join(" ").split(/\s+/u).filter(Boolean).length;+ if (consumedWords < words.length && lines.length > 0) {+ const lastLine = lines[lines.length - 1]!;+ lines[lines.length - 1] = `${lastLine.replace(/[. ]+$/u, "")}β¦`;+ }++ return lines;+};++const balanceCanvasText = (+ value: string,+ maxLineLength: number,+ maxLines: number,+) => {+ const lineCount = Math.min(+ maxLines,+ Math.ceil(value.length / maxLineLength),+ );+ if (lineCount <= 1) return [value];++ const chunks: string[] = [];+ const baseLength = Math.floor(value.length / lineCount);+ let remainder = value.length % lineCount;+ let offset = 0;++ for (let index = 0; index < lineCount; index++) {+ const chunkLength = baseLength + (remainder > 0 ? 1 : 0);+ chunks.push(value.slice(offset, offset + chunkLength));+ offset += chunkLength;+ if (remainder > 0) remainder -= 1;+ }++ return chunks;+};++const fitCodeFont = (+ context: CanvasRenderingContext2D,+ lines: string[],+ maxWidth: number,+ maxHeight: number,+) => {+ for (let fontSize = 24; fontSize >= 18; fontSize -= 1) {+ context.font = `500 ${fontSize}px Menlo, Monaco, "Courier New", monospace`;+ const widestLine = Math.max(+ ...lines.map((line) => context.measureText(line).width),+ );+ const lineHeight = fontSize + 4;+ if (widestLine <= maxWidth && lineHeight * lines.length <= maxHeight) {+ return { fontSize, lineHeight };+ }+ }++ return { fontSize: 18, lineHeight: 22 };+};++const drawQr = (+ context: CanvasRenderingContext2D,+ modules: ShareCardAsset["qrModules"],+ qrSize: number,+ left: number,+ top: number,+ size: number,+) => {+ const moduleSize = size / qrSize;++ context.fillStyle = "#ffffff";+ context.fillRect(left, top, size, size);++ for (const module of modules) {+ context.fillStyle = "#111111";+ context.fillRect(+ left + module.x * moduleSize,+ top + module.y * moduleSize,+ moduleSize,+ moduleSize,+ );+ }+};++const ensureShareCardFonts = async () => {+ if (typeof document === "undefined" || !("fonts" in document)) return;++ await Promise.allSettled([+ document.fonts.load('700 54px "Space Grotesk"'),+ document.fonts.load('700 36px "Space Grotesk"'),+ document.fonts.load('500 32px "Space Grotesk"'),+ document.fonts.load('700 22px "Space Grotesk"'),+ document.fonts.load('500 22px "Space Grotesk"'),+ ]);+};++export const renderShareCard = async ({+ qrModules,+ qrSize,+ shareIndex,+ shareText,+ title,+}: ShareCardAsset) => {+ await ensureShareCardFonts();++ const fingerprint = parseShare(shareText).id.slice(0, 8).toUpperCase();+ const shareLines = balanceCanvasText(+ shareText,+ PRINTED_SHARE_CHARS_PER_LINE,+ PRINTED_SHARE_LINE_COUNT,+ );+ const canvas = document.createElement("canvas");+ canvas.width = CARD_WIDTH;+ canvas.height = CARD_HEIGHT;++ const context = canvas.getContext("2d");+ if (!context) throw new Error("Could not render canvas.");++ context.fillStyle = "#ffffff";+ context.fillRect(0, 0, CARD_WIDTH, CARD_HEIGHT);++ context.fillStyle = "#ffffff";+ context.beginPath();+ context.roundRect(48, 48, CARD_WIDTH - 96, CARD_HEIGHT - 96, CARD_RADIUS);+ context.fill();+ context.lineWidth = 3;+ context.strokeStyle = "#111111";+ context.stroke();++ context.fillStyle = "rgb(252, 239, 93)";+ context.beginPath();+ context.roundRect(84, 84, CARD_WIDTH - 168, 132, 32);+ context.fill();++ context.fillStyle = "#111111";+ context.font = '700 36px "Space Grotesk", sans-serif';+ context.fillText(`Card ${shareIndex}`, 124, 166);++ context.fillStyle = "rgba(17,17,17,0.62)";+ context.font = '500 32px "Space Grotesk", sans-serif';+ const appLinkWidth = context.measureText(APP_LINK).width;+ context.fillText(APP_LINK, CARD_WIDTH - 124 - appLinkWidth, 166);++ context.fillStyle = "#111111";+ context.font = '700 54px "Space Grotesk", sans-serif';+ const titleLines = wrapCanvasText(context, title, 940, 2);+ titleLines.forEach((line, index) => {+ context.fillText(line, 120, 304 + index * 66);+ });++ context.fillStyle = "#ffffff";+ context.beginPath();+ context.roundRect(120, 392, 1160, 1088, 48);+ context.fill();+ context.lineWidth = 2.5;+ context.strokeStyle = "rgba(17,17,17,0.22)";+ context.stroke();++ drawQr(context, qrModules, qrSize, 270, 506, QR_SIZE);++ context.fillStyle = "rgba(17,17,17,0.68)";+ context.font = '700 22px "Space Grotesk", sans-serif';+ context.fillText("Code", 120, 1536);++ context.fillStyle = "rgba(17,17,17,0.45)";+ context.font = '500 22px "Space Grotesk", sans-serif';+ const fingerprintLabel = `#${fingerprint}`;+ const fingerprintWidth = context.measureText(fingerprintLabel).width;+ context.fillText(+ fingerprintLabel,+ CARD_WIDTH - 120 - fingerprintWidth,+ 1536,+ );++ context.fillStyle = "rgba(17,17,17,0.04)";+ context.beginPath();+ context.roundRect(120, 1560, 1160, 148, 28);+ context.fill();+ context.lineWidth = 2;+ context.strokeStyle = "rgba(17,17,17,0.18)";+ context.stroke();++ const codeLeft = 148;+ const codeTop = 1603;+ const codeMaxWidth = 1104;+ const codeMaxHeight = 104;+ const codeFont = fitCodeFont(+ context,+ shareLines,+ codeMaxWidth,+ codeMaxHeight,+ );+ context.fillStyle = "#111111";+ context.font = `500 ${codeFont.fontSize}px Menlo, Monaco, "Courier New", monospace`;+ shareLines.forEach((line, index) => {+ context.fillText(line, codeLeft, codeTop + index * codeFont.lineHeight);+ });++ return canvas;+};++export const canvasToBlob = async (canvas: HTMLCanvasElement) =>+ new Promise<Blob>((resolve, reject) => {+ canvas.toBlob((blob) => {+ if (!blob) {+ reject(new Error("Could not encode PNG."));+ return;+ }+ resolve(blob);+ }, "image/png");+ });++export const createOfflineRecoveryHtml = () => `<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>2of3 recovery</title>+ <style>+ :root {+ color-scheme: light;+ --bg: #ffffff;+ --paper: #ffffff;+ --field: rgba(252, 239, 93, 0.12);+ --ink: #111111;+ --muted: rgba(17,17,17,0.72);+ --yellow: rgb(252, 239, 93);+ --line: rgba(17, 17, 17, 0.18);+ --line-strong: rgba(17, 17, 17, 0.22);+ }+ * { box-sizing: border-box; }+ body {+ margin: 0;+ font-family: "Space Grotesk", "Helvetica Neue", sans-serif;+ background: var(--bg);+ color: var(--ink);+ }+ main {+ width: min(960px, calc(100vw - 32px));+ margin: 0 auto;+ padding: 32px 0 56px;+ }+ .panel {+ background: var(--paper);+ border: 2px solid var(--ink);+ border-radius: 24px;+ padding: 24px;+ }+ h1 {+ font-family: "Space Grotesk", sans-serif;+ font-size: clamp(2.1rem, 5vw, 3.4rem);+ line-height: 0.92;+ letter-spacing: -0.06em;+ margin: 0 0 12px;+ }+ p { color: var(--muted); line-height: 1.6; }+ .eyebrow {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ margin-bottom: 16px;+ padding: 10px 14px;+ border-radius: 999px;+ background: var(--yellow);+ border: 2px solid var(--ink);+ font-weight: 700;+ }+ .grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));+ gap: 16px;+ margin-top: 24px;+ }+ textarea, input[type="file"] {+ width: 100%;+ border-radius: 18px;+ border: 2px solid var(--ink);+ background: white;+ padding: 14px 16px;+ font: inherit;+ }+ textarea {+ min-height: 180px;+ resize: vertical;+ }+ button {+ margin-top: 18px;+ border: 0;+ border-radius: 999px;+ padding: 14px 20px;+ background: var(--yellow);+ color: var(--ink);+ font: inherit;+ font-weight: 700;+ cursor: pointer;+ }+ .result {+ margin-top: 18px;+ white-space: pre-wrap;+ background: var(--paper);+ border: 2px solid var(--ink);+ padding: 16px;+ border-radius: 18px;+ }+ .error {+ color: var(--ink);+ background: var(--yellow);+ border: 2px solid var(--ink);+ border-radius: 18px;+ padding: 12px 14px;+ margin-top: 12px;+ }+ </style>+</head>+<body>+ <main>+ <div class="panel">+ <div class="eyebrow">Recover later</div>+ <h1>Recover with any two cards.</h1>+ <p>This file works offline. Upload two card images if your browser can read QR codes, or paste the two code strings manually.</p>+ <div class="grid">+ <div>+ <input id="file-a" type="file" accept="image/*,text/plain" />+ <textarea id="input-a" placeholder="Paste share 1"></textarea>+ </div>+ <div>+ <input id="file-b" type="file" accept="image/*,text/plain" />+ <textarea id="input-b" placeholder="Paste share 2"></textarea>+ </div>+ </div>+ <button id="recover">Recover secret</button>+ <div id="error" class="error"></div>+ <div id="result" class="result" hidden></div>+ </div>+ </main>+ <script>+ const GF_POLY = 0x11b;+ const VERSION = 1;+ const HEADER_LENGTH = 14;+ const gfMul = (left, right) => {+ let result = 0;+ let a = left;+ let b = right;+ while (b > 0) {+ if (b & 1) result ^= a;+ a <<= 1;+ if (a & 0x100) a ^= GF_POLY;+ b >>= 1;+ }+ return result;+ };+ const gfPow = (value, exponent) => {+ let result = 1;+ for (let count = 0; count < exponent; count++) {+ result = gfMul(result, value);+ }+ return result;+ };+ const gfInv = (value) => {+ if (value === 0) throw new Error("Division by zero");+ return gfPow(value, 254);+ };+ const gfDiv = (left, right) => {+ if (left === 0) return 0;+ return gfMul(left, gfInv(right));+ };+ const checksumBytes = (bytes) => {+ let hash = 0x811c9dc5;+ for (const byte of bytes) {+ hash ^= byte;+ hash = Math.imul(hash, 0x01000193) >>> 0;+ }+ return new Uint8Array([(hash >>> 24) & 255, (hash >>> 16) & 255, (hash >>> 8) & 255, hash & 255]);+ };+ const base64UrlEncode = (bytes) => {+ let binary = "";+ for (const byte of bytes) binary += String.fromCharCode(byte);+ return btoa(binary).replace(/\\+/g, "-").replace(/\\//g, "_").replace(/=+$/u, "");+ };+ const base64UrlDecode = (value) => {+ const padded = value.replace(/-/g, "+").replace(/_/g, "/");+ const normalized = padded + "=".repeat((4 - (padded.length % 4 || 4)) % 4);+ const binary = atob(normalized);+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));+ };+ const parseShare = (input) => {+ const encoded = input.trim();+ if (!encoded.startsWith("2of3-")) throw new Error("That code does not look like a 2of3 share.");+ const payload = base64UrlDecode(encoded.slice(5));+ if (payload.length <= HEADER_LENGTH) throw new Error("That share looks incomplete.");+ const version = payload[0];+ const index = payload[1];+ const length = ((payload[2] || 0) << 8) | (payload[3] || 0);+ if (version !== VERSION) throw new Error("This share was created by a newer format.");+ if (![1,2,3].includes(index)) throw new Error("This share number is invalid.");+ if (payload.length !== HEADER_LENGTH + length) throw new Error("This share was cut off.");+ return {+ checksum: payload.slice(10, 14),+ data: payload.slice(14),+ id: base64UrlEncode(payload.slice(4, 10)),+ index,+ length,+ };+ };+ const combineShares = (firstInput, secondInput) => {+ const first = parseShare(firstInput);+ const second = parseShare(secondInput);+ if (first.id !== second.id || first.length !== second.length) throw new Error("These two cards are from different sets. Match the # on both cards.");+ if (first.index === second.index) throw new Error("Use two different cards from the same set.");+ const output = new Uint8Array(first.length);+ const denominator = first.index ^ second.index;+ for (let index = 0; index < first.length; index++) {+ const left = gfMul(first.data[index], gfDiv(second.index, denominator));+ const right = gfMul(second.data[index], gfDiv(first.index, denominator));+ output[index] = left ^ right;+ }+ const expectedChecksum = checksumBytes(output);+ for (let i = 0; i < expectedChecksum.length; i++) {+ if (expectedChecksum[i] !== first.checksum[i] || expectedChecksum[i] !== second.checksum[i]) {+ throw new Error("These shares did not reconstruct a valid secret.");+ }+ }+ return new TextDecoder().decode(output);+ };+ const fileToText = async (file) => {+ if (file.type.startsWith("text/")) return file.text();+ if (!("BarcodeDetector" in window)) throw new Error("QR image upload is not supported in this browser. Paste the code instead.");+ const detector = new BarcodeDetector({ formats: ["qr_code"] });+ const bitmap = await createImageBitmap(file);+ const results = await detector.detect(bitmap);+ bitmap.close();+ const value = results[0] && results[0].rawValue;+ if (!value) throw new Error("Could not read a QR code from that image.");+ return value;+ };+ const bindFile = (fileId, textareaId) => {+ const fileInput = document.getElementById(fileId);+ const textarea = document.getElementById(textareaId);+ fileInput.addEventListener("change", async (event) => {+ const file = event.target.files && event.target.files[0];+ if (!file) return;+ try {+ textarea.value = (await fileToText(file)).trim();+ } catch (error) {+ document.getElementById("error").textContent = error.message || String(error);+ }+ });+ };+ bindFile("file-a", "input-a");+ bindFile("file-b", "input-b");+ document.getElementById("recover").addEventListener("click", () => {+ const errorNode = document.getElementById("error");+ const resultNode = document.getElementById("result");+ errorNode.textContent = "";+ resultNode.hidden = true;+ try {+ const secret = combineShares(+ document.getElementById("input-a").value,+ document.getElementById("input-b").value+ );+ resultNode.textContent = secret;+ resultNode.hidden = false;+ } catch (error) {+ errorNode.textContent = error.message || String(error);+ }+ });+ </script>+</body>+</html>`;++export const offlineRecoveryFile = () =>+ new File([createOfflineRecoveryHtml()], "2of3-recovery.html", {+ type: "text/html;charset=utf-8",+ });++export const shareFiles = async (files: File[]) => {+ const api = navigator as Navigator & {+ canShare?: (data?: ShareData) => boolean;+ share?: (data?: ShareData) => Promise<void>;+ };++ if (+ typeof api.share !== "function" ||+ typeof api.canShare !== "function" ||+ !api.canShare({ files })+ ) {+ throw new Error("Sharing files is not supported here.");+ }++ await api.share({+ files,+ title: "2of3 cards",+ text: "Keep these cards separate. Any 2 can recover the secret.",+ });+};++export const printBlob = (blob: Blob, title: string) => {+ const url = URL.createObjectURL(blob);+ const popup = window.open("", "_blank", "noopener,noreferrer");+ if (!popup) {+ URL.revokeObjectURL(url);+ throw new Error("Allow pop-ups to print this card.");+ }++ const { document } = popup;+ document.title = title;++ const style = document.createElement("style");+ style.textContent =+ "body{margin:0;background:#fff;display:grid;place-items:center;min-height:100vh}img{max-width:100vw;max-height:100vh}@media print{body{margin:0}}";+ document.head.appendChild(style);++ const image = document.createElement("img");+ image.src = url;+ image.alt = title;+ image.addEventListener("load", () => {+ popup.print();+ popup.setTimeout(() => popup.close(), 100);+ });+ document.body.appendChild(image);+ popup.addEventListener("beforeunload", () => {+ URL.revokeObjectURL(url);+ });+};++export const downloadBlob = (blob: Blob, filename: string) => {+ const url = URL.createObjectURL(blob);+ const anchor = document.createElement("a");+ anchor.href = url;+ anchor.download = filename;+ anchor.click();+ setTimeout(() => URL.revokeObjectURL(url), 1000);+};++export const sanitizeFilename = (value: string) =>+ value+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .slice(0, 48) || "2of3";diff --git a/web/apps/twoof3/src/features/twoof3/utils/qrCode.ts b/web/apps/twoof3/src/features/twoof3/utils/qrCode.tsnew file mode 100644index 0000000000..010a5c3290--- /dev/null+++ b/web/apps/twoof3/src/features/twoof3/utils/qrCode.ts@@ -0,0 +1,52 @@+import qrcodegen from "nayuki-qr-code-generator";++export interface QrModule {+ finder: boolean;+ x: number;+ y: number;+}++export interface QrSvgData {+ modules: QrModule[];+ viewBoxSize: number;+}++const QR_BORDER_MODULES = 2;++const isFinderModule = (x: number, y: number, size: number) => {+ const inTopBand = y < 7;+ const inBottomBand = y >= size - 7;+ const inLeftBand = x < 7;+ const inRightBand = x >= size - 7;++ return (+ (inTopBand && inLeftBand) ||+ (inTopBand && inRightBand) ||+ (inBottomBand && inLeftBand)+ );+};++export const createQrSvgData = (value: string): QrSvgData | null => {+ try {+ const qr = qrcodegen.QrCode.encodeText(+ value,+ qrcodegen.QrCode.Ecc.MEDIUM,+ );+ const modules: QrModule[] = [];++ for (let y = 0; y < qr.size; y++) {+ for (let x = 0; x < qr.size; x++) {+ if (!qr.getModule(x, y)) continue;+ modules.push({+ finder: isFinderModule(x, y, qr.size),+ x: x + QR_BORDER_MODULES,+ y: y + QR_BORDER_MODULES,+ });+ }+ }++ return { modules, viewBoxSize: qr.size + QR_BORDER_MODULES * 2 };+ } catch {+ return null;+ }+};diff --git a/web/apps/twoof3/src/features/twoof3/utils/shamir.ts b/web/apps/twoof3/src/features/twoof3/utils/shamir.tsnew file mode 100644index 0000000000..41c701baf1--- /dev/null+++ b/web/apps/twoof3/src/features/twoof3/utils/shamir.ts@@ -0,0 +1,263 @@+const GF_POLY = 0x11b;+const VERSION = 1;+const HEADER_LENGTH = 14;+const ID_LENGTH = 6;+const MAX_SECRET_BYTES = 2048;+export const SHARE_PREFIX = "2of3-";++const gfMul = (left: number, right: number) => {+ let result = 0;+ let a = left;+ let b = right;++ while (b > 0) {+ if (b & 1) result ^= a;+ a <<= 1;+ if (a & 0x100) a ^= GF_POLY;+ b >>= 1;+ }++ return result;+};++const gfPow = (value: number, exponent: number) => {+ let result = 1;++ for (let count = 0; count < exponent; count++) {+ result = gfMul(result, value);+ }++ return result;+};++const gfInv = (value: number) => {+ if (value === 0) {+ throw new Error("Cannot divide by zero in GF(256)");+ }++ return gfPow(value, 254);+};++const gfDiv = (left: number, right: number) => {+ if (left === 0) return 0;+ return gfMul(left, gfInv(right));+};++const checksumBytes = (bytes: Uint8Array) => {+ let hash = 0x811c9dc5;++ for (const byte of bytes) {+ hash ^= byte;+ hash = Math.imul(hash, 0x01000193) >>> 0;+ }++ return new Uint8Array([+ (hash >>> 24) & 0xff,+ (hash >>> 16) & 0xff,+ (hash >>> 8) & 0xff,+ hash & 0xff,+ ]);+};++const base64UrlEncode = (bytes: Uint8Array) => {+ let binary = "";+ for (const byte of bytes) {+ binary += String.fromCharCode(byte);+ }++ return btoa(binary)+ .replace(/\+/g, "-")+ .replace(/\//g, "_")+ .replace(/=+$/u, "");+};++const base64UrlLength = (byteLength: number) => {+ const fullGroups = Math.floor(byteLength / 3);+ const remainder = byteLength % 3;+ return fullGroups * 4 + (remainder === 0 ? 0 : remainder + 1);+};++const base64UrlDecode = (value: string) => {+ const padded = value.replace(/-/g, "+").replace(/_/g, "/");+ const normalized = padded + "=".repeat((4 - (padded.length % 4 || 4)) % 4);++ const binary = atob(normalized);+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));+};++const joinBytes = (...chunks: Uint8Array[]) => {+ const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);+ const output = new Uint8Array(totalLength);+ let offset = 0;++ for (const chunk of chunks) {+ output.set(chunk, offset);+ offset += chunk.length;+ }++ return output;+};++export interface SplitShare {+ encoded: string;+ index: 1 | 2 | 3;+}++export interface ParsedShare {+ checksum: Uint8Array;+ data: Uint8Array;+ encoded: string;+ id: string;+ index: 1 | 2 | 3;+ length: number;+}++export const encodedShareLengthForSecretBytes = (secretByteLength: number) =>+ SHARE_PREFIX.length + base64UrlLength(HEADER_LENGTH + secretByteLength);++export const maxSecretBytesForEncodedShareLength = (maxShareLength: number) => {+ let best = 0;++ for (+ let secretByteLength = 1;+ secretByteLength <= MAX_SECRET_BYTES;+ secretByteLength+++ ) {+ if (+ encodedShareLengthForSecretBytes(secretByteLength) > maxShareLength+ ) {+ break;+ }+ best = secretByteLength;+ }++ return best;+};++export const splitSecret = (secret: string): SplitShare[] => {+ const secretBytes = new TextEncoder().encode(secret);++ if (secretBytes.length === 0) {+ throw new Error("Enter something first.");+ }++ if (secretBytes.length > MAX_SECRET_BYTES) {+ throw new Error("This secret is too large for 2of3.");+ }++ const randomId = crypto.getRandomValues(new Uint8Array(ID_LENGTH));+ const checksum = checksumBytes(secretBytes);+ const coefficients = crypto.getRandomValues(+ new Uint8Array(secretBytes.length),+ );+ const shares = [+ new Uint8Array(secretBytes.length),+ new Uint8Array(secretBytes.length),+ new Uint8Array(secretBytes.length),+ ];++ for (let index = 0; index < secretBytes.length; index++) {+ const secretByte = secretBytes[index]!;+ const coefficient = coefficients[index]!;+ shares[0]![index] = secretByte ^ coefficient;+ shares[1]![index] = secretByte ^ gfMul(coefficient, 2);+ shares[2]![index] = secretByte ^ gfMul(coefficient, 3);+ }++ return shares.map((shareBytes, shareOffset) => {+ const index = (shareOffset + 1) as 1 | 2 | 3;+ const header = new Uint8Array([+ VERSION,+ index,+ (secretBytes.length >>> 8) & 0xff,+ secretBytes.length & 0xff,+ ]);++ const payload = joinBytes(header, randomId, checksum, shareBytes);+ return { encoded: `${SHARE_PREFIX}${base64UrlEncode(payload)}`, index };+ });+};++export const parseShare = (input: string): ParsedShare => {+ const encoded = input.trim();+ if (!encoded.startsWith(SHARE_PREFIX)) {+ throw new Error("That code does not look like a 2of3 share.");+ }++ const payload = base64UrlDecode(encoded.slice(SHARE_PREFIX.length));+ if (payload.length <= HEADER_LENGTH) {+ throw new Error("That share looks incomplete.");+ }++ const version = payload[0];+ const index = payload[1];+ const length = ((payload[2] ?? 0) << 8) | (payload[3] ?? 0);++ if (version !== VERSION) {+ throw new Error("This share was created by a newer format.");+ }++ if (index !== 1 && index !== 2 && index !== 3) {+ throw new Error("This share number is invalid.");+ }++ if (payload.length !== HEADER_LENGTH + length) {+ throw new Error("This share was cut off.");+ }++ const idBytes = payload.slice(4, 10);+ const checksum = payload.slice(10, 14);+ const data = payload.slice(14);++ return {+ checksum,+ data,+ encoded,+ id: base64UrlEncode(idBytes),+ index,+ length,+ };+};++export const combineShares = (firstInput: string, secondInput: string) => {+ const first = parseShare(firstInput);+ const second = parseShare(secondInput);++ if (first.id !== second.id || first.length !== second.length) {+ throw new Error(+ "These two cards are from different sets. Match the # on both cards.",+ );+ }++ if (first.index === second.index) {+ throw new Error("Use two different cards from the same set.");+ }++ const output = new Uint8Array(first.length);+ const denominator = first.index ^ second.index;++ for (let index = 0; index < first.length; index++) {+ const left = gfMul(+ first.data[index]!,+ gfDiv(second.index, denominator),+ );+ const right = gfMul(+ second.data[index]!,+ gfDiv(first.index, denominator),+ );+ output[index] = left ^ right;+ }++ const expectedChecksum = checksumBytes(output);+ if (+ expectedChecksum.some(+ (byte, index) =>+ byte !== first.checksum[index] ||+ byte !== second.checksum[index],+ )+ ) {+ throw new Error("These shares did not reconstruct a valid secret.");+ }++ return new TextDecoder().decode(output);+};diff --git a/web/apps/twoof3/src/pages/_app.tsx b/web/apps/twoof3/src/pages/_app.tsxnew file mode 100644index 0000000000..02e0d9892b--- /dev/null+++ b/web/apps/twoof3/src/pages/_app.tsx@@ -0,0 +1,69 @@+import "@fontsource/space-grotesk/400.css";+import "@fontsource/space-grotesk/500.css";+import "@fontsource/space-grotesk/700.css";+import {+ CssBaseline,+ ThemeProvider,+ createTheme,+ useMediaQuery,+} from "@mui/material";+import { CustomHead } from "ente-base/components/Head";+import { useSetupLogs } from "ente-base/components/utils/hooks-app";+import type { AppProps } from "next/app";++const App = ({ Component, pageProps }: AppProps) => {+ useSetupLogs({ disableDiskLogs: true });+ const prefersDarkMode = useMediaQuery("(prefers-color-scheme: dark)", {+ noSsr: true,+ });++ const theme = createTheme({+ palette: {+ mode: prefersDarkMode ? "dark" : "light",+ primary: { main: "rgb(252, 239, 93)", contrastText: "#111111" },+ background: {+ default: prefersDarkMode ? "#0b0b0b" : "#ffffff",+ paper: prefersDarkMode ? "#111111" : "#ffffff",+ },+ text: {+ primary: prefersDarkMode ? "#fafafa" : "#111111",+ secondary: prefersDarkMode+ ? "rgba(250,250,250,0.68)"+ : "rgba(17,17,17,0.68)",+ },+ divider: prefersDarkMode+ ? "rgba(255,255,255,0.18)"+ : "rgba(17,17,17,0.18)",+ },+ shape: { borderRadius: 20 },+ typography: {+ fontFamily:+ '"Space Grotesk", "Inter Variable", "Helvetica Neue", sans-serif',+ h1: { fontWeight: 700, letterSpacing: "-0.05em" },+ h2: { fontWeight: 700, letterSpacing: "-0.04em" },+ h3: { fontWeight: 700, letterSpacing: "-0.04em" },+ button: {+ fontWeight: 700,+ letterSpacing: "-0.01em",+ textTransform: "none",+ },+ },+ components: {+ MuiButton: {+ styleOverrides: {+ root: { borderRadius: 18, boxShadow: "none" },+ },+ },+ },+ });++ return (+ <ThemeProvider theme={theme}>+ <CustomHead title="2of3" />+ <CssBaseline enableColorScheme />+ <Component {...pageProps} />+ </ThemeProvider>+ );+};++export default App;diff --git a/web/apps/twoof3/src/pages/index.tsx b/web/apps/twoof3/src/pages/index.tsxnew file mode 100644index 0000000000..f68316f8e9--- /dev/null+++ b/web/apps/twoof3/src/pages/index.tsx@@ -0,0 +1,1442 @@+import {+ Box,+ Button,+ Container,+ Stack,+ TextField,+ Typography,+} from "@mui/material";+import {+ MAX_SECRET_BYTES_FOR_PRINTED_CARD,+ canvasToBlob,+ downloadBlob,+ offlineRecoveryFile,+ printBlob,+ renderShareCard,+ sanitizeFilename,+ shareFiles,+} from "features/twoof3/utils/export";+import { createQrSvgData } from "features/twoof3/utils/qrCode";+import {+ combineShares,+ parseShare,+ splitSecret,+} from "features/twoof3/utils/shamir";+import Head from "next/head";+import type { ChangeEvent, ReactNode } from "react";+import { useDeferredValue, useEffect, useState } from "react";++const APP_LINK = "2of3.ente.io";+const textEncoder = new TextEncoder();++const byteLength = (value: string) => textEncoder.encode(value).length;++const trimToByteLength = (value: string, maxBytes: number) => {+ if (byteLength(value) <= maxBytes) return value;++ const chars = Array.from(value);+ while (chars.length > 0 && byteLength(chars.join("")) > maxBytes) {+ chars.pop();+ }++ return chars.join("");+};++interface ShareCardState {+ encoded: string;+ fingerprint: string;+ index: 1 | 2 | 3;+ qr: NonNullable<ReturnType<typeof createQrSvgData>>;+}++interface SplitSnapshot {+ cards: ShareCardState[];+ error: string | null;+ secret: string;+}++interface RecoverSlot {+ fileName: string;+ value: string;+}++interface RecoverSlotDetails {+ fingerprint: string;+ index: 1 | 2 | 3;+ length: number;+}++interface BrowserWithBarcodeDetector extends Window {+ BarcodeDetector?: new (options?: { formats?: string[] }) => {+ detect: (source: ImageBitmap) => Promise<{ rawValue?: string }[]>;+ };+}++const todayLabel = () =>+ new Intl.DateTimeFormat(undefined, {+ day: "numeric",+ month: "long",+ year: "numeric",+ }).format(new Date());++const shareFingerprint = (value: string) =>+ parseShare(value).id.slice(0, 8).toUpperCase();++const EMPTY_SPLIT_SNAPSHOT: SplitSnapshot = {+ cards: [],+ error: null,+ secret: "",+};++const fieldSx = {+ "& .MuiOutlinedInput-root": {+ borderRadius: "18px",+ bgcolor: "var(--paper)",+ "& fieldset": {+ borderWidth: "1.5px",+ borderColor: "var(--line-strong)",+ },+ "&:hover fieldset": { borderWidth: "1.5px", borderColor: "var(--ink)" },+ "&.Mui-focused fieldset": {+ borderWidth: "1.5px",+ borderColor: "var(--ink)",+ },+ },+ "& .MuiInputBase-input": { fontSize: "0.98rem", lineHeight: 1.55 },+ "& .MuiInputLabel-root": { fontWeight: 700, color: "var(--muted)" },+ "& .MuiInputLabel-root.Mui-focused": { color: "var(--ink)" },+};++const Note = ({+ children,+ tone = "plain",+}: {+ children: ReactNode;+ tone?: "plain" | "accent" | "field";+}) => (+ <Box+ sx={{+ border: "1.5px solid",+ borderColor:+ tone === "accent"+ ? "#111111"+ : tone === "plain"+ ? "var(--line-strong)"+ : "var(--ink)",+ borderRadius: "18px",+ px: 1.5,+ py: 1.15,+ bgcolor:+ tone === "accent"+ ? "var(--accent)"+ : tone === "field"+ ? "var(--field-soft)"+ : "var(--paper)",+ }}+ >+ <Typography+ sx={{+ color: tone === "accent" ? "#111111" : "var(--ink)",+ fontSize: "0.95rem",+ lineHeight: 1.45,+ fontWeight: tone === "accent" ? 700 : 500,+ }}+ >+ {children}+ </Typography>+ </Box>+);++const QrPreview = ({+ value,+}: {+ value: NonNullable<ReturnType<typeof createQrSvgData>>;+}) => (+ <svg+ viewBox={`0 0 ${value.viewBoxSize} ${value.viewBoxSize}`}+ role="img"+ aria-label="QR code"+ style={{+ width: "100%",+ height: "100%",+ display: "block",+ background: "#ffffff",+ }}+ >+ <rect+ width={value.viewBoxSize}+ height={value.viewBoxSize}+ rx="2.5"+ fill="#ffffff"+ />+ {value.modules.map((module) => (+ <rect+ key={`${module.x}-${module.y}`}+ x={module.x}+ y={module.y}+ width="1"+ height="1"+ rx="0.08"+ fill="#111111"+ />+ ))}+ </svg>+);++const ActionButton = ({+ children,+ onClick,+ disabled,+}: {+ children: ReactNode;+ disabled?: boolean;+ onClick: () => void;+}) => (+ <Button+ variant="outlined"+ size="small"+ disabled={disabled}+ onClick={onClick}+ sx={{+ minWidth: 0,+ px: 1.35,+ py: 0.75,+ borderRadius: "999px",+ borderWidth: "1.5px",+ borderColor: "var(--line-strong)",+ color: "var(--ink)",+ bgcolor: "rgba(255,255,255,0.88)",+ "&:hover": {+ borderWidth: "1.5px",+ borderColor: "var(--ink)",+ bgcolor: "var(--paper)",+ },+ }}+ >+ {children}+ </Button>+);++const splitIfPossible = (secret: string): SplitSnapshot => {+ if (!secret.trim()) return EMPTY_SPLIT_SNAPSHOT;++ try {+ const rawShares = splitSecret(secret);+ const cards = rawShares.map((share) => {+ const qr = createQrSvgData(share.encoded);+ if (!qr) {+ throw new Error(+ "This secret is too long for a clean QR. Keep it shorter.",+ );+ }++ return { ...share, qr };+ });++ return {+ cards: cards.map((card) => ({+ ...card,+ fingerprint: shareFingerprint(card.encoded),+ })),+ error: null,+ secret,+ };+ } catch (error) {+ return {+ cards: [],+ error:+ error instanceof Error+ ? error.message+ : "Could not split this secret.",+ secret,+ };+ }+};++const describeRecoverSlot = (value: string): RecoverSlotDetails | null => {+ if (!value.trim()) return null;++ try {+ const parsed = parseShare(value);+ return {+ fingerprint: parsed.id.slice(0, 8).toUpperCase(),+ index: parsed.index,+ length: parsed.length,+ };+ } catch {+ return null;+ }+};++const readShareFile = async (file: File) => {+ if (file.type.startsWith("text/")) {+ return (await file.text()).trim();+ }++ const barcodeWindow = window as BrowserWithBarcodeDetector;+ if (!barcodeWindow.BarcodeDetector) {+ throw new Error(+ "This browser cannot read QR images. Paste the code instead.",+ );+ }++ const detector = new barcodeWindow.BarcodeDetector({+ formats: ["qr_code"],+ });+ const bitmap = await createImageBitmap(file);++ try {+ const matches = await detector.detect(bitmap);+ const rawValue = matches[0]?.rawValue?.trim();+ if (!rawValue) {+ throw new Error("Could not find a QR code in that image.");+ }+ return rawValue;+ } finally {+ bitmap.close();+ }+};++const copyTextToClipboard = async (value: string) => {+ if ("clipboard" in navigator) {+ await navigator.clipboard.writeText(value);+ return;+ }++ throw new Error("Copy is not supported in this browser.");+};++const Page = () => {+ const [secret, setSecret] = useState("");+ const [title, setTitle] = useState(todayLabel);+ const [busyCard, setBusyCard] = useState<number | null>(null);+ const [downloadAllBusy, setDownloadAllBusy] = useState(false);+ const [actionError, setActionError] = useState<string | null>(null);+ const [copiedCardIndex, setCopiedCardIndex] = useState<number | null>(null);+ const [recoverSlots, setRecoverSlots] = useState<RecoverSlot[]>([+ { fileName: "", value: "" },+ { fileName: "", value: "" },+ ]);+ const [recoverError, setRecoverError] = useState<string | null>(null);+ const [recoveredSecret, setRecoveredSecret] = useState("");+ const [copiedRecoveredSecret, setCopiedRecoveredSecret] = useState(false);+ const [splitSnapshot, setSplitSnapshot] =+ useState<SplitSnapshot>(EMPTY_SPLIT_SNAPSHOT);+ const deferredSecret = useDeferredValue(secret);++ const cards = splitSnapshot.cards;+ const isCardsStale = splitSnapshot.secret !== secret;+ const isReady = !isCardsStale && cards.length === 3;+ const splitError = isCardsStale ? null : splitSnapshot.error;+ const inputStatus = splitError ?? actionError;+ const secretLength = byteLength(secret);+ const cardLabel = title.trim() || todayLabel();+ const recoverSlotDetails = recoverSlots.map((slot) =>+ describeRecoverSlot(slot.value),+ );+ const recoverMismatch =+ recoverSlotDetails[0] &&+ recoverSlotDetails[1] &&+ (recoverSlotDetails[0].fingerprint !==+ recoverSlotDetails[1].fingerprint ||+ recoverSlotDetails[0].length !== recoverSlotDetails[1].length);+ const recoverDuplicateCards =+ !recoverMismatch &&+ recoverSlotDetails[0] &&+ recoverSlotDetails[1] &&+ recoverSlotDetails[0].index === recoverSlotDetails[1].index;+ const hasTwoRecoverValues = recoverSlots.every((slot) => slot.value.trim());+ const canRecover =+ hasTwoRecoverValues && !recoverMismatch && !recoverDuplicateCards;+ const recoverStatus = recoverMismatch+ ? "These two cards are from different sets. Match the # on both cards."+ : recoverDuplicateCards+ ? "Use two different cards from the same set."+ : recoverError;++ useEffect(() => {+ if (!secret.trim()) {+ setSplitSnapshot(EMPTY_SPLIT_SNAPSHOT);+ }+ }, [secret]);++ useEffect(() => {+ if (!deferredSecret.trim()) return;+ setSplitSnapshot(splitIfPossible(deferredSecret));+ }, [deferredSecret]);++ useEffect(() => {+ setRecoveredSecret("");+ setRecoverError(null);+ }, [recoverSlots]);++ useEffect(() => {+ setActionError(null);+ setCopiedCardIndex(null);+ }, [secret]);++ useEffect(() => {+ if (copiedCardIndex === null) return;+ const timer = window.setTimeout(() => {+ setCopiedCardIndex(null);+ }, 1600);+ return () => window.clearTimeout(timer);+ }, [copiedCardIndex]);++ useEffect(() => {+ if (!copiedRecoveredSecret) return;+ const timer = window.setTimeout(() => {+ setCopiedRecoveredSecret(false);+ }, 1600);+ return () => window.clearTimeout(timer);+ }, [copiedRecoveredSecret]);++ const makeCardFile = async (card: ShareCardState) => {+ const canvas = await renderShareCard({+ qrModules: card.qr.modules,+ qrSize: card.qr.viewBoxSize,+ shareIndex: card.index,+ shareText: card.encoded,+ title: cardLabel,+ });+ const blob = await canvasToBlob(canvas);+ const filename = `${sanitizeFilename(cardLabel)}-set-${card.fingerprint.toLowerCase()}-card-${card.index}.png`;+ return new File([blob], filename, { type: "image/png" });+ };++ const runCardAction = async (+ index: number,+ action: (file: File, card: ShareCardState) => Promise<void> | void,+ ) => {+ const card = cards[index];+ if (!card || isCardsStale) return;+ setActionError(null);+ setBusyCard(index);++ try {+ const file = await makeCardFile(card);+ await action(file, card);+ } catch (error) {+ setActionError(+ error instanceof Error ? error.message : "That action failed.",+ );+ } finally {+ setBusyCard(null);+ }+ };++ const onDownloadAll = async () => {+ if (!isReady) return;+ setActionError(null);+ setDownloadAllBusy(true);++ try {+ for (const card of cards) {+ const file = await makeCardFile(card);+ downloadBlob(file, file.name);+ }++ const recovery = offlineRecoveryFile();+ downloadBlob(recovery, recovery.name);+ } catch (error) {+ setActionError(+ error instanceof Error+ ? error.message+ : "Could not download the kit.",+ );+ } finally {+ setDownloadAllBusy(false);+ }+ };++ const onRecover = () => {+ setRecoveredSecret("");+ setRecoverError(null);+ setCopiedRecoveredSecret(false);++ if (!hasTwoRecoverValues) {+ setRecoverError("Upload or paste two cards first.");+ return;+ }++ if (recoverMismatch) {+ setRecoverError(+ "These two cards are from different sets. Match the # on both cards.",+ );+ return;+ }++ if (recoverDuplicateCards) {+ setRecoverError("Use two different cards from the same set.");+ return;+ }++ try {+ const result = combineShares(+ recoverSlots[0]!.value,+ recoverSlots[1]!.value,+ );+ setRecoveredSecret(result);+ } catch (error) {+ setRecoverError(+ error instanceof Error+ ? error.message+ : "Could not recover secret.",+ );+ }+ };++ const onCopyCardCode = async (card: ShareCardState) => {+ if (isCardsStale) return;+ setActionError(null);++ try {+ await copyTextToClipboard(card.encoded);+ setCopiedCardIndex(card.index - 1);+ } catch (error) {+ setActionError(+ error instanceof Error+ ? error.message+ : "Could not copy that code.",+ );+ }+ };++ const onRecoverFile = async (+ slotIndex: number,+ event: ChangeEvent<HTMLInputElement>,+ ) => {+ const file = event.target.files?.[0];+ if (!file) return;++ try {+ const value = await readShareFile(file);+ parseShare(value);+ setRecoverSlots((previous) =>+ previous.map((slot, index) =>+ index === slotIndex ? { fileName: file.name, value } : slot,+ ),+ );+ setRecoverError(null);+ } catch (error) {+ setRecoverError(+ error instanceof Error+ ? error.message+ : "Could not read that share.",+ );+ } finally {+ event.target.value = "";+ }+ };++ return (+ <>+ <Head>+ <meta+ name="description"+ content="Split an Ente recovery key, master password, or another secret into three printable cards. Any two recover it."+ />+ <meta property="og:title" content="2of3" />+ <meta+ property="og:description"+ content="A direct, printable 2-of-3 split for important secrets."+ />+ </Head>++ <Box+ sx={(theme) => ({+ "--app-bg":+ theme.palette.mode === "dark" ? "#0b0b0b" : "#ffffff",+ "--shell":+ theme.palette.mode === "dark" ? "#111111" : "#ffffff",+ "--paper":+ theme.palette.mode === "dark" ? "#111111" : "#ffffff",+ "--field":+ theme.palette.mode === "dark"+ ? "rgba(252,239,93,0.16)"+ : "rgba(252,239,93,0.18)",+ "--field-soft":+ theme.palette.mode === "dark"+ ? "rgba(252,239,93,0.1)"+ : "rgba(252,239,93,0.12)",+ "--ink":+ theme.palette.mode === "dark" ? "#fafafa" : "#111111",+ "--muted":+ theme.palette.mode === "dark"+ ? "rgba(250,250,250,0.68)"+ : "rgba(17,17,17,0.68)",+ "--line":+ theme.palette.mode === "dark"+ ? "rgba(255,255,255,0.18)"+ : "rgba(17,17,17,0.18)",+ "--line-strong":+ theme.palette.mode === "dark"+ ? "rgba(255,255,255,0.24)"+ : "rgba(17,17,17,0.22)",+ "--accent": theme.palette.primary.main,+ minHeight: "100vh",+ bgcolor: "var(--app-bg)",+ color: "var(--ink)",+ backgroundImage: "none",+ })}+ >+ <Container maxWidth="xl" sx={{ py: { xs: 2, md: 3 } }}>+ <Stack spacing={3}>+ <Stack+ direction="row"+ justifyContent="space-between"+ alignItems="center"+ sx={{ px: { xs: 0.5, md: 1 } }}+ >+ <Typography+ sx={{+ fontWeight: 700,+ letterSpacing: "-0.07em",+ fontSize: { xs: "1.7rem", md: "2rem" },+ }}+ >+ 2of3+ </Typography>+ <Box+ sx={{+ fontSize: { xs: "0.85rem", md: "0.95rem" },+ color: "var(--muted)",+ display: "flex",+ alignItems: "center",+ gap: 0.4,+ }}+ >+ <Box component="span">by</Box>+ <Box+ component="a"+ href="https://ente.io"+ target="_blank"+ rel="noreferrer"+ sx={{+ color: "var(--ink)",+ fontWeight: 700,+ textDecoration: "none",+ "&:hover": {+ textDecoration: "underline",+ },+ }}+ >+ Ente+ </Box>+ </Box>+ </Stack>++ <Box+ sx={{+ border: "2px solid",+ borderColor: "var(--ink)",+ borderRadius: "32px",+ overflow: "hidden",+ bgcolor: "var(--shell)",+ boxShadow: "0 22px 48px rgba(17,17,17,0.06)",+ display: "grid",+ gridTemplateColumns: {+ xs: "1fr",+ lg: "minmax(320px, 430px) minmax(0, 1fr)",+ },+ minHeight: { lg: "calc(100svh - 112px)" },+ }}+ >+ <Stack+ spacing={2.2}+ sx={{+ p: { xs: 2.25, md: 3 },+ bgcolor: "var(--paper)",+ borderRight: {+ xs: "none",+ lg: "2px solid",+ },+ borderBottom: {+ xs: "2px solid",+ lg: "none",+ },+ borderColor: "var(--ink)",+ }}+ >+ <Box+ sx={{+ width: "fit-content",+ px: 1.35,+ py: 0.7,+ borderRadius: "999px",+ border: "1.5px solid",+ borderColor: "var(--ink)",+ bgcolor: "var(--accent)",+ }}+ >+ <Typography+ sx={{+ fontSize: "0.86rem",+ fontWeight: 700,+ color: "#111111",+ }}+ >+ Any 2 cards recover it+ </Typography>+ </Box>++ <Typography+ variant="h1"+ sx={{+ fontSize: {+ xs: "2.65rem",+ md: "3.45rem",+ },+ lineHeight: 0.9,+ maxWidth: 360,+ }}+ >+ Enter a secret.+ <br />+ Get 3 cards.+ </Typography>++ <Typography+ sx={{+ color: "var(--muted)",+ maxWidth: 360,+ fontSize: "0.98rem",+ }}+ >+ Turn a recovery key, password, or other+ secret into 3 cards you can keep in+ different places.+ </Typography>++ <TextField+ label="Secret"+ multiline+ minRows={7}+ maxRows={12}+ value={secret}+ onChange={(event) =>+ setSecret(+ trimToByteLength(+ event.target.value,+ MAX_SECRET_BYTES_FOR_PRINTED_CARD,+ ),+ )+ }+ sx={fieldSx}+ />++ <Stack spacing={0.8}>+ <TextField+ label="Card label (optional)"+ value={title}+ placeholder={todayLabel()}+ onChange={(event) =>+ setTitle(event.target.value)+ }+ sx={fieldSx}+ />+ <Typography+ sx={{+ color: "var(--muted)",+ fontSize: "0.88rem",+ textAlign: "right",+ }}+ >+ {secretLength}/+ {MAX_SECRET_BYTES_FOR_PRINTED_CARD}+ </Typography>+ </Stack>++ <Stack spacing={1.1} alignItems="flex-start">+ <Button+ variant="contained"+ size="large"+ disabled={!isReady || downloadAllBusy}+ onClick={() => {+ void onDownloadAll();+ }}+ sx={{+ px: 2.6,+ py: 1.25,+ borderRadius: "999px",+ border: "1.5px solid",+ borderColor: "var(--line-strong)",+ bgcolor: "var(--accent)",+ color: "#111111",+ boxShadow: "none",+ "&:hover": {+ boxShadow: "none",+ borderColor: "var(--ink)",+ bgcolor: "var(--accent)",+ },+ "&.Mui-disabled": {+ bgcolor: "transparent",+ color: "var(--muted)",+ borderColor:+ "var(--line-strong)",+ },+ }}+ >+ {downloadAllBusy+ ? "Preparing downloads..."+ : "Download all cards"}+ </Button>+ <Typography+ sx={{+ color: "var(--muted)",+ fontSize: "0.9rem",+ }}+ >+ Includes an offline recovery page.+ </Typography>+ </Stack>++ {inputStatus && (+ <Note tone="accent">{inputStatus}</Note>+ )}+ </Stack>++ <Stack+ spacing={2}+ sx={{ p: { xs: 1.75, md: 2.25 } }}+ >+ <Stack+ spacing={0.65}+ sx={{ px: { xs: 0.3, md: 0.6 } }}+ >+ <Typography+ sx={{+ fontWeight: 700,+ fontSize: "1.05rem",+ }}+ >+ 3 recovery cards+ </Typography>+ <Typography+ sx={{+ color: "var(--muted)",+ fontSize: "0.93rem",+ }}+ >+ Each card is harmless on its own. Print,+ save, or share them separately.+ </Typography>+ </Stack>++ <Box+ sx={{+ display: "grid",+ gridTemplateColumns: {+ xs: "1fr",+ md: "repeat(2, minmax(0, 1fr))",+ },+ gap: 1.5,+ alignContent: "start",+ }}+ >+ {Array.from({ length: 3 }, (_, index) => {+ const card = cards[index];+ const fingerprint = card+ ? `#${card.fingerprint}`+ : null;++ return (+ <Stack+ key={index}+ sx={{+ border: "1.5px solid",+ borderColor: "var(--ink)",+ borderRadius: "26px",+ bgcolor: "var(--paper)",+ boxShadow:+ "0 14px 28px rgba(17,17,17,0.06)",+ minHeight: 0,+ overflow: "hidden",+ }}+ >+ <Box+ sx={{+ px: 1.35,+ py: 1.05,+ bgcolor:+ "var(--accent)",+ borderBottom:+ "1.5px solid",+ borderColor:+ "var(--ink)",+ }}+ >+ <Stack+ direction="row"+ justifyContent="space-between"+ alignItems="center"+ spacing={1}+ >+ <Typography+ sx={{+ fontWeight: 700,+ fontSize:+ "0.92rem",+ color: "#111111",+ }}+ >+ Card {index + 1}+ </Typography>+ <Typography+ sx={{+ color: "rgba(17,17,17,0.62)",+ fontSize:+ "0.8rem",+ fontWeight: 500,+ }}+ >+ {APP_LINK}+ </Typography>+ </Stack>+ </Box>++ <Stack+ spacing={1.2}+ sx={{ p: 1.35 }}+ >+ <Typography+ sx={{+ fontWeight: 700,+ fontSize: "1rem",+ lineHeight: 1.2,+ }}+ >+ {cardLabel}+ </Typography>++ <Box+ sx={{+ aspectRatio:+ "1 / 1",+ border: "1.5px solid",+ borderColor:+ "var(--line-strong)",+ bgcolor: "#ffffff",+ borderRadius:+ "22px",+ overflow: "hidden",+ p: 1.35,+ display: "grid",+ placeItems:+ "center",+ }}+ >+ {card ? (+ <QrPreview+ value={card.qr}+ />+ ) : (+ <Typography+ sx={{+ textAlign:+ "center",+ color: "#111111",+ opacity: 0.6,+ px: 3,+ fontSize:+ "0.95rem",+ }}+ >+ Enter a secret+ to generate card{" "}+ {index + 1}.+ </Typography>+ )}+ </Box>++ {card && (+ <Stack+ direction="row"+ justifyContent="space-between"+ alignItems="center"+ spacing={1}+ sx={{ mt: 0.15 }}+ >+ <Button+ variant="text"+ size="small"+ disabled={+ isCardsStale+ }+ onClick={() => {+ void onCopyCardCode(+ card,+ );+ }}+ sx={{+ minWidth: 0,+ px: 0,+ py: 0,+ color: "var(--muted)",+ fontSize:+ "0.8rem",+ fontWeight: 700,+ textTransform:+ "none",+ "&:hover": {+ bgcolor:+ "transparent",+ color: "var(--ink)",+ },+ }}+ >+ {copiedCardIndex ===+ index+ ? "Copied"+ : "Copy code"}+ </Button>+ <Typography+ sx={{+ color: "var(--muted)",+ fontSize:+ "0.78rem",+ fontWeight: 500,+ textAlign:+ "right",+ }}+ >+ {fingerprint}+ </Typography>+ </Stack>+ )}++ <Stack+ direction="row"+ spacing={0.8}+ useFlexGap+ flexWrap="wrap"+ >+ <ActionButton+ disabled={+ !card ||+ isCardsStale ||+ busyCard ===+ index+ }+ onClick={() => {+ void runCardAction(+ index,+ (file) => {+ printBlob(+ file,+ file.name,+ );+ },+ );+ }}+ >+ </ActionButton>+ <ActionButton+ disabled={+ !card ||+ isCardsStale ||+ busyCard ===+ index+ }+ onClick={() => {+ void runCardAction(+ index,+ (file) => {+ downloadBlob(+ file,+ file.name,+ );+ },+ );+ }}+ >+ Download+ </ActionButton>+ <ActionButton+ disabled={+ !card ||+ isCardsStale ||+ busyCard ===+ index+ }+ onClick={() => {+ void runCardAction(+ index,+ async (+ file,+ ) => {+ try {+ await shareFiles(+ [+ file,+ ],+ );+ } catch {+ downloadBlob(+ file,+ file.name,+ );+ }+ },+ );+ }}+ >+ Share+ </ActionButton>+ </Stack>+ </Stack>+ </Stack>+ );+ })}+ </Box>+ </Stack>+ </Box>++ <Box+ sx={{+ border: "2px solid",+ borderColor: "var(--ink)",+ borderRadius: "28px",+ overflow: "hidden",+ bgcolor: "var(--shell)",+ boxShadow: "0 16px 34px rgba(17,17,17,0.04)",+ }}+ >+ <Stack+ spacing={2.25}+ sx={{ p: { xs: 2.1, md: 2.6 } }}+ >+ <Box+ sx={{+ width: "fit-content",+ px: 1.1,+ py: 0.45,+ borderRadius: "999px",+ bgcolor: "var(--paper)",+ border: "1.5px solid",+ borderColor: "var(--line-strong)",+ }}+ >+ <Typography+ sx={{+ fontWeight: 700,+ fontSize: "0.82rem",+ }}+ >+ Recover later+ </Typography>+ </Box>++ <Box>+ <Typography+ variant="h2"+ sx={{+ fontSize: {+ xs: "2rem",+ md: "2.55rem",+ },+ lineHeight: 0.92,+ }}+ >+ Use any 2 cards to recover+ </Typography>+ <Typography+ sx={{+ color: "var(--muted)",+ mt: 1,+ maxWidth: 680,+ }}+ >+ Upload two card images, or paste two+ codes if you copied them earlier.+ </Typography>+ </Box>++ <Box+ sx={{+ display: "grid",+ gridTemplateColumns: {+ xs: "1fr",+ md: "repeat(2, minmax(0, 1fr))",+ },+ gap: 1.5,+ }}+ >+ {recoverSlots.map((slot, index) => {+ const slotDetails =+ recoverSlotDetails[index];++ return (+ <Stack+ key={index}+ spacing={1.15}+ sx={{+ p: 1.45,+ border: "1.5px solid",+ borderColor:+ "var(--line-strong)",+ borderRadius: "24px",+ bgcolor: "var(--paper)",+ }}+ >+ <Stack+ direction="row"+ justifyContent="space-between"+ alignItems="center"+ spacing={1}+ >+ <Box+ sx={{+ width: "fit-content",+ px: 1,+ py: 0.42,+ borderRadius:+ "999px",+ border: "1.5px solid",+ borderColor:+ "var(--line-strong)",+ }}+ >+ <Typography+ sx={{+ fontWeight: 700,+ fontSize:+ "0.84rem",+ }}+ >+ Card {index + 1}+ </Typography>+ </Box>+ <Button+ variant="outlined"+ component="label"+ size="small"+ sx={{+ alignSelf:+ "flex-start",+ borderWidth:+ "1.5px",+ borderColor:+ "var(--line-strong)",+ color: "var(--ink)",+ bgcolor:+ "var(--paper)",+ "&:hover": {+ borderWidth:+ "1.5px",+ borderColor:+ "var(--ink)",+ },+ }}+ >+ {slot.fileName+ ? "Replace image"+ : "Upload image"}+ <input+ hidden+ type="file"+ accept="image/*,text/plain"+ onChange={(+ event,+ ) => {+ void onRecoverFile(+ index,+ event,+ );+ }}+ />+ </Button>+ </Stack>++ <Typography+ sx={{+ color:+ slot.fileName ||+ slotDetails+ ? "var(--ink)"+ : "var(--muted)",+ fontSize: "0.88rem",+ }}+ >+ {slotDetails+ ? `${slot.fileName ? `${slot.fileName} Β· ` : ""}Card ${slotDetails.index} from #${slotDetails.fingerprint}`+ : slot.fileName+ ? slot.fileName+ : "Upload a saved card image, or paste a copied code."}+ </Typography>+ <TextField+ label={`Code ${index + 1}`}+ multiline+ minRows={6}+ value={slot.value}+ onChange={(event) =>+ setRecoverSlots(+ (previous) =>+ previous.map(+ (+ current,+ currentIndex,+ ) =>+ currentIndex ===+ index+ ? {+ ...current,+ fileName:+ "",+ value: event+ .target+ .value,+ }+ : current,+ ),+ )+ }+ placeholder={`Paste code ${index + 1}`}+ sx={fieldSx}+ />+ </Stack>+ );+ })}+ </Box>++ {recoverStatus && (+ <Note tone="accent">{recoverStatus}</Note>+ )}++ <Stack+ direction={{ xs: "column", sm: "row" }}+ spacing={1.25}+ alignItems={{+ xs: "stretch",+ sm: "flex-start",+ }}+ >+ <Button+ variant="outlined"+ size="large"+ onClick={onRecover}+ disabled={!canRecover}+ sx={{+ alignSelf: "flex-start",+ px: 2.3,+ py: 1.15,+ borderRadius: "999px",+ borderWidth: "1.5px",+ borderColor: "var(--ink)",+ color: "#111111",+ bgcolor: "var(--accent)",+ "&:hover": {+ borderWidth: "1.5px",+ borderColor: "var(--ink)",+ bgcolor: "var(--accent)",+ },+ "&.Mui-disabled": {+ bgcolor: "transparent",+ color: "var(--muted)",+ borderColor:+ "var(--line-strong)",+ },+ }}+ >+ Recover secret+ </Button>+ </Stack>++ {recoveredSecret && (+ <Stack+ spacing={1.2}+ sx={{+ p: 1.45,+ border: "1.5px solid",+ borderColor: "var(--ink)",+ borderRadius: "24px",+ bgcolor: "var(--field-soft)",+ }}+ >+ <Stack+ direction={{+ xs: "column",+ sm: "row",+ }}+ justifyContent="space-between"+ alignItems={{+ xs: "flex-start",+ sm: "center",+ }}+ spacing={1}+ >+ <Typography+ sx={{+ fontWeight: 700,+ fontSize: "1rem",+ }}+ >+ Recovered secret+ </Typography>+ <Button+ variant="outlined"+ size="small"+ onClick={() => {+ void copyTextToClipboard(+ recoveredSecret,+ )+ .then(() => {+ setCopiedRecoveredSecret(+ true,+ );+ })+ .catch(+ (+ error: unknown,+ ) => {+ setRecoverError(+ error instanceof+ Error+ ? error.message+ : "Could not copy the recovered secret.",+ );+ },+ );+ }}+ sx={{+ borderWidth: "1.5px",+ borderColor: "var(--ink)",+ color: "#111111",+ bgcolor: "var(--accent)",+ "&:hover": {+ borderWidth: "1.5px",+ borderColor:+ "var(--ink)",+ bgcolor:+ "var(--accent)",+ },+ }}+ >+ {copiedRecoveredSecret+ ? "Copied"+ : "Copy"}+ </Button>+ </Stack>++ <TextField+ multiline+ minRows={4}+ value={recoveredSecret}+ slotProps={{+ input: { readOnly: true },+ }}+ sx={fieldSx}+ />+ </Stack>+ )}+ </Stack>+ </Box>+ </Stack>+ </Container>+ </Box>+ </>+ );+};++export default Page;diff --git a/web/apps/twoof3/tsconfig.json b/web/apps/twoof3/tsconfig.jsonnew file mode 100644index 0000000000..f6be56cfbf--- /dev/null+++ b/web/apps/twoof3/tsconfig.json@@ -0,0 +1,10 @@+{+ "extends": "ente-build-config/tsconfig-next.json",+ "compilerOptions": { "baseUrl": "./src" },+ "include": [+ "src",+ "next-env.d.ts",+ "../../packages/base/global-electron.d.ts",+ "../../packages/base/components/utils/mui-theme.d.ts"+ ]+}diff --git a/web/package.json b/web/package.jsonindex eca972a742..c2dc2374b2 100644--- a/web/package.json+++ b/web/package.json@@ -18,6 +18,7 @@"build:payments": "yarn workspace payments build","build:photos": "yarn build:wasm && yarn workspace photos next build","build:share": "yarn build:wasm && yarn workspace share next build && yarn workspace share build:post",+ "build:twoof3": "yarn workspace twoof3 next build","build:wasm": "yarn workspace ente-wasm build --no-pack","dev": "yarn dev:photos","dev:accounts": "yarn build:wasm && yarn workspace accounts next dev -p 3001",@@ -31,6 +32,7 @@"dev:payments": "yarn workspace payments dev","dev:photos": "yarn build:wasm && yarn workspace photos next dev -p 3000","dev:share": "yarn build:wasm && yarn workspace share next dev -p 3005",+ "dev:twoof3": "yarn workspace twoof3 next dev -p 3009","lint": "concurrently --names 'prettier,eslint,tsc' \"yarn prettier --check --log-level warn .\" \"yarn workspaces run eslint\" \"yarn workspaces run tsc\"","lint-fix": "concurrently --names 'prettier,eslint,tsc' \"yarn prettier --write --log-level warn .\" \"yarn workspaces run eslint --fix\" \"yarn workspaces run tsc\"","test": "yarn workspace ente-wasm test",diff --git a/web/yarn.lock b/web/yarn.lockindex b379f922e6..40f439f34f 100644--- a/web/yarn.lock+++ b/web/yarn.lock@@ -660,6 +660,11 @@resolved "https://registry.npmjs.org/@fontsource/source-serif-4/-/source-serif-4-5.2.9.tgz"integrity sha512-er/Pym9emsEVJNf947umJ4kXarXfsiN6CN7kTYinefKRaHLwiquiiHOZvKvxWgkV8JMCf3pV3g0NcsPFpVCH9w==+"@fontsource/space-grotesk@^5.2.10":+ version "5.2.10"+ resolved "https://registry.yarnpkg.com/@fontsource/space-grotesk/-/space-grotesk-5.2.10.tgz#36eef6a105be125d1025c206eb48f1a3d37ad512"+ integrity sha512-XNXEbT74OIITPqw2H6HXwPDp85fy43uxfBwFR5PU+9sLnjuLj12KlhVM9nZVN6q6dlKjkuN8JisW/OBxwxgUew==+"@hugeicons/core-free-icons@^1.0.5", "@hugeicons/core-free-icons@^1.1.0":version "1.2.1"resolved "https://registry.npmjs.org/@hugeicons/core-free-icons/-/core-free-icons-1.2.1.tgz"@@ -4230,6 +4235,11 @@ natural-compare@^1.4.0:resolved "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz"integrity sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==+nayuki-qr-code-generator@^1.8.0:+ version "1.8.0"+ resolved "https://registry.yarnpkg.com/nayuki-qr-code-generator/-/nayuki-qr-code-generator-1.8.0.tgz#dbeebd7b3d2b53119c51a596ad43199ef6798916"+ integrity sha512-wnpXdJ+zJ+8QzzGJTEnESaRYfNIUHSgX4ykvYuaomqqUbhJdun3v0sK/39BQjw3on/vf7ujPKIg2V07WejjmLw==+next@^15.5.9:version "15.5.9"resolved "https://registry.npmjs.org/next/-/next-15.5.9.tgz"