Skip to content

应用服务接口约定(v0.1) ​

CLI(pn)和桌面 App 都通过同一个服务层操作保险库:Rust crate passno-service,对外是一个 PassnoService trait。桌面端用 Tauri command 暴露同名方法(snake_case),前端 TypeScript 接口和下面的定义一一对应(camelCase 字段)。

改这份约定要同时改 Rust 和 TypeScript 两边,并更新本文。

类型 ​

rust
pub struct Status { pub initialized: bool, pub locked: bool, pub vault_path: String, pub item_count: u32 }

pub struct InitResult {
    pub secret_key: String,          // 例如 "A3-K7Q2PZ-…",只在这里显示一次
    pub emergency_kit_markdown: String,
}

pub enum ItemKind { Login, Password, SecureNote, Card, Identity, SshKey, ApiCredential, Document, Wifi, Custom }

pub struct ItemSummary {
    pub id: String, pub kind: ItemKind, pub title: String,
    pub subtitle: String,            // 登录类条目显示用户名,卡片显示“•••• 尾号”(取卡号字段:CardNumber 类型或标签含 number / 卡号;没有就取“尾号 / last 4”字段),其他为空
    pub primary_url: Option<String>, pub tags: Vec<String>,
    pub favorite: bool, pub archived: bool, pub vault: String,
    pub updated_at: i64,             // Unix 秒
    pub has_totp: bool,
}

pub struct ItemFilter {
    pub query: Option<String>, pub kind: Option<ItemKind>, pub tag: Option<String>,
    pub vault: Option<String>, pub include_archived: bool, pub favorites_only: bool,
}

pub enum FieldType { Text, Concealed, Email, Url, Phone, Date, MonthYear, Address, Menu, Reference, File, Totp, SshKey, CardNumber, CardType, Gender }

pub struct FieldView {
    pub id: String, pub label: String, pub section: Option<String>,
    pub field_type: FieldType, pub designation: Option<String>, // "username" | "password"
    pub value: Option<String>,       // 隐藏类字段(Concealed / Totp / SshKey / CardNumber)为 None,要用 reveal_field 取
    pub concealed: bool,
}

pub struct Item {
    pub summary: ItemSummary, pub urls: Vec<String>, pub fields: Vec<FieldView>,
    pub notes: Option<String>, pub created_at: i64,
    pub password_history_count: u32,
}

pub struct ItemDraft {
    pub kind: ItemKind, pub title: String, pub urls: Vec<String>,
    pub fields: Vec<FieldDraft>, pub notes: Option<String>, pub tags: Vec<String>, pub favorite: bool,
}
pub struct FieldDraft { pub id: Option<String>, pub label: String, pub section: Option<String>,
                        pub field_type: FieldType, pub designation: Option<String>, pub value: String }

pub enum GeneratorKind { Random, Passphrase, Pin }
pub struct GeneratorOptions {
    pub kind: GeneratorKind, pub length: u32,     // Random/Pin 是字符数,Passphrase 是单词数
    pub uppercase: bool, pub digits: bool, pub symbols: bool, pub avoid_ambiguous: bool,
    pub separator: Option<String>, pub capitalize: bool,
    pub for_domain: Option<String>,               // 有值时套用 PMR 网站规则
}
pub struct Generated { pub password: String, pub entropy_bits: f64, pub strength: Strength, pub rules_applied: Option<String> }
pub enum Strength { Weak, Fair, Strong, VeryStrong }

pub struct TotpCode { pub code: String, pub period: u32, pub remaining: u32 }

pub enum ImportFormat { OnePux, OnePasswordCsv, AppleCsv }
pub struct ImportPreview {
    pub format: ImportFormat, pub accounts: u32, pub vaults: Vec<String>, pub items: u32,
    pub attachments: u32, pub by_kind: Vec<(ItemKind, u32)>,
    pub not_migrated: Vec<String>,   // 用户能看懂的说明,例如"通行密钥(1Password 桌面版导不出)"
    pub warnings: Vec<String>,
}
pub enum DuplicatePolicy { Skip, KeepBoth }
pub struct ImportReport { pub imported: u32, pub skipped_duplicates: u32, pub downgraded_fields: Vec<String>, pub errors: Vec<String> }

pub struct Stats { pub total: u32, pub weak: u32, pub reused: u32, pub missing_totp_where_supported: u32 }
pub struct ReusedPasswordGroup { pub item_ids: Vec<String>, pub count: u32 }
pub struct SecurityAudit { pub weak_item_ids: Vec<String>, pub reused_groups: Vec<ReusedPasswordGroup>, pub missing_totp_item_ids: Vec<String> }

pub struct AttachmentInfo {
    pub id: String, pub file_name: String, pub size_bytes: u64, pub sha256: String,
    pub media_type: Option<String>, pub has_blob: bool,
}
pub struct PasswordHistoryMeta { pub index: u32, pub changed_at: i64 }

方法 ​

方法说明错误
status() -> Status不需要解锁—
init(master_password) -> InitResult新建保险库,生成 Secret KeyAlreadyInitialized、WeakPassword
unlock(master_password, secret_key: Option)secret_key 为 None 时从本机的 SecretKeyStore 读取WrongPassword、SecretKeyMissing
lock()清空内存里的密钥—
list_items(filter) -> Vec<ItemSummary>按 updated_at 倒序Locked
get_item(id) -> Item隐藏类字段的值为 NoneLocked、NotFound
reveal_field(item_id, field_id) -> String只有本人操作的界面和交互式终端可以调用Locked、NotFound
create_item(draft) -> String返回新 idLocked、Invalid
update_item(id, draft)修改密码时,旧值进历史Locked、NotFound、Invalid
delete_item(id) / restore_item(id)软删除,进回收站Locked、NotFound
set_item_archived(id, archived) / set_item_favorite(id, favorite)更新归档或收藏标记Locked、NotFound
generate(options) -> Generated不需要解锁Invalid
totp(item_id) -> TotpCodeLocked、NotFound、NoTotp
import_preview(path, format) -> ImportPreview只读,不写保险库Locked、ParseError
import_commit(path, format, policy) -> ImportReport幂等:同一来源的 UUID 不会重复导入Locked、ParseError
stats() -> Stats汇总统计Locked
security_audit() -> SecurityAudit返回弱密码、复用组及缺少 2FA 条目 ID(不含明文)Locked
reload_if_changed() -> bool检测共享 $PASSNO_HOME 外部写入并重载Io、TamperingDetected、RollbackDetected
list_attachments(item_id) -> Vec<AttachmentInfo>列出条目附件元数据(不含文件内容)Locked、NotFound
add_attachment(item_id, path) -> AttachmentInfo流式加密并附加文件(上限 128 MiB)Locked、NotFound、Invalid、Io
export_attachment(item_id, attachment_id, dest_path)校验签名/摘要并流式解密导出(支持附件 ID 或唯一文件名)Locked、NotFound、Invalid、Io
delete_attachment(item_id, attachment_id)删除附件引用并清理未引用加密块Locked、NotFound、Invalid
list_password_history(item_id) -> Vec<PasswordHistoryMeta>仅返回历史索引与变更时间戳(不含明文)Locked、NotFound
reveal_password_history(item_id, index) -> String仅限人类交互界面 / 交互式 TTY 调用Locked、NotFound
list_trashed_items(filter) -> Vec<ItemSummary>列出回收站条目(按 updated_at 倒序)Locked
purge_item(id)永久粉碎指定回收站条目(活跃条目拒绝,返回 Invalid)并 GC 密文块Locked、NotFound、Invalid
empty_trash() -> u32清空回收站并 GC 未引用密文块,返回清除数量Locked

Tauri 桌面端另提供以下应用级命令:copy_secret(value, clear_after_seconds)、clear_clipboard()、stage_import_file(file_name, bytes)、cli_install_status()、install_cli(scope)、uninstall_cli(scope);v0.2 守护进程阶段补充可选扩展命令:daemon_status()、unlock_with_biometrics(reason?)、enroll_biometrics()、disable_biometrics()、set_auto_lock_settings(settings);修改主密码 change_master_password(current_password?, new_password) 与忘记主密码时的 move_vault_aside()(2026-11-16,见 修改主密码,只返回元数据);回收站列表 list_trashed()(等同 list_trashed_items 的默认过滤,供设置页的回收站使用)。当共享保险库变更或状态切换时通过事件 vault-changed(守护进程自动/手动锁定时同步发射 vault-locked 与 vault-changed)通知前端刷新。

错误 ​

rust
pub enum ServiceError {
    NotInitialized, AlreadyInitialized, Locked, WrongPassword, SecretKeyMissing, WeakPassword,
    NotFound, Invalid(String), NoTotp, ParseError(String), Io(String), Internal(String),
}

CLI 退出码对应:

错误退出码
Invalid2
Locked / WrongPassword / SecretKeyMissing / MasterPasswordRequired3
NotFound5
DaemonUnavailable / PeerDenied7
PolicyDenied(如非 TTY --reveal)8
其余1

Tauri 侧: 返回 { code: "Locked", message: "…" },前端按 code 处理。

iOS FFI(v0.2) ​

passno-ffi 的 PassnoClient 经 UniFFI 生成 Swift 绑定,供本人 App / AutoFill 进程内调用,不是 agent / CLI / MCP 接口。既有 PassnoService trait 未添加 agent 可调用的明文路径。新增原生专用 AUK 初始化/导出/打开、登录/通行密钥匹配、系统 credential identities、密码/验证码填充、通行密钥注册/断言、目录导入;签名与私钥只在 Rust 中处理。具体返回类型见 crates/passno-ffi/src/types.rs,安全边界及合并需要核对的增量见 iOS 工作线。

v0.2 首次启动:发现已有保险库 → 恢复(sync 工作线) ​

以下为 passno-sync 已实现的应用服务函数;与 v0.1 PassnoService 条目接口分离,由启动器注入 RecoveryBundleStore / VaultDiscovery / SecretKeyStore 后调用。尚未新增 Tauri/IPC command 或 TypeScript 方法,协调者接线时须同步前后端定义。

应用动作Rust 服务入口返回/边界
自动发现discover_all(&[&dyn VaultDiscovery]) -> DiscoveryResult{vaults: [{vault_id,name,source,header_verified,has_recovery_bundle,location}],warnings};location 为无凭据位置或 recovery 引用;不含 Secret Key。UI 将 warnings 展示为来源不可用,不误报“没有保险库”
发现来源RecoveryDiscovery、FolderDiscovery、GitDiscovery苹果默认恢复包+iCloud 路径;GitHub 私库用用户显式选择触发。iOS 容器 URL 由原生宿主传入 FolderDiscovery
从 iCloud/其他位置恢复restore_from_bundle(home,vault_id,password,bundle_store,secret_store) -> Vault只需主密码,Secret Key 和凭据由 store 内部读取。成功持有新设备 Vault;WrongCredentials→提示重试,不修改目标库;TamperingDetected→停止;AlreadyInitialized→不覆盖
自定义传输/测试恢复restore_with_transport(home,recovery_vault,password,location,transport,secret_store)应用内部方法,RecoveryVault 不得序列化给 agent/前端日志
配置主位置/备份configure_location(vault,secret_store,bundle_store,location,credentials,backup,name)返回 SyncConfig;完整凭据只进安全 store,backup=true 追加备份
同步SyncEngine::sync_unlocked / sync_locked,随后 sync_backups主位置报告 + 备份错误;daemon 可直接调用 SyncScheduler hooks
生成/导入应急套件emergency_kit(&RecoveryVault) / decode_emergency_kit(text)包含 Secret Key 和访问凭据,必须是本人明确操作;不要经普通 agent/MCP 输出。导入存储完成只返回成功状态

首次启动顺序:发现 → 显示来源及可用恢复材料 → 用户选择 vault ID → 输入主密码 → staging 验证 → 安装新设备 → 由宿主建立本机生物识别便利解锁 → 同步发布新设备。恢复包缺失时引导用户导入应急套件;不要循环问主密码。可同步钥匙串写失败必须提示,不能静默宣称“已备份”。header_verified=true 只表示发现时签名校验通过,只有成功恢复才建立账户信任。

v0.2 浏览器匹配补充(integrate1) ​

Rust / daemon 的 Item 增加 url_rules: Vec<passno_model::ItemUrl>,保留每个网址的 match_mode 和 label,原 urls: Vec<String> 不变。未收到规则的宿主拒绝匹配,不能自行推测 为 BaseDomain。update_item 保留未改动网址的原始规则,避免更新密码时放宽 Never / Exact 等策略。

浏览器插件(integrate1) ​

  • browser_extension_status() -> { available, installed, hostPath?, extensionPath?, manifestPath }
  • install_browser_extension() -> 同上:用户点击后安装 Chrome native manifest;必须找到当前 bundle 的宿主与扩展资源,固定允许的扩展 ID。无管理权限、不启动浏览器、不改密码保存偏好。

桌面数据与安全入口(integrate1) ​

均为 Tauri 命令,参数和返回字段使用 camelCase;不新增 pn 明文能力。

命令参数返回
list_attachmentsitemIdAttachmentInfo[](id / fileName / sizeBytes / sha256 / mediaType / hasBlob)
add_attachmentitemId, pathAttachmentInfo
export_attachmentitemId, attachmentId, destPathvoid;沿用服务层禁止覆盖现有文件的行为
delete_attachmentitemId, attachmentIdvoid
choose_attachment_file无用户选中的路径或 null;只由点击触发原生文件选择器
choose_attachment_destinationfileName导出目标路径或 null
list_password_historyitemId{ index, changedAt }[],不含明文
reveal_password_historyitemId, index本人点击后返回一次历史明文;前端 30 秒 / 失焦 / 锁定时隐藏
purge_itemidvoid;仅永久删除已进回收站的条目
empty_trash无删除数量

前端同时接上已有的 daemon_status、unlock_with_biometrics、enroll_biometrics、 disable_biometrics、set_auto_lock_settings。真实界面只按 daemon 的策略锁定; 本地浏览器演示模式才保留 UI 定时器。vault-locked 立即清空界面与弹窗, vault-changed 会先读 status,再决定加载数据或返回解锁页。

浏览器内部原子操作(integrate1) ​

PassnoService / IPC 增加两个受信任浏览器客户端操作,不暴露到 pn 或 MCP:

方法返回保证
browser_fill(id, url)BrowserFill { title, username, password, totp? }单个保险库锁内验证未删除 / 未归档的登录、当前 URL 策略并读秘密
update_login_credentials(id, url, username, password)bool 是否改变同一锁内验证 URL,仅更新凭据字段;保留最新元数据及其他字段,沿用密码历史记录

Never / 不支持的 Regex / HTTPS 降级等匹配失败均拒绝;不回退到通用 reveal。 请求 / 响应 Debug 不含用户名、密码或 TOTP。缺少实现的后端默认返回不支持错误。

integrate2:同步、发现与恢复 IPC ​

前述“尚未新增 Tauri/IPC command”已由本轮接线完成。Tauri sync_command({command}) 转发 daemon RequestBody::Sync,TypeScript PassnoApi.syncCommand 对应同一 tagged union。 请求按 action 区分:

action参数(camelCase)返回 type / data
status / now无status / SyncStatusRecord(沿用核心 snake_case)
locations无locations / {id,kind,label,primary,lastSyncAtMs,error}[]
discover`location: SyncLocationnull, credentials?`
restorevaultId,masterPassword,location,secretKey,emergencyKit,credentials?done,随后发出解锁事件
configurelocation,credentials?,backuplocations;null 使用 iCloud Drive 默认路径,保存后开启自动同步
remove_backupidlocations;只删除配置及恢复存储中的凭据,不删除远端密文
devices无devices / {id,name,current,revoked}[]
remove_deviceiddone;要求解锁、不能移除当前设备,轮换纪元后排队同步

SyncLocation 沿用核心 snake_case tag(folder/git/s3/web_dav/stored);凭据 username/password/access_key/secret_key 只允许输入,不提供读取接口。请求 Debug 整体遮蔽。 restore 有恢复包时只需主密码;显式位置须附 Secret Key,或导入包含 URI 的 v0.2 应急套件。 新设备恢复后通过普通主密码解锁策略建立 daemon 会话;不自动触发生物识别注册弹窗。 错误只返回固定中文信息,不原样传播传输地址、凭据或远端响应。

sharing:共享与设备丢失(2026-11-16) ​

新增 LocalPassnoService::sharing_command(SharingCommand) -> serde_json::Value,经 RequestBody::Sharing 与 Tauri sharing_command 传递。SharingCommand 用 action 判别,字段 为 camelCase;敏感输入 Debug 为 [REDACTED],传输错误不重放任何共享操作。普通返回仅包含 公钥身份、指纹、成员角色、库/条目元数据、收件人绑定邀请码与改密清单;不提供共享明文读取 RPC。

copy_item / import_item 在后端复制完整条目,值不经过 CLI/IPC;跨库附件引用拒绝。 revoke_device 要求 deviceId,newPassword,confirmed,完整换账户 generation 后强制锁定, 响应为 RevocationReport,应急套件只返回 emergency_kit_path;失败中断由 resume_revocation 重试。不改变 PassnoService trait,因此其他工作线已有 mock 无需实现新方法。 详细命令、权限与协作边界见 共享。

手机批准解锁(phoneapprove) ​

新增 Tauri phone_approve(command: String, fingerprint?: String) -> JSON,前端 phoneApprove 为可选能力。仅已验证桌面进程可调用,命令及字段见 手机批准。新增 UnlockMethod::Phone。不返回 AUK/私钥,CLI/MCP 不暴露该命令。

UniFFI PhoneApprovalClient 为本人原生 UI 专用;receive_capability 的 capsule 只能交给 PhoneCapabilityStoring 做 Secure Enclave 包裹(模拟器 Keychain);不能转发给 CLI/MCP/IPC。批准前逐次认证,取回的明文 capsule 在 Swift 使用后清零。

文档对应提交 56d1c45 · 由仓库 docs/ 自动生成