Repository Public
1// Import (CSV / JSON exports of other managers) and export (encrypted backup, plaintext on explicit request).2import { type Bytes, b64u, ctx, fromUtf8, random, unb64u, utf8, uuid } from "./bytes.ts";3import { aeadOpen, aeadSeal, hkdf } from "./primitives.ts";4import { type Item, newItem, normalizeItem, type VaultMeta } from "./items.ts";5import { type KeysetBlob, openRecoveryEnvelope } from "./keys.ts";67// ── CSV (RFC 4180) ────────────────────────────────────────────────────────────────────────────────────────────89export function parseCsv(text: string): string[][] {10 if (text.length > 50_000_000) throw new Error("file too large");11 const rows: string[][] = [];12 let row: string[] = [], cell = "", quoted = false, i = 0;13 const t = text.replace(/^/, "");14 while (i < t.length) {15 const c = t[i]!;16 if (quoted) {17 if (c === '"') { if (t[i + 1] === '"') { cell += '"'; i += 2; continue; } quoted = false; i++; continue; }18 cell += c; i++; continue;19 }20 if (c === '"' && cell === "") { quoted = true; i++; continue; }21 if (c === ",") { row.push(cell); cell = ""; i++; continue; }22 if (c === "\n" || c === "\r") {23 if (c === "\r" && t[i + 1] === "\n") i++;24 row.push(cell); cell = ""; if (row.length > 1 || row[0] !== "") rows.push(row); row = []; i++; continue;25 }26 cell += c; i++;27 }28 if (quoted) throw new Error("unterminated quoted field");29 row.push(cell);30 if (row.length > 1 || row[0] !== "") rows.push(row);31 return rows;32}3334export type ImportFormat = "apple" | "1password" | "bitwarden-csv" | "bitwarden-json" | "chrome" | "generic";35export interface ImportResult { format: ImportFormat; items: Item[]; skipped: number; warnings: string[] }3637const login = (title: string, url: string, username: string, password: string, notes: string, totp: string): Item => {38 const it = newItem("login", title || hostOf(url) || username || "Imported login");39 if (username) it.fields.username = username;40 if (password) it.fields.password = password;41 if (totp) it.fields.totp = totp;42 if (url) it.urls = url.split(/[\n,]\s*(?=https?:\/\/)/).filter(Boolean).map((u) => ({ url: u.trim(), match: "domain" as const }));43 it.notes = notes ?? "";44 return it;45};46const hostOf = (u: string) => { try { return new URL(/^[a-z]+:\/\//i.test(u) ? u : "https://" + u).hostname.replace(/^www\./, ""); } catch { return ""; } };4748function detectCsv(header: string[]): ImportFormat {49 const h = header.map((x) => x.trim().toLowerCase());50 const has = (...k: string[]) => k.every((x) => h.includes(x));51 if (has("login_uri", "login_username", "login_password")) return "bitwarden-csv";52 if (has("title", "url", "username", "password", "otpauth") && h.includes("favorite")) return "1password";53 if (has("title", "url", "username", "password") && (h.includes("otpauth") || h.includes("notes"))) return "apple";54 if (has("name", "url", "username", "password")) return "chrome";55 return "generic";56}5758export function importCsv(text: string): ImportResult {59 const rows = parseCsv(text);60 if (rows.length < 1) throw new Error("the file is empty");61 const header = rows[0]!.map((x) => x.trim().toLowerCase()), format = detectCsv(header);62 const col = (...names: string[]) => { for (const n of names) { const i = header.indexOf(n); if (i >= 0) return i; } return -1; };63 const c = {64 title: col("title", "name", "account", "site"), url: col("url", "login_uri", "website", "web site", "uri"), user: col("username", "login_username", "login", "user", "email"),65 pass: col("password", "login_password", "pass"), notes: col("notes", "note", "comments"), totp: col("otpauth", "login_totp", "totp", "otp"),66 fav: col("favorite"), tags: col("tags", "folder"), type: col("type"),67 };68 if (c.pass < 0 && format === "generic") throw new Error("no password column found; expected a header row such as title,url,username,password");69 const items: Item[] = [], warnings: string[] = [];70 let skipped = 0;71 for (const r of rows.slice(1)) {72 const g = (i: number) => (i >= 0 ? (r[i] ?? "").trim() : "");73 if (format === "bitwarden-csv" && g(c.type) === "note") {74 const n = newItem("note", g(c.title) || "Imported note"); n.notes = g(c.notes); items.push(n); continue;75 }76 if (!g(c.pass) && !g(c.user) && !g(c.url) && !g(c.notes)) { skipped++; continue; }77 const it = login(g(c.title), g(c.url), g(c.user), c.pass >= 0 ? (r[c.pass] ?? "") : "", g(c.notes), g(c.totp));78 if (g(c.fav) === "1" || g(c.fav).toLowerCase() === "true") it.favorite = true;79 if (g(c.tags)) it.tags = g(c.tags).split(/[;,/]/).map((x) => x.trim()).filter(Boolean);80 items.push(it);81 }82 if (format === "generic") warnings.push("Unrecognised layout: columns were mapped by name. Review the imported items.");83 return { format, items: items.map(normalizeItem), skipped, warnings };84}8586/** Bitwarden unencrypted JSON export. Encrypted exports are refused (they need Bitwarden's key). */87export function importBitwardenJson(text: string): ImportResult {88 const j = JSON.parse(text);89 if (j?.encrypted) throw new Error("this Bitwarden export is encrypted; export as unencrypted JSON, import, then delete the file");90 if (!Array.isArray(j?.items)) throw new Error("not a Bitwarden JSON export");91 const folders = new Map<string, string>((j.folders ?? []).map((f: any) => [f.id, f.name]));92 const items: Item[] = [];93 let skipped = 0;94 for (const x of j.items) {95 let it: Item;96 if (x.type === 1) {97 it = login(x.name ?? "", "", x.login?.username ?? "", x.login?.password ?? "", x.notes ?? "", x.login?.totp ?? "");98 it.urls = (x.login?.uris ?? []).filter((u: any) => u?.uri).map((u: any) => ({ url: u.uri, match: u.match === 3 ? "exact" : u.match === 1 ? "host" : u.match === 5 ? "never" : "domain" }));99 } else if (x.type === 2) { it = newItem("note", x.name ?? ""); it.notes = x.notes ?? ""; }100 else if (x.type === 3) {101 it = newItem("card", x.name ?? ""); it.notes = x.notes ?? "";102 it.fields = { holder: x.card?.cardholderName ?? "", number: x.card?.number ?? "", cvv: x.card?.code ?? "", expiry: x.card?.expMonth ? `${String(x.card.expMonth).padStart(2, "0")}/${String(x.card.expYear ?? "").slice(-2)}` : "" };103 } else if (x.type === 4) {104 it = newItem("identity", x.name ?? ""); it.notes = x.notes ?? "";105 it.fields = { fullName: [x.identity?.firstName, x.identity?.middleName, x.identity?.lastName].filter(Boolean).join(" "), number: x.identity?.passportNumber ?? x.identity?.licenseNumber ?? x.identity?.ssn ?? "", country: x.identity?.country ?? "" };106 } else { skipped++; continue; }107 for (const f of x.fields ?? []) if (f?.name) it.custom.push({ label: String(f.name), value: String(f.value ?? ""), kind: f.type === 1 ? "secret" : "text" });108 if (x.favorite) it.favorite = true;109 if (x.folderId && folders.get(x.folderId)) it.tags = [folders.get(x.folderId)!];110 items.push(normalizeItem(it));111 }112 return { format: "bitwarden-json", items, skipped, warnings: [] };113}114115export function importAny(fileName: string, text: string): ImportResult {116 const trimmed = text.trimStart();117 if (fileName.toLowerCase().endsWith(".json") || trimmed.startsWith("{")) return importBitwardenJson(text);118 return importCsv(text);119}120121// ── Plaintext export (explicit, after reauthentication) ───────────────────────────────────────────────────────122123// Spreadsheet formula injection: a leading = + - @ (or tab / CR) is neutralised with an apostrophe, except in the password124// column, which must round-trip exactly (it is quoted, and importers read it as text).125const q = (s: string, raw = false) => `"${((!raw && /^[=+\-@\t\r]/.test(s ?? "")) ? "'" + s : (s ?? "")).replace(/"/g, '""')}"`;126export function exportCsv(items: Item[]): string {127 const rows = [["Title", "URL", "Username", "Password", "Notes", "OTPAuth"].join(",")];128 for (const it of items) if (it.type === "login") rows.push([q(it.title), q(it.urls[0]?.url ?? ""), q(it.fields.username ?? ""), q(it.fields.password ?? "", true), q(it.notes), q(it.fields.totp ?? "")].join(","));129 return rows.join("\r\n") + "\r\n";130}131132// ── Encrypted offline backup ──────────────────────────────────────────────────────────────────────────────────133// Self-contained: restorable with the file + the recovery key, without the server.134// backup key = HKDF(ARK, info=ctx("backup-key", backup_id)); the file carries the recovery envelope (ARK under RK).135136export interface BackupFile {137 format: "spvault-backup"; v: 1; backupId: string; accountId: string; createdAt: string; recoveryEpoch: number;138 recoveryEnvelope: string; keyset: KeysetBlob; nonce: string; ct: string;139}140export interface BackupPayload { vaults: { id: string; meta: VaultMeta; items: { id: string; item: Item }[] }[] }141142export async function createBackup(ark: Bytes, accountId: string, recovery: { epoch: number; envelope: string }, keyset: KeysetBlob, payload: BackupPayload): Promise<BackupFile> {143 const backupId = uuid(), createdAt = new Date().toISOString(), nonce = random(12);144 const key = await hkdf(ark, new Uint8Array(0), ctx("backup-key", backupId));145 const ct = await aeadSeal(key, nonce, utf8(JSON.stringify(payload)), ctx("backup", backupId, accountId, createdAt));146 return { format: "spvault-backup", v: 1, backupId, accountId, createdAt, recoveryEpoch: recovery.epoch, recoveryEnvelope: recovery.envelope, keyset, nonce: b64u(nonce), ct: b64u(ct) };147}148149export function parseBackup(text: string): BackupFile {150 const f = JSON.parse(text) as BackupFile;151 if (f?.format !== "spvault-backup" || f.v !== 1) throw new Error("not an SP Vault backup (or unsupported version)");152 return f;153}154155/** Opens a backup with either the unlocked ARK or the recovery key. */156export async function openBackup(f: BackupFile, secret: { ark: Bytes } | { recoveryKey: Bytes }): Promise<{ ark: Bytes; payload: BackupPayload }> {157 const ark = "ark" in secret ? secret.ark : await openRecoveryEnvelope(secret.recoveryKey, f.accountId, f.recoveryEpoch, f.recoveryEnvelope);158 const key = await hkdf(ark, new Uint8Array(0), ctx("backup-key", f.backupId));159 const pt = await aeadOpen(key, unb64u(f.nonce), unb64u(f.ct), ctx("backup", f.backupId, f.accountId, f.createdAt));160 const payload = JSON.parse(fromUtf8(pt)) as BackupPayload;161 for (const v of payload.vaults) v.items = v.items.map((x) => ({ id: x.id, item: normalizeItem(x.item) }));162 return { ark, payload };163}164165