SPB Git

Repository Public

items.ts 9.6 KB 140 lines typescript

1// Plaintext item model (what lives inside an encrypted "item" record). Shared by web and Swift (same JSON).2import type { AttachmentRef } from "./record.ts";34export type ItemType =5  | "login" | "passkey" | "card" | "identity" | "note" | "wifi" | "license" | "document"6  | "ssh-key" | "api-token" | "certificate" | "database" | "env";78export type FieldKind = "text" | "secret" | "url" | "multiline" | "date" | "totp";9export interface FieldDef { key: string; label: string; kind: FieldKind }10export interface CustomField { label: string; value: string; kind: FieldKind }11export type UrlMatch = "domain" | "host" | "exact" | "never";12export interface ItemUrl { url: string; match: UrlMatch }1314export interface Item {15  type: ItemType;16  title: string;17  fields: Record<string, string>;18  urls: ItemUrl[];19  custom: CustomField[];20  notes: string;21  tags: string[];22  favorite: boolean;23  collection?: string;24  attachments: AttachmentRef[];25  passwordHistory: { value: string; at: string }[];26  expiresAt?: string;        // ISO date: credential / document / certificate expiry27  rotateEveryDays?: number;  // rotation schedule (developer secrets)28  createdAt: string;29  updatedAt: string;30  conflictOf?: string;       // record id this item is a conflict copy of31  deleted?: boolean;         // tombstone32  trashedAt?: string;        // in trash (recoverable)33}3435export const TEMPLATES: Record<ItemType, { label: string; section: Section; fields: FieldDef[] }> = {36  login: { label: "Login", section: "passwords", fields: [37    { key: "username", label: "Username", kind: "text" }, { key: "password", label: "Password", kind: "secret" },38    { key: "totp", label: "One-time code", kind: "totp" }, { key: "recoveryCodes", label: "Recovery codes", kind: "multiline" }] },39  passkey: { label: "Passkey", section: "passkeys", fields: [40    { key: "rpId", label: "Website", kind: "text" }, { key: "userName", label: "Account", kind: "text" },41    { key: "credentialId", label: "Credential ID", kind: "text" }, { key: "userHandle", label: "User handle", kind: "text" },42    { key: "privateKey", label: "Private key", kind: "secret" }, { key: "signCount", label: "Signature counter", kind: "text" }] },43  card: { label: "Payment card", section: "cards", fields: [44    { key: "holder", label: "Cardholder", kind: "text" }, { key: "number", label: "Number", kind: "secret" },45    { key: "expiry", label: "Expiry (MM/YY)", kind: "text" }, { key: "cvv", label: "Security code", kind: "secret" },46    { key: "pin", label: "PIN", kind: "secret" }] },47  identity: { label: "Identity document", section: "documents", fields: [48    { key: "kind", label: "Document type", kind: "text" }, { key: "fullName", label: "Full name", kind: "text" },49    { key: "number", label: "Number", kind: "secret" }, { key: "country", label: "Country / issuer", kind: "text" },50    { key: "issued", label: "Issued", kind: "date" }, { key: "birthDate", label: "Date of birth", kind: "date" }] },51  note: { label: "Secure note", section: "notes", fields: [] },52  wifi: { label: "Wi-Fi", section: "passwords", fields: [53    { key: "ssid", label: "Network name", kind: "text" }, { key: "password", label: "Password", kind: "secret" },54    { key: "security", label: "Security", kind: "text" }] },55  license: { label: "Software license", section: "documents", fields: [56    { key: "product", label: "Product", kind: "text" }, { key: "licensee", label: "Licensed to", kind: "text" },57    { key: "key", label: "License key", kind: "secret" }, { key: "version", label: "Version", kind: "text" }] },58  document: { label: "Document", section: "documents", fields: [] },59  "ssh-key": { label: "SSH key", section: "developer", fields: [60    { key: "publicKey", label: "Public key", kind: "multiline" }, { key: "privateKey", label: "Private key", kind: "secret" },61    { key: "fingerprint", label: "Fingerprint", kind: "text" }, { key: "passphrase", label: "Passphrase", kind: "secret" },62    { key: "host", label: "Host", kind: "text" }] },63  "api-token": { label: "API token", section: "developer", fields: [64    { key: "service", label: "Service", kind: "text" }, { key: "keyId", label: "Key ID", kind: "text" },65    { key: "token", label: "Token", kind: "secret" }, { key: "scopes", label: "Scopes", kind: "text" }] },66  certificate: { label: "Certificate", section: "developer", fields: [67    { key: "subject", label: "Subject", kind: "text" }, { key: "certificate", label: "Certificate (PEM)", kind: "multiline" },68    { key: "privateKey", label: "Private key", kind: "secret" }, { key: "issuer", label: "Issuer", kind: "text" }] },69  database: { label: "Database", section: "developer", fields: [70    { key: "engine", label: "Engine", kind: "text" }, { key: "host", label: "Host", kind: "text" },71    { key: "port", label: "Port", kind: "text" }, { key: "database", label: "Database", kind: "text" },72    { key: "username", label: "Username", kind: "text" }, { key: "password", label: "Password", kind: "secret" }] },73  env: { label: "Environment secrets", section: "developer", fields: [74    { key: "project", label: "Project", kind: "text" }, { key: "environment", label: "Environment", kind: "text" },75    { key: "dotenv", label: ".env contents", kind: "secret" }] },76};7778export type Section = "passwords" | "passkeys" | "cards" | "notes" | "documents" | "developer";7980export function newItem(type: ItemType, title = ""): Item {81  const now = new Date().toISOString();82  return { type, title, fields: {}, urls: [], custom: [], notes: "", tags: [], favorite: false, attachments: [], passwordHistory: [], createdAt: now, updatedAt: now };83}8485const str = (v: unknown, max: number) => (typeof v === "string" ? v.slice(0, max) : "");8687/** Normalises untrusted decrypted or imported JSON into an Item; never throws on unknown extra keys. */88export function normalizeItem(x: any): Item {89  if (!x || typeof x !== "object") throw new Error("item is not an object");90  if (x.deleted === true) return { ...newItem("note"), deleted: true };91  const type: ItemType = (typeof x.type === "string" && Object.hasOwn(TEMPLATES, x.type) ? x.type : "note"); // hasOwn: "toString" etc. are not types92  const fields: Record<string, string> = {};93  if (x.fields && typeof x.fields === "object") for (const [k, v] of Object.entries(x.fields)) if (typeof v === "string" && k.length <= 64) fields[k] = v.slice(0, 200_000);94  const kinds = new Set<FieldKind>(["text", "secret", "url", "multiline", "date", "totp"]);95  const matches = new Set<UrlMatch>(["domain", "host", "exact", "never"]);96  return {97    type, title: str(x.title, 500), fields,98    urls: Array.isArray(x.urls) ? x.urls.filter((u: any) => u && typeof u.url === "string").slice(0, 50).map((u: any) => ({ url: u.url.slice(0, 2048), match: matches.has(u.match) ? u.match : "domain" })) : [],99    custom: Array.isArray(x.custom) ? x.custom.filter((c: any) => c && typeof c.label === "string" && typeof c.value === "string").slice(0, 100).map((c: any) => ({ label: c.label.slice(0, 200), value: c.value.slice(0, 200_000), kind: kinds.has(c.kind) ? c.kind : "text" })) : [],100    notes: str(x.notes, 500_000),101    tags: Array.isArray(x.tags) ? [...new Set<string>(x.tags.filter((t: any) => typeof t === "string" && t.trim()).map((t: string) => t.trim().slice(0, 64)))].slice(0, 50) : [],102    favorite: x.favorite === true,103    collection: typeof x.collection === "string" ? x.collection.slice(0, 64) : undefined,104    attachments: Array.isArray(x.attachments) ? x.attachments.filter((a: any) => a && typeof a.id === "string" && typeof a.key === "string" && typeof a.prefix === "string" && Number.isInteger(a.size) && Number.isInteger(a.chunks)).slice(0, 50) : [],105    passwordHistory: Array.isArray(x.passwordHistory) ? x.passwordHistory.filter((h: any) => h && typeof h.value === "string" && typeof h.at === "string").slice(-20) : [],106    expiresAt: typeof x.expiresAt === "string" ? x.expiresAt : undefined,107    rotateEveryDays: Number.isInteger(x.rotateEveryDays) && x.rotateEveryDays > 0 ? x.rotateEveryDays : undefined,108    createdAt: str(x.createdAt, 40) || new Date(0).toISOString(), updatedAt: str(x.updatedAt, 40) || new Date(0).toISOString(),109    conflictOf: typeof x.conflictOf === "string" ? x.conflictOf : undefined,110    trashedAt: typeof x.trashedAt === "string" ? x.trashedAt : undefined,111  };112}113114/** The item's primary secret (what "copy password" copies). */115export function primarySecret(item: Item): string | undefined {116  const def = TEMPLATES[item.type].fields.find((f) => f.kind === "secret");117  return def ? item.fields[def.key] || undefined : undefined;118}119120/** Applies an edit, maintaining password history and timestamps. */121export function applyEdit(prev: Item, next: Item): Item {122  const out = { ...next, updatedAt: new Date().toISOString(), createdAt: prev.createdAt };123  const a = prev.fields.password, b = next.fields.password;124  if (a && a !== b) out.passwordHistory = [...prev.passwordHistory, { value: a, at: out.updatedAt }].slice(-20);125  return out;126}127128export interface VaultMeta { name: string; kind: "personal" | "work" | "infrastructure" | "shared"; icon?: string; retentionDays?: number }129130/** Local-only search over decrypted items. */131export function searchText(item: Item): string {132  return [item.title, item.fields.username, item.fields.userName, item.fields.rpId, item.fields.service, item.fields.host, item.fields.ssid, item.fields.product,133    ...item.urls.map((u) => u.url), ...item.tags, ...item.custom.filter((c) => c.kind !== "secret").map((c) => `${c.label} ${c.value}`), item.notes]134    .filter(Boolean).join("\n").toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "");135}136export function matchesQuery(haystack: string, query: string): boolean {137  const q = query.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").split(/\s+/).filter(Boolean);138  return q.every((w) => haystack.includes(w));139}140
Files main
Menu

Theme