types.ts

16.3 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; // HIBP exposure count; 0 or undefined = clean — only for login entries96  /**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  /**153   * Firefox path: when present, the popup performs the navigator.credentials154   * call itself rather than completing a chrome.webAuthenticationProxy155   * request. Absent for Chrome (the existing webAuthenticationProxy flow).156   */157  browser?: "chrome" | "firefox";158  /** Firefox create: base64url challenge minted by the popup-context flow. */159  challenge?: string;160  /** Firefox create: base64url user handle. Generated if absent. */161  userHandle?: string;162}163164export interface PasskeyProviderState {165  supported: boolean;166  enabled: boolean;167  attached: boolean;168  browserLabel: string;169  statusLabel: string;170  conflict?: string;171}172173export type RecoveryResult = { committed: true; unlocked: boolean };174175export interface StoredVault {176  // Not authenticated as AAD — the actual AES-GCM AAD is the slot's constant177  // aadTag string (see background/aes.ts). The version field is unauthenticated178  // metadata; downgrade prevention does not rest on it.179  version: 1;180  salt: string; // hex --- 16 bytes, CSPRNG, stored not secret181  nonce: string; // hex --- 12 bytes, CSPRNG, fresh per write182  ciphertext: string; // hex --- AES-256-GCM output183  tag: string; // hex --- 16-byte GCM auth tag184  // Recovery escrow: root key wrapped under recovery words via AES-256-GCM.185  recovery_salt?: string; // hex --- 16 bytes, CSPRNG, HKDF salt for recovery key186  recovery_wrapped_root_key?: string; // hex --- AES-256-GCM ciphertext of 32-byte root key187  recovery_nonce?: string; // hex --- 12 bytes, fresh nonce for the above188  recovery_tag?: string; // hex --- 16-byte GCM auth tag for the above189  // Second wrapping of the same root key under the password-derived key.190  // Lets unlock() recover the rootKey bytes without the user's recovery191  // words, so GET_RECOVERY_WORDS works across lock/unlock cycles. Refreshed192  // on every password change so the words stay valid (H2/COR-006).193  pw_root_ciphertext?: string; // hex --- AES-256-GCM ciphertext of 32-byte root key (hex-encoded)194  pw_root_nonce?: string; // hex --- 12-byte nonce195  pw_root_tag?: string; // hex --- 16-byte GCM auth tag196  /// Browser-local vault key escrow for recovery without the old password.197  recovery_vault_key?: { nonce: string; ciphertext: string; tag: string };198}199200// Background-bound message types — sent from popup/content scripts,201// handled in src/background/messages.ts. Everything in this group must202// have a matching case in that file's switch statement.203export type MessageType =204  | "CLEAR_CLIPBOARD"205  | "GET_SYNC_ALERTS"206  | "DISMISS_SYNC_ALERTS"207  | "GET_PENDING_VOUCHED_DEVICES"208  | "CONFIRM_VOUCHED_DEVICE"209  | "REJECT_VOUCHED_DEVICE"210  | "VOUCHED_DEVICE_PENDING"211  | "ROTATE_SYNC_IDENTITY"212  | "DEVICE_KEY_ROTATED"213  | "UNLOCK"214  | "UNLOCK_WITH_PIN"215  | "GET_PIN_STATUS"216  | "LOCK"217  | "IS_UNLOCKED"218  | "HAS_VAULT"219  | "GET_ENTRIES"220  | "EXPORT_ENTRIES"221  | "ADD_ENTRY"222  | "BATCH_ADD_ENTRIES"223  | "RESTORE_ENTRIES"224  | "CLEAR_VAULT_ENTRIES"225  | "UPDATE_ENTRY"226  | "ADD_ADDITIONAL_URL"227  | "REQUEST_REMEMBER_SITE"228  | "DELETE_ENTRY"229  | "AUTOFILL_QUERY"230  | "COPY"231  | "CREATE_VAULT"232  | "CREATE_VAULT_FROM_ROOT_KEY"233  | "GET_ENTRY_FOR_FILL"234  | "GET_ENTRY_FOR_EDIT"235  | "CHECK_ALL_BREACHES"236  | "GET_SETTINGS"237  | "UPDATE_SETTINGS"238  | "SETUP_PIN"239  | "DISABLE_PIN"240  | "FIRE_CANARY_PING"241  | "ACTIVATE_LICENSE"242  | "GET_LICENSE"243  | "GET_LICENSE_KEY"244  | "IS_DURESS_ENABLED"245  | "SETUP_DURESS"246  | "DISABLE_DURESS"247  | "VERIFY_MAIN_PASSWORD"248  | "CHANGE_PASSWORD"249  | "GET_SITE_PASSWORD_POLICY"250  | "GET_LOCAL_IDENTITY"251  | "LIST_PAIRED_DEVICES"252  | "RENAME_PAIRED_DEVICE"253  | "UNPAIR_DEVICE"254  | "RENAME_LOCAL_DEVICE"255  // Relay pairing. START/CONFIRM/CANCEL are popup→bg requests handled in the256  // switch; ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT are bg→popup pushes.257  | "START_ADOPTION_SOURCE"258  | "START_ADOPTION_RECEIVER"259  | "LIST_PENDING_ADOPTION_HOLDERS"260  | "REMOVE_PENDING_ADOPTION_HOLDER"261  | "CANCEL_ADOPTION_SOURCE"262  | "SOURCE_SAS_DECISION"263  | "RECEIVER_SAS_DECISION"264  | "ADOPTION_SOURCE_SAS"265  | "ADOPTION_SOURCE_RESULT"266  | "TRIGGER_SYNC"267  | "GET_SYNC_STATE"268  | "GET_SYNC_GENERATION"269  | "SECURE_RESET"270  | "GET_SYNC_SETTINGS"271  | "SET_SYNC_SETTINGS"272  | "GET_PENDING_PASSKEY"273  | "APPROVE_PASSKEY"274  | "DENY_PASSKEY"275  | "GET_PASSKEY_PROVIDER_STATE"276  | "SET_PASSKEY_PROVIDER_ENABLED"277  | "GET_DELETED_ENTRIES"278  | "RESTORE_ENTRY"279  | "PURGE_ENTRY"280  | "PURGE_EXPIRED_TRASH"281  | "GET_VAULT_HISTORY"282  | "RESTORE_VAULT_SNAPSHOT"283  | "COUNT_DUPLICATES"284  | "DEDUPLICATE_ENTRIES"285  | "RECORD_MANUAL_SUMMON"286  | "DECLINE_CARD_SAVE"287  | "IS_CARD_DECLINED"288  | "GET_VAULT_STATUS"289  | "GET_ADVANCED_HEALTH_REPORT"290  | "DEACTIVATE_LICENSE"291  | "GET_IDENTITIES"292  | "DESTROY_VAULT"293  | "INITIATE_FIREFOX_PASSKEY_CREATE"294  | "COMPLETE_FIREFOX_PASSKEY_CREATE"295  | "PASSKEY_OFFER_DECLINE"296  | "GET_PASSKEY_OFFER_DECLINED"297  | "GET_PASSKEY_FOR_DOMAIN"298  | "MARK_PASSKEY_BANNER_SHOWN"299  // Firefox content-script proxy path (v2.12.0). Sent FROM the page-world300  // monkey-patch through the extension-world relay TO the background. See301  // src/shared/passkey-flags.ts for removal conditions.302  | "PASSKEY_HAS_CREDENTIALS"303  | "PASSKEY_CREATE"304  | "PASSKEY_GET"305  // Recovery word messages306  | "VALIDATE_RECOVERY_WORDS"307  | "RECOVER_WITH_WORDS"308  | "GET_RECOVERY_WORDS"309  | "GET_RECOVERY_CONFIRM_PENDING"310  | "SET_RECOVERY_CONFIRM_PENDING"311  | "CLEAR_RECOVERY_CONFIRM_PENDING"312  | "GET_IDENTITY_SUGGESTIONS"313  | "TOUCH_AUTO_LOCK"314  | "SAVE_NOTE"315  | "DELETE_NOTE"316  | "GET_NOTES"317  | "SEARCH_VAULT"318  | "ML_INIT"319  | "ML_PREDICT_BATCH"320  // Content-script-bound message types — sent BY the background TO content321  // scripts. They never reach messages.ts's switch. Kept in this union so322  // existing call sites type-check; do not add cases for them in the323  // background handler.324  | "PING"            // background → content: liveness probe325  | "SUMMON_AUTOFILL" // background → content: open the in-page palette326  | "VAULT_LOCKED"    // background → content/popup: vault just locked327  | "VAULT_UNLOCKED"  // background → content/popup: vault just unlocked328  | "VAULT_ENTRIES_CHANGED" // background → popup: a sync round merged remote entries329  | "PRO_GATE_TRIGGERED" // background → popup: a Pro feature was attempted on free330  | "PASSKEY_PRO_GATE" // background → content: show passkey Pro gate in inline popup331  | "OPEN_PRO_GATE" // content → background: open popup and navigate to License section332  | "OPEN_POPUP" // content → background: open the extension popup (e.g. to unlock)333  | "REQUEST_REMEMBER_SITE" // content → background: queue "use this entry on this site" for the popup to confirm334  | "OPEN_DETACHED_POPUP" // popup → background: open the popup HTML in a standalone window (file-picker flows)335  | "SHOW_PASSKEY_TOAST"    // background → content tab: show passkey auth toast336  | "DISMISS_PASSKEY_TOAST" // background → content tab: dismiss passkey auth toast337  | "PASSKEY_AUTH_RESPONSE" // content → background: user approved or denied the toast338  | "SHOULD_PLAY_CELEBRATION"339  | "MARK_CELEBRATION_PLAYED"340  // Peach Codex (v2.42.0). Generation runs in the popup — the SW only341  // sources vault data and applies the restored slots.342  | "GET_CODEX_VAULT_DATA"343  | "ESTIMATE_CODEX_PAGES"344  | "GENERATE_CODEX"345  | "RESTORE_FROM_CODEX";346347export type ProFeature =348  | "sync"349  | "passkeys"350  | "advanced_health"351  | "ios_app"352  | "codex"353  | "canary_entry"354  | "duress_vault";355356/**357 * License export shape included in PeachScript and encrypted JSON backups.358 * `celebrationPlayed` is intentionally absent — a new device deserves the moment.359 */360export interface PeachLicenseExport {361  key: string;362  activatedAt?: number;363}364365export interface AdvancedHealthEntryReport {366  id: string;367  title: string;368  domain: string;369  url?: string;370  score: number;371  ageDays: number;372  reasons: string[];373  factors: {374    breached: boolean;375    breachCount: number;376    reused: boolean;377    aged: boolean;378    weak: boolean;379    missingTotpOnSensitive: boolean;380  };381}382383export interface AdvancedHealthReport {384  vaultScore: number;385  generatedAt: number;386  entryCount: number;387  reusedGroups: number;388  agedCount: number;389  remediation: AdvancedHealthEntryReport[];390}391392export const ACCENT_COLORS = [393  { name: "peach",    hex: "#F49C70" },394  { name: "rose",     hex: "#FF8AA6" },395  { name: "plum",     hex: "#D597F2" },396  { name: "lavender", hex: "#A6A8FF" },397  { name: "sky",      hex: "#5BC8EE" },398  { name: "mint",     hex: "#5EE0B0" },399  { name: "sage",     hex: "#B5D870" },400  { name: "butter",   hex: "#FFD45A" },401  { name: "sand",     hex: "#EDBC85" },402  { name: "clay",     hex: "#F08660" },403  { name: "slate",    hex: "#80BEDE" },404  { name: "stone",    hex: "#C8B8A8" },405] as const;406407export type AccentColorName = typeof ACCENT_COLORS[number]["name"];408409export interface SavedIdentity {410  value: string;411  type: "email" | "username";412  lastUsed: number;413  useCount: number;414  exampleDomain?: string;415}416417export interface PasswordPolicy {418  minLength?: number;419  maxLength?: number;420  requiresUppercase?: boolean;421  requiresLowercase?: boolean;422  requiresNumbers?: boolean;423  requiresSymbols?: boolean;424  forbidsSymbols?: boolean;425  allowedSymbols?: string;426  /** Characters the site explicitly disallows. Filtered from every pool before generation. */427  forbiddenChars?: string;428}429430/**431 * A single vault history snapshot. The `vault_a` and `vault_b` fields are the432 * raw encrypted blobs from chrome.storage.local — already AES-256-GCM433 * protected by the master password, so storing them in history adds no434 * security surface.435 *436 * Snapshots are taken BEFORE every vault write so the saved blob represents437 * what is about to be lost, not what was just written. The reason field438 * documents the trigger so the UI can render "saved" / "synced" / "imported"439 * / "restored" labels next to each row.440 */441export interface VaultSnapshot {442  id: string;443  savedAt: number;444  reason: "local_save" | "sync_received" | "import" | "restore";445  vault_a: string;446  vault_b: string;447  /**448   * Coarse size bucket (ceiling) of active entries when the snapshot was taken;449   * null if vault was locked or in decoy mode. PCH-01-023: bucketed, not exact,450   * so the plaintext value cannot leak vault size or per-write deltas. UI should451   * render it as "up to N", never as an exact count.452   */453  entryCount: number | null;454}455456export interface VaultHistory {457  /** Newest first; capped at HISTORY_MAX (10). */458  snapshots: VaultSnapshot[];459}460461export interface Message {462  type: MessageType;463  payload?: unknown;464}465466export interface MessageResponse {467  ok: boolean;468  data?: unknown;469  error?: string;470  vaultId?: string;471  unlocked?: boolean;472  // Set on UNLOCK responses when the vault decrypted but failed schema473  // validation (M7/COR-007). The popup may offer a history-restore flow.474  canRestoreFromHistory?: boolean;475  // Set on COPY responses: the effective clipboard auto-clear delay in seconds,476  // so the content script's TOTP toast can advertise the real configured time.477  clearSeconds?: number;478}