types.ts

16.8 KB · raw

1/**2 * types.ts — cross-boundary types and the `MessageType` union.3 *4 * `MessageType` mixes background-bound and content-script-bound messages.5 * Background-bound types have a case in `src/background/messages.ts`.6 * Content-script-bound types (PING, SUMMON_AUTOFILL, VAULT_LOCKED,7 * RESTART_AUTO_LOCK, etc.) are sent *to* content scripts or the popup and8 * have no handler in messages.ts by design — that absence is not a missing9 * handler. Add new cross-boundary types here, not inline in call sites.10 */1112export interface ManualSummonRecord {13  firstSummonedAt: number;14  summonCount: number;15  lastSummonedAt: number;16}1718export interface Canary {19  webhookUrl: string;20  label?: string;21  lastPinged?: number;22  pingCount?: number;23}2425export type CardNetwork = "visa" | "mastercard" | "amex" | "discover" | "unknown";2627/**28 * Passkey credential data attached to a VaultEntry. New in v2.11.0 — passkeys29 * are no longer a separate entry type; instead they hang off any login entry.30 * A passkey-only entry is a `type:"login"` entry with no username/password31 * but a `passkey` sub-object set. A login that ALSO has a passkey is just a32 * normal login with `passkey` populated.33 *34 * privateKeyJwk is present only on Chrome-created passkeys, where Peach is35 * the authenticator. Firefox-created passkeys delegate to the platform36 * authenticator, so the field is absent — `browser` distinguishes the two.37 */38export interface PasskeyData {39  rpId: string;40  rpName: string;41  credentialId: string;42  publicKeyCose: string;43  privateKeyJwk?: JsonWebKey;44  userHandle: string;45  userName: string;46  userDisplayName: string;47  algorithm: -7 | -8;48  signCount: number;49  aaguid: string;50  backupEligible: boolean;51  backupState: boolean;52  lastUsedAt?: number;53  browser?: "chrome" | "firefox";54  transports?: string[];55  /** When the credential was first registered with Peach. */56  createdAt: number;57}5859/** One past password kept in an entry's {@link VaultEntry.passwordHistory}. */60export interface PasswordHistoryItem {61  /** The old password value, replaced by a newer one. */62  password: string;63  /**64   * When this password stopped being current — i.e. the `passwordChangedAt`65   * (or `createdAt`) it carried at the moment it was swapped out.66   */67  changedAt: number;68}6970export interface VaultEntry {71  id: string; // crypto.randomUUID()72  /** Entry type. Passkey credentials are carried in the nested `passkey` field. */73  type?: "login" | "note" | "passkey" | "card";74  title: string;75  username?: string; // only for login entries76  email?: string; // separate email address — for sites that require both a username and an email77  password?: string; // only for login entries78  url?: string; // only for login entries79  /**80   * Additional sites this entry should match for autofill. Login entries only.81   * Each value is a full origin or URL (e.g. `https://login.foo.com`).82   * The vault domain index keys against the hostname of every entry in this83   * list, in addition to `url`.84   */85  additionalUrls?: string[];86  totp?: string; // base32 seed, stored encrypted — only for login entries87  /**88   * Optional TOTP parameters parsed from an otpauth:// URI. Absent fields fall89   * back to RFC defaults (SHA-1 / 6 digits / 30-second period). Login entries only.90   */91  totpAlgorithm?: "SHA1" | "SHA256" | "SHA512";92  totpDigits?: number;93  totpPeriod?: number;94  notes?: string;95  breach?: number; // Last known HIBP exposure count; absence does not prove a completed check96  /**97   * When the password field was last changed. Set on first-write of `password`98   * and refreshed on every subsequent change.99   */100  passwordChangedAt?: number;101  /**102   * Previously-used passwords for this entry, newest first. A snapshot of the103   * old password is pushed here automatically whenever the password changes104   * (see `updateEntry` in vault.ts). Capped at PASSWORD_HISTORY_MAX. Lets the105   * user reveal, copy, or restore a password they used before — handy when a106   * site rejects a rotation or an old credential resurfaces.107   */108  passwordHistory?: PasswordHistoryItem[];109  canary?: Canary;110  createdAt: number; // Date.now()111  modifiedAt: number;112  deletedAt?: number;113  tags?: string[];114  /** Passkey credential attached to this entry, if any. */115  passkey?: PasskeyData;116  // Card entry fields117  cardholderName?: string;118  cardNumber?: string;       // full PAN, stored encrypted in vault119  expMonth?: string;120  expYear?: string;121  cvc?: string;122  cardNickname?: string;123  network?: CardNetwork;124  last4?: string;125}126127/** Returns true when an entry has a passkey credential attached. */128export function hasPasskey(entry: VaultEntry): boolean {129  return entry.passkey !== undefined && entry.passkey.credentialId.length > 0;130}131132/** Returns true when an entry is passkey-only and has no password to fill. */133export function isPasskeyOnly(entry: VaultEntry): boolean {134  // An entry is "passkey only" when it holds SOLELY a passkey credential —135  // no password, no TOTP, and no dedicated email. Username is intentionally136  // excluded because it is useful for searching passkey credentials.137  // Entries with passkey + TOTP or passkey + email are NOT passkey-only: they138  // carry fillable credentials and must show the full login-fields UI.139  return hasPasskey(entry) && !entry.password && !entry.totp && !entry.email;140}141142export interface PendingPasskeyRequest {143  requestId: number;144  type: "create" | "get";145  rpId: string;146  rpName: string;147  userName: string;148  userDisplayName?: string;149  /** Originating tab and frame binding for content-script approval responses. */150  tabId?: number;151  origin?: string;152  crossOrigin?: boolean;153  /**154   * Firefox path: when present, the popup performs the navigator.credentials155   * call itself rather than completing a chrome.webAuthenticationProxy156   * request. Absent for Chrome (the existing webAuthenticationProxy flow).157   */158  browser?: "chrome" | "firefox";159  /** Firefox create: base64url challenge minted by the popup-context flow. */160  challenge?: string;161  /** Firefox create: base64url user handle. Generated if absent. */162  userHandle?: string;163}164165export interface PasskeyProviderState {166  supported: boolean;167  enabled: boolean;168  attached: boolean;169  browserLabel: string;170  statusLabel: string;171  conflict?: string;172}173174export type RecoveryResult = { committed: true; unlocked: boolean };175176export interface StoredVault {177  // Not authenticated as AAD — the actual AES-GCM AAD is the slot's constant178  // aadTag string (see background/aes.ts). The version field is unauthenticated179  // metadata; downgrade prevention does not rest on it.180  version: 1;181  salt: string; // hex --- 16 bytes, CSPRNG, stored not secret182  nonce: string; // hex --- 12 bytes, CSPRNG, fresh per write183  ciphertext: string; // hex --- AES-256-GCM output184  tag: string; // hex --- 16-byte GCM auth tag185  // Recovery escrow: root key wrapped under recovery words via AES-256-GCM.186  recovery_salt?: string; // hex --- 16 bytes, CSPRNG, HKDF salt for recovery key187  recovery_wrapped_root_key?: string; // hex --- AES-256-GCM ciphertext of 32-byte root key188  recovery_nonce?: string; // hex --- 12 bytes, fresh nonce for the above189  recovery_tag?: string; // hex --- 16-byte GCM auth tag for the above190  // Second wrapping of the same root key under the password-derived key.191  // Lets unlock() recover the rootKey bytes without the user's recovery192  // words, so GET_RECOVERY_WORDS works across lock/unlock cycles. Refreshed193  // on every password change so the words stay valid (H2/COR-006).194  pw_root_ciphertext?: string; // hex --- AES-256-GCM ciphertext of 32-byte root key (hex-encoded)195  pw_root_nonce?: string; // hex --- 12-byte nonce196  pw_root_tag?: string; // hex --- 16-byte GCM auth tag197  /// Browser-local vault key escrow for recovery without the old password.198  recovery_vault_key?: { nonce: string; ciphertext: string; tag: string };199}200201// Background-bound message types — sent from popup/content scripts,202// handled in src/background/messages.ts. Everything in this group must203// have a matching case in that file's switch statement.204export type BreachScanStatus = {205  id: string | null;206  state: "idle" | "running" | "complete" | "cancelled";207  total: number;208  scanned: number;209  unknown: number;210  unapplied: number;211  breached: number;212  cancelled: number;213};214215export type MessageType =216  | "CLEAR_CLIPBOARD"217  | "GET_SYNC_ALERTS"218  | "DISMISS_SYNC_ALERTS"219  | "GET_PENDING_VOUCHED_DEVICES"220  | "CONFIRM_VOUCHED_DEVICE"221  | "REJECT_VOUCHED_DEVICE"222  | "VOUCHED_DEVICE_PENDING"223  | "ROTATE_SYNC_IDENTITY"224  | "DEVICE_KEY_ROTATED"225  | "UNLOCK"226  | "UNLOCK_WITH_PIN"227  | "GET_PIN_STATUS"228  | "LOCK"229  | "IS_UNLOCKED"230  | "HAS_VAULT"231  | "GET_ENTRIES"232  | "EXPORT_ENTRIES"233  | "ADD_ENTRY"234  | "BATCH_ADD_ENTRIES"235  | "RESTORE_ENTRIES"236  | "CLEAR_VAULT_ENTRIES"237  | "UPDATE_ENTRY"238  | "ADD_ADDITIONAL_URL"239  | "REQUEST_REMEMBER_SITE"240  | "DELETE_ENTRY"241  | "CHECK_SAVE_CREDENTIAL"242  | "AUTOFILL_QUERY"243  | "COPY"244  | "CREATE_VAULT"245  | "CREATE_VAULT_FROM_ROOT_KEY"246  | "GET_ENTRY_FOR_FILL"247  | "GET_ENTRY_FOR_EDIT"248  | "CHECK_ALL_BREACHES"249  | "GET_BREACH_SCAN_STATUS"250  | "GET_SETTINGS"251  | "UPDATE_SETTINGS"252  | "SETUP_PIN"253  | "DISABLE_PIN"254  | "FIRE_CANARY_PING"255  | "ACTIVATE_LICENSE"256  | "GET_LICENSE"257  | "GET_LICENSE_KEY"258  | "IS_DURESS_ENABLED"259  | "SETUP_DURESS"260  | "DISABLE_DURESS"261  | "VERIFY_MAIN_PASSWORD"262  | "CHANGE_PASSWORD"263  | "GET_SITE_PASSWORD_POLICY"264  | "GET_LOCAL_IDENTITY"265  | "LIST_PAIRED_DEVICES"266  | "RENAME_PAIRED_DEVICE"267  | "UNPAIR_DEVICE"268  | "RENAME_LOCAL_DEVICE"269  // Relay pairing. START/CONFIRM/CANCEL are popup→bg requests handled in the270  // switch; ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT are bg→popup pushes.271  | "START_ADOPTION_SOURCE"272  | "START_ADOPTION_RECEIVER"273  | "LIST_PENDING_ADOPTION_HOLDERS"274  | "REMOVE_PENDING_ADOPTION_HOLDER"275  | "CANCEL_ADOPTION_SOURCE"276  | "SOURCE_SAS_DECISION"277  | "RECEIVER_SAS_DECISION"278  | "ADOPTION_SOURCE_SAS"279  | "ADOPTION_SOURCE_RESULT"280  | "TRIGGER_SYNC"281  | "GET_SYNC_STATE"282  | "GET_SYNC_GENERATION"283  | "SECURE_RESET"284  | "GET_SYNC_SETTINGS"285  | "SET_SYNC_SETTINGS"286  | "GET_PENDING_PASSKEY"287  | "APPROVE_PASSKEY"288  | "DENY_PASSKEY"289  | "GET_PASSKEY_PROVIDER_STATE"290  | "SET_PASSKEY_PROVIDER_ENABLED"291  | "GET_DELETED_ENTRIES"292  | "RESTORE_ENTRY"293  | "PURGE_ENTRY"294  | "PURGE_EXPIRED_TRASH"295  | "GET_VAULT_HISTORY"296  | "RESTORE_VAULT_SNAPSHOT"297  | "COUNT_DUPLICATES"298  | "DEDUPLICATE_ENTRIES"299  | "RECORD_MANUAL_SUMMON"300  | "DECLINE_CARD_SAVE"301  | "IS_CARD_DECLINED"302  | "GET_VAULT_STATUS"303  | "GET_ADVANCED_HEALTH_REPORT"304  | "DEACTIVATE_LICENSE"305  | "GET_IDENTITIES"306  | "DESTROY_VAULT"307  | "INITIATE_FIREFOX_PASSKEY_CREATE"308  | "COMPLETE_FIREFOX_PASSKEY_CREATE"309  | "PASSKEY_OFFER_DECLINE"310  | "GET_PASSKEY_OFFER_DECLINED"311  | "GET_PASSKEY_FOR_DOMAIN"312  | "MARK_PASSKEY_BANNER_SHOWN"313  // Firefox content-script proxy path (v2.12.0). Sent FROM the page-world314  // monkey-patch through the extension-world relay TO the background. See315  // src/shared/passkey-flags.ts for removal conditions.316  | "PASSKEY_HAS_CREDENTIALS"317  | "PASSKEY_CREATE"318  | "PASSKEY_GET"319  // Recovery word messages320  | "VALIDATE_RECOVERY_WORDS"321  | "RECOVER_WITH_WORDS"322  | "GET_RECOVERY_WORDS"323  | "GET_RECOVERY_CONFIRM_PENDING"324  | "SET_RECOVERY_CONFIRM_PENDING"325  | "CLEAR_RECOVERY_CONFIRM_PENDING"326  | "GET_IDENTITY_SUGGESTIONS"327  | "TOUCH_AUTO_LOCK"328  | "SAVE_NOTE"329  | "DELETE_NOTE"330  | "GET_NOTES"331  | "SEARCH_VAULT"332  | "ML_INIT"333  | "ML_PREDICT_BATCH"334  // Content-script-bound message types — sent BY the background TO content335  // scripts. They never reach messages.ts's switch. Kept in this union so336  // existing call sites type-check; do not add cases for them in the337  // background handler.338  | "PING"            // background → content: liveness probe339  | "SUMMON_AUTOFILL" // background → content: open the in-page palette340  | "VAULT_LOCKED"    // background → content/popup: vault just locked341  | "VAULT_UNLOCKED"  // background → content/popup: vault just unlocked342  | "VAULT_ENTRIES_CHANGED" // background → popup: a sync round merged remote entries343  | "PRO_GATE_TRIGGERED" // background → popup: a Pro feature was attempted on free344  | "PASSKEY_PRO_GATE" // background → content: show passkey Pro gate in inline popup345  | "OPEN_PRO_GATE" // content → background: open popup and navigate to License section346  | "OPEN_POPUP" // content → background: open the extension popup (e.g. to unlock)347  | "REQUEST_REMEMBER_SITE" // content → background: queue "use this entry on this site" for the popup to confirm348  | "OPEN_DETACHED_POPUP" // popup → background: open the popup HTML in a standalone window (file-picker flows)349  | "SHOW_PASSKEY_TOAST"    // background → content tab: show passkey auth toast350  | "DISMISS_PASSKEY_TOAST" // background → content tab: dismiss passkey auth toast351  | "PASSKEY_AUTH_RESPONSE" // content → background: user approved or denied the toast352  | "SHOULD_PLAY_CELEBRATION"353  | "MARK_CELEBRATION_PLAYED"354  // Peach Codex (v2.42.0). Generation runs in the popup — the SW only355  // sources vault data and applies the restored slots.356  | "GET_CODEX_VAULT_DATA"357  | "ESTIMATE_CODEX_PAGES"358  | "GENERATE_CODEX"359  | "RESTORE_FROM_CODEX";360361export type SaveCredentialCheckResult =362  | { status: "new" | "same" | "ambiguous" }363  | { status: "changed"; id: string };364365export type ProFeature =366  | "sync"367  | "passkeys"368  | "advanced_health"369  | "ios_app"370  | "codex"371  | "canary_entry"372  | "duress_vault";373374/**375 * License export shape included in PeachScript and encrypted JSON backups.376 * `celebrationPlayed` is intentionally absent — a new device deserves the moment.377 */378export interface PeachLicenseExport {379  key: string;380  activatedAt?: number;381}382383export interface AdvancedHealthEntryReport {384  id: string;385  title: string;386  domain: string;387  url?: string;388  score: number;389  ageDays: number;390  reasons: string[];391  factors: {392    breached: boolean;393    breachCount: number;394    reused: boolean;395    aged: boolean;396    weak: boolean;397    missingTotpOnSensitive: boolean;398  };399}400401export interface AdvancedHealthReport {402  vaultScore: number;403  generatedAt: number;404  entryCount: number;405  reusedGroups: number;406  agedCount: number;407  remediation: AdvancedHealthEntryReport[];408}409410export const ACCENT_COLORS = [411  { name: "peach",    hex: "#F49C70" },412  { name: "rose",     hex: "#FF8AA6" },413  { name: "plum",     hex: "#D597F2" },414  { name: "lavender", hex: "#A6A8FF" },415  { name: "sky",      hex: "#5BC8EE" },416  { name: "mint",     hex: "#5EE0B0" },417  { name: "sage",     hex: "#B5D870" },418  { name: "butter",   hex: "#FFD45A" },419  { name: "sand",     hex: "#EDBC85" },420  { name: "clay",     hex: "#F08660" },421  { name: "slate",    hex: "#80BEDE" },422  { name: "stone",    hex: "#C8B8A8" },423] as const;424425export type AccentColorName = typeof ACCENT_COLORS[number]["name"];426427export interface SavedIdentity {428  value: string;429  type: "email" | "username";430  lastUsed: number;431  useCount: number;432  exampleDomain?: string;433}434435export interface PasswordPolicy {436  minLength?: number;437  maxLength?: number;438  requiresUppercase?: boolean;439  requiresLowercase?: boolean;440  requiresNumbers?: boolean;441  requiresSymbols?: boolean;442  forbidsSymbols?: boolean;443  allowedSymbols?: string;444  /** Characters the site explicitly disallows. Filtered from every pool before generation. */445  forbiddenChars?: string;446}447448/**449 * A single vault history snapshot. The `vault_a` and `vault_b` fields are the450 * raw encrypted blobs from chrome.storage.local — already AES-256-GCM451 * protected by the master password, so storing them in history adds no452 * security surface.453 *454 * Snapshots are taken BEFORE every vault write so the saved blob represents455 * what is about to be lost, not what was just written. The reason field456 * documents the trigger so the UI can render "saved" / "synced" / "imported"457 * / "restored" labels next to each row.458 */459export interface VaultSnapshot {460  id: string;461  savedAt: number;462  reason: "local_save" | "sync_received" | "import" | "restore";463  vault_a: string;464  vault_b: string;465  /**466   * Coarse size bucket (ceiling) of active entries when the snapshot was taken;467   * null if vault was locked or in decoy mode. PCH-01-023: bucketed, not exact,468   * so the plaintext value cannot leak vault size or per-write deltas. UI should469   * render it as "up to N", never as an exact count.470   */471  entryCount: number | null;472}473474export interface VaultHistory {475  /** Newest first; capped at HISTORY_MAX (10). */476  snapshots: VaultSnapshot[];477}478479export interface Message {480  type: MessageType;481  payload?: unknown;482}483484export interface MessageResponse {485  ok: boolean;486  data?: unknown;487  error?: string;488  vaultId?: string;489  unlocked?: boolean;490  // Set on UNLOCK responses when the vault decrypted but failed schema491  // validation (M7/COR-007). The popup may offer a history-restore flow.492  canRestoreFromHistory?: boolean;493  // Set on COPY responses: the effective clipboard auto-clear delay in seconds,494  // so the content script's TOTP toast can advertise the real configured time.495  clearSeconds?: number;496}