types.ts

15.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}5859export interface VaultEntry {60  id: string; // crypto.randomUUID()61  /**62   * Entry type. As of v2.11.0 passkeys are stored on `type:"login"` entries63   * via the `passkey` sub-object — `"passkey"` here is a legacy value still64   * accepted on read but rewritten to `"login"` on next vault save.65   */66  type?: "login" | "note" | "passkey" | "card";67  title: string;68  username?: string; // only for login entries69  email?: string; // separate email address — for sites that require both a username and an email70  password?: string; // only for login entries71  url?: string; // only for login entries72  /**73   * Additional sites this entry should match for autofill. Login entries only.74   * Each value is a full origin or URL (e.g. `https://login.foo.com`).75   * The vault domain index keys against the hostname of every entry in this76   * list, in addition to `url`.77   */78  additionalUrls?: string[];79  totp?: string; // base32 seed, stored encrypted — only for login entries80  notes?: string;81  breach?: number; // HIBP exposure count; 0 or undefined = clean — only for login entries82  /**83   * When the password field was last changed. Set on first-write of `password`84   * and refreshed on every subsequent change. Defaults to `createdAt` when85   * legacy entries are read by the advanced health analyser.86   */87  passwordChangedAt?: number;88  canary?: Canary;89  createdAt: number; // Date.now()90  modifiedAt: number;91  deletedAt?: number;92  tags?: string[];93  /** Passkey credential attached to this entry, if any. */94  passkey?: PasskeyData;95  // ── Legacy passkey flat fields (pre-v2.11.0). Populated by vault read96  // migration so that the old import/sanitize paths keep typing; new code97  // should always read `entry.passkey?.*` instead. The migration drops these98  // on next vault save. Do not introduce new readers of these fields.99  rpId?: string;100  rpName?: string;101  credentialId?: string;102  publicKeyCose?: string;103  privateKeyJwk?: JsonWebKey;104  userHandle?: string;105  userName?: string;106  userDisplayName?: string;107  algorithm?: -7 | -8;108  signCount?: number;109  aaguid?: string;110  backupEligible?: boolean;111  backupState?: boolean;112  lastUsedAt?: number;113  browser?: "chrome" | "firefox";114  transports?: string[];115  // Card entry fields116  cardholderName?: string;117  cardNumber?: string;       // full PAN, stored encrypted in vault118  expMonth?: string;119  expYear?: string;120  cvc?: string;121  cardNickname?: string;122  network?: CardNetwork;123  last4?: string;124}125126/**127 * Returns true when an entry has a passkey credential attached. After v2.11.0128 * migration this is the canonical check; pre-migration entries with a flat129 * `rpId`/`credentialId` shape get rewritten by the vault read pass before130 * any consumer sees them.131 */132export function hasPasskey(entry: VaultEntry): boolean {133  return entry.passkey !== undefined && entry.passkey.credentialId.length > 0;134}135136/**137 * Returns true when an entry is "passkey-only" — has a passkey credential138 * but no password to fill into a form. Login fields hide for these entries139 * and the inline autofill selector filters them out (signing in via the140 * passkey is a separate WebAuthn flow). Username may still be populated141 * (the migration mirrors passkey.userName onto the entry's username so the142 * domain-index/search keep working) and is not part of this discriminator.143 */144export function isPasskeyOnly(entry: VaultEntry): boolean {145  return hasPasskey(entry) && !entry.password;146}147148export interface LegacyVaultEntry {149  id: string;150  title: string;151  username: string;152  password: string;153  url: string;154  totp?: string;155  notes?: string;156  breach?: number;157  created: number;158  updated: number;159  deletedAt?: number;160}161162export interface CardEntry extends VaultEntry {163  type: "card";164  cardholderName: string;165  cardNumber: string;166  expMonth: string;167  expYear: string;168  cvc: string;169}170171172export interface PendingPasskeyRequest {173  requestId: number;174  type: "create" | "get";175  rpId: string;176  rpName: string;177  userName: string;178  userDisplayName?: string;179  /**180   * Firefox path: when present, the popup performs the navigator.credentials181   * call itself rather than completing a chrome.webAuthenticationProxy182   * request. Absent for Chrome (the existing webAuthenticationProxy flow).183   */184  browser?: "chrome" | "firefox";185  /** Firefox create: base64url challenge minted by the popup-context flow. */186  challenge?: string;187  /** Firefox create: base64url user handle. Generated if absent. */188  userHandle?: string;189}190191export interface PasskeyProviderState {192  supported: boolean;193  enabled: boolean;194  attached: boolean;195  browserLabel: string;196  statusLabel: string;197  conflict?: string;198}199200export interface StoredVault {201  version: 1; // AAD for AES-GCM --- prevents downgrade202  salt: string; // hex --- 16 bytes, CSPRNG, stored not secret203  nonce: string; // hex --- 12 bytes, CSPRNG, fresh per write204  ciphertext: string; // hex --- AES-256-GCM output205  tag: string; // hex --- 16-byte GCM auth tag206  // Recovery escrow: root key wrapped under recovery words via AES-256-GCM.207  // Absent on vaults created before v2.12 (migrateToRecovery adds them on first unlock).208  recovery_salt?: string; // hex --- 16 bytes, CSPRNG, HKDF salt for recovery key209  recovery_wrapped_root_key?: string; // hex --- AES-256-GCM ciphertext of 32-byte root key210  recovery_nonce?: string; // hex --- 12 bytes, fresh nonce for the above211  recovery_tag?: string; // hex --- 16-byte GCM auth tag for the above212  // Second wrapping of the same root key under the password-derived key.213  // Lets unlock() recover the rootKey bytes without the user's recovery214  // words, so GET_RECOVERY_WORDS works across lock/unlock cycles. Refreshed215  // on every password change so the words stay valid (H2/COR-006).216  pw_root_ciphertext?: string; // hex --- AES-256-GCM ciphertext of 32-byte root key (hex-encoded)217  pw_root_nonce?: string; // hex --- 12-byte nonce218  pw_root_tag?: string; // hex --- 16-byte GCM auth tag219}220221// Background-bound message types — sent from popup/content scripts,222// handled in src/background/messages.ts. Everything in this group must223// have a matching case in that file's switch statement.224export type MessageType =225  | "UNLOCK"226  | "LOCK"227  | "IS_UNLOCKED"228  | "HAS_VAULT"229  | "GET_ENTRIES"230  | "ADD_ENTRY"231  | "BATCH_ADD_ENTRIES"232  | "RESTORE_ENTRIES"233  | "CLEAR_VAULT_ENTRIES"234  | "UPDATE_ENTRY"235  | "ADD_ADDITIONAL_URL"236  | "DELETE_ENTRY"237  | "AUTOFILL_QUERY"238  | "COPY"239  | "CREATE_VAULT"240  | "GET_ENTRY_FOR_FILL"241  | "CHECK_ALL_BREACHES"242  | "GET_SETTINGS"243  | "UPDATE_SETTINGS"244  | "FIRE_CANARY_PING"245  | "ACTIVATE_LICENSE"246  | "GET_LICENSE"247  | "GET_LICENSE_KEY"248  | "IS_DURESS_ENABLED"249  | "SETUP_DURESS"250  | "DISABLE_DURESS"251  | "VERIFY_MAIN_PASSWORD"252  | "CHANGE_PASSWORD"253  | "GET_SITE_PASSWORD_POLICY"254  | "CHIRP_GET_LOCAL_IDENTITY"255  | "CHIRP_COMPLETE_PAIRING"256  | "CHIRP_LIST_PAIRED_DEVICES"257  | "CHIRP_UNPAIR_DEVICE"258  | "CHIRP_RENAME_LOCAL_DEVICE"259  | "GET_PENDING_PASSKEY"260  | "APPROVE_PASSKEY"261  | "DENY_PASSKEY"262  | "GET_PASSKEY_PROVIDER_STATE"263  | "SET_PASSKEY_PROVIDER_ENABLED"264  | "GET_DELETED_ENTRIES"265  | "RESTORE_ENTRY"266  | "PURGE_ENTRY"267  | "PURGE_EXPIRED_TRASH"268  | "GET_VAULT_HISTORY"269  | "RESTORE_VAULT_SNAPSHOT"270  | "COUNT_DUPLICATES"271  | "DEDUPLICATE_ENTRIES"272  | "RECORD_MANUAL_SUMMON"273  | "DECLINE_CARD_SAVE"274  | "IS_CARD_DECLINED"275  | "SUBMIT_FEEDBACK"276  | "GET_VAULT_STATUS"277  | "GET_ADVANCED_HEALTH_REPORT"278  | "INITIATE_PASSWORD_CHANGE"279  | "DEACTIVATE_LICENSE"280  | "GET_IDENTITIES"281  | "DESTROY_VAULT"282  | "INITIATE_FIREFOX_PASSKEY_CREATE"283  | "COMPLETE_FIREFOX_PASSKEY_CREATE"284  | "PASSKEY_OFFER_DECLINE"285  | "GET_PASSKEY_OFFER_DECLINED"286  | "GET_PASSKEY_FOR_DOMAIN"287  // Firefox content-script proxy path (v2.12.0). Sent FROM the page-world288  // monkey-patch through the extension-world relay TO the background. See289  // src/shared/passkey-flags.ts for removal conditions.290  | "PASSKEY_HAS_CREDENTIALS"291  | "PASSKEY_CREATE"292  | "PASSKEY_GET"293  // Android / iOS message types — activate only when Capacitor.isNativePlatform() is true.294  | "UNLOCK_WITH_KEY"295  | "GET_DERIVED_KEY"296  // Recovery word messages297  | "VALIDATE_RECOVERY_WORDS"298  | "RECOVER_WITH_WORDS"299  | "GET_RECOVERY_WORDS"300  | "GET_IDENTITY_SUGGESTIONS"301  | "TOUCH_AUTO_LOCK"302  | "POPULATE_INLINE_VAULT"303  | "SAVE_NOTE"304  | "DELETE_NOTE"305  | "GET_NOTES"306  | "SEARCH_VAULT"307  | "ML_INIT"308  | "ML_PREDICT_BATCH"309  // Content-script-bound message types — sent BY the background TO content310  // scripts. They never reach messages.ts's switch. Kept in this union so311  // existing call sites type-check; do not add cases for them in the312  // background handler.313  | "PING"            // background → content: liveness probe314  | "SUMMON_AUTOFILL" // background → content: open the in-page palette315  | "VAULT_LOCKED"    // background → content/popup: vault just locked316  | "VAULT_UNLOCKED"  // background → content/popup: vault just unlocked317  | "PRO_GATE_TRIGGERED" // background → popup: a Pro feature was attempted on free318  | "PASSKEY_PRO_GATE" // background → content: show passkey Pro gate in inline popup319  | "OPEN_PRO_GATE" // content → background: open popup and navigate to License section320  | "SHOW_PASSKEY_TOAST"    // background → content tab: show passkey auth toast321  | "DISMISS_PASSKEY_TOAST" // background → content tab: dismiss passkey auth toast322  | "PASSKEY_AUTH_RESPONSE" // content → background: user approved or denied the toast323  | "SHOULD_PLAY_CELEBRATION"324  | "MARK_CELEBRATION_PLAYED"325  // Peach Codex (v2.42.0). Generation runs in the popup — the SW only326  // sources vault data and applies the restored slots.327  | "GET_CODEX_VAULT_DATA"328  | "ESTIMATE_CODEX_PAGES"329  | "GENERATE_CODEX"330  | "RESTORE_FROM_CODEX";331332export type ProFeature =333  | "sync"334  | "passkeys"335  | "advanced_health"336  | "smart_password_change"337  | "ios_app"338  | "codex";339340/**341 * License export shape included in PeachScript and encrypted JSON backups.342 * `celebrationPlayed` is intentionally absent — a new device deserves the moment.343 */344export interface PeachLicenseExport {345  key: string;346  activatedAt?: number;347}348349export interface AdvancedHealthEntryReport {350  id: string;351  title: string;352  domain: string;353  url?: string;354  score: number;355  ageDays: number;356  reasons: string[];357  factors: {358    breached: boolean;359    breachCount: number;360    reused: boolean;361    aged: boolean;362    weak: boolean;363    missingTotpOnSensitive: boolean;364  };365}366367export interface AdvancedHealthReport {368  vaultScore: number;369  generatedAt: number;370  entryCount: number;371  reusedGroups: number;372  agedCount: number;373  remediation: AdvancedHealthEntryReport[];374}375376export const ACCENT_COLORS = [377  { name: "peach",    hex: "#F49C70" },378  { name: "rose",     hex: "#FF8AA6" },379  { name: "plum",     hex: "#D597F2" },380  { name: "lavender", hex: "#A6A8FF" },381  { name: "sky",      hex: "#5BC8EE" },382  { name: "mint",     hex: "#5EE0B0" },383  { name: "sage",     hex: "#B5D870" },384  { name: "butter",   hex: "#FFD45A" },385  { name: "sand",     hex: "#EDBC85" },386  { name: "clay",     hex: "#F08660" },387  { name: "slate",    hex: "#80BEDE" },388  { name: "stone",    hex: "#C8B8A8" },389] as const;390391export type AccentColorName = typeof ACCENT_COLORS[number]["name"];392393export interface SavedIdentity {394  value: string;395  type: "email" | "username";396  lastUsed: number;397  useCount: number;398  exampleDomain?: string;399}400401export interface PasswordPolicy {402  minLength?: number;403  maxLength?: number;404  requiresUppercase?: boolean;405  requiresLowercase?: boolean;406  requiresNumbers?: boolean;407  requiresSymbols?: boolean;408  forbidsSymbols?: boolean;409  allowedSymbols?: string;410  /** Characters the site explicitly disallows. Filtered from every pool before generation. */411  forbiddenChars?: string;412}413414/**415 * A single vault history snapshot. The `vault_a` and `vault_b` fields are the416 * raw encrypted blobs from chrome.storage.local — already AES-256-GCM417 * protected by the master password, so storing them in history adds no418 * security surface.419 *420 * Snapshots are taken BEFORE every vault write so the saved blob represents421 * what is about to be lost, not what was just written. The reason field422 * documents the trigger so the UI can render "saved" / "synced" / "imported"423 * / "restored" labels next to each row.424 */425export interface VaultSnapshot {426  id: string;427  savedAt: number;428  reason: "local_save" | "sync_received" | "import" | "restore";429  vault_a: string;430  vault_b: string;431  /** Active entry count when the snapshot was taken; null if vault was locked. */432  entryCount: number | null;433}434435export interface VaultHistory {436  /** Newest first; capped at HISTORY_MAX (10). */437  snapshots: VaultSnapshot[];438}439440export interface Message {441  type: MessageType;442  payload?: unknown;443}444445// Canonical snake_case error codes returned by message handlers. Keep this446// union the authoritative catalogue — new handlers must reuse an entry or447// add one here. Free-form strings still appear (network/operation failures448// surface their raw .message), so error stays string at runtime; the union449// is the documented set callers should switch on.450export type ErrorCode =451  | "vault_locked"452  | "vault_corrupted"453  | "no_vault"454  | "entry_not_found"455  | "invalid_payload"456  | "invalid_message"457  | "invalid_sender"458  | "wrong_passphrase"459  | "incorrect_current_password"460  | "recovery_not_setup"461  | "android_only"462  | "not_available"463  | "pro_required"464  | "pairing_not_verified"465  | "sync_rejected_unpaired_initiator"466  | "vault_not_applied"467  | "url_required"468  | "domain_required"469  | "rpid_required"470  | "rpid_and_username_required"471  | "publickeyhex_required"472  | "missing_payload"473  | "login_entries_only"474  | "passkey_not_fillable"475  | "invalid_webhook_url"476  | "invalid_feedback_endpoint"477  | "message_empty"478  | "network_error"479  | "no_reset_url"480  | "failed_to_open_tab"481  | "operation_failed"482  | "unknown_message_type";483484export interface MessageResponse {485  ok: boolean;486  data?: unknown;487  error?: string;488  unlocked?: boolean;489  // Set on UNLOCK responses when the vault decrypted but failed schema490  // validation (M7/COR-007). The popup may offer a history-restore flow.491  canRestoreFromHistory?: boolean;492}