types.ts

15.5 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  /**150   * Firefox path: when present, the popup performs the navigator.credentials151   * call itself rather than completing a chrome.webAuthenticationProxy152   * request. Absent for Chrome (the existing webAuthenticationProxy flow).153   */154  browser?: "chrome" | "firefox";155  /** Firefox create: base64url challenge minted by the popup-context flow. */156  challenge?: string;157  /** Firefox create: base64url user handle. Generated if absent. */158  userHandle?: string;159}160161export interface PasskeyProviderState {162  supported: boolean;163  enabled: boolean;164  attached: boolean;165  browserLabel: string;166  statusLabel: string;167  conflict?: string;168}169170export interface StoredVault {171  // Not authenticated as AAD — the actual AES-GCM AAD is the slot's constant172  // aadTag string (see background/aes.ts). The version field is unauthenticated173  // metadata; downgrade prevention does not rest on it.174  version: 1;175  salt: string; // hex --- 16 bytes, CSPRNG, stored not secret176  nonce: string; // hex --- 12 bytes, CSPRNG, fresh per write177  ciphertext: string; // hex --- AES-256-GCM output178  tag: string; // hex --- 16-byte GCM auth tag179  // Recovery escrow: root key wrapped under recovery words via AES-256-GCM.180  recovery_salt?: string; // hex --- 16 bytes, CSPRNG, HKDF salt for recovery key181  recovery_wrapped_root_key?: string; // hex --- AES-256-GCM ciphertext of 32-byte root key182  recovery_nonce?: string; // hex --- 12 bytes, fresh nonce for the above183  recovery_tag?: string; // hex --- 16-byte GCM auth tag for the above184  // Second wrapping of the same root key under the password-derived key.185  // Lets unlock() recover the rootKey bytes without the user's recovery186  // words, so GET_RECOVERY_WORDS works across lock/unlock cycles. Refreshed187  // on every password change so the words stay valid (H2/COR-006).188  pw_root_ciphertext?: string; // hex --- AES-256-GCM ciphertext of 32-byte root key (hex-encoded)189  pw_root_nonce?: string; // hex --- 12-byte nonce190  pw_root_tag?: string; // hex --- 16-byte GCM auth tag191}192193// Background-bound message types — sent from popup/content scripts,194// handled in src/background/messages.ts. Everything in this group must195// have a matching case in that file's switch statement.196export type MessageType =197  | "GET_SYNC_ALERTS"198  | "CLEAR_CLIPBOARD"199  | "GET_PENDING_VOUCHED_DEVICES"200  | "CONFIRM_VOUCHED_DEVICE"201  | "REJECT_VOUCHED_DEVICE"202  | "VOUCHED_DEVICE_PENDING"203  | "ROTATE_SYNC_IDENTITY"204  | "DEVICE_KEY_ROTATED"205  | "UNLOCK"206  | "UNLOCK_WITH_PIN"207  | "GET_PIN_STATUS"208  | "LOCK"209  | "IS_UNLOCKED"210  | "HAS_VAULT"211  | "GET_ENTRIES"212  | "ADD_ENTRY"213  | "BATCH_ADD_ENTRIES"214  | "RESTORE_ENTRIES"215  | "CLEAR_VAULT_ENTRIES"216  | "UPDATE_ENTRY"217  | "ADD_ADDITIONAL_URL"218  | "DELETE_ENTRY"219  | "AUTOFILL_QUERY"220  | "COPY"221  | "CREATE_VAULT"222  | "CREATE_VAULT_FROM_ROOT_KEY"223  | "GET_ENTRY_FOR_FILL"224  | "GET_ENTRY_FOR_EDIT"225  | "CHECK_ALL_BREACHES"226  | "GET_SETTINGS"227  | "UPDATE_SETTINGS"228  | "SETUP_PIN"229  | "DISABLE_PIN"230  | "FIRE_CANARY_PING"231  | "ACTIVATE_LICENSE"232  | "GET_LICENSE"233  | "GET_LICENSE_KEY"234  | "IS_DURESS_ENABLED"235  | "SETUP_DURESS"236  | "DISABLE_DURESS"237  | "VERIFY_MAIN_PASSWORD"238  | "CHANGE_PASSWORD"239  | "GET_SITE_PASSWORD_POLICY"240  | "GET_LOCAL_IDENTITY"241  | "LIST_PAIRED_DEVICES"242  | "RENAME_PAIRED_DEVICE"243  | "UNPAIR_DEVICE"244  | "RENAME_LOCAL_DEVICE"245  // Relay pairing. START/CONFIRM/CANCEL are popup→bg requests handled in the246  // switch; ADOPTION_SOURCE_SAS / ADOPTION_SOURCE_RESULT are bg→popup pushes.247  | "START_ADOPTION_SOURCE"248  | "START_ADOPTION_RECEIVER"249  | "CANCEL_ADOPTION_SOURCE"250  | "SOURCE_SAS_DECISION"251  | "ADOPTION_SOURCE_SAS"252  | "ADOPTION_SOURCE_RESULT"253  | "TRIGGER_SYNC"254  | "GET_SYNC_STATE"255  | "GET_SYNC_SETTINGS"256  | "SET_SYNC_SETTINGS"257  | "GET_PENDING_PASSKEY"258  | "APPROVE_PASSKEY"259  | "DENY_PASSKEY"260  | "GET_PASSKEY_PROVIDER_STATE"261  | "SET_PASSKEY_PROVIDER_ENABLED"262  | "GET_DELETED_ENTRIES"263  | "RESTORE_ENTRY"264  | "PURGE_ENTRY"265  | "PURGE_EXPIRED_TRASH"266  | "GET_VAULT_HISTORY"267  | "RESTORE_VAULT_SNAPSHOT"268  | "COUNT_DUPLICATES"269  | "DEDUPLICATE_ENTRIES"270  | "RECORD_MANUAL_SUMMON"271  | "DECLINE_CARD_SAVE"272  | "IS_CARD_DECLINED"273  | "GET_VAULT_STATUS"274  | "GET_ADVANCED_HEALTH_REPORT"275  | "DEACTIVATE_LICENSE"276  | "GET_IDENTITIES"277  | "DESTROY_VAULT"278  | "INITIATE_FIREFOX_PASSKEY_CREATE"279  | "COMPLETE_FIREFOX_PASSKEY_CREATE"280  | "PASSKEY_OFFER_DECLINE"281  | "GET_PASSKEY_OFFER_DECLINED"282  | "GET_PASSKEY_FOR_DOMAIN"283  // Firefox content-script proxy path (v2.12.0). Sent FROM the page-world284  // monkey-patch through the extension-world relay TO the background. See285  // src/shared/passkey-flags.ts for removal conditions.286  | "PASSKEY_HAS_CREDENTIALS"287  | "PASSKEY_CREATE"288  | "PASSKEY_GET"289  // Recovery word messages290  | "VALIDATE_RECOVERY_WORDS"291  | "RECOVER_WITH_WORDS"292  | "GET_RECOVERY_WORDS"293  | "GET_RECOVERY_CONFIRM_PENDING"294  | "SET_RECOVERY_CONFIRM_PENDING"295  | "CLEAR_RECOVERY_CONFIRM_PENDING"296  | "GET_IDENTITY_SUGGESTIONS"297  | "TOUCH_AUTO_LOCK"298  | "SAVE_NOTE"299  | "DELETE_NOTE"300  | "GET_NOTES"301  | "SEARCH_VAULT"302  | "ML_INIT"303  | "ML_PREDICT_BATCH"304  // Content-script-bound message types — sent BY the background TO content305  // scripts. They never reach messages.ts's switch. Kept in this union so306  // existing call sites type-check; do not add cases for them in the307  // background handler.308  | "PING"            // background → content: liveness probe309  | "SUMMON_AUTOFILL" // background → content: open the in-page palette310  | "VAULT_LOCKED"    // background → content/popup: vault just locked311  | "VAULT_UNLOCKED"  // background → content/popup: vault just unlocked312  | "PRO_GATE_TRIGGERED" // background → popup: a Pro feature was attempted on free313  | "PASSKEY_PRO_GATE" // background → content: show passkey Pro gate in inline popup314  | "OPEN_PRO_GATE" // content → background: open popup and navigate to License section315  | "OPEN_POPUP" // content → background: open the extension popup (e.g. to unlock)316  | "OPEN_DETACHED_POPUP" // popup → background: open the popup HTML in a standalone window (file-picker flows)317  | "SHOW_PASSKEY_TOAST"    // background → content tab: show passkey auth toast318  | "DISMISS_PASSKEY_TOAST" // background → content tab: dismiss passkey auth toast319  | "PASSKEY_AUTH_RESPONSE" // content → background: user approved or denied the toast320  | "SHOULD_PLAY_CELEBRATION"321  | "MARK_CELEBRATION_PLAYED"322  // Peach Codex (v2.42.0). Generation runs in the popup — the SW only323  // sources vault data and applies the restored slots.324  | "GET_CODEX_VAULT_DATA"325  | "ESTIMATE_CODEX_PAGES"326  | "GENERATE_CODEX"327  | "RESTORE_FROM_CODEX";328329export type ProFeature =330  | "sync"331  | "passkeys"332  | "advanced_health"333  | "ios_app"334  | "codex"335  | "canary_entry"336  | "duress_vault";337338/**339 * License export shape included in PeachScript and encrypted JSON backups.340 * `celebrationPlayed` is intentionally absent — a new device deserves the moment.341 */342export interface PeachLicenseExport {343  key: string;344  activatedAt?: number;345}346347export interface AdvancedHealthEntryReport {348  id: string;349  title: string;350  domain: string;351  url?: string;352  score: number;353  ageDays: number;354  reasons: string[];355  factors: {356    breached: boolean;357    breachCount: number;358    reused: boolean;359    aged: boolean;360    weak: boolean;361    missingTotpOnSensitive: boolean;362  };363}364365export interface AdvancedHealthReport {366  vaultScore: number;367  generatedAt: number;368  entryCount: number;369  reusedGroups: number;370  agedCount: number;371  remediation: AdvancedHealthEntryReport[];372}373374export const ACCENT_COLORS = [375  { name: "peach",    hex: "#F49C70" },376  { name: "rose",     hex: "#FF8AA6" },377  { name: "plum",     hex: "#D597F2" },378  { name: "lavender", hex: "#A6A8FF" },379  { name: "sky",      hex: "#5BC8EE" },380  { name: "mint",     hex: "#5EE0B0" },381  { name: "sage",     hex: "#B5D870" },382  { name: "butter",   hex: "#FFD45A" },383  { name: "sand",     hex: "#EDBC85" },384  { name: "clay",     hex: "#F08660" },385  { name: "slate",    hex: "#80BEDE" },386  { name: "stone",    hex: "#C8B8A8" },387] as const;388389export type AccentColorName = typeof ACCENT_COLORS[number]["name"];390391export interface SavedIdentity {392  value: string;393  type: "email" | "username";394  lastUsed: number;395  useCount: number;396  exampleDomain?: string;397}398399export interface PasswordPolicy {400  minLength?: number;401  maxLength?: number;402  requiresUppercase?: boolean;403  requiresLowercase?: boolean;404  requiresNumbers?: boolean;405  requiresSymbols?: boolean;406  forbidsSymbols?: boolean;407  allowedSymbols?: string;408  /** Characters the site explicitly disallows. Filtered from every pool before generation. */409  forbiddenChars?: string;410}411412/**413 * A single vault history snapshot. The `vault_a` and `vault_b` fields are the414 * raw encrypted blobs from chrome.storage.local — already AES-256-GCM415 * protected by the master password, so storing them in history adds no416 * security surface.417 *418 * Snapshots are taken BEFORE every vault write so the saved blob represents419 * what is about to be lost, not what was just written. The reason field420 * documents the trigger so the UI can render "saved" / "synced" / "imported"421 * / "restored" labels next to each row.422 */423export interface VaultSnapshot {424  id: string;425  savedAt: number;426  reason: "local_save" | "sync_received" | "import" | "restore";427  vault_a: string;428  vault_b: string;429  /**430   * Coarse size bucket (ceiling) of active entries when the snapshot was taken;431   * null if vault was locked or in decoy mode. PCH-01-023: bucketed, not exact,432   * so the plaintext value cannot leak vault size or per-write deltas. UI should433   * render it as "up to N", never as an exact count.434   */435  entryCount: number | null;436}437438export interface VaultHistory {439  /** Newest first; capped at HISTORY_MAX (10). */440  snapshots: VaultSnapshot[];441}442443export interface Message {444  type: MessageType;445  payload?: unknown;446}447448export interface MessageResponse {449  ok: boolean;450  data?: unknown;451  error?: string;452  vaultId?: string;453  unlocked?: boolean;454  // Set on UNLOCK responses when the vault decrypted but failed schema455  // validation (M7/COR-007). The popup may offer a history-restore flow.456  canRestoreFromHistory?: boolean;457  // Set on COPY responses: the effective clipboard auto-clear delay in seconds,458  // so the content script's TOTP toast can advertise the real configured time.459  clearSeconds?: number;460}