Compare commits
36 Commits
3035a77579
...
v1.7.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 5048cc0720 | |||
| 3f785febc8 | |||
| 907126d152 | |||
| c1f57957c0 | |||
| cd2ec8240b | |||
| 16bde22604 | |||
| 4900de0444 | |||
| 79ed7c9f85 | |||
| 9a21504f40 | |||
| 045b23fc47 | |||
| 42b765b113 | |||
| f9fe53285f | |||
| 46ba8b9950 | |||
| f096681a2b | |||
| fe0c66c561 | |||
| add921b3b3 | |||
| f1b716fb31 | |||
| 8f2704fd41 | |||
| 7e0406f751 | |||
| d5c2ab2b0f | |||
| 9e0908f43c | |||
| 7b3be2c819 | |||
| a8183166ac | |||
| f6169b7610 | |||
| 493f901ec1 | |||
| b4dfb0409b | |||
| a06cb0ed71 | |||
| b0242265f4 | |||
| b444c0f4b8 | |||
| b1b25fe678 | |||
| 7cf2ab7c88 | |||
| 1918735520 | |||
| c652cc1533 | |||
| e9aef72df7 | |||
| 9adb24d4bb | |||
| 563570e3e0 |
@@ -1,17 +1,5 @@
|
||||
# CodeGraph data files
|
||||
# These are local to each machine and should not be committed
|
||||
|
||||
# Database
|
||||
*.db
|
||||
*.db-wal
|
||||
*.db-shm
|
||||
|
||||
# Cache
|
||||
cache/
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
|
||||
# Hook markers
|
||||
.dirty
|
||||
*.pid
|
||||
# CodeGraph data files — local to each machine, not for committing.
|
||||
# Ignore everything in .codegraph/ except this file itself, so transient
|
||||
# files (the database, daemon.pid, sockets, logs) never show up in git.
|
||||
*
|
||||
!.gitignore
|
||||
|
||||
@@ -18,6 +18,7 @@ build/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
docs/
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
@@ -55,3 +56,9 @@ NodeWarden-compat/
|
||||
.codex-upstream/bitwarden-browser/
|
||||
|
||||
.reasonix/
|
||||
|
||||
# Compatibility analysis documents
|
||||
BITWARDEN_COMPATIBILITY_ANALYSIS.md
|
||||
.mcp.json
|
||||
opencode.jsonc
|
||||
.cursor/
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
| **PWA 支持** | ⚠️ 基础 | ✅ | **可安装、离线使用、App快捷方式** |
|
||||
| **Web Vault 离线查看** | ❌ | ✅ | **网页端支持离线查看保险库** |
|
||||
| **Passkey 登录** | ✅ | ✅ | **支持WebAuthn/FIDO2无密码登录** |
|
||||
| 全量同步 `/api/sync` | ✅ | ✅ | 已针对官方客户端做兼容优化 |
|
||||
| 实时同步 | ✅ | ✅ | 网页端、浏览器扩展、电脑端和手机端实时同步 |
|
||||
| 附件上传 / 下载 | ✅ | ✅ | Cloudflare R2 或 KV |
|
||||
| Send | ✅ | ✅ | 支持文本与文件 Send |
|
||||
| 导入 / 导出 | ✅ | ✅ | 支持 Bitwarden JSON / CSV / **ZIP 导入(包括附件)** |
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
| **PWA Support** | ⚠️ Basic | ✅ | **Installable, offline-capable, app shortcuts** |
|
||||
| **Web Vault Offline Access** | ❌ | ✅ | **Web client supports offline vault viewing** |
|
||||
| **Passkey Login** | ✅ | ✅ | **WebAuthn/FIDO2 passwordless login** |
|
||||
| Full sync `/api/sync` | ✅ | ✅ | Compatibility optimized for official clients |
|
||||
| Real-time sync | ✅ | ✅ | Web, browser extension, desktop, and mobile clients stay in sync in real time |
|
||||
| Attachment upload / download | ✅ | ✅ | Cloudflare R2 or KV |
|
||||
| Send | ✅ | ✅ | Supports both text and file Sends |
|
||||
| Import / Export | ✅ | ✅ | Supports Bitwarden JSON / CSV / **ZIP import with attachments** |
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# Security Policy
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Thank you for helping keep NodeWarden safe.
|
||||
|
||||
Please **do not report security vulnerabilities through public GitHub issues, discussions, pull requests, or chat groups**.
|
||||
|
||||
Use GitHub Private Vulnerability Reporting instead:
|
||||
|
||||
1. Open the NodeWarden repository on GitHub.
|
||||
2. Go to **Security and quality**.
|
||||
3. Click **Report a vulnerability**.
|
||||
4. Submit the report privately.
|
||||
|
||||
NodeWarden is independent from Bitwarden. Please do not report NodeWarden-specific issues to the official Bitwarden team.
|
||||
|
||||
## What to Include
|
||||
|
||||
Please include as much detail as possible:
|
||||
|
||||
* A clear description of the vulnerability.
|
||||
* Steps to reproduce.
|
||||
* Affected version, commit, or deployment method.
|
||||
* Affected area, such as login, sync, vault data, attachments, Send, import/export, backup/restore, Passkey, WebAuthn, or API routes.
|
||||
* Expected behavior and actual behavior.
|
||||
* Security impact, such as authentication bypass, authorization bypass, replay, cross-user access, token misuse, data leakage, or secret exposure.
|
||||
* Proof of concept, logs, screenshots, or request examples, if safe to share privately.
|
||||
|
||||
Please redact real passwords, tokens, private keys, recovery keys, vault data, and other secrets before submitting.
|
||||
|
||||
## Scope
|
||||
|
||||
Security reports are welcome for issues affecting NodeWarden itself, including:
|
||||
|
||||
* Authentication and session handling.
|
||||
* User authorization and cross-user access.
|
||||
* Vault data, cipher sync, attachments, and Send.
|
||||
* Import, export, backup, and restore.
|
||||
* Passkey, WebAuthn, and two-factor authentication.
|
||||
* Secret handling and provider credentials.
|
||||
* Cloudflare Workers, D1, R2, KV, WebDAV, or S3 behavior caused by NodeWarden code or documentation.
|
||||
|
||||
## Out of Scope
|
||||
|
||||
The following are usually out of scope:
|
||||
|
||||
* Issues only affecting third-party services or user infrastructure.
|
||||
* Misconfigured personal deployments not caused by NodeWarden defaults.
|
||||
* Social engineering or phishing.
|
||||
* Denial-of-service testing.
|
||||
* Scanner-only reports without a practical exploit path.
|
||||
* Reports that only mention outdated dependencies without showing real impact.
|
||||
|
||||
## Response
|
||||
|
||||
NodeWarden is maintained on a best-effort basis.
|
||||
|
||||
We aim to acknowledge valid private reports within 72 hours, investigate the issue, and release a fix or mitigation when appropriate.
|
||||
|
||||
Please do not publicly disclose vulnerability details before a fix or mitigation is available.
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Security fixes are generally provided for the latest release and the latest code on the default branch.
|
||||
|
||||
| Version | Supported |
|
||||
| -------------- | ---------------------- |
|
||||
| Latest release | Yes |
|
||||
| `main` branch | Yes |
|
||||
| Older releases | Best effort |
|
||||
| Modified forks | Not directly supported |
|
||||
|
||||
## Rewards
|
||||
|
||||
NodeWarden does not currently operate a paid bug bounty program.
|
||||
@@ -1,785 +0,0 @@
|
||||
# NodeWarden Passkey 登录研究记录
|
||||
|
||||
记录日期:2026-06-09
|
||||
研究范围:NodeWarden 自己的 server、web 登录/注册链路,以及官方 Bitwarden server、web、browser extension 对账户 passkey 登录的实现方式。
|
||||
|
||||
## 结论先放前面
|
||||
|
||||
NodeWarden 现在已经有完整的主密码注册、主密码登录、刷新 token、2FA、设备记录、官方客户端兼容的 `UserDecryptionOptions`,也支持 vault item 里的 `login.fido2Credentials` 字段。但它还没有“账户 passkey 登录”。现有 `src/utils/passkey.ts` 只有 base64url、challenge、clientData 解析这类工具函数,不能完成 FIDO2/WebAuthn 服务端注册和认证验证。
|
||||
|
||||
要支持“自己的 web 用 passkey 登录”和“官方/自定义浏览器扩展也能 passkey 登录”,不能只加一个登录按钮。必须补齐四块:
|
||||
|
||||
1. Server 端新增账户 WebAuthn credential 表、challenge/token 防重放机制、FIDO2 attestation/assertion 验证、`grant_type=webauthn`。
|
||||
2. Server 响应里按 Bitwarden 形状返回 PRF 解密材料:登录 token 响应用单个 `UserDecryptionOptions.WebAuthnPrfOption`,sync 响应用多个 `UserDecryption.WebAuthnPrfOptions`。
|
||||
3. NodeWarden web 新增 passkey 注册、管理、登录和 PRF 解锁 vault key 的客户端流程。
|
||||
4. 扩展兼容要跟官方 Bitwarden endpoint 和 response shape 对齐。官方 browser extension 当前只在 Chromium 系浏览器开放 passkey 登录,因为 Firefox/Safari 扩展环境还不能按官方代码需要的方式覆盖 RP ID。
|
||||
|
||||
下面按代码链路展开。
|
||||
|
||||
## 术语边界
|
||||
|
||||
这里有三个容易混淆的东西,文档后面严格区分:
|
||||
|
||||
- 账户 passkey 登录:用户不用主密码,使用 WebAuthn/passkey 完成账号认证,并且用 PRF 解开 vault user key。官方 Bitwarden 叫 `WebAuthnLogin`。
|
||||
- Vault item 里的 passkey:某个登录条目保存网站 passkey/FIDO2 credential 数据,对应 NodeWarden 的 `cipher.login.fido2Credentials`。这是“保险库保存别的网站 passkey”,不是“登录 NodeWarden 账号”。
|
||||
- WebAuthn 2FA:主密码登录之后用安全密钥做第二因素。官方旧 web repo 里主要是这一类,不等于 passkey 登录。
|
||||
|
||||
## NodeWarden 现状
|
||||
|
||||
### 路由和入口
|
||||
|
||||
NodeWarden 后端是 Cloudflare Workers + D1。主入口 `src/index.ts` 初始化存储后进入 router。认证边界在:
|
||||
|
||||
- `src/router-public.ts`:公开接口,包含 `/identity/connect/token`、`/identity/accounts/prelogin`、`/api/accounts/register`。
|
||||
- `src/router-authenticated.ts`:需要 access token 的接口,包含 profile、change password、TOTP、sync、vault、devices。
|
||||
- `src/handlers/identity.ts`:OAuth/token 兼容入口。
|
||||
- `src/handlers/accounts.ts`:注册、profile、密码变更、TOTP、API key 等账户接口。
|
||||
|
||||
目前公开路由没有:
|
||||
|
||||
- `GET /identity/accounts/webauthn/assertion-options`
|
||||
- `POST /identity/connect/token` 的 `grant_type=webauthn`
|
||||
- `POST /api/webauthn/attestation-options`
|
||||
- `POST /api/webauthn/assertion-options`
|
||||
- `GET/POST/PUT /api/webauthn`
|
||||
|
||||
### 注册链路
|
||||
|
||||
NodeWarden 自己 web 的注册入口在 `webapp/src/lib/api/auth.ts` 的 `registerAccount()`:
|
||||
|
||||
- 使用邮箱作为 salt,用 PBKDF2 派生 master key。
|
||||
- 再用 PBKDF2(masterKey, password, 1) 得到 client master password hash。
|
||||
- 随机生成 64 字节 vault symmetric key。
|
||||
- 用 masterKey 经 HKDF 拆成 enc/mac,把 vault key 加密成 Bitwarden `Key`。
|
||||
- 生成 RSA-OAEP key pair,把 private key 用 vault symmetric key 加密。
|
||||
- POST `/api/accounts/register`,提交 `email`、`name`、`masterPasswordHash`、`key`、KDF 参数、invite code、`keys.publicKey`、`keys.encryptedPrivateKey`。
|
||||
|
||||
后端 `src/handlers/accounts.ts` 的 `handleRegister()`:
|
||||
|
||||
- 第一个用户自动成为 admin,后续用户需要 invite。
|
||||
- 校验 `JWT_SECRET`、邮箱、KDF 下限、加密字符串形状、公钥/私钥。
|
||||
- 不直接保存 client hash,而是 `AuthService.hashPasswordServer(masterPasswordHash, email)` 后保存到 `users.master_password_hash`。
|
||||
- 保存 `users.key`、`users.private_key`、`users.public_key`、KDF 参数、`security_stamp`。
|
||||
|
||||
结论:账户 passkey 注册不是替代账号注册,而是“用户已登录后在安全设置里新增一个可登录 credential”。仍然需要已有 vault user key 来生成 PRF keyset。
|
||||
|
||||
### 主密码登录链路
|
||||
|
||||
NodeWarden 自己 web 的登录入口是 `webapp/src/lib/app-auth.ts` 的 `performPasswordLogin()`:
|
||||
|
||||
- 先 `deriveLoginHashLocally()` 得到 masterKey 和 client hash。
|
||||
- 调 `loginWithPassword()` POST `/identity/connect/token`。
|
||||
- token 成功后 `completeLogin()` 用 `token.Key` 和本地 masterKey 解开 vault key。
|
||||
- 保存离线解锁记录。
|
||||
|
||||
`webapp/src/lib/api/auth.ts` 也有 `deriveLoginHash()` 和 `getPreloginKdfConfig()` 会调用 `/identity/accounts/prelogin`,但当前 `performPasswordLogin()` 走的是本地 fallback iterations。passkey 登录不应复用这条 masterKey 路径,因为 passkey 登录没有主密码,拿不到 password-derived masterKey。
|
||||
|
||||
后端 `src/handlers/identity.ts` 的 `handleToken()` 当前支持:
|
||||
|
||||
- `grant_type=password`
|
||||
- `grant_type=client_credentials`
|
||||
- `grant_type=refresh_token`
|
||||
|
||||
密码登录成功后会:
|
||||
|
||||
- 验证 IP 登录频率和用户状态。
|
||||
- `AuthService.verifyPassword()` 验证 client hash。
|
||||
- 处理 TOTP 或 remember 2FA token。
|
||||
- 记录/更新 device。
|
||||
- 生成 access token 和 refresh token。
|
||||
- 返回 `Key`、`PrivateKey`、`AccountKeys`、KDF 参数、`UserDecryptionOptions`。
|
||||
|
||||
### UserDecryptionOptions 和 sync
|
||||
|
||||
NodeWarden 的 `src/utils/user-decryption.ts` 当前只构造主密码解锁:
|
||||
|
||||
- `HasMasterPassword: true`
|
||||
- `MasterPasswordUnlock`
|
||||
- `TrustedDeviceOption: null`
|
||||
- `KeyConnectorOption: null`
|
||||
|
||||
`src/types/index.ts` 的 sync 类型里预留了 `UserDecryption.WebAuthnPrfOption?: null`,但当前 `src/handlers/sync.ts` 实际只返回 `MasterPasswordUnlock`,没有账户 passkey PRF 解密选项。
|
||||
|
||||
passkey 登录必须新增两类 shape:
|
||||
|
||||
- 登录 token 响应:`UserDecryptionOptions.WebAuthnPrfOption`,只返回本次认证所用 credential 的 PRF 解密材料。
|
||||
- sync 响应:`UserDecryption.WebAuthnPrfOptions`,返回该用户所有已启用 PRF keyset 的 passkey 解密材料,供官方客户端锁定/解锁和 key rotation 使用。
|
||||
|
||||
### 现有 passkey 相关代码
|
||||
|
||||
NodeWarden 已支持 vault item 里的 FIDO2/passkey 字段:
|
||||
|
||||
- `src/types/index.ts`:`CipherLogin.fido2Credentials`
|
||||
- `src/handlers/ciphers.ts`:读写 cipher 时保留/规范化 `fido2Credentials`
|
||||
- `webapp/src/lib/api/vault.ts`:加密/解密 vault item 内的 `fido2Credentials`
|
||||
- `webapp/src/lib/types.ts`:`CipherLoginPasskey`
|
||||
|
||||
这部分是“保存网站 passkey”,不是账户登录。
|
||||
|
||||
`src/utils/passkey.ts` 只有:
|
||||
|
||||
- `bytesToBase64Url()`
|
||||
- `base64UrlToBytes()`
|
||||
- `randomChallenge()`
|
||||
- `parseClientDataJSON()`
|
||||
|
||||
缺少的核心能力:
|
||||
|
||||
- attestation verification
|
||||
- assertion verification
|
||||
- authenticator public key 格式处理
|
||||
- signature verification
|
||||
- sign counter 更新
|
||||
- userHandle 与 user id 绑定验证
|
||||
- origin/RP ID 验证
|
||||
- challenge 过期和防重放
|
||||
|
||||
### 数据库和备份影响
|
||||
|
||||
NodeWarden schema 在这些地方需要同步:
|
||||
|
||||
- `migrations/0001_init.sql`
|
||||
- `src/services/storage-schema.ts`
|
||||
- `wrangler.toml` migrations
|
||||
- `src/services/backup-archive.ts`
|
||||
- `src/services/backup-import.ts`
|
||||
- `shared/backup-schema` 相关类型
|
||||
|
||||
当前表里没有账户 passkey credential,也没有 WebAuthn challenge 表。`devices` 表保存设备 trust/key 信息,不适合混入 passkey credential,因为 WebAuthn credential 需要自己的 public key、credential id、counter、AAGUID、PRF keyset 等字段。
|
||||
|
||||
## 官方 Bitwarden server 参考
|
||||
|
||||
上游代码位置:
|
||||
|
||||
- `.codex-upstream/bitwarden-server`
|
||||
- 研究时 HEAD:`574f3fd`
|
||||
|
||||
官方 server 里也有两个 WebAuthn 概念:
|
||||
|
||||
- 传统 WebAuthn 2FA:`TwoFactorController`、`WebAuthnTokenProvider`
|
||||
- 账户 passkey 登录:`WebAuthnLogin`
|
||||
|
||||
本项目要参考的是后者。
|
||||
|
||||
### 公开 passkey 登录入口
|
||||
|
||||
`src/Identity/Controllers/AccountsController.cs`
|
||||
|
||||
- `GET /accounts/webauthn/assertion-options`
|
||||
- 返回 `WebAuthnLoginAssertionOptionsResponseModel`
|
||||
- response 包含:
|
||||
- `options`
|
||||
- `token`
|
||||
- token 使用 `WebAuthnLoginAssertionOptionsTokenable`
|
||||
- scope 为 `Authentication`
|
||||
- token 生命周期约 17 分钟
|
||||
|
||||
`src/Identity/IdentityServer/RequestValidators/WebAuthnGrantValidator.cs`
|
||||
|
||||
- 新增 OAuth extension grant:`grant_type=webauthn`
|
||||
- 从 form 读取:
|
||||
- `token`
|
||||
- `deviceResponse`
|
||||
- 解开 token,校验 scope 必须是 `Authentication`
|
||||
- 反序列化 `AuthenticatorAssertionRawResponse`
|
||||
- 调用 `AssertWebAuthnLoginCredential`
|
||||
- 把成功认证的 credential 传给 `UserDecryptionOptionsBuilder.WithWebAuthnLoginCredential(credential)`
|
||||
- 之后走通用登录成功逻辑,返回 access/refresh token 和账号加密状态。
|
||||
|
||||
`src/Identity/IdentityServer/ApiClient.cs`
|
||||
|
||||
- official identity client 的 allowed grant types 包含 `WebAuthnGrantValidator.GrantType`。
|
||||
|
||||
`TwoFactorAuthenticationValidator` 里有一个重要行为:FIDO2 user verification 已经被视为第二因素,所以 passkey 登录成功后官方不会再要求额外 2FA。NodeWarden 之后需要明确策略:要兼容官方客户端,应把 passkey 登录视作已满足 2FA,否则官方 `LoginViaWebAuthnComponent` 会显示“不支持 passkey 2FA”的错误。
|
||||
|
||||
### 账户 passkey 管理接口
|
||||
|
||||
`src/Api/Auth/Controllers/WebAuthnController.cs`
|
||||
|
||||
官方 authenticated API:
|
||||
|
||||
- `GET /webauthn`:列出账户 passkey credentials。
|
||||
- `POST /webauthn/attestation-options`:主密码/secret verification 后生成 credential create options 和 token。
|
||||
- `POST /webauthn/assertion-options`:主密码/secret verification 后生成 assertion options 和 token,用于给已有 credential 启用/更新 PRF keyset。
|
||||
- `POST /webauthn`:保存新 credential。
|
||||
- `PUT /webauthn`:更新 credential 的 PRF encryption keyset。
|
||||
- `POST /webauthn/{id}/delete`:删除 credential。
|
||||
|
||||
官方创建 credential 时保存:
|
||||
|
||||
- `name`
|
||||
- `token`
|
||||
- `deviceResponse`
|
||||
- `supportsPrf`
|
||||
- 可选 `encryptedUserKey`
|
||||
- 可选 `encryptedPublicKey`
|
||||
- 可选 `encryptedPrivateKey`
|
||||
|
||||
官方最多允许 5 个账户 passkey credentials。
|
||||
|
||||
### 官方 WebAuthnCredential 表
|
||||
|
||||
`src/Core/Auth/Entities/WebAuthnCredential.cs`
|
||||
|
||||
字段:
|
||||
|
||||
- `Id`
|
||||
- `UserId`
|
||||
- `Name`
|
||||
- `PublicKey`
|
||||
- `CredentialId`
|
||||
- `Counter`
|
||||
- `Type`
|
||||
- `AaGuid`
|
||||
- `EncryptedUserKey`
|
||||
- `EncryptedPrivateKey`
|
||||
- `EncryptedPublicKey`
|
||||
- `SupportsPrf`
|
||||
- `CreationDate`
|
||||
- `RevisionDate`
|
||||
|
||||
SQLite migration:`util/SqliteMigrations/Migrations/20231213032045_WebAuthnLoginCredentials.cs`
|
||||
|
||||
表名是 `WebAuthnCredential`,对 `User` 做 cascade delete,并按 `UserId` 建索引。
|
||||
|
||||
`GetPrfStatus()`:
|
||||
|
||||
- `Unsupported`:`SupportsPrf` 为 false。
|
||||
- `Supported`:credential 支持 PRF,但还没有完整 encrypted keyset。
|
||||
- `Enabled`:`EncryptedUserKey`、`EncryptedPrivateKey`、`EncryptedPublicKey` 都存在。
|
||||
|
||||
### 官方创建和认证策略
|
||||
|
||||
`GetWebAuthnLoginCredentialCreateOptionsCommand.cs`
|
||||
|
||||
- 使用 Fido2NetLib。
|
||||
- `user.id` 是用户 id bytes。
|
||||
- `user.name/displayName` 使用用户邮箱。
|
||||
- 排除当前用户已有 credential ids。
|
||||
- `residentKey: required`
|
||||
- `userVerification: required`
|
||||
- `attestation: none`
|
||||
|
||||
`GetWebAuthnLoginCredentialAssertionOptionsCommand.cs`
|
||||
|
||||
- `allowCredentials` 传空数组。
|
||||
- `userVerification: required`
|
||||
- 空 allow list 代表使用 discoverable credentials,也就是 passkey 登录页可以不先输入邮箱。
|
||||
|
||||
`CreateWebAuthnLoginCredentialCommand.cs`
|
||||
|
||||
- 限制每用户最多 5 个。
|
||||
- 检查 credential id 在该用户下不能重复。
|
||||
- FIDO `MakeNewCredentialAsync` 验证 attestation。
|
||||
- 保存 credential id/public key/counter/type/AAGUID/PRF keyset。
|
||||
|
||||
`AssertWebAuthnLoginCredentialCommand.cs`
|
||||
|
||||
- 先用 challenge cache 防重放。
|
||||
- 从 assertion response 的 `userHandle` 解析出 user id。
|
||||
- 加载该用户所有 WebAuthn credentials。
|
||||
- 用 credential id 找到记录。
|
||||
- FIDO `MakeAssertionAsync` 验证签名、challenge、origin、RP ID、user verification。
|
||||
- 成功后更新 counter。
|
||||
|
||||
### 官方 PRF 解密协议
|
||||
|
||||
`src/Core/Auth/Models/Api/Response/UserDecryptionOptions.cs`
|
||||
|
||||
`WebAuthnPrfDecryptionOption` 字段:
|
||||
|
||||
- `EncryptedPrivateKey`
|
||||
- `EncryptedUserKey`
|
||||
- `CredentialId`
|
||||
- `Transports`
|
||||
|
||||
`src/Identity/IdentityServer/UserDecryptionOptionsBuilder.cs`
|
||||
|
||||
- `WithWebAuthnLoginCredential()` 只在 credential 的 PRF status 是 `Enabled` 时加入 `WebAuthnPrfOption`。
|
||||
- 如果 credential 没有 PRF keyset,passkey 只能认证账号,不能解开 vault。
|
||||
|
||||
`src/Api/Vault/Models/Response/SyncResponseModel.cs`
|
||||
|
||||
- sync response 会把所有 enabled PRF credentials 放进 `UserDecryption.WebAuthnPrfOptions`。
|
||||
|
||||
## 官方 Bitwarden web/browser client 参考
|
||||
|
||||
上游代码位置:
|
||||
|
||||
- `.codex-upstream/bitwarden-clients`
|
||||
- `.codex-upstream/bitwarden-browser`
|
||||
- 两者研究时 HEAD 都是 `825f9be`,browser repo 内容和 clients monorepo 对应。
|
||||
|
||||
旧的 `.codex-upstream/bitwarden-web` 主要有 WebAuthn connector 和 2FA 设置页,没有现代账户 passkey 登录主流程。账户 passkey 登录应以 `bitwarden-clients` 为准。
|
||||
|
||||
### 登录按钮可见性
|
||||
|
||||
`libs/auth/src/angular/login/default-login-component.service.ts`
|
||||
|
||||
- 默认只对 `ClientType.Web` 开启 passkey 登录。
|
||||
|
||||
`apps/browser/src/auth/popup/login/extension-login-component.service.ts`
|
||||
|
||||
- browser extension 覆盖逻辑:只对 Chromium 开启。
|
||||
- 注释说明 Firefox 和 Safari 不能在扩展里覆盖 relying party ID。
|
||||
- 官方代码引用了 W3C webextensions issue 238、Mozilla bug 1956484、Apple forum thread 774351。
|
||||
|
||||
结论:NodeWarden 后端即使完全兼容官方 passkey API,官方扩展也只有 Chromium 系会显示 passkey 登录入口。
|
||||
|
||||
### Passkey 登录页
|
||||
|
||||
`libs/angular/src/auth/login-via-webauthn/login-via-webauthn.component.ts`
|
||||
|
||||
流程:
|
||||
|
||||
1. 进入 `/login-with-passkey` 后自动开始认证。
|
||||
2. 调 `webAuthnLoginService.getCredentialAssertionOptions()`。
|
||||
3. 调 `webAuthnLoginService.assertCredential(options)` 触发 `navigator.credentials.get()`。
|
||||
4. 调 `webAuthnLoginService.logIn(assertion)` 走 identity token grant。
|
||||
5. 如果 `authResult.requiresTwoFactor` 为 true,显示“客户端不支持 passkey 2FA”错误。
|
||||
6. 只有本地 `keyService.userKey$(authResult.userId)` 已经拿到 user key,才运行 login success handler。
|
||||
7. 成功路由:
|
||||
- Web:`/vault`
|
||||
- Browser:`/tabs/vault`
|
||||
- Desktop:`/vault`
|
||||
|
||||
Browser popout 下还会在成功后重新打开普通 popup 并关闭 popout。
|
||||
|
||||
### 客户端 passkey 登录请求
|
||||
|
||||
`libs/common/src/auth/services/webauthn-login/webauthn-login-api.service.ts`
|
||||
|
||||
- GET `${identityUrl}/accounts/webauthn/assertion-options`
|
||||
- 如果 NodeWarden 的 identityUrl 是站点 origin + `/identity`,实际路径就是 `/identity/accounts/webauthn/assertion-options`。
|
||||
|
||||
`libs/common/src/auth/services/webauthn-login/webauthn-login.service.ts`
|
||||
|
||||
- `navigator.credentials.get({ publicKey: options })`
|
||||
- 会主动加 PRF extension:
|
||||
- salt 是 `SHA-256("passwordless-login")`
|
||||
- extension shape 是 `extensions.prf.eval.first`
|
||||
- 从 `credential.getClientExtensionResults().prf.results.first` 取 PRF 输出。
|
||||
- 用 `WebAuthnLoginPrfKeyService.createSymmetricKeyFromPrf()` 转成 PRF key。
|
||||
- 构造 `WebAuthnLoginAssertionResponseRequest`。
|
||||
- 明确检查 `deviceResponse.extensions` 里不能含 `prf`,避免把 PRF 输出泄漏给服务端。
|
||||
|
||||
`libs/common/src/auth/services/webauthn-login/webauthn-login-prf-key.service.ts`
|
||||
|
||||
- salt 常量:`passwordless-login`
|
||||
- 先 SHA-256。
|
||||
- 再用 HKDF expand 拆成 64 字节:
|
||||
- `"enc"` 32 bytes
|
||||
- `"mac"` 32 bytes
|
||||
|
||||
`libs/common/src/auth/models/request/identity-token/webauthn-login-token.request.ts`
|
||||
|
||||
form encoded token 请求字段:
|
||||
|
||||
- `grant_type=webauthn`
|
||||
- `token=<server assertion options token>`
|
||||
- `deviceResponse=<JSON string>`
|
||||
- 还会带 common device request 字段。
|
||||
|
||||
`libs/common/src/auth/services/webauthn-login/request/webauthn-login-assertion-response.request.ts`
|
||||
|
||||
`deviceResponse` shape:
|
||||
|
||||
- `id`
|
||||
- `rawId`
|
||||
- `type`
|
||||
- `extensions: {}`
|
||||
- `response.authenticatorData`
|
||||
- `response.signature`
|
||||
- `response.clientDataJSON`
|
||||
- `response.userHandle`
|
||||
|
||||
全部二进制字段使用 base64url。
|
||||
|
||||
### 客户端如何用 PRF 解 vault key
|
||||
|
||||
`libs/auth/src/common/login-strategies/webauthn-login.strategy.ts`
|
||||
|
||||
- `setMasterKey()` 是空实现,因为 passkey 登录没有主密码 masterKey。
|
||||
- `setUserKey()`:
|
||||
- 如果 token response 有 `key`,保存为 master-key-encrypted user key,兼容主密码解锁。
|
||||
- 如果 `userDecryptionOptions.webAuthnPrfOption` 存在,且本地 assertion 得到了 `prfKey`:
|
||||
1. 用 PRF key unwrap `encryptedPrivateKey`。
|
||||
2. 用 private key decapsulate `encryptedUserKey`。
|
||||
3. 得到 user key,写入 `keyService`。
|
||||
|
||||
核心约束:服务端永远看不到 PRF 输出。服务端只保存和返回被 PRF 相关密钥加密后的 keyset。
|
||||
|
||||
### 官方 web 设置页注册 passkey
|
||||
|
||||
`apps/web/src/app/auth/core/services/webauthn-login/webauthn-login-admin-api.service.ts`
|
||||
|
||||
调用的 API:
|
||||
|
||||
- `POST /webauthn/attestation-options`
|
||||
- `POST /webauthn/assertion-options`
|
||||
- `POST /webauthn`
|
||||
- `GET /webauthn`
|
||||
- `POST /webauthn/{id}/delete`
|
||||
- `PUT /webauthn`
|
||||
|
||||
`apps/web/src/app/auth/core/services/webauthn-login/webauthn-login-admin.service.ts`
|
||||
|
||||
创建流程:
|
||||
|
||||
1. 用户做 secret verification。
|
||||
2. 请求 attestation options。
|
||||
3. `navigator.credentials.create({ publicKey: options })`,并带 `extensions.prf = {}`。
|
||||
4. 从 client extension results 判断 `supportsPrf`。
|
||||
5. 如果要用于 vault encryption,再立即做一次 `navigator.credentials.get()`:
|
||||
- `allowCredentials` 锁定刚创建的 credential。
|
||||
- 使用同一个 challenge、rpId、timeout、userVerification。
|
||||
- 带 PRF eval salt。
|
||||
6. 用 PRF key 和当前 user key 创建 rotateable keyset。
|
||||
7. 保存 credential,带上 `encryptedUserKey`、`encryptedPublicKey`、`encryptedPrivateKey`。
|
||||
|
||||
删除流程需要 secret verification。启用 encryption 的流程是对已有 credential 做 assertion,再创建并 PUT keyset。
|
||||
|
||||
`apps/web/src/app/auth/core/enums/webauthn-login-credential-prf-status.enum.ts`
|
||||
|
||||
- `Enabled = 0`
|
||||
- `Supported = 1`
|
||||
- `Unsupported = 2`
|
||||
|
||||
## NodeWarden 应实现的协议形状
|
||||
|
||||
### 公开登录流程
|
||||
|
||||
目标兼容官方客户端和 NodeWarden 自己 web:
|
||||
|
||||
1. `GET /identity/accounts/webauthn/assertion-options`
|
||||
- 生成 discoverable credential assertion options。
|
||||
- `allowCredentials: []`
|
||||
- `userVerification: "required"`
|
||||
- 返回 `{ options, token }`。
|
||||
- token 绑定 challenge、scope=`Authentication`、RP ID、origin/audience、过期时间。
|
||||
|
||||
2. Browser/web 调 `navigator.credentials.get()`。
|
||||
- NodeWarden 自己 web 也要使用 PRF extension。
|
||||
- PRF salt 必须和官方一致:`SHA-256("passwordless-login")`。
|
||||
|
||||
3. `POST /identity/connect/token`
|
||||
- 支持 `grant_type=webauthn`。
|
||||
- 接收 `token`、`deviceResponse`、device fields。
|
||||
- 解 token,校验 challenge/scope/过期。
|
||||
- 验证 assertion。
|
||||
- 从 `userHandle` 找到 user id。
|
||||
- 从 credential id 找到 passkey record。
|
||||
- 更新 counter。
|
||||
- 记录/更新 device。
|
||||
- 返回 access/refresh token、`AccountKeys`、`UserDecryptionOptions.WebAuthnPrfOption`。
|
||||
|
||||
如果用户启用了 TOTP,建议为了官方兼容先遵循 Bitwarden:passkey 的 user verification 视作已满足第二因素。否则官方 passkey 登录页会进入 unsupported 2FA 错误状态。
|
||||
|
||||
### 账户 passkey 管理流程
|
||||
|
||||
建议对齐官方 API,同时在 NodeWarden 内部可挂到 `/api/webauthn`:
|
||||
|
||||
- `GET /api/webauthn`
|
||||
- `POST /api/webauthn/attestation-options`
|
||||
- `POST /api/webauthn/assertion-options`
|
||||
- `POST /api/webauthn`
|
||||
- `PUT /api/webauthn`
|
||||
- `POST /api/webauthn/:id/delete`
|
||||
|
||||
为了官方客户端兼容,可能还需要接受无 `/api` 前缀的 aliases:
|
||||
|
||||
- `/webauthn`
|
||||
- `/webauthn/attestation-options`
|
||||
- `/webauthn/assertion-options`
|
||||
- `/webauthn/:id/delete`
|
||||
|
||||
NodeWarden 自己 web 可以直接用 `/api/webauthn`,官方 web/browser 客户端会按它自己的 API base 组装 `/webauthn`。
|
||||
|
||||
### 建议新增表
|
||||
|
||||
按 NodeWarden 命名风格,建议用小写 snake_case:
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS webauthn_credentials (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
public_key TEXT NOT NULL,
|
||||
credential_id TEXT NOT NULL,
|
||||
counter INTEGER NOT NULL DEFAULT 0,
|
||||
type TEXT,
|
||||
aa_guid TEXT,
|
||||
transports TEXT,
|
||||
encrypted_user_key TEXT,
|
||||
encrypted_public_key TEXT,
|
||||
encrypted_private_key TEXT,
|
||||
supports_prf INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_webauthn_credentials_user_credential
|
||||
ON webauthn_credentials(user_id, credential_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_webauthn_credentials_user
|
||||
ON webauthn_credentials(user_id);
|
||||
```
|
||||
|
||||
如果要更严格防止同一个 credential id 被跨用户重复注册,也可以加全局 unique index `credential_id`。官方代码至少检查同用户唯一;实际安全上更建议全局唯一,因为 credential id 本身应该唯一标识 authenticator credential。
|
||||
|
||||
PRF status 不必落库为枚举,可以由字段计算:
|
||||
|
||||
- `supports_prf = 0` => `Unsupported`
|
||||
- `supports_prf = 1` 且三段 encrypted key 不全 => `Supported`
|
||||
- `supports_prf = 1` 且三段 encrypted key 全存在 => `Enabled`
|
||||
|
||||
### Challenge/token 存储
|
||||
|
||||
官方 server 用 protected token 携带 options,再用 challenge cache 防重放。NodeWarden 在 Workers/D1 里建议组合:
|
||||
|
||||
- token:HMAC/JWT 样式,绑定 `scope`、`challenge`、`userId?`、`rpId`、`createdAt`、`expiresAt`。
|
||||
- D1 表或 KV:记录 challenge 是否使用过,至少字段 `challenge_hash`、`scope`、`user_id`、`expires_at`、`used_at`。
|
||||
- 登录 assertion options 是公开接口,不绑定 user id;create/update/delete 管理流程应绑定 user id。
|
||||
- 验证成功后立即 mark used。
|
||||
|
||||
建议 scopes:
|
||||
|
||||
- `Authentication`
|
||||
- `CreateCredential`
|
||||
- `UpdateKeySet`
|
||||
|
||||
官方还有 `PrfRegistration` 语义,NodeWarden 可以用 `CreateCredential` 覆盖,只要 token 逻辑严谨即可。
|
||||
|
||||
### 服务端 WebAuthn 验证库
|
||||
|
||||
NodeWarden 当前没有 FIDO2/WebAuthn 服务端验证依赖。不要手写签名和 attestation 解析。
|
||||
|
||||
候选:`@simplewebauthn/server`。官方文档当前说明它提供 `generateRegistrationOptions`、`verifyRegistrationResponse`、`generateAuthenticationOptions`、`verifyAuthenticationResponse`,并记录了 RP ID、origin、credential public key、counter、transports 等数据结构。文档地址:https://simplewebauthn.dev/docs/packages/server
|
||||
|
||||
注意:NodeWarden 跑在 Cloudflare Workers,不是普通 Node server。正式选库前需要做一次构建/runtime 验证,确认包不会依赖 Workers 不支持的 Node API。这个验证属于实现阶段,不在本研究文档里写测试程序。
|
||||
|
||||
## NodeWarden web 需要改的地方
|
||||
|
||||
### 登录页
|
||||
|
||||
当前登录 UI 在 `webapp/src/components/AuthViews.tsx`,状态和行为主要由 `webapp/src/App.tsx`、`webapp/src/lib/app-auth.ts` 管。
|
||||
|
||||
新增:
|
||||
|
||||
- 登录页增加“使用 passkey 登录”按钮。
|
||||
- 新增 `performPasskeyLogin()`:
|
||||
1. GET `/identity/accounts/webauthn/assertion-options`
|
||||
2. 转换 server options 里的 base64url challenge/user id/credential id 为 ArrayBuffer。
|
||||
3. `navigator.credentials.get()`,带 PRF salt。
|
||||
4. POST `/identity/connect/token`,`grant_type=webauthn`。
|
||||
5. 从 response 的 `UserDecryptionOptions.WebAuthnPrfOption` 取 encrypted keyset。
|
||||
6. 用本地 PRF key 解出 user key。
|
||||
7. 构造 `SessionState` 并进入 app。
|
||||
|
||||
不能复用 `completeLogin(token, email, masterKey, fallbackKdfIterations)`,因为它要求 masterKey。应新增 passkey 专用 complete 函数。
|
||||
|
||||
### 设置页
|
||||
|
||||
当前账户/安全相关 UI 在 `webapp/src/components/SettingsPage.tsx` 一带。
|
||||
|
||||
新增:
|
||||
|
||||
- Passkey 列表。
|
||||
- 新建 passkey dialog。
|
||||
- 删除 passkey。
|
||||
- 对支持 PRF 但未启用 encryption 的 passkey,提供“启用用于登录解锁”的操作。
|
||||
|
||||
自己 web 的新建流程要和官方一致:
|
||||
|
||||
1. 已登录状态下先验证主密码或现有 session secret。
|
||||
2. 请求 attestation options。
|
||||
3. `navigator.credentials.create()` 带 `extensions.prf = {}`。
|
||||
4. 如果用户希望这个 passkey 可直接解锁 vault,再对刚创建 credential 做一次 `navigator.credentials.get()` 获取 PRF 输出。
|
||||
5. 用 PRF key 加密/封装当前 user key,发送到 server 保存。
|
||||
|
||||
### 客户端加密能力
|
||||
|
||||
NodeWarden web 当前已经有:
|
||||
|
||||
- PBKDF2
|
||||
- HKDF expand
|
||||
- Bitwarden EncString 加解密
|
||||
- RSA-OAEP private key 加密
|
||||
|
||||
但 passkey PRF keyset 需要和官方策略对齐:
|
||||
|
||||
- PRF key 是 64 字节 symmetric key,前 32 enc、后 32 mac。
|
||||
- `encryptedPrivateKey` 用 PRF key wrap 一个 decapsulation private key。
|
||||
- `encryptedUserKey` 用对应 public key encapsulate user key。
|
||||
- `encryptedPublicKey` 用于 key rotation。
|
||||
|
||||
这里需要认真复用或补齐 NodeWarden 现有 crypto helper,避免做出和官方客户端无法互解的 keyset。
|
||||
|
||||
## 扩展兼容要求
|
||||
|
||||
### 官方 browser extension
|
||||
|
||||
官方 extension passkey 登录入口在:
|
||||
|
||||
- `apps/browser/src/auth/popup/login/extension-login-component.service.ts`
|
||||
- 只在 Chromium 开启。
|
||||
|
||||
如果要官方/派生扩展能对 NodeWarden passkey 登录:
|
||||
|
||||
- identity URL 必须能访问 `/accounts/webauthn/assertion-options`。
|
||||
- token URL 必须支持 `grant_type=webauthn`。
|
||||
- API URL 必须能访问 `/webauthn` 管理接口。
|
||||
- response 大小写和字段名要同时照顾 PascalCase/camelCase,NodeWarden 当前 token response 已经在一些字段上双写,这个风格应继续沿用。
|
||||
- passkey 登录成功时必须返回可解开 vault 的 `webAuthnPrfOption`,否则官方组件虽然认证成功,也不会进入可用 vault。
|
||||
|
||||
### RP ID 和 origin
|
||||
|
||||
自己的 web:
|
||||
|
||||
- RP ID 通常是站点 host,例如 `vault.example.com`。
|
||||
- origin 是 `https://vault.example.com`。
|
||||
|
||||
官方 browser extension:
|
||||
|
||||
- 扩展页面 origin 是 `chrome-extension://...`。
|
||||
- 官方之所以只开 Chromium,是因为 Chromium extension 具备它需要的 RP ID 覆盖能力。
|
||||
- NodeWarden server 验证 assertion 时必须允许正确的 origin/RP ID 组合。这里不能简单只接受当前 request origin,否则扩展登录会失败。
|
||||
|
||||
建议配置化:
|
||||
|
||||
- `WEBAUTHN_RP_ID`
|
||||
- `WEBAUTHN_RP_NAME`
|
||||
- `WEBAUTHN_ALLOWED_ORIGINS`
|
||||
|
||||
默认可以从 request URL 推导 web origin,但生产建议显式配置。
|
||||
|
||||
## 安全约束
|
||||
|
||||
- 所有账户 passkey 必须 `userVerification: required`。
|
||||
- 登录 assertion 使用 discoverable credential,`userHandle` 必须能解析成 user id 并和 credential 记录一致。
|
||||
- challenge 必须有过期时间和一次性使用标记。
|
||||
- PRF 输出绝不能传给 server,也不能写入日志。
|
||||
- token 里要绑定 scope,防止 attestation token 被拿去 authentication 用。
|
||||
- counter 要更新。遇到 counter 异常时至少记录 audit event,是否阻断要结合 multi-device passkey 现实处理。
|
||||
- 每用户 credential 数量限制建议沿用官方 5 个。
|
||||
- 删除/新增/启用 encryption 必须要求已登录用户二次验证。
|
||||
- 密码变更、user key rotation 后,所有 enabled PRF credentials 的 keyset 也要 rotation,否则 passkey 登录会解不开新 vault key。
|
||||
- 备份导出/导入必须包含账户 passkey 表,否则恢复后 passkey 登录会全部失效。
|
||||
- 审计日志建议新增:
|
||||
- `auth.passkey.login.success`
|
||||
- `auth.passkey.login.failed`
|
||||
- `account.passkey.create`
|
||||
- `account.passkey.delete`
|
||||
- `account.passkey.encryption.enable`
|
||||
- `account.passkey.rotate`
|
||||
|
||||
## 建议实施顺序
|
||||
|
||||
### 第一阶段:后端基础
|
||||
|
||||
1. 新增 `webauthn_credentials` 和 challenge 表。
|
||||
2. 新增 storage repo。
|
||||
3. 接入 WebAuthn 服务端验证库。
|
||||
4. 实现 assertion options 和 `grant_type=webauthn`。
|
||||
5. token response 加 `WebAuthnPrfOption` shape。
|
||||
|
||||
这阶段先能让“已有手工塞入的 enabled credential”完成登录验证,但还不做 UI。
|
||||
|
||||
### 第二阶段:账户 passkey 管理 API
|
||||
|
||||
1. 实现 `/api/webauthn` 和 `/webauthn` aliases。
|
||||
2. 实现 attestation options、save credential、list、delete、enable/update encryption。
|
||||
3. 加 audit event。
|
||||
4. 接入 backup export/import。
|
||||
5. sync response 加 `WebAuthnPrfOptions`。
|
||||
|
||||
### 第三阶段:NodeWarden 自己 web
|
||||
|
||||
1. 登录页 passkey 按钮和 `performPasskeyLogin()`。
|
||||
2. Passkey 设置页。
|
||||
3. PRF keyset 创建、保存、删除、启用 encryption。
|
||||
4. 浏览器能力判断和错误提示。
|
||||
|
||||
### 第四阶段:扩展兼容
|
||||
|
||||
1. 用官方 browser extension 的 Chromium passkey 登录流程校对 endpoint。
|
||||
2. 校对 `/config` 里 identity/api/web vault URL。
|
||||
3. 校对 RP ID、allowed origins。
|
||||
4. 必要时加兼容字段或 alias route。
|
||||
|
||||
按用户要求,本阶段只需要代码跑通不报错;不在这里写可视化测试或测试程序。
|
||||
|
||||
## 待实现清单
|
||||
|
||||
- [ ] 设计并落库 `webauthn_credentials`。
|
||||
- [ ] 设计并落库 WebAuthn challenge/replay cache。
|
||||
- [ ] 选定并验证 Workers 可用的 WebAuthn server library。
|
||||
- [ ] `GET /identity/accounts/webauthn/assertion-options`。
|
||||
- [ ] `POST /identity/connect/token` 支持 `grant_type=webauthn`。
|
||||
- [ ] `UserDecryptionOptions.WebAuthnPrfOption`。
|
||||
- [ ] `UserDecryption.WebAuthnPrfOptions`。
|
||||
- [ ] `/api/webauthn` 管理接口。
|
||||
- [ ] `/webauthn` 官方客户端 alias。
|
||||
- [ ] NodeWarden web passkey 登录入口。
|
||||
- [ ] NodeWarden web passkey 管理页。
|
||||
- [ ] key rotation 时同步 rotate PRF keysets。
|
||||
- [ ] backup export/import 覆盖新表。
|
||||
- [ ] audit logs 覆盖 passkey 管理和登录。
|
||||
|
||||
## 关键文件索引
|
||||
|
||||
NodeWarden:
|
||||
|
||||
- `src/router-public.ts`
|
||||
- `src/router-authenticated.ts`
|
||||
- `src/handlers/accounts.ts`
|
||||
- `src/handlers/identity.ts`
|
||||
- `src/handlers/sync.ts`
|
||||
- `src/services/auth.ts`
|
||||
- `src/services/storage-schema.ts`
|
||||
- `src/services/storage-user-repo.ts`
|
||||
- `src/services/storage-device-repo.ts`
|
||||
- `src/utils/passkey.ts`
|
||||
- `src/utils/user-decryption.ts`
|
||||
- `src/types/index.ts`
|
||||
- `webapp/src/lib/api/auth.ts`
|
||||
- `webapp/src/lib/app-auth.ts`
|
||||
- `webapp/src/components/AuthViews.tsx`
|
||||
- `webapp/src/components/SettingsPage.tsx`
|
||||
|
||||
Bitwarden server:
|
||||
|
||||
- `.codex-upstream/bitwarden-server/src/Identity/Controllers/AccountsController.cs`
|
||||
- `.codex-upstream/bitwarden-server/src/Identity/IdentityServer/RequestValidators/WebAuthnGrantValidator.cs`
|
||||
- `.codex-upstream/bitwarden-server/src/Identity/IdentityServer/ApiClient.cs`
|
||||
- `.codex-upstream/bitwarden-server/src/Api/Auth/Controllers/WebAuthnController.cs`
|
||||
- `.codex-upstream/bitwarden-server/src/Core/Auth/Entities/WebAuthnCredential.cs`
|
||||
- `.codex-upstream/bitwarden-server/src/Core/Auth/UserFeatures/WebAuthnLogin/Implementations/GetWebAuthnLoginCredentialCreateOptionsCommand.cs`
|
||||
- `.codex-upstream/bitwarden-server/src/Core/Auth/UserFeatures/WebAuthnLogin/Implementations/GetWebAuthnLoginCredentialAssertionOptionsCommand.cs`
|
||||
- `.codex-upstream/bitwarden-server/src/Core/Auth/UserFeatures/WebAuthnLogin/Implementations/CreateWebAuthnLoginCredentialCommand.cs`
|
||||
- `.codex-upstream/bitwarden-server/src/Core/Auth/UserFeatures/WebAuthnLogin/Implementations/AssertWebAuthnLoginCredentialCommand.cs`
|
||||
- `.codex-upstream/bitwarden-server/src/Core/Auth/Models/Api/Response/UserDecryptionOptions.cs`
|
||||
- `.codex-upstream/bitwarden-server/util/SqliteMigrations/Migrations/20231213032045_WebAuthnLoginCredentials.cs`
|
||||
|
||||
Bitwarden clients/browser:
|
||||
|
||||
- `.codex-upstream/bitwarden-clients/libs/auth/src/angular/login/default-login-component.service.ts`
|
||||
- `.codex-upstream/bitwarden-clients/apps/browser/src/auth/popup/login/extension-login-component.service.ts`
|
||||
- `.codex-upstream/bitwarden-clients/libs/angular/src/auth/login-via-webauthn/login-via-webauthn.component.ts`
|
||||
- `.codex-upstream/bitwarden-clients/libs/common/src/auth/services/webauthn-login/webauthn-login-api.service.ts`
|
||||
- `.codex-upstream/bitwarden-clients/libs/common/src/auth/services/webauthn-login/webauthn-login.service.ts`
|
||||
- `.codex-upstream/bitwarden-clients/libs/common/src/auth/services/webauthn-login/webauthn-login-prf-key.service.ts`
|
||||
- `.codex-upstream/bitwarden-clients/libs/common/src/auth/models/request/identity-token/webauthn-login-token.request.ts`
|
||||
- `.codex-upstream/bitwarden-clients/libs/common/src/auth/services/webauthn-login/request/webauthn-login-response.request.ts`
|
||||
- `.codex-upstream/bitwarden-clients/libs/common/src/auth/services/webauthn-login/request/webauthn-login-assertion-response.request.ts`
|
||||
- `.codex-upstream/bitwarden-clients/libs/auth/src/common/login-strategies/webauthn-login.strategy.ts`
|
||||
- `.codex-upstream/bitwarden-clients/apps/web/src/app/auth/core/services/webauthn-login/webauthn-login-admin-api.service.ts`
|
||||
- `.codex-upstream/bitwarden-clients/apps/web/src/app/auth/core/services/webauthn-login/webauthn-login-admin.service.ts`
|
||||
- `.codex-upstream/bitwarden-clients/apps/web/src/app/auth/core/services/webauthn-login/request/save-credential.request.ts`
|
||||
- `.codex-upstream/bitwarden-clients/apps/web/src/app/auth/core/services/webauthn-login/request/enable-credential-encryption.request.ts`
|
||||
- `.codex-upstream/bitwarden-clients/apps/web/src/app/auth/core/services/webauthn-login/request/webauthn-login-attestation-response.request.ts`
|
||||
- `.codex-upstream/bitwarden-clients/apps/web/src/app/auth/core/enums/webauthn-login-credential-prf-status.enum.ts`
|
||||
- `.codex-upstream/bitwarden-clients/libs/common/src/auth/models/response/user-decryption-options/webauthn-prf-decryption-option.response.ts`
|
||||
- `.codex-upstream/bitwarden-clients/libs/auth/src/common/models/domain/user-decryption-options.ts`
|
||||
|
||||
@@ -176,6 +176,8 @@ CREATE TABLE IF NOT EXISTS devices (
|
||||
encrypted_user_key TEXT,
|
||||
encrypted_public_key TEXT,
|
||||
encrypted_private_key TEXT,
|
||||
push_uuid TEXT,
|
||||
push_token TEXT,
|
||||
banned INTEGER NOT NULL DEFAULT 0,
|
||||
banned_at TEXT,
|
||||
device_note TEXT,
|
||||
@@ -187,6 +189,34 @@ CREATE TABLE IF NOT EXISTS devices (
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_devices_user_updated ON devices(user_id, updated_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_devices_user_last_seen ON devices(user_id, last_seen_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_devices_user_push ON devices(user_id, push_token);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS auth_requests (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
organization_id TEXT,
|
||||
type INTEGER NOT NULL,
|
||||
request_device_identifier TEXT NOT NULL,
|
||||
request_device_type INTEGER NOT NULL,
|
||||
request_ip_address TEXT,
|
||||
request_country_name TEXT,
|
||||
response_device_identifier TEXT,
|
||||
access_code TEXT NOT NULL,
|
||||
public_key TEXT NOT NULL,
|
||||
key TEXT,
|
||||
master_password_hash TEXT,
|
||||
approved INTEGER,
|
||||
creation_date TEXT NOT NULL,
|
||||
response_date TEXT,
|
||||
authentication_date TEXT,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_auth_requests_user_created
|
||||
ON auth_requests(user_id, creation_date);
|
||||
CREATE INDEX IF NOT EXISTS idx_auth_requests_user_pending
|
||||
ON auth_requests(user_id, approved, response_date, authentication_date, creation_date);
|
||||
CREATE INDEX IF NOT EXISTS idx_auth_requests_device_pending
|
||||
ON auth_requests(user_id, request_device_identifier, creation_date);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS trusted_two_factor_device_tokens (
|
||||
token TEXT PRIMARY KEY,
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "nodewarden",
|
||||
"version": "1.5.2",
|
||||
"version": "1.7.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "nodewarden",
|
||||
"version": "1.5.2",
|
||||
"version": "1.7.0",
|
||||
"license": "LGPL-3.0",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.0.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "nodewarden",
|
||||
"version": "1.6.0",
|
||||
"version": "1.7.0",
|
||||
"description": "Minimal Bitwarden-compatible server running on Cloudflare Workers",
|
||||
"author": "shuaiplus",
|
||||
"license": "LGPL-3.0",
|
||||
|
||||
@@ -1 +1 @@
|
||||
export const APP_VERSION = '1.6.0';
|
||||
export const APP_VERSION = '1.7.0';
|
||||
|
||||
@@ -14,10 +14,12 @@ export const BACKUP_DEFAULT_INTERVAL_HOURS = 24;
|
||||
export const BACKUP_DEFAULT_START_TIME = '03:00';
|
||||
|
||||
export type BackupDestinationType = 's3' | 'webdav';
|
||||
export type S3BackupAddressingStyle = 'path-style' | 'virtual-hosted-style';
|
||||
|
||||
export interface S3BackupDestination {
|
||||
endpoint: string;
|
||||
bucket: string;
|
||||
addressingStyle: S3BackupAddressingStyle;
|
||||
region: string;
|
||||
accessKeyId: string;
|
||||
secretAccessKey: string;
|
||||
@@ -103,6 +105,7 @@ export function createDefaultBackupDestinationConfig(type: BackupDestinationType
|
||||
return {
|
||||
endpoint: '',
|
||||
bucket: '',
|
||||
addressingStyle: 'path-style',
|
||||
region: BACKUP_DEFAULT_S3_REGION,
|
||||
accessKeyId: '',
|
||||
secretAccessKey: '',
|
||||
|
||||
@@ -1,17 +1,32 @@
|
||||
import { DurableObject, waitUntil } from 'cloudflare:workers';
|
||||
import type { Env } from '../types';
|
||||
import { notifyMobilePush } from '../services/push-relay';
|
||||
|
||||
const SIGNALR_RECORD_SEPARATOR = 0x1e;
|
||||
const SIGNALR_HANDSHAKE_ACK = new Uint8Array([0x7b, 0x7d, SIGNALR_RECORD_SEPARATOR]);
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_CIPHER_UPDATE = 0;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_CIPHER_CREATE = 1;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_FOLDER_DELETE = 3;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_CIPHERS = 4;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_VAULT = 5;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_FOLDER_CREATE = 7;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_FOLDER_UPDATE = 8;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_CIPHER_DELETE = 9;
|
||||
const SIGNALR_UPDATE_TYPE_LOG_OUT = 11;
|
||||
const SIGNALR_UPDATE_TYPE_DEVICE_STATUS = 12;
|
||||
const SIGNALR_UPDATE_TYPE_BACKUP_RESTORE_PROGRESS = 13;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_SEND_CREATE = 12;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_SEND_UPDATE = 13;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_SEND_DELETE = 14;
|
||||
const SIGNALR_UPDATE_TYPE_AUTH_REQUEST = 15;
|
||||
const SIGNALR_UPDATE_TYPE_AUTH_REQUEST_RESPONSE = 16;
|
||||
const SIGNALR_UPDATE_TYPE_BACKUP_RESTORE_PROGRESS = 102;
|
||||
|
||||
type HubProtocol = 'json' | 'messagepack';
|
||||
type HubKind = 'user' | 'anonymous-auth-request';
|
||||
|
||||
interface WsAttachment {
|
||||
userId: string;
|
||||
kind: HubKind;
|
||||
userId: string | null;
|
||||
authRequestId: string | null;
|
||||
handshakeComplete: boolean;
|
||||
protocol: HubProtocol;
|
||||
deviceIdentifier: string | null;
|
||||
@@ -137,11 +152,12 @@ function frameSignalRBinary(payload: Uint8Array): Uint8Array {
|
||||
function buildSignalRJsonInvocation(
|
||||
updateType: number,
|
||||
payload: Record<string, unknown>,
|
||||
contextId: string | null
|
||||
contextId: string | null,
|
||||
target: string = 'ReceiveMessage'
|
||||
): string {
|
||||
return JSON.stringify({
|
||||
type: 1,
|
||||
target: 'ReceiveMessage',
|
||||
target,
|
||||
arguments: [
|
||||
{
|
||||
ContextId: contextId,
|
||||
@@ -155,15 +171,16 @@ function buildSignalRJsonInvocation(
|
||||
function buildSignalRMessagePackInvocation(
|
||||
updateType: number,
|
||||
messagePayload: Record<string, unknown>,
|
||||
contextId: string | null
|
||||
contextId: string | null,
|
||||
target: string = 'ReceiveMessage'
|
||||
): Uint8Array {
|
||||
// SignalR MessagePack hub protocol uses an array-based invocation shape:
|
||||
// [type, headers, invocationId, target, arguments]
|
||||
// [type, headers, invocationId, target, arguments, streamIds]
|
||||
const encodedPayload = encodeMsgPack([
|
||||
1,
|
||||
{},
|
||||
null,
|
||||
'ReceiveMessage',
|
||||
target,
|
||||
[
|
||||
{
|
||||
ContextId: contextId,
|
||||
@@ -171,6 +188,7 @@ function buildSignalRMessagePackInvocation(
|
||||
Payload: messagePayload,
|
||||
},
|
||||
],
|
||||
[],
|
||||
]);
|
||||
return frameSignalRBinary(encodedPayload);
|
||||
}
|
||||
@@ -201,7 +219,9 @@ export class NotificationsHub extends DurableObject<Env> {
|
||||
const revisionDate = String(body?.revisionDate || '').trim() || new Date().toISOString();
|
||||
const userId = String(request.headers.get('X-NodeWarden-UserId') || body?.userId || '').trim();
|
||||
const contextId = String(body?.contextId || '').trim() || null;
|
||||
const updateType = Number(body?.updateType || SIGNALR_UPDATE_TYPE_SYNC_VAULT) || SIGNALR_UPDATE_TYPE_SYNC_VAULT;
|
||||
const rawUpdateType = body?.updateType;
|
||||
const parsedUpdateType = typeof rawUpdateType === 'number' ? rawUpdateType : Number(rawUpdateType);
|
||||
const updateType = Number.isFinite(parsedUpdateType) ? parsedUpdateType : SIGNALR_UPDATE_TYPE_SYNC_VAULT;
|
||||
const targetDeviceIdentifier = String(body?.targetDeviceIdentifier || '').trim() || null;
|
||||
const payload = body?.payload && typeof body.payload === 'object'
|
||||
? body.payload
|
||||
@@ -213,6 +233,20 @@ export class NotificationsHub extends DurableObject<Env> {
|
||||
return new Response(null, { status: 204 });
|
||||
}
|
||||
|
||||
if (url.pathname === '/internal/auth-request-response' && request.method === 'POST') {
|
||||
const body = (await request.json().catch(() => null)) as {
|
||||
userId?: string;
|
||||
authRequestId?: string;
|
||||
contextId?: string | null;
|
||||
} | null;
|
||||
const userId = String(body?.userId || '').trim();
|
||||
const authRequestId = String(body?.authRequestId || '').trim();
|
||||
if (!userId || !authRequestId) return new Response('Invalid auth request notification', { status: 400 });
|
||||
|
||||
this.broadcastAuthRequestResponse(userId, authRequestId, String(body?.contextId || '').trim() || null);
|
||||
return new Response(null, { status: 204 });
|
||||
}
|
||||
|
||||
if (url.pathname === '/internal/online' && request.method === 'GET') {
|
||||
return new Response(JSON.stringify({ deviceIdentifiers: this.getOnlineDeviceIdentifiers() }), {
|
||||
status: 200,
|
||||
@@ -222,7 +256,7 @@ export class NotificationsHub extends DurableObject<Env> {
|
||||
});
|
||||
}
|
||||
|
||||
if (url.pathname !== '/notifications/hub') {
|
||||
if (url.pathname !== '/notifications/hub' && url.pathname !== '/notifications/anonymous-hub') {
|
||||
return new Response('Not found', { status: 404 });
|
||||
}
|
||||
|
||||
@@ -232,8 +266,13 @@ export class NotificationsHub extends DurableObject<Env> {
|
||||
|
||||
const requestUserId = String(url.searchParams.get('nw_uid') || '').trim();
|
||||
const requestDeviceIdentifier = String(url.searchParams.get('nw_did') || '').trim() || null;
|
||||
const requestAuthRequestId = String(url.searchParams.get('nw_auth_request_id') || '').trim() || null;
|
||||
const isAnonymousAuthRequestHub = url.pathname === '/notifications/anonymous-hub';
|
||||
|
||||
if (!requestUserId) {
|
||||
if (!isAnonymousAuthRequestHub && !requestUserId) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
if (isAnonymousAuthRequestHub && !requestAuthRequestId) {
|
||||
return new Response('Unauthorized', { status: 401 });
|
||||
}
|
||||
|
||||
@@ -248,7 +287,9 @@ export class NotificationsHub extends DurableObject<Env> {
|
||||
this.ctx.acceptWebSocket(server, tags);
|
||||
|
||||
server.serializeAttachment({
|
||||
userId: requestUserId,
|
||||
kind: isAnonymousAuthRequestHub ? 'anonymous-auth-request' : 'user',
|
||||
userId: isAnonymousAuthRequestHub ? null : requestUserId,
|
||||
authRequestId: requestAuthRequestId,
|
||||
handshakeComplete: false,
|
||||
protocol: 'messagepack',
|
||||
deviceIdentifier: requestDeviceIdentifier,
|
||||
@@ -274,7 +315,6 @@ export class NotificationsHub extends DurableObject<Env> {
|
||||
attachment.handshakeComplete = true;
|
||||
ws.serializeAttachment(attachment);
|
||||
ws.send(SIGNALR_HANDSHAKE_ACK);
|
||||
this.broadcastDeviceStatus(attachment.userId);
|
||||
return;
|
||||
} catch {
|
||||
// Ignore malformed pre-handshake payloads.
|
||||
@@ -293,26 +333,22 @@ export class NotificationsHub extends DurableObject<Env> {
|
||||
}
|
||||
|
||||
async webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean): Promise<void> {
|
||||
const attachment = ws.deserializeAttachment() as WsAttachment | null;
|
||||
const shouldBroadcast = !!attachment?.handshakeComplete;
|
||||
if (shouldBroadcast && attachment?.userId) {
|
||||
this.broadcastDeviceStatus(attachment.userId);
|
||||
}
|
||||
void ws;
|
||||
void code;
|
||||
void reason;
|
||||
void wasClean;
|
||||
}
|
||||
|
||||
async webSocketError(ws: WebSocket, error: unknown): Promise<void> {
|
||||
const attachment = ws.deserializeAttachment() as WsAttachment | null;
|
||||
const shouldBroadcast = !!attachment?.handshakeComplete;
|
||||
if (shouldBroadcast && attachment?.userId) {
|
||||
this.broadcastDeviceStatus(attachment.userId);
|
||||
}
|
||||
void ws;
|
||||
void error;
|
||||
}
|
||||
|
||||
private getOnlineDeviceIdentifiers(): string[] {
|
||||
const out = new Set<string>();
|
||||
for (const ws of this.ctx.getWebSockets()) {
|
||||
const attachment = ws.deserializeAttachment() as WsAttachment | null;
|
||||
if (!attachment?.handshakeComplete || !attachment.deviceIdentifier) continue;
|
||||
if (!attachment?.handshakeComplete || attachment.kind !== 'user' || !attachment.deviceIdentifier) continue;
|
||||
out.add(attachment.deviceIdentifier);
|
||||
}
|
||||
return Array.from(out);
|
||||
@@ -349,16 +385,45 @@ export class NotificationsHub extends DurableObject<Env> {
|
||||
}
|
||||
}
|
||||
|
||||
private broadcastDeviceStatus(userId: string): void {
|
||||
this.broadcastMessage(
|
||||
SIGNALR_UPDATE_TYPE_DEVICE_STATUS,
|
||||
{
|
||||
private broadcastAuthRequestResponse(userId: string, authRequestId: string, contextId: string | null): void {
|
||||
for (const ws of this.ctx.getWebSockets()) {
|
||||
const attachment = ws.deserializeAttachment() as WsAttachment | null;
|
||||
if (
|
||||
!attachment?.handshakeComplete ||
|
||||
attachment.kind !== 'anonymous-auth-request' ||
|
||||
attachment.authRequestId !== authRequestId
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
UserId: userId,
|
||||
Date: new Date().toISOString(),
|
||||
},
|
||||
null,
|
||||
null
|
||||
);
|
||||
Id: authRequestId,
|
||||
};
|
||||
try {
|
||||
if (attachment.protocol === 'json') {
|
||||
ws.send(buildSignalRJsonInvocation(
|
||||
SIGNALR_UPDATE_TYPE_AUTH_REQUEST_RESPONSE,
|
||||
payload,
|
||||
contextId,
|
||||
'AuthRequestResponseRecieved'
|
||||
));
|
||||
} else {
|
||||
ws.send(buildSignalRMessagePackInvocation(
|
||||
SIGNALR_UPDATE_TYPE_AUTH_REQUEST_RESPONSE,
|
||||
payload,
|
||||
contextId,
|
||||
'AuthRequestResponseRecieved'
|
||||
));
|
||||
}
|
||||
} catch {
|
||||
try {
|
||||
ws.close(1011, 'Notification send failed');
|
||||
} catch {
|
||||
// ignore close races
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -371,6 +436,243 @@ export function notifyUserVaultSync(
|
||||
waitUntil(notifyUserUpdate(env, userId, SIGNALR_UPDATE_TYPE_SYNC_VAULT, revisionDate, contextId ?? null, null));
|
||||
}
|
||||
|
||||
export function notifyUserCiphersSync(
|
||||
env: Env,
|
||||
userId: string,
|
||||
revisionDate: string,
|
||||
contextId?: string | null
|
||||
): void {
|
||||
waitUntil(notifyUserUpdate(env, userId, SIGNALR_UPDATE_TYPE_SYNC_CIPHERS, revisionDate, contextId ?? null, null));
|
||||
}
|
||||
|
||||
export function notifyUserCipherCreate(
|
||||
env: Env,
|
||||
payload: {
|
||||
userId: string;
|
||||
cipherId: string;
|
||||
revisionDate: string;
|
||||
organizationId?: string | null;
|
||||
collectionIds?: string[] | null;
|
||||
contextId?: string | null;
|
||||
}
|
||||
): void {
|
||||
waitUntil(notifyUserUpdate(
|
||||
env,
|
||||
payload.userId,
|
||||
SIGNALR_UPDATE_TYPE_SYNC_CIPHER_CREATE,
|
||||
payload.revisionDate,
|
||||
payload.contextId ?? null,
|
||||
null,
|
||||
{
|
||||
UserId: payload.userId,
|
||||
Id: payload.cipherId,
|
||||
OrganizationId: payload.organizationId ?? null,
|
||||
CollectionIds: Array.isArray(payload.collectionIds) ? payload.collectionIds : null,
|
||||
RevisionDate: payload.revisionDate,
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
export function notifyUserCipherUpdate(
|
||||
env: Env,
|
||||
payload: {
|
||||
userId: string;
|
||||
cipherId: string;
|
||||
revisionDate: string;
|
||||
organizationId?: string | null;
|
||||
collectionIds?: string[] | null;
|
||||
contextId?: string | null;
|
||||
}
|
||||
): void {
|
||||
waitUntil(notifyUserUpdate(
|
||||
env,
|
||||
payload.userId,
|
||||
SIGNALR_UPDATE_TYPE_SYNC_CIPHER_UPDATE,
|
||||
payload.revisionDate,
|
||||
payload.contextId ?? null,
|
||||
null,
|
||||
{
|
||||
UserId: payload.userId,
|
||||
Id: payload.cipherId,
|
||||
OrganizationId: payload.organizationId ?? null,
|
||||
CollectionIds: Array.isArray(payload.collectionIds) ? payload.collectionIds : null,
|
||||
RevisionDate: payload.revisionDate,
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
export function notifyUserCipherDelete(
|
||||
env: Env,
|
||||
payload: {
|
||||
userId: string;
|
||||
cipherId: string;
|
||||
revisionDate: string;
|
||||
organizationId?: string | null;
|
||||
collectionIds?: string[] | null;
|
||||
contextId?: string | null;
|
||||
}
|
||||
): void {
|
||||
waitUntil(notifyUserUpdate(
|
||||
env,
|
||||
payload.userId,
|
||||
SIGNALR_UPDATE_TYPE_SYNC_CIPHER_DELETE,
|
||||
payload.revisionDate,
|
||||
payload.contextId ?? null,
|
||||
null,
|
||||
{
|
||||
UserId: payload.userId,
|
||||
Id: payload.cipherId,
|
||||
OrganizationId: payload.organizationId ?? null,
|
||||
CollectionIds: Array.isArray(payload.collectionIds) ? payload.collectionIds : null,
|
||||
RevisionDate: payload.revisionDate,
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
export function notifyUserFolderCreate(
|
||||
env: Env,
|
||||
payload: {
|
||||
userId: string;
|
||||
folderId: string;
|
||||
revisionDate: string;
|
||||
contextId?: string | null;
|
||||
}
|
||||
): void {
|
||||
waitUntil(notifyUserUpdate(
|
||||
env,
|
||||
payload.userId,
|
||||
SIGNALR_UPDATE_TYPE_SYNC_FOLDER_CREATE,
|
||||
payload.revisionDate,
|
||||
payload.contextId ?? null,
|
||||
null,
|
||||
{
|
||||
UserId: payload.userId,
|
||||
Id: payload.folderId,
|
||||
RevisionDate: payload.revisionDate,
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
export function notifyUserFolderUpdate(
|
||||
env: Env,
|
||||
payload: {
|
||||
userId: string;
|
||||
folderId: string;
|
||||
revisionDate: string;
|
||||
contextId?: string | null;
|
||||
}
|
||||
): void {
|
||||
waitUntil(notifyUserUpdate(
|
||||
env,
|
||||
payload.userId,
|
||||
SIGNALR_UPDATE_TYPE_SYNC_FOLDER_UPDATE,
|
||||
payload.revisionDate,
|
||||
payload.contextId ?? null,
|
||||
null,
|
||||
{
|
||||
UserId: payload.userId,
|
||||
Id: payload.folderId,
|
||||
RevisionDate: payload.revisionDate,
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
export function notifyUserFolderDelete(
|
||||
env: Env,
|
||||
payload: {
|
||||
userId: string;
|
||||
folderId: string;
|
||||
revisionDate: string;
|
||||
contextId?: string | null;
|
||||
}
|
||||
): void {
|
||||
waitUntil(notifyUserUpdate(
|
||||
env,
|
||||
payload.userId,
|
||||
SIGNALR_UPDATE_TYPE_SYNC_FOLDER_DELETE,
|
||||
payload.revisionDate,
|
||||
payload.contextId ?? null,
|
||||
null,
|
||||
{
|
||||
UserId: payload.userId,
|
||||
Id: payload.folderId,
|
||||
RevisionDate: payload.revisionDate,
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
export function notifyUserSendCreate(
|
||||
env: Env,
|
||||
payload: {
|
||||
userId: string;
|
||||
sendId: string;
|
||||
revisionDate: string;
|
||||
contextId?: string | null;
|
||||
}
|
||||
): void {
|
||||
waitUntil(notifyUserUpdate(
|
||||
env,
|
||||
payload.userId,
|
||||
SIGNALR_UPDATE_TYPE_SYNC_SEND_CREATE,
|
||||
payload.revisionDate,
|
||||
payload.contextId ?? null,
|
||||
null,
|
||||
{
|
||||
UserId: payload.userId,
|
||||
Id: payload.sendId,
|
||||
RevisionDate: payload.revisionDate,
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
export function notifyUserSendUpdate(
|
||||
env: Env,
|
||||
payload: {
|
||||
userId: string;
|
||||
sendId: string;
|
||||
revisionDate: string;
|
||||
contextId?: string | null;
|
||||
}
|
||||
): void {
|
||||
waitUntil(notifyUserUpdate(
|
||||
env,
|
||||
payload.userId,
|
||||
SIGNALR_UPDATE_TYPE_SYNC_SEND_UPDATE,
|
||||
payload.revisionDate,
|
||||
payload.contextId ?? null,
|
||||
null,
|
||||
{
|
||||
UserId: payload.userId,
|
||||
Id: payload.sendId,
|
||||
RevisionDate: payload.revisionDate,
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
export function notifyUserSendDelete(
|
||||
env: Env,
|
||||
payload: {
|
||||
userId: string;
|
||||
sendId: string;
|
||||
revisionDate: string;
|
||||
contextId?: string | null;
|
||||
}
|
||||
): void {
|
||||
waitUntil(notifyUserUpdate(
|
||||
env,
|
||||
payload.userId,
|
||||
SIGNALR_UPDATE_TYPE_SYNC_SEND_DELETE,
|
||||
payload.revisionDate,
|
||||
payload.contextId ?? null,
|
||||
null,
|
||||
{
|
||||
UserId: payload.userId,
|
||||
Id: payload.sendId,
|
||||
RevisionDate: payload.revisionDate,
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
export function notifyUserLogout(
|
||||
env: Env,
|
||||
userId: string,
|
||||
@@ -392,13 +694,59 @@ export async function getOnlineUserDevices(env: Env, userId: string): Promise<st
|
||||
}
|
||||
}
|
||||
|
||||
export async function notifyAuthRequestResponse(
|
||||
env: Env,
|
||||
userId: string,
|
||||
authRequestId: string,
|
||||
contextId?: string | null
|
||||
): Promise<void> {
|
||||
try {
|
||||
const id = env.NOTIFICATIONS_HUB.idFromName(authRequestId);
|
||||
const stub = env.NOTIFICATIONS_HUB.get(id);
|
||||
await stub.fetch('https://notifications/internal/auth-request-response', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
userId,
|
||||
authRequestId,
|
||||
contextId: contextId || null,
|
||||
}),
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to broadcast auth request response notification:', error);
|
||||
}
|
||||
}
|
||||
|
||||
export function notifyUserAuthRequest(
|
||||
env: Env,
|
||||
userId: string,
|
||||
authRequestId: string,
|
||||
contextId?: string | null
|
||||
): void {
|
||||
waitUntil(notifyUserUpdate(
|
||||
env,
|
||||
userId,
|
||||
SIGNALR_UPDATE_TYPE_AUTH_REQUEST,
|
||||
new Date().toISOString(),
|
||||
contextId ?? null,
|
||||
null,
|
||||
{
|
||||
UserId: userId,
|
||||
Id: authRequestId,
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
async function notifyUserUpdate(
|
||||
env: Env,
|
||||
userId: string,
|
||||
updateType: number,
|
||||
revisionDate: string,
|
||||
contextId: string | null,
|
||||
targetDeviceIdentifier: string | null
|
||||
targetDeviceIdentifier: string | null,
|
||||
payloadOverride?: Record<string, unknown> | null
|
||||
): Promise<void> {
|
||||
try {
|
||||
const id = env.NOTIFICATIONS_HUB.idFromName(userId);
|
||||
@@ -414,12 +762,22 @@ async function notifyUserUpdate(
|
||||
contextId: contextId || null,
|
||||
updateType,
|
||||
targetDeviceIdentifier: targetDeviceIdentifier || null,
|
||||
payload: {
|
||||
payload: payloadOverride || {
|
||||
UserId: userId,
|
||||
Date: revisionDate,
|
||||
},
|
||||
}),
|
||||
});
|
||||
await notifyMobilePush(env, {
|
||||
userId,
|
||||
updateType,
|
||||
revisionDate,
|
||||
contextId,
|
||||
payload: payloadOverride || {
|
||||
UserId: userId,
|
||||
Date: revisionDate,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to broadcast realtime notification:', error);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Env, User, ProfileResponse, DEFAULT_DEV_SECRET } from '../types';
|
||||
import { Env, User, DEFAULT_DEV_SECRET } from '../types';
|
||||
import { StorageService } from '../services/storage';
|
||||
import { AuthService } from '../services/auth';
|
||||
import { RateLimitService, getClientIdentifier } from '../services/ratelimit';
|
||||
@@ -9,6 +9,11 @@ import { LIMITS } from '../config/limits';
|
||||
import { isTotpEnabled, verifyTotpToken } from '../utils/totp';
|
||||
import { createRecoveryCode, recoveryCodeEquals } from '../utils/recovery-code';
|
||||
import { buildAccountKeys } from '../utils/user-decryption';
|
||||
import { buildProfileResponse } from '../utils/profile-response';
|
||||
|
||||
const TWO_FACTOR_PROVIDER_AUTHENTICATOR = 0;
|
||||
const TOTP_USER_VERIFICATION_TOKEN_TTL_MS = 10 * 60 * 1000;
|
||||
const TOTP_BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
|
||||
// CONTRACT:
|
||||
// users.master_password_hash is server-side login verification only. It does
|
||||
@@ -64,6 +69,77 @@ function normalizeTotpSecret(input: string): string {
|
||||
return out;
|
||||
}
|
||||
|
||||
function randomBase32Secret(length: number = 32): string {
|
||||
const bytes = new Uint8Array(length);
|
||||
crypto.getRandomValues(bytes);
|
||||
let out = '';
|
||||
for (const byte of bytes) {
|
||||
out += TOTP_BASE32_ALPHABET[byte % TOTP_BASE32_ALPHABET.length];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function base64UrlEncodeBytes(data: Uint8Array): string {
|
||||
const base64 = btoa(String.fromCharCode(...data));
|
||||
return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
function base64UrlDecodeBytes(input: string): Uint8Array {
|
||||
let base64 = input.replace(/-/g, '+').replace(/_/g, '/');
|
||||
while (base64.length % 4) base64 += '=';
|
||||
const binary = atob(base64);
|
||||
const out = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
||||
return out;
|
||||
}
|
||||
|
||||
async function hmacSha256(secret: string, data: string): Promise<Uint8Array> {
|
||||
const key = await crypto.subtle.importKey(
|
||||
'raw',
|
||||
new TextEncoder().encode(secret),
|
||||
{ name: 'HMAC', hash: 'SHA-256' },
|
||||
false,
|
||||
['sign']
|
||||
);
|
||||
return new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(data)));
|
||||
}
|
||||
|
||||
async function createTotpUserVerificationToken(env: Env, user: User, key: string): Promise<string> {
|
||||
const payload = {
|
||||
sub: user.id,
|
||||
key,
|
||||
stamp: user.securityStamp,
|
||||
exp: Date.now() + TOTP_USER_VERIFICATION_TOKEN_TTL_MS,
|
||||
};
|
||||
const payloadB64 = base64UrlEncodeBytes(new TextEncoder().encode(JSON.stringify(payload)));
|
||||
const signatureB64 = base64UrlEncodeBytes(await hmacSha256(env.JWT_SECRET, payloadB64));
|
||||
return `${payloadB64}.${signatureB64}`;
|
||||
}
|
||||
|
||||
async function verifyTotpUserVerificationToken(env: Env, user: User, key: string, token: string): Promise<boolean> {
|
||||
try {
|
||||
const [payloadB64, signatureB64] = String(token || '').split('.');
|
||||
if (!payloadB64 || !signatureB64) return false;
|
||||
const expected = base64UrlEncodeBytes(await hmacSha256(env.JWT_SECRET, payloadB64));
|
||||
if (expected !== signatureB64) return false;
|
||||
const payload = JSON.parse(new TextDecoder().decode(base64UrlDecodeBytes(payloadB64))) as {
|
||||
sub?: string;
|
||||
key?: string;
|
||||
stamp?: string;
|
||||
exp?: number;
|
||||
};
|
||||
return (
|
||||
payload.sub === user.id &&
|
||||
payload.key === key &&
|
||||
payload.stamp === user.securityStamp &&
|
||||
typeof payload.exp === 'number' &&
|
||||
payload.exp >= Date.now()
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeRecoveryCodeInput(input: string): string {
|
||||
return String(input || '').toUpperCase().replace(/[^A-Z2-7]/g, '');
|
||||
}
|
||||
@@ -91,34 +167,67 @@ async function verifyUserSecret(
|
||||
return auth.verifyPassword(normalized, user.masterPasswordHash, user.email);
|
||||
}
|
||||
|
||||
function toProfile(user: User, env: Env): ProfileResponse {
|
||||
void env;
|
||||
function readBodyString(body: Record<string, unknown>, names: string[]): string {
|
||||
for (const name of names) {
|
||||
const value = body[name];
|
||||
if (typeof value === 'string') return value;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function readNestedString(source: unknown, path: string[]): string {
|
||||
let current = source;
|
||||
for (const key of path) {
|
||||
if (!current || typeof current !== 'object') return '';
|
||||
current = (current as Record<string, unknown>)[key];
|
||||
}
|
||||
return typeof current === 'string' ? current : '';
|
||||
}
|
||||
|
||||
function readNestedNumber(source: unknown, path: string[]): number | undefined {
|
||||
let current = source;
|
||||
for (const key of path) {
|
||||
if (!current || typeof current !== 'object') return undefined;
|
||||
current = (current as Record<string, unknown>)[key];
|
||||
}
|
||||
return typeof current === 'number' ? current : undefined;
|
||||
}
|
||||
|
||||
async function readRequestBody(request: Request): Promise<Record<string, unknown>> {
|
||||
const contentType = request.headers.get('content-type') || '';
|
||||
if (contentType.includes('application/x-www-form-urlencoded')) {
|
||||
const formData = await request.formData();
|
||||
return Object.fromEntries(formData.entries()) as Record<string, unknown>;
|
||||
}
|
||||
return await request.json();
|
||||
}
|
||||
|
||||
function masterPasswordPolicyResponse(): Record<string, unknown> {
|
||||
return {
|
||||
minComplexity: 0,
|
||||
minLength: 0,
|
||||
requireUpper: false,
|
||||
requireLower: false,
|
||||
requireNumbers: false,
|
||||
requireSpecial: false,
|
||||
enforceOnLogin: false,
|
||||
object: 'masterPasswordPolicy',
|
||||
};
|
||||
}
|
||||
|
||||
function keysResponse(user: User): Record<string, unknown> {
|
||||
const accountKeys = buildAccountKeys(user);
|
||||
return {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
emailVerified: true,
|
||||
premium: true,
|
||||
premiumFromOrganization: false,
|
||||
usesKeyConnector: false,
|
||||
masterPasswordHint: user.masterPasswordHint,
|
||||
culture: 'en-US',
|
||||
twoFactorEnabled: !!user.totpSecret,
|
||||
Key: user.key,
|
||||
PublicKey: user.publicKey ?? '',
|
||||
PrivateKey: user.privateKey ?? '',
|
||||
AccountKeys: accountKeys,
|
||||
Object: 'keys',
|
||||
key: user.key,
|
||||
privateKey: user.privateKey,
|
||||
publicKey: user.publicKey ?? '',
|
||||
privateKey: user.privateKey ?? '',
|
||||
accountKeys,
|
||||
securityStamp: user.securityStamp || user.id,
|
||||
organizations: [],
|
||||
providers: [],
|
||||
providerOrganizations: [],
|
||||
forcePasswordReset: false,
|
||||
avatarColor: null,
|
||||
creationDate: user.createdAt,
|
||||
verifyDevices: user.verifyDevices,
|
||||
role: user.role,
|
||||
status: user.status,
|
||||
object: 'profile',
|
||||
object: 'keys',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -353,7 +462,7 @@ export async function handleGetProfile(request: Request, env: Env, userId: strin
|
||||
const storage = new StorageService(env.DB);
|
||||
const user = await storage.getUserById(userId);
|
||||
if (!user) return errorResponse('User not found', 404);
|
||||
return jsonResponse(toProfile(user, env));
|
||||
return jsonResponse(buildProfileResponse(user, env));
|
||||
}
|
||||
|
||||
// PUT /api/accounts/profile
|
||||
@@ -392,7 +501,7 @@ export async function handleUpdateProfile(request: Request, env: Env, userId: st
|
||||
},
|
||||
});
|
||||
|
||||
return jsonResponse(toProfile(user, env));
|
||||
return jsonResponse(buildProfileResponse(user, env));
|
||||
}
|
||||
|
||||
// PUT/POST /api/accounts/verify-devices
|
||||
@@ -406,6 +515,7 @@ export async function handleSetVerifyDevices(request: Request, env: Env, userId:
|
||||
secret?: string;
|
||||
masterPasswordHash?: string;
|
||||
verifyDevices?: boolean;
|
||||
VerifyDevices?: boolean;
|
||||
};
|
||||
try {
|
||||
body = await request.json();
|
||||
@@ -413,7 +523,8 @@ export async function handleSetVerifyDevices(request: Request, env: Env, userId:
|
||||
return errorResponse('Invalid JSON', 400);
|
||||
}
|
||||
|
||||
if (typeof body.verifyDevices !== 'boolean') {
|
||||
const verifyDevices = typeof body.verifyDevices === 'boolean' ? body.verifyDevices : body.VerifyDevices;
|
||||
if (typeof verifyDevices !== 'boolean') {
|
||||
return errorResponse('verifyDevices must be true or false', 400);
|
||||
}
|
||||
|
||||
@@ -422,7 +533,7 @@ export async function handleSetVerifyDevices(request: Request, env: Env, userId:
|
||||
return errorResponse('User verification failed.', 400);
|
||||
}
|
||||
|
||||
user.verifyDevices = body.verifyDevices;
|
||||
user.verifyDevices = verifyDevices;
|
||||
user.updatedAt = new Date().toISOString();
|
||||
await storage.saveUser(user);
|
||||
await writeAuditEvent(storage, {
|
||||
@@ -441,6 +552,19 @@ export async function handleSetVerifyDevices(request: Request, env: Env, userId:
|
||||
return new Response(null, { status: 200 });
|
||||
}
|
||||
|
||||
// GET /api/accounts/keys
|
||||
export async function handleGetKeys(request: Request, env: Env, userId: string): Promise<Response> {
|
||||
void request;
|
||||
const storage = new StorageService(env.DB);
|
||||
const user = await storage.getUserById(userId);
|
||||
|
||||
if (!user) {
|
||||
return errorResponse('User not found', 404);
|
||||
}
|
||||
|
||||
return jsonResponse(keysResponse(user));
|
||||
}
|
||||
|
||||
// POST /api/accounts/keys
|
||||
export async function handleSetKeys(request: Request, env: Env, userId: string): Promise<Response> {
|
||||
const storage = new StorageService(env.DB);
|
||||
@@ -501,7 +625,7 @@ export async function handleSetKeys(request: Request, env: Env, userId: string):
|
||||
},
|
||||
});
|
||||
|
||||
return handleGetProfile(request, env, userId);
|
||||
return jsonResponse(keysResponse(user));
|
||||
}
|
||||
|
||||
// POST/PUT /api/accounts/password
|
||||
@@ -515,6 +639,7 @@ export async function handleChangePassword(request: Request, env: Env, userId: s
|
||||
masterPasswordHash?: string;
|
||||
currentPasswordHash?: string;
|
||||
newMasterPasswordHash?: string;
|
||||
masterPasswordHint?: string | null;
|
||||
key?: string;
|
||||
newKey?: string;
|
||||
encryptedPrivateKey?: string;
|
||||
@@ -525,6 +650,8 @@ export async function handleChangePassword(request: Request, env: Env, userId: s
|
||||
kdfIterations?: number;
|
||||
kdfMemory?: number;
|
||||
kdfParallelism?: number;
|
||||
authenticationData?: Record<string, unknown>;
|
||||
unlockData?: Record<string, unknown>;
|
||||
};
|
||||
try {
|
||||
body = await request.json();
|
||||
@@ -537,10 +664,16 @@ export async function handleChangePassword(request: Request, env: Env, userId: s
|
||||
const valid = await auth.verifyPassword(currentHash, user.masterPasswordHash, user.email);
|
||||
if (!valid) return errorResponse('Invalid password', 400);
|
||||
|
||||
if (!body.newMasterPasswordHash) {
|
||||
const newMasterPasswordHash =
|
||||
body.newMasterPasswordHash ||
|
||||
readNestedString(body, ['authenticationData', 'masterPasswordAuthenticationHash']);
|
||||
if (!newMasterPasswordHash) {
|
||||
return errorResponse('newMasterPasswordHash is required', 400);
|
||||
}
|
||||
const nextKey = body.newKey || body.key;
|
||||
const nextKey =
|
||||
body.newKey ||
|
||||
body.key ||
|
||||
readNestedString(body, ['unlockData', 'masterKeyWrappedUserKey']);
|
||||
const nextPrivateKey = body.newEncryptedPrivateKey || body.encryptedPrivateKey;
|
||||
const nextPublicKey = body.newPublicKey || body.publicKey;
|
||||
if (nextKey && !looksLikeEncString(nextKey)) {
|
||||
@@ -550,17 +683,24 @@ export async function handleChangePassword(request: Request, env: Env, userId: s
|
||||
return errorResponse('new encryptedPrivateKey is not a valid encrypted string', 400);
|
||||
}
|
||||
|
||||
const kdfErr = validateKdfParams(body.kdf ?? user.kdfType, body.kdfIterations, body.kdfMemory, body.kdfParallelism);
|
||||
const nextKdf = body.kdf ?? readNestedNumber(body, ['unlockData', 'kdf', 'kdfType']) ?? user.kdfType;
|
||||
const nextKdfIterations = body.kdfIterations ?? readNestedNumber(body, ['unlockData', 'kdf', 'iterations']);
|
||||
const nextKdfMemory = body.kdfMemory ?? readNestedNumber(body, ['unlockData', 'kdf', 'memory']);
|
||||
const nextKdfParallelism = body.kdfParallelism ?? readNestedNumber(body, ['unlockData', 'kdf', 'parallelism']);
|
||||
const kdfErr = validateKdfParams(nextKdf, nextKdfIterations, nextKdfMemory, nextKdfParallelism);
|
||||
if (kdfErr) return errorResponse(kdfErr, 400);
|
||||
|
||||
user.masterPasswordHash = await auth.hashPasswordServer(body.newMasterPasswordHash, user.email);
|
||||
user.masterPasswordHash = await auth.hashPasswordServer(newMasterPasswordHash, user.email);
|
||||
if (nextKey) user.key = nextKey;
|
||||
if (nextPrivateKey) user.privateKey = nextPrivateKey;
|
||||
if (nextPublicKey) user.publicKey = nextPublicKey;
|
||||
if (typeof body.kdf === 'number') user.kdfType = body.kdf;
|
||||
if (typeof body.kdfIterations === 'number') user.kdfIterations = body.kdfIterations;
|
||||
if (typeof body.kdfMemory === 'number') user.kdfMemory = body.kdfMemory;
|
||||
if (typeof body.kdfParallelism === 'number') user.kdfParallelism = body.kdfParallelism;
|
||||
if (typeof nextKdf === 'number') user.kdfType = nextKdf;
|
||||
if (typeof nextKdfIterations === 'number') user.kdfIterations = nextKdfIterations;
|
||||
if (typeof nextKdfMemory === 'number') user.kdfMemory = nextKdfMemory;
|
||||
if (typeof nextKdfParallelism === 'number') user.kdfParallelism = nextKdfParallelism;
|
||||
if (typeof body.masterPasswordHint === 'string' || body.masterPasswordHint === null) {
|
||||
user.masterPasswordHint = body.masterPasswordHint;
|
||||
}
|
||||
user.securityStamp = generateUUID();
|
||||
user.updatedAt = new Date().toISOString();
|
||||
await storage.saveUser(user);
|
||||
@@ -592,6 +732,164 @@ export async function handleGetTotpStatus(request: Request, env: Env, userId: st
|
||||
});
|
||||
}
|
||||
|
||||
function twoFactorProviderResponse(type: number, enabled: boolean): Record<string, unknown> {
|
||||
return {
|
||||
Enabled: enabled,
|
||||
Type: type,
|
||||
Object: 'twoFactorProvider',
|
||||
};
|
||||
}
|
||||
|
||||
function twoFactorAuthenticatorResponse(
|
||||
enabled: boolean,
|
||||
key: string,
|
||||
userVerificationToken?: string
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
Enabled: enabled,
|
||||
Key: key,
|
||||
UserVerificationToken: userVerificationToken ?? null,
|
||||
Object: 'twoFactorAuthenticator',
|
||||
};
|
||||
}
|
||||
|
||||
// GET /api/two-factor
|
||||
export async function handleGetTwoFactorProviders(request: Request, env: Env, userId: string): Promise<Response> {
|
||||
void request;
|
||||
const storage = new StorageService(env.DB);
|
||||
const user = await storage.getUserById(userId);
|
||||
if (!user) return errorResponse('User not found', 404);
|
||||
|
||||
const data = user.totpSecret
|
||||
? [twoFactorProviderResponse(TWO_FACTOR_PROVIDER_AUTHENTICATOR, true)]
|
||||
: [];
|
||||
|
||||
return jsonResponse({
|
||||
Data: data,
|
||||
ContinuationToken: null,
|
||||
Object: 'list',
|
||||
});
|
||||
}
|
||||
|
||||
// POST /api/two-factor/get-authenticator
|
||||
export async function handleGetTwoFactorAuthenticator(request: Request, env: Env, userId: string): Promise<Response> {
|
||||
const storage = new StorageService(env.DB);
|
||||
const auth = new AuthService(env);
|
||||
const user = await storage.getUserById(userId);
|
||||
if (!user) return errorResponse('User not found', 404);
|
||||
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
body = await readRequestBody(request);
|
||||
} catch {
|
||||
return errorResponse('Invalid JSON', 400);
|
||||
}
|
||||
|
||||
const secret = readBodyString(body, ['masterPasswordHash', 'MasterPasswordHash', 'otp', 'OTP', 'secret', 'Secret']);
|
||||
const verified = await verifyUserSecret(auth, user, secret);
|
||||
if (!verified) return errorResponse('User verification failed.', 400);
|
||||
|
||||
const key = normalizeTotpSecret(user.totpSecret || '') || randomBase32Secret();
|
||||
const userVerificationToken = await createTotpUserVerificationToken(env, user, key);
|
||||
return jsonResponse(twoFactorAuthenticatorResponse(!!user.totpSecret, key, userVerificationToken));
|
||||
}
|
||||
|
||||
// PUT/POST /api/two-factor/authenticator
|
||||
export async function handlePutTwoFactorAuthenticator(request: Request, env: Env, userId: string): Promise<Response> {
|
||||
const storage = new StorageService(env.DB);
|
||||
const user = await storage.getUserById(userId);
|
||||
if (!user) return errorResponse('User not found', 404);
|
||||
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
body = await readRequestBody(request);
|
||||
} catch {
|
||||
return errorResponse('Invalid JSON', 400);
|
||||
}
|
||||
|
||||
const key = normalizeTotpSecret(readBodyString(body, ['key', 'Key']));
|
||||
const token = readBodyString(body, ['token', 'Token']).trim();
|
||||
const userVerificationToken = readBodyString(body, ['userVerificationToken', 'UserVerificationToken']);
|
||||
if (!key || !token || !userVerificationToken) {
|
||||
return errorResponse('Key, token and userVerificationToken are required', 400);
|
||||
}
|
||||
if (!await verifyTotpUserVerificationToken(env, user, key, userVerificationToken)) {
|
||||
return errorResponse('User verification failed.', 400);
|
||||
}
|
||||
if (!isTotpEnabled(key)) return errorResponse('Invalid TOTP secret', 400);
|
||||
if (!await verifyTotpToken(key, token)) return errorResponse('Invalid token.', 400);
|
||||
|
||||
user.totpSecret = key;
|
||||
if (!user.totpRecoveryCode) {
|
||||
user.totpRecoveryCode = createRecoveryCode();
|
||||
}
|
||||
user.updatedAt = new Date().toISOString();
|
||||
await storage.saveUser(user);
|
||||
await storage.deleteRefreshTokensByUserId(user.id);
|
||||
AuthService.invalidateUserCache(user.id);
|
||||
await writeAuditEvent(storage, {
|
||||
actorUserId: user.id,
|
||||
action: 'account.totp.enable',
|
||||
category: 'security',
|
||||
level: 'security',
|
||||
targetType: 'user',
|
||||
targetId: user.id,
|
||||
metadata: auditRequestMetadata(request),
|
||||
});
|
||||
|
||||
return jsonResponse(twoFactorAuthenticatorResponse(true, key));
|
||||
}
|
||||
|
||||
// DELETE /api/two-factor/authenticator and PUT/POST /api/two-factor/disable
|
||||
export async function handleDisableTwoFactorProvider(request: Request, env: Env, userId: string): Promise<Response> {
|
||||
const storage = new StorageService(env.DB);
|
||||
const auth = new AuthService(env);
|
||||
const user = await storage.getUserById(userId);
|
||||
if (!user) return errorResponse('User not found', 404);
|
||||
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
body = await readRequestBody(request);
|
||||
} catch {
|
||||
return errorResponse('Invalid JSON', 400);
|
||||
}
|
||||
|
||||
const typeRaw = body.type ?? body.Type ?? TWO_FACTOR_PROVIDER_AUTHENTICATOR;
|
||||
const type = typeof typeRaw === 'number' ? typeRaw : Number.parseInt(String(typeRaw), 10);
|
||||
if (type !== TWO_FACTOR_PROVIDER_AUTHENTICATOR) {
|
||||
return errorResponse('Two-factor provider is not supported by this server.', 400);
|
||||
}
|
||||
|
||||
const key = normalizeTotpSecret(readBodyString(body, ['key', 'Key']));
|
||||
const userVerificationToken = readBodyString(body, ['userVerificationToken', 'UserVerificationToken']);
|
||||
const secret = readBodyString(body, ['masterPasswordHash', 'MasterPasswordHash', 'otp', 'OTP', 'secret', 'Secret']);
|
||||
let verified = false;
|
||||
if (key && userVerificationToken) {
|
||||
verified = await verifyTotpUserVerificationToken(env, user, key, userVerificationToken);
|
||||
}
|
||||
if (!verified) {
|
||||
verified = await verifyUserSecret(auth, user, secret);
|
||||
}
|
||||
if (!verified) return errorResponse('User verification failed.', 400);
|
||||
|
||||
user.totpSecret = null;
|
||||
user.updatedAt = new Date().toISOString();
|
||||
await storage.saveUser(user);
|
||||
await storage.deleteRefreshTokensByUserId(user.id);
|
||||
AuthService.invalidateUserCache(user.id);
|
||||
await writeAuditEvent(storage, {
|
||||
actorUserId: user.id,
|
||||
action: 'account.totp.disable',
|
||||
category: 'security',
|
||||
level: 'security',
|
||||
targetType: 'user',
|
||||
targetId: user.id,
|
||||
metadata: auditRequestMetadata(request),
|
||||
});
|
||||
|
||||
return jsonResponse(twoFactorProviderResponse(TWO_FACTOR_PROVIDER_AUTHENTICATOR, false));
|
||||
}
|
||||
|
||||
// PUT /api/accounts/totp
|
||||
// enable: { enabled: true, secret: "...", token: "123456" }
|
||||
// disable: { enabled: false, masterPasswordHash: "..." }
|
||||
@@ -699,7 +997,9 @@ export async function handleGetTotpRecoveryCode(request: Request, env: Env, user
|
||||
}
|
||||
|
||||
return jsonResponse({
|
||||
Code: user.totpRecoveryCode,
|
||||
code: user.totpRecoveryCode,
|
||||
Object: 'twoFactorRecover',
|
||||
object: 'twoFactorRecover',
|
||||
});
|
||||
}
|
||||
@@ -809,23 +1109,26 @@ export async function handleVerifyPassword(request: Request, env: Env, userId: s
|
||||
return errorResponse('User not found', 404);
|
||||
}
|
||||
|
||||
let body: { masterPasswordHash?: string };
|
||||
let body: { masterPasswordHash?: string; authenticationData?: Record<string, unknown> };
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return errorResponse('Invalid JSON', 400);
|
||||
}
|
||||
|
||||
if (!body.masterPasswordHash) {
|
||||
const masterPasswordHash =
|
||||
body.masterPasswordHash ||
|
||||
readNestedString(body, ['authenticationData', 'masterPasswordAuthenticationHash']);
|
||||
if (!masterPasswordHash) {
|
||||
return errorResponse('masterPasswordHash is required', 400);
|
||||
}
|
||||
|
||||
const valid = await auth.verifyPassword(body.masterPasswordHash, user.masterPasswordHash, user.email);
|
||||
const valid = await auth.verifyPassword(masterPasswordHash, user.masterPasswordHash, user.email);
|
||||
if (!valid) {
|
||||
return errorResponse('Invalid password', 400);
|
||||
}
|
||||
|
||||
return new Response(null, { status: 200 });
|
||||
return jsonResponse(masterPasswordPolicyResponse());
|
||||
}
|
||||
|
||||
// POST /api/accounts/api-key
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Env, Attachment, DEFAULT_DEV_SECRET } from '../types';
|
||||
import { notifyUserVaultSync } from '../durable/notifications-hub';
|
||||
import { Env, Attachment, Cipher, DEFAULT_DEV_SECRET } from '../types';
|
||||
import { notifyUserCipherUpdate, notifyUserVaultSync } from '../durable/notifications-hub';
|
||||
import { StorageService } from '../services/storage';
|
||||
import { jsonResponse, errorResponse } from '../utils/response';
|
||||
import { buildDirectUploadUrl, getSafeJwtSecret, parseDirectUploadPayload } from '../utils/direct-upload';
|
||||
@@ -31,6 +31,38 @@ function notifyVaultSyncForRequest(
|
||||
notifyUserVaultSync(env, userId, revisionDate, readActingDeviceIdentifier(request));
|
||||
}
|
||||
|
||||
function normalizeOptionalId(value: unknown): string | null {
|
||||
if (value == null) return null;
|
||||
const normalized = String(value).trim();
|
||||
return normalized ? normalized : null;
|
||||
}
|
||||
|
||||
function notifyCipherUpdateForRequest(
|
||||
request: Request,
|
||||
env: Env,
|
||||
cipher: Cipher,
|
||||
revisionDate: string
|
||||
): void {
|
||||
notifyUserCipherUpdate(env, {
|
||||
userId: cipher.userId,
|
||||
cipherId: cipher.id,
|
||||
revisionDate,
|
||||
organizationId: normalizeOptionalId((cipher as any).organizationId ?? null),
|
||||
collectionIds: Array.isArray((cipher as any).collectionIds)
|
||||
? (cipher as any).collectionIds.map((id: unknown) => String(id || '').trim()).filter(Boolean)
|
||||
: null,
|
||||
contextId: readActingDeviceIdentifier(request),
|
||||
});
|
||||
}
|
||||
|
||||
function contentDispositionAttachment(fileName: string | null | undefined): string {
|
||||
const fallback = 'attachment';
|
||||
const value = String(fileName || fallback)
|
||||
.replace(/[\r\n"]/g, '_')
|
||||
.trim() || fallback;
|
||||
return `attachment; filename="${value}"`;
|
||||
}
|
||||
|
||||
async function writeAttachmentAudit(
|
||||
storage: StorageService,
|
||||
request: Request,
|
||||
@@ -75,6 +107,7 @@ async function runWithConcurrency<T>(
|
||||
async function processAttachmentUpload(
|
||||
request: Request,
|
||||
env: Env,
|
||||
cipher: Cipher,
|
||||
attachment: Attachment,
|
||||
cipherId: string
|
||||
): Promise<Response> {
|
||||
@@ -116,6 +149,7 @@ async function processAttachmentUpload(
|
||||
const revisionInfo = await storage.updateCipherRevisionDate(cipherId);
|
||||
if (revisionInfo) {
|
||||
notifyVaultSyncForRequest(request, env, revisionInfo.userId, revisionInfo.revisionDate);
|
||||
notifyCipherUpdateForRequest(request, env, cipher, revisionInfo.revisionDate);
|
||||
}
|
||||
|
||||
return new Response(null, { status: 201 });
|
||||
@@ -176,6 +210,7 @@ export async function handleCreateAttachment(
|
||||
const revisionInfo = await storage.updateCipherRevisionDate(cipherId);
|
||||
if (revisionInfo) {
|
||||
notifyVaultSyncForRequest(request, env, revisionInfo.userId, revisionInfo.revisionDate);
|
||||
notifyCipherUpdateForRequest(request, env, cipher, revisionInfo.revisionDate);
|
||||
}
|
||||
|
||||
// Get updated cipher for response
|
||||
@@ -219,7 +254,7 @@ export async function handleUploadAttachment(
|
||||
return errorResponse('Attachment not found', 404);
|
||||
}
|
||||
|
||||
return processAttachmentUpload(request, env, attachment, cipherId);
|
||||
return processAttachmentUpload(request, env, cipher, attachment, cipherId);
|
||||
}
|
||||
|
||||
export async function handlePublicUploadAttachment(
|
||||
@@ -257,7 +292,7 @@ export async function handlePublicUploadAttachment(
|
||||
return errorResponse('Attachment not found', 404);
|
||||
}
|
||||
|
||||
return processAttachmentUpload(request, env, attachment, cipherId);
|
||||
return processAttachmentUpload(request, env, cipher, attachment, cipherId);
|
||||
}
|
||||
|
||||
// GET /api/ciphers/{cipherId}/attachment/{attachmentId}
|
||||
@@ -348,6 +383,7 @@ export async function handleUpdateAttachmentMetadata(
|
||||
const revisionInfo = await storage.updateCipherRevisionDate(cipherId);
|
||||
if (revisionInfo) {
|
||||
notifyVaultSyncForRequest(request, env, revisionInfo.userId, revisionInfo.revisionDate);
|
||||
notifyCipherUpdateForRequest(request, env, cipher, revisionInfo.revisionDate);
|
||||
}
|
||||
|
||||
return jsonResponse({
|
||||
@@ -415,7 +451,9 @@ export async function handlePublicDownloadAttachment(
|
||||
headers: {
|
||||
'Content-Type': object.contentType || 'application/octet-stream',
|
||||
'Content-Length': String(object.size),
|
||||
'Content-Disposition': contentDispositionAttachment(attachment.fileName),
|
||||
'Cache-Control': 'private, no-cache',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -453,6 +491,7 @@ export async function handleDeleteAttachment(
|
||||
const revisionInfo = await storage.updateCipherRevisionDate(cipherId);
|
||||
if (revisionInfo) {
|
||||
notifyVaultSyncForRequest(request, env, revisionInfo.userId, revisionInfo.revisionDate);
|
||||
notifyCipherUpdateForRequest(request, env, cipher, revisionInfo.revisionDate);
|
||||
await writeAttachmentAudit(storage, request, revisionInfo.userId, 'attachment.delete', {
|
||||
id: attachmentId,
|
||||
cipherId,
|
||||
@@ -463,9 +502,13 @@ export async function handleDeleteAttachment(
|
||||
// Get updated cipher for response
|
||||
const updatedCipher = await storage.getCipher(cipherId);
|
||||
const attachments = await storage.getAttachmentsByCipher(cipherId);
|
||||
const cipherResponse = cipherToResponse(updatedCipher!, attachments);
|
||||
|
||||
return jsonResponse({
|
||||
cipher: cipherToResponse(updatedCipher!, attachments),
|
||||
Cipher: cipherResponse,
|
||||
cipher: cipherResponse,
|
||||
Object: 'deleteAttachment',
|
||||
object: 'deleteAttachment',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
import type { AuthRequestRecord, AuthRequestType, Env } from '../types';
|
||||
import { StorageService } from '../services/storage';
|
||||
import { generateUUID } from '../utils/uuid';
|
||||
import { readAuthRequestDeviceInfo, readActingDeviceIdentifier } from '../utils/device';
|
||||
import { errorResponse, jsonResponse } from '../utils/response';
|
||||
import { isAuthRequestExpired } from '../services/storage-auth-request-repo';
|
||||
import { notifyAuthRequestResponse, notifyUserAuthRequest } from '../durable/notifications-hub';
|
||||
|
||||
const AUTH_REQUEST_TYPE_AUTHENTICATE_AND_UNLOCK = 0;
|
||||
const AUTH_REQUEST_TYPE_UNLOCK = 1;
|
||||
const AUTH_REQUEST_TYPE_ADMIN_APPROVAL = 2;
|
||||
|
||||
function normalizeText(value: unknown, maxLength: number): string {
|
||||
return String(value ?? '').trim().slice(0, maxLength);
|
||||
}
|
||||
|
||||
function getClientIp(request: Request): string | null {
|
||||
return (
|
||||
request.headers.get('CF-Connecting-IP') ||
|
||||
request.headers.get('X-Forwarded-For')?.split(',')[0]?.trim() ||
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
function getCountryName(request: Request): string | null {
|
||||
return request.headers.get('CF-IPCountry') || null;
|
||||
}
|
||||
|
||||
function deviceTypeName(type: number): string {
|
||||
const names: Record<number, string> = {
|
||||
0: 'Android',
|
||||
1: 'iOS',
|
||||
2: 'Chrome Extension',
|
||||
3: 'Firefox Extension',
|
||||
4: 'Opera Extension',
|
||||
5: 'Edge Extension',
|
||||
6: 'Windows Desktop',
|
||||
7: 'macOS Desktop',
|
||||
8: 'Linux Desktop',
|
||||
9: 'Chrome',
|
||||
10: 'Firefox',
|
||||
11: 'Opera',
|
||||
12: 'Edge',
|
||||
13: 'Internet Explorer',
|
||||
14: 'Unknown Browser',
|
||||
15: 'Android',
|
||||
16: 'Windows UWP',
|
||||
17: 'Safari',
|
||||
18: 'Vivaldi',
|
||||
19: 'Vivaldi Extension',
|
||||
20: 'Safari Extension',
|
||||
21: 'SDK',
|
||||
22: 'Server',
|
||||
23: 'Windows CLI',
|
||||
24: 'macOS CLI',
|
||||
25: 'Linux CLI',
|
||||
26: 'DuckDuckGo',
|
||||
};
|
||||
return names[type] || `Device ${type}`;
|
||||
}
|
||||
|
||||
function buildOrigin(request: Request): string {
|
||||
return new URL(request.url).host;
|
||||
}
|
||||
|
||||
function toAuthRequestResponse(request: Request, authRequest: AuthRequestRecord, requestDeviceId?: string | null) {
|
||||
return {
|
||||
id: authRequest.id,
|
||||
Id: authRequest.id,
|
||||
publicKey: authRequest.publicKey,
|
||||
PublicKey: authRequest.publicKey,
|
||||
requestDeviceIdentifier: authRequest.requestDeviceIdentifier,
|
||||
RequestDeviceIdentifier: authRequest.requestDeviceIdentifier,
|
||||
requestDeviceTypeValue: authRequest.requestDeviceType,
|
||||
RequestDeviceTypeValue: authRequest.requestDeviceType,
|
||||
requestDeviceType: deviceTypeName(authRequest.requestDeviceType),
|
||||
RequestDeviceType: deviceTypeName(authRequest.requestDeviceType),
|
||||
requestIpAddress: authRequest.requestIpAddress,
|
||||
RequestIpAddress: authRequest.requestIpAddress,
|
||||
requestCountryName: authRequest.requestCountryName,
|
||||
RequestCountryName: authRequest.requestCountryName,
|
||||
key: authRequest.key,
|
||||
Key: authRequest.key,
|
||||
masterPasswordHash: authRequest.masterPasswordHash,
|
||||
MasterPasswordHash: authRequest.masterPasswordHash,
|
||||
creationDate: authRequest.creationDate,
|
||||
CreationDate: authRequest.creationDate,
|
||||
responseDate: authRequest.responseDate,
|
||||
ResponseDate: authRequest.responseDate,
|
||||
requestApproved: authRequest.approved ?? false,
|
||||
RequestApproved: authRequest.approved ?? false,
|
||||
requestDeviceId: requestDeviceId ?? null,
|
||||
RequestDeviceId: requestDeviceId ?? null,
|
||||
origin: buildOrigin(request),
|
||||
Origin: buildOrigin(request),
|
||||
object: 'auth-request',
|
||||
Object: 'auth-request',
|
||||
};
|
||||
}
|
||||
|
||||
function listResponse<T>(data: T[]) {
|
||||
return {
|
||||
data,
|
||||
Data: data,
|
||||
object: 'list',
|
||||
Object: 'list',
|
||||
continuationToken: null,
|
||||
ContinuationToken: null,
|
||||
};
|
||||
}
|
||||
|
||||
async function readJsonBody(request: Request): Promise<Record<string, any> | null> {
|
||||
try {
|
||||
const body = await request.json();
|
||||
return body && typeof body === 'object' ? body as Record<string, any> : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function readBodyValue(body: Record<string, any>, names: string[]): unknown {
|
||||
for (const name of names) {
|
||||
if (body[name] !== undefined) return body[name];
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function isSupportedAuthRequestType(value: number): value is AuthRequestType {
|
||||
return value === AUTH_REQUEST_TYPE_AUTHENTICATE_AND_UNLOCK || value === AUTH_REQUEST_TYPE_UNLOCK || value === AUTH_REQUEST_TYPE_ADMIN_APPROVAL;
|
||||
}
|
||||
|
||||
export async function handleCreateAuthRequest(request: Request, env: Env): Promise<Response> {
|
||||
const storage = new StorageService(env.DB);
|
||||
const body = await readJsonBody(request);
|
||||
if (!body) return errorResponse('Invalid request payload', 400);
|
||||
|
||||
const email = normalizeText(readBodyValue(body, ['email', 'Email']), 320).toLowerCase();
|
||||
const publicKey = normalizeText(readBodyValue(body, ['publicKey', 'PublicKey']), 8192);
|
||||
const accessCode = normalizeText(readBodyValue(body, ['accessCode', 'AccessCode']), 25);
|
||||
const requestedType = Number(readBodyValue(body, ['type', 'Type']));
|
||||
const type = Number.isFinite(requestedType) ? requestedType : AUTH_REQUEST_TYPE_AUTHENTICATE_AND_UNLOCK;
|
||||
const deviceInfo = readAuthRequestDeviceInfo(
|
||||
{
|
||||
deviceIdentifier: normalizeText(readBodyValue(body, ['deviceIdentifier', 'DeviceIdentifier']), 128),
|
||||
deviceName: normalizeText(readBodyValue(body, ['deviceName', 'DeviceName']), 128),
|
||||
deviceType: String(readBodyValue(body, ['deviceType', 'DeviceType']) ?? ''),
|
||||
},
|
||||
request
|
||||
);
|
||||
|
||||
if (!email || !publicKey || !accessCode || !deviceInfo.deviceIdentifier) {
|
||||
return errorResponse('Email, public key, device identifier, and access code are required.', 400);
|
||||
}
|
||||
if (!isSupportedAuthRequestType(type) || type === AUTH_REQUEST_TYPE_ADMIN_APPROVAL) {
|
||||
return errorResponse('Invalid auth request type.', 400);
|
||||
}
|
||||
|
||||
const user = await storage.getUser(email);
|
||||
if (!user || user.status !== 'active') {
|
||||
return errorResponse('User or known device not found.', 400);
|
||||
}
|
||||
|
||||
await storage.pruneExpiredAuthRequests();
|
||||
const now = new Date().toISOString();
|
||||
const authRequest: AuthRequestRecord = {
|
||||
id: generateUUID(),
|
||||
userId: user.id,
|
||||
organizationId: null,
|
||||
type,
|
||||
requestDeviceIdentifier: deviceInfo.deviceIdentifier,
|
||||
requestDeviceType: deviceInfo.deviceType,
|
||||
requestIpAddress: getClientIp(request),
|
||||
requestCountryName: getCountryName(request),
|
||||
responseDeviceIdentifier: null,
|
||||
accessCode,
|
||||
publicKey,
|
||||
key: null,
|
||||
masterPasswordHash: null,
|
||||
approved: null,
|
||||
creationDate: now,
|
||||
responseDate: null,
|
||||
authenticationDate: null,
|
||||
};
|
||||
await storage.createAuthRequest(authRequest);
|
||||
notifyUserAuthRequest(env, user.id, authRequest.id, deviceInfo.deviceIdentifier);
|
||||
return jsonResponse(toAuthRequestResponse(request, authRequest));
|
||||
}
|
||||
|
||||
export async function handleGetAuthRequest(request: Request, env: Env, userId: string, id: string): Promise<Response> {
|
||||
const storage = new StorageService(env.DB);
|
||||
const authRequest = await storage.getAuthRequestById(id);
|
||||
if (!authRequest || authRequest.userId !== userId) return errorResponse('Not found', 404);
|
||||
return jsonResponse(toAuthRequestResponse(request, authRequest));
|
||||
}
|
||||
|
||||
export async function handleGetAuthRequestResponse(request: Request, env: Env, id: string): Promise<Response> {
|
||||
const storage = new StorageService(env.DB);
|
||||
const url = new URL(request.url);
|
||||
const accessCode = normalizeText(url.searchParams.get('code'), 25);
|
||||
const authRequest = await storage.getAuthRequestById(id);
|
||||
if (!authRequest || authRequest.accessCode !== accessCode || isAuthRequestExpired(authRequest)) {
|
||||
return errorResponse('Not found', 404);
|
||||
}
|
||||
return jsonResponse(toAuthRequestResponse(request, authRequest));
|
||||
}
|
||||
|
||||
export async function handleListAuthRequests(request: Request, env: Env, userId: string): Promise<Response> {
|
||||
const storage = new StorageService(env.DB);
|
||||
const authRequests = await storage.listAuthRequestsByUserId(userId);
|
||||
return jsonResponse(listResponse(authRequests.map((authRequest) => toAuthRequestResponse(request, authRequest))));
|
||||
}
|
||||
|
||||
export async function handleListPendingAuthRequests(request: Request, env: Env, userId: string): Promise<Response> {
|
||||
const storage = new StorageService(env.DB);
|
||||
await storage.pruneExpiredAuthRequests();
|
||||
const authRequests = await storage.listPendingAuthRequestsByUserId(userId);
|
||||
const rows = await Promise.all(authRequests.map(async (authRequest) => {
|
||||
const device = await storage.getDevice(userId, authRequest.requestDeviceIdentifier);
|
||||
return toAuthRequestResponse(request, authRequest, device?.deviceIdentifier ?? authRequest.requestDeviceIdentifier);
|
||||
}));
|
||||
return jsonResponse(listResponse(rows));
|
||||
}
|
||||
|
||||
export async function handleUpdateAuthRequest(request: Request, env: Env, userId: string, id: string): Promise<Response> {
|
||||
const storage = new StorageService(env.DB);
|
||||
const body = await readJsonBody(request);
|
||||
if (!body) return errorResponse('Invalid request payload', 400);
|
||||
|
||||
const authRequest = await storage.getAuthRequestById(id);
|
||||
if (!authRequest || authRequest.userId !== userId || isAuthRequestExpired(authRequest)) {
|
||||
return errorResponse('Not found', 404);
|
||||
}
|
||||
if (authRequest.approved !== null || authRequest.responseDate || authRequest.authenticationDate) {
|
||||
return errorResponse('Auth request has already been answered.', 409);
|
||||
}
|
||||
|
||||
const latestForUser = await storage.listPendingAuthRequestsByUserId(userId);
|
||||
const latestForDevice = latestForUser.find((item) => item.requestDeviceIdentifier === authRequest.requestDeviceIdentifier);
|
||||
if (latestForDevice?.id !== authRequest.id) {
|
||||
return errorResponse('This request is no longer valid. Make sure to approve the most recent request.', 400);
|
||||
}
|
||||
|
||||
const approved = Boolean(readBodyValue(body, ['requestApproved', 'RequestApproved']));
|
||||
const key = normalizeText(readBodyValue(body, ['key', 'Key']), 20000);
|
||||
const masterPasswordHash = normalizeText(readBodyValue(body, ['masterPasswordHash', 'MasterPasswordHash']), 20000) || null;
|
||||
const responseDeviceIdentifier =
|
||||
normalizeText(readBodyValue(body, ['deviceIdentifier', 'DeviceIdentifier']), 128) ||
|
||||
readActingDeviceIdentifier(request) ||
|
||||
'web';
|
||||
|
||||
if (approved && !key) {
|
||||
return errorResponse('Encrypted key is required to approve the request.', 400);
|
||||
}
|
||||
|
||||
const updated = await storage.updateAuthRequestResponse(id, userId, {
|
||||
approved,
|
||||
responseDeviceIdentifier,
|
||||
key,
|
||||
masterPasswordHash,
|
||||
});
|
||||
if (!updated) return errorResponse('Auth request has already been answered.', 409);
|
||||
const updatedRequest = await storage.getAuthRequestById(id);
|
||||
// Match Bitwarden upstream behavior: only approval wakes the originating anonymous
|
||||
// client. Denials are not pushed to avoid leaking that a login attempt was rejected.
|
||||
if (approved) {
|
||||
await notifyAuthRequestResponse(env, userId, id);
|
||||
}
|
||||
return jsonResponse(toAuthRequestResponse(request, updatedRequest || authRequest));
|
||||
}
|
||||
@@ -11,7 +11,13 @@ import {
|
||||
PasswordHistory,
|
||||
} from '../types';
|
||||
import { StorageService } from '../services/storage';
|
||||
import { notifyUserVaultSync } from '../durable/notifications-hub';
|
||||
import {
|
||||
notifyUserCipherCreate,
|
||||
notifyUserCipherDelete,
|
||||
notifyUserCipherUpdate,
|
||||
notifyUserCiphersSync,
|
||||
notifyUserVaultSync,
|
||||
} from '../durable/notifications-hub';
|
||||
import { jsonResponse, errorResponse } from '../utils/response';
|
||||
import { generateUUID } from '../utils/uuid';
|
||||
import { deleteAllAttachmentsForCipher, deleteAllAttachmentsForCiphers } from './attachments';
|
||||
@@ -42,6 +48,22 @@ function normalizeOptionalId(value: unknown): string | null {
|
||||
return normalized ? normalized : null;
|
||||
}
|
||||
|
||||
function readBooleanOrFallback(value: unknown, fallback: boolean): boolean {
|
||||
return typeof value === 'boolean' ? value : fallback;
|
||||
}
|
||||
|
||||
function buildCipherPermissions(passthrough: Record<string, unknown>): { delete: boolean; restore: boolean } {
|
||||
const raw = passthrough.permissions;
|
||||
const source = raw && typeof raw === 'object' && !Array.isArray(raw)
|
||||
? raw as Record<string, unknown>
|
||||
: null;
|
||||
|
||||
return {
|
||||
delete: readBooleanOrFallback(source?.delete, true),
|
||||
restore: readBooleanOrFallback(source?.restore, true),
|
||||
};
|
||||
}
|
||||
|
||||
function notifyVaultSyncForRequest(
|
||||
request: Request,
|
||||
env: Env,
|
||||
@@ -51,6 +73,60 @@ function notifyVaultSyncForRequest(
|
||||
notifyUserVaultSync(env, userId, revisionDate, readActingDeviceIdentifier(request));
|
||||
}
|
||||
|
||||
function notifyCipherCreateForRequest(
|
||||
request: Request,
|
||||
env: Env,
|
||||
cipher: Cipher,
|
||||
revisionDate: string
|
||||
): void {
|
||||
notifyUserCipherCreate(env, {
|
||||
userId: cipher.userId,
|
||||
cipherId: cipher.id,
|
||||
revisionDate,
|
||||
organizationId: normalizeOptionalId((cipher as any).organizationId ?? null),
|
||||
collectionIds: Array.isArray((cipher as any).collectionIds)
|
||||
? (cipher as any).collectionIds.map((id: unknown) => String(id || '').trim()).filter(Boolean)
|
||||
: null,
|
||||
contextId: readActingDeviceIdentifier(request),
|
||||
});
|
||||
}
|
||||
|
||||
function notifyCipherUpdateForRequest(
|
||||
request: Request,
|
||||
env: Env,
|
||||
cipher: Cipher,
|
||||
revisionDate: string
|
||||
): void {
|
||||
notifyUserCipherUpdate(env, {
|
||||
userId: cipher.userId,
|
||||
cipherId: cipher.id,
|
||||
revisionDate,
|
||||
organizationId: normalizeOptionalId((cipher as any).organizationId ?? null),
|
||||
collectionIds: Array.isArray((cipher as any).collectionIds)
|
||||
? (cipher as any).collectionIds.map((id: unknown) => String(id || '').trim()).filter(Boolean)
|
||||
: null,
|
||||
contextId: readActingDeviceIdentifier(request),
|
||||
});
|
||||
}
|
||||
|
||||
function notifyCipherDeleteForRequest(
|
||||
request: Request,
|
||||
env: Env,
|
||||
cipher: Cipher,
|
||||
revisionDate: string
|
||||
): void {
|
||||
notifyUserCipherDelete(env, {
|
||||
userId: cipher.userId,
|
||||
cipherId: cipher.id,
|
||||
revisionDate,
|
||||
organizationId: normalizeOptionalId((cipher as any).organizationId ?? null),
|
||||
collectionIds: Array.isArray((cipher as any).collectionIds)
|
||||
? (cipher as any).collectionIds.map((id: unknown) => String(id || '').trim()).filter(Boolean)
|
||||
: null,
|
||||
contextId: readActingDeviceIdentifier(request),
|
||||
});
|
||||
}
|
||||
|
||||
function getAliasedProp(source: any, aliases: string[]): { present: boolean; value: any } {
|
||||
if (!source || typeof source !== 'object') return { present: false, value: undefined };
|
||||
for (const key of aliases) {
|
||||
@@ -141,6 +217,12 @@ function optionalEncString(value: unknown): string | null {
|
||||
return isValidEncString(value) ? value.trim() : null;
|
||||
}
|
||||
|
||||
function optionalEncStringWithin(value: unknown, maxLength: number): string | null {
|
||||
const normalized = optionalEncString(value);
|
||||
if (!normalized) return null;
|
||||
return normalized.length <= maxLength ? normalized : null;
|
||||
}
|
||||
|
||||
function shouldAcceptCipherKey(value: unknown): boolean {
|
||||
return value == null || value === '' || isValidEncString(value);
|
||||
}
|
||||
@@ -151,13 +233,16 @@ function normalizeCipherKeyForStorage(value: unknown): string | null {
|
||||
|
||||
function sanitizeEncryptedObject<T extends Record<string, any>>(
|
||||
source: T | null | undefined,
|
||||
encryptedKeys: readonly string[]
|
||||
encryptedKeys: readonly string[] | Record<string, number>
|
||||
): T | null {
|
||||
if (!source || typeof source !== 'object') return source ?? null;
|
||||
const next: Record<string, any> = { ...source };
|
||||
for (const key of encryptedKeys) {
|
||||
const entries = Array.isArray(encryptedKeys)
|
||||
? encryptedKeys.map((key) => [key, 10000] as const)
|
||||
: Object.entries(encryptedKeys);
|
||||
for (const [key, maxLength] of entries) {
|
||||
if (!Object.prototype.hasOwnProperty.call(next, key)) continue;
|
||||
next[key] = optionalEncString(next[key]);
|
||||
next[key] = optionalEncStringWithin(next[key], maxLength);
|
||||
}
|
||||
return next as T;
|
||||
}
|
||||
@@ -188,7 +273,12 @@ export function normalizeCipherLoginForCompatibility(
|
||||
): any {
|
||||
const normalized = normalizeCipherLoginForStorage(login);
|
||||
if (!normalized || typeof normalized !== 'object') return normalized ?? null;
|
||||
const next = sanitizeEncryptedObject(normalized, ['username', 'password', 'totp', 'uri']);
|
||||
const next = sanitizeEncryptedObject(normalized, {
|
||||
username: 1000,
|
||||
password: 5000,
|
||||
totp: 1000,
|
||||
uri: 10000,
|
||||
});
|
||||
if (!next) return null;
|
||||
next.uris = normalizeCipherLoginUrisForCompatibility(next.uris, {
|
||||
requiresUriChecksum,
|
||||
@@ -214,23 +304,19 @@ function normalizeCipherLoginUrisForCompatibility(
|
||||
const hasChecksum = isValidEncString(next.uriChecksum);
|
||||
const hasMatch = next.match != null;
|
||||
|
||||
if (hasUri && hasChecksum) {
|
||||
if (hasUri && String(next.uri).trim().length > 10000) continue;
|
||||
if (hasChecksum && String(next.uriChecksum).trim().length > 10000) {
|
||||
next.uriChecksum = null;
|
||||
}
|
||||
|
||||
if (hasUri && isValidEncString(next.uriChecksum)) {
|
||||
out.push(next);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (hasUri && !hasChecksum) {
|
||||
if (options.preserveRepairableUris) {
|
||||
// Preserve the encrypted URI so NodeWarden Web can decrypt it and repair
|
||||
// the missing checksum. Dropping it here makes the URI appear lost and
|
||||
// can turn a display-only compatibility issue into data loss on save.
|
||||
out.push({ ...next, uriChecksum: null });
|
||||
continue;
|
||||
}
|
||||
// Bitwarden browser clients using the SDK drop item-key encrypted URIs
|
||||
// whose checksum is missing/invalid. User-key encrypted legacy/import
|
||||
// entries bypass this validation and can safely keep the URI.
|
||||
if (options.requiresUriChecksum) continue;
|
||||
// Official Bitwarden treats UriChecksum as nullable encrypted metadata.
|
||||
// Keep the URI intact and let clients that can repair checksums do so.
|
||||
out.push({ ...next, uriChecksum: null });
|
||||
continue;
|
||||
}
|
||||
@@ -243,14 +329,27 @@ function normalizeCipherLoginUrisForCompatibility(
|
||||
return out.length ? out : null;
|
||||
}
|
||||
|
||||
function hasMissingLoginUriChecksum(cipher: Cipher): boolean {
|
||||
if (!cipher.key || !cipher.login || typeof cipher.login !== 'object') return false;
|
||||
const uris = (cipher.login as any).uris;
|
||||
if (!Array.isArray(uris)) return false;
|
||||
return uris.some((uri: any) => {
|
||||
if (!uri || typeof uri !== 'object') return false;
|
||||
return isValidEncString(uri.uri) && !isValidEncString(uri.uriChecksum);
|
||||
});
|
||||
export function validateCipherEncryptedFieldsForCompatibility(cipher: Cipher): string | null {
|
||||
if (cipher.name != null && !optionalEncStringWithin(cipher.name, 1000)) return 'Cipher name must be an encrypted string up to 1000 characters.';
|
||||
if (cipher.notes != null && !optionalEncStringWithin(cipher.notes, 10000)) return 'Cipher notes must be an encrypted string up to 10000 characters.';
|
||||
|
||||
const login = cipher.login as any;
|
||||
if (login && typeof login === 'object') {
|
||||
if (login.username != null && !optionalEncStringWithin(login.username, 1000)) return 'Login username must be an encrypted string up to 1000 characters.';
|
||||
if (login.password != null && !optionalEncStringWithin(login.password, 5000)) return 'Login password must be an encrypted string up to 5000 characters.';
|
||||
if (login.totp != null && !optionalEncStringWithin(login.totp, 1000)) return 'Login TOTP must be an encrypted string up to 1000 characters.';
|
||||
if (login.uri != null && !optionalEncStringWithin(login.uri, 10000)) return 'Login URI must be an encrypted string up to 10000 characters.';
|
||||
|
||||
if (Array.isArray(login.uris)) {
|
||||
for (const uri of login.uris) {
|
||||
if (!uri || typeof uri !== 'object') continue;
|
||||
if (uri.uri != null && !optionalEncStringWithin(uri.uri, 10000)) return 'Login URI must be an encrypted string up to 10000 characters.';
|
||||
if (uri.uriChecksum != null && !optionalEncStringWithin(uri.uriChecksum, 10000)) return 'Login URI checksum must be an encrypted string up to 10000 characters.';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeFido2CredentialsForCompatibility(credentials: any): any[] | null {
|
||||
@@ -589,7 +688,14 @@ export function cipherToResponse(
|
||||
!!responseCipherKey,
|
||||
!!options.preserveRepairableUris
|
||||
);
|
||||
const normalizedCard = sanitizeEncryptedObject((passthrough as any).card ?? null, ['cardholderName', 'brand', 'number', 'expMonth', 'expYear', 'code']);
|
||||
const normalizedCard = sanitizeEncryptedObject((passthrough as any).card ?? null, {
|
||||
cardholderName: 1000,
|
||||
brand: 1000,
|
||||
number: 1000,
|
||||
expMonth: 1000,
|
||||
expYear: 1000,
|
||||
code: 1000,
|
||||
});
|
||||
const normalizedIdentity = sanitizeEncryptedObject((passthrough as any).identity ?? null, [
|
||||
'title',
|
||||
'firstName',
|
||||
@@ -615,6 +721,7 @@ export function cipherToResponse(
|
||||
? normalizeCipherSecureNoteForCompatibility((passthrough as any).secureNote ?? null) ?? { type: 0 }
|
||||
: null;
|
||||
const responseAttachments = applyCipherEmbeddedAttachmentMetadata(cipher, attachments);
|
||||
const responsePermissions = buildCipherPermissions(passthrough);
|
||||
|
||||
return {
|
||||
// Pass through ALL stored cipher fields (known + unknown)
|
||||
@@ -628,12 +735,9 @@ export function cipherToResponse(
|
||||
revisionDate: updatedAt,
|
||||
deletedDate: deletedAt,
|
||||
archivedDate: archivedAt ?? null,
|
||||
edit: true,
|
||||
viewPassword: true,
|
||||
permissions: {
|
||||
delete: true,
|
||||
restore: true,
|
||||
},
|
||||
edit: readBooleanOrFallback((passthrough as any).edit, true),
|
||||
viewPassword: readBooleanOrFallback((passthrough as any).viewPassword, true),
|
||||
permissions: responsePermissions,
|
||||
object: 'cipherDetails',
|
||||
collectionIds: Array.isArray((passthrough as any).collectionIds) ? (passthrough as any).collectionIds : [],
|
||||
attachments: formatAttachments(responseAttachments),
|
||||
@@ -647,6 +751,7 @@ export function cipherToResponse(
|
||||
passwordHistory: normalizePasswordHistoryForCompatibility((passthrough as any).passwordHistory),
|
||||
sshKey: normalizedSshKey,
|
||||
key: responseCipherKey,
|
||||
data: typeof (passthrough as any).data === 'string' ? (passthrough as any).data : null,
|
||||
encryptedFor: (passthrough as any).encryptedFor ?? null,
|
||||
};
|
||||
}
|
||||
@@ -772,6 +877,8 @@ export async function handleCreateCipher(request: Request, env: Env, userId: str
|
||||
const createFields = getAliasedProp(cipherData, ['fields', 'Fields']);
|
||||
cipher.fields = createFields.present ? (createFields.value ?? null) : (cipher.fields ?? null);
|
||||
normalizeCipherForStorage(cipher);
|
||||
const compatibilityError = validateCipherEncryptedFieldsForCompatibility(cipher);
|
||||
if (compatibilityError) return errorResponse(compatibilityError, 400);
|
||||
|
||||
// Prevent referencing a folder owned by another user.
|
||||
if (cipher.folderId) {
|
||||
@@ -779,13 +886,10 @@ export async function handleCreateCipher(request: Request, env: Env, userId: str
|
||||
if (!folderOk) return errorResponse('Folder not found', 404);
|
||||
}
|
||||
|
||||
if (hasMissingLoginUriChecksum(cipher)) {
|
||||
return errorResponse('Login URI checksum is required for item-key encrypted ciphers. Refresh NodeWarden and save the item again.', 400);
|
||||
}
|
||||
|
||||
await storage.saveCipher(cipher);
|
||||
const revisionDate = await storage.updateRevisionDate(userId);
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifyCipherCreateForRequest(request, env, cipher, revisionDate);
|
||||
const responseOptions = cipherResponseOptionsForRequest(request);
|
||||
|
||||
return jsonResponse(
|
||||
@@ -835,10 +939,6 @@ export async function handleUpdateCipher(request: Request, env: Env, userId: str
|
||||
return errorResponse('The client copy of this cipher is out of date. Resync the client and try again.', 400);
|
||||
}
|
||||
|
||||
if (!shouldPreserveRepairableCipherUris(request) && incomingLogin.present && hasMissingLoginUriChecksum(existingCipher)) {
|
||||
return errorResponse('This item has login URIs that must be repaired in NodeWarden Web before updating from this client. Open NodeWarden Web once, then resync.', 400);
|
||||
}
|
||||
|
||||
const nextType = Number(cipherData.type) || existingCipher.type;
|
||||
|
||||
// Opaque passthrough: merge existing stored data with ALL incoming client fields.
|
||||
@@ -887,6 +987,8 @@ export async function handleUpdateCipher(request: Request, env: Env, userId: str
|
||||
cipher.fields = null;
|
||||
}
|
||||
normalizeCipherForStorage(cipher);
|
||||
const compatibilityError = validateCipherEncryptedFieldsForCompatibility(cipher);
|
||||
if (compatibilityError) return errorResponse(compatibilityError, 400);
|
||||
|
||||
// Prevent referencing a folder owned by another user.
|
||||
if (cipher.folderId) {
|
||||
@@ -894,14 +996,11 @@ export async function handleUpdateCipher(request: Request, env: Env, userId: str
|
||||
if (!folderOk) return errorResponse('Folder not found', 404);
|
||||
}
|
||||
|
||||
if (hasMissingLoginUriChecksum(cipher)) {
|
||||
return errorResponse('Login URI checksum is required for item-key encrypted ciphers. Refresh NodeWarden and save the item again.', 400);
|
||||
}
|
||||
|
||||
await syncIncomingAttachmentMetadata(storage, cipher.id, cipherData);
|
||||
await storage.saveCipher(cipher);
|
||||
const revisionDate = await storage.updateRevisionDate(userId);
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifyCipherUpdateForRequest(request, env, cipher, revisionDate);
|
||||
const attachments = await storage.getAttachmentsByCipher(cipher.id);
|
||||
const responseOptions = cipherResponseOptionsForRequest(request);
|
||||
|
||||
@@ -926,6 +1025,7 @@ export async function handleDeleteCipher(request: Request, env: Env, userId: str
|
||||
await storage.saveCipher(cipher);
|
||||
const revisionDate = await storage.updateRevisionDate(userId);
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifyCipherDeleteForRequest(request, env, cipher, revisionDate);
|
||||
await writeCipherAudit(storage, request, userId, 'cipher.delete.soft', {
|
||||
id: cipher.id,
|
||||
type: cipher.type,
|
||||
@@ -955,6 +1055,7 @@ export async function handleDeleteCipherCompat(request: Request, env: Env, userI
|
||||
await storage.deleteCipher(id, userId);
|
||||
const revisionDate = await storage.updateRevisionDate(userId);
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifyCipherDeleteForRequest(request, env, cipher, revisionDate);
|
||||
await writeCipherAudit(storage, request, userId, 'cipher.delete.permanent', {
|
||||
id,
|
||||
type: cipher.type,
|
||||
@@ -982,6 +1083,7 @@ export async function handlePermanentDeleteCipher(request: Request, env: Env, us
|
||||
await storage.deleteCipher(id, userId);
|
||||
const revisionDate = await storage.updateRevisionDate(userId);
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifyCipherDeleteForRequest(request, env, cipher, revisionDate);
|
||||
await writeCipherAudit(storage, request, userId, 'cipher.delete.permanent', {
|
||||
id,
|
||||
type: cipher.type,
|
||||
@@ -1006,6 +1108,7 @@ export async function handleRestoreCipher(request: Request, env: Env, userId: st
|
||||
await storage.saveCipher(cipher);
|
||||
const revisionDate = await storage.updateRevisionDate(userId);
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifyCipherUpdateForRequest(request, env, cipher, revisionDate);
|
||||
|
||||
return jsonResponse(
|
||||
cipherToResponse(cipher, [], cipherResponseOptionsForRequest(request))
|
||||
@@ -1045,6 +1148,7 @@ export async function handlePartialUpdateCipher(request: Request, env: Env, user
|
||||
await storage.saveCipher(cipher);
|
||||
const revisionDate = await storage.updateRevisionDate(userId);
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifyCipherUpdateForRequest(request, env, cipher, revisionDate);
|
||||
|
||||
return jsonResponse(
|
||||
cipherToResponse(cipher, [], cipherResponseOptionsForRequest(request))
|
||||
@@ -1121,6 +1225,7 @@ export async function handleArchiveCipher(request: Request, env: Env, userId: st
|
||||
await storage.saveCipher(cipher);
|
||||
const revisionDate = await storage.updateRevisionDate(userId);
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifyCipherUpdateForRequest(request, env, cipher, revisionDate);
|
||||
|
||||
const attachments = await storage.getAttachmentsByCipher(cipher.id);
|
||||
return jsonResponse(
|
||||
@@ -1169,6 +1274,7 @@ export async function handleBulkArchiveCiphers(request: Request, env: Env, userI
|
||||
const revisionDate = await storage.bulkArchiveCiphers(ids, userId);
|
||||
if (revisionDate) {
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifyUserCiphersSync(env, userId, revisionDate, readActingDeviceIdentifier(request));
|
||||
}
|
||||
|
||||
return buildCipherListResponse(request, storage, userId, ids);
|
||||
@@ -1193,6 +1299,7 @@ export async function handleBulkUnarchiveCiphers(request: Request, env: Env, use
|
||||
const revisionDate = await storage.bulkUnarchiveCiphers(ids, userId);
|
||||
if (revisionDate) {
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifyUserCiphersSync(env, userId, revisionDate, readActingDeviceIdentifier(request));
|
||||
}
|
||||
|
||||
return buildCipherListResponse(request, storage, userId, ids);
|
||||
@@ -1216,6 +1323,7 @@ export async function handleBulkDeleteCiphers(request: Request, env: Env, userId
|
||||
const revisionDate = await storage.bulkSoftDeleteCiphers(body.ids, userId);
|
||||
if (revisionDate) {
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifyUserCiphersSync(env, userId, revisionDate, readActingDeviceIdentifier(request));
|
||||
await writeCipherAudit(storage, request, userId, 'cipher.delete.soft.bulk', {
|
||||
count: body.ids.length,
|
||||
});
|
||||
@@ -1242,6 +1350,7 @@ export async function handleBulkRestoreCiphers(request: Request, env: Env, userI
|
||||
const revisionDate = await storage.bulkRestoreCiphers(body.ids, userId);
|
||||
if (revisionDate) {
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifyUserCiphersSync(env, userId, revisionDate, readActingDeviceIdentifier(request));
|
||||
}
|
||||
|
||||
return new Response(null, { status: 204 });
|
||||
@@ -1278,6 +1387,7 @@ export async function handleBulkPermanentDeleteCiphers(request: Request, env: En
|
||||
const revisionDate = await storage.bulkDeleteCiphers(ownedIds, userId);
|
||||
if (revisionDate) {
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifyUserCiphersSync(env, userId, revisionDate, readActingDeviceIdentifier(request));
|
||||
await writeCipherAudit(storage, request, userId, 'cipher.delete.permanent.bulk', {
|
||||
count: ownedIds.length,
|
||||
requestedCount: ids.length,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Env } from '../types';
|
||||
import { getOnlineUserDevices, notifyUserLogout } from '../durable/notifications-hub';
|
||||
import { AuthService } from '../services/auth';
|
||||
import { auditRequestMetadata, writeAuditEvent } from '../services/audit-events';
|
||||
import { registerMobilePushDevice, unregisterMobilePushDevice } from '../services/push-relay';
|
||||
import { StorageService } from '../services/storage';
|
||||
import { errorResponse, jsonResponse } from '../utils/response';
|
||||
import { readKnownDeviceProbe } from '../utils/device';
|
||||
@@ -223,6 +224,8 @@ export async function handleGetAuthorizedDevices(request: Request, env: Env, use
|
||||
encryptedUserKey: null,
|
||||
encryptedPublicKey: null,
|
||||
encryptedPrivateKey: null,
|
||||
pushUuid: null,
|
||||
pushToken: null,
|
||||
devicePendingAuthRequest: null,
|
||||
deviceNote: null,
|
||||
lastSeenAt: null,
|
||||
@@ -325,10 +328,12 @@ export async function handleDeleteDevice(
|
||||
if (!normalized) return errorResponse('Invalid device identifier', 400);
|
||||
|
||||
const storage = new StorageService(env.DB);
|
||||
const device = await storage.getDevice(userId, normalized);
|
||||
await storage.deleteTrustedTwoFactorTokensByDevice(userId, normalized);
|
||||
await storage.deleteRefreshTokensByDevice(userId, normalized);
|
||||
const deleted = await storage.deleteDevice(userId, normalized);
|
||||
if (deleted) {
|
||||
await unregisterMobilePushDevice(env, device?.pushUuid);
|
||||
AuthService.invalidateDeviceCache(userId, normalized);
|
||||
notifyUserLogout(env, userId, normalized);
|
||||
}
|
||||
@@ -537,10 +542,12 @@ export async function handleDeactivateDevice(
|
||||
if (!normalized) return errorResponse('Invalid device identifier', 400);
|
||||
|
||||
const storage = new StorageService(env.DB);
|
||||
const device = await storage.getDevice(userId, normalized);
|
||||
await storage.deleteTrustedTwoFactorTokensByDevice(userId, normalized);
|
||||
await storage.deleteRefreshTokensByDevice(userId, normalized);
|
||||
const deleted = await storage.deleteDevice(userId, normalized);
|
||||
if (deleted) {
|
||||
await unregisterMobilePushDevice(env, device?.pushUuid);
|
||||
AuthService.invalidateDeviceCache(userId, normalized);
|
||||
notifyUserLogout(env, userId, normalized);
|
||||
}
|
||||
@@ -557,18 +564,36 @@ export async function handleDeactivateDevice(
|
||||
}
|
||||
|
||||
// PUT /api/devices/identifier/{deviceIdentifier}/token
|
||||
// Bitwarden mobile reports push token updates to this endpoint.
|
||||
// NodeWarden does not implement push notifications, so accept and no-op.
|
||||
// Bitwarden mobile reports APNs/FCM push token updates to this endpoint.
|
||||
export async function handleUpdateDeviceToken(
|
||||
request: Request,
|
||||
env: Env,
|
||||
userId: string,
|
||||
deviceIdentifier: string
|
||||
): Promise<Response> {
|
||||
void request;
|
||||
void env;
|
||||
void userId;
|
||||
void deviceIdentifier;
|
||||
const normalized = normalizeIdentifier(deviceIdentifier);
|
||||
if (!normalized) return errorResponse('Invalid device identifier', 400);
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
const pushToken = String(body?.pushToken ?? body?.PushToken ?? '').trim();
|
||||
if (!pushToken) return errorResponse('Invalid push token', 400);
|
||||
|
||||
const storage = new StorageService(env.DB);
|
||||
const device = await storage.getDevice(userId, normalized);
|
||||
if (!device) return errorResponse('Device not found', 404);
|
||||
|
||||
const pushUuid = device.pushUuid || generateUUID();
|
||||
const updated = await storage.updateDevicePushToken(userId, normalized, pushUuid, pushToken);
|
||||
if (updated) {
|
||||
await registerMobilePushDevice(env, {
|
||||
userId,
|
||||
deviceIdentifier: normalized,
|
||||
type: device.type,
|
||||
pushUuid,
|
||||
pushToken,
|
||||
});
|
||||
}
|
||||
|
||||
return new Response(null, { status: 200 });
|
||||
}
|
||||
|
||||
@@ -594,9 +619,15 @@ export async function handleClearDeviceToken(
|
||||
deviceIdentifier: string
|
||||
): Promise<Response> {
|
||||
void request;
|
||||
void env;
|
||||
void userId;
|
||||
void deviceIdentifier;
|
||||
const normalized = normalizeIdentifier(deviceIdentifier);
|
||||
if (!normalized) return errorResponse('Invalid device identifier', 400);
|
||||
|
||||
const storage = new StorageService(env.DB);
|
||||
const cleared = await storage.clearDevicePushToken(userId, normalized);
|
||||
if (cleared?.pushUuid) {
|
||||
await unregisterMobilePushDevice(env, cleared.pushUuid);
|
||||
}
|
||||
|
||||
return new Response(null, { status: 200 });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { Env, Folder, FolderResponse } from '../types';
|
||||
import { notifyUserVaultSync } from '../durable/notifications-hub';
|
||||
import {
|
||||
notifyUserFolderCreate,
|
||||
notifyUserFolderDelete,
|
||||
notifyUserFolderUpdate,
|
||||
notifyUserVaultSync,
|
||||
} from '../durable/notifications-hub';
|
||||
import { StorageService } from '../services/storage';
|
||||
import { jsonResponse, errorResponse } from '../utils/response';
|
||||
import { readActingDeviceIdentifier } from '../utils/device';
|
||||
@@ -111,6 +116,12 @@ export async function handleCreateFolder(request: Request, env: Env, userId: str
|
||||
await storage.saveFolder(folder);
|
||||
const revisionDate = await storage.updateRevisionDate(userId);
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifyUserFolderCreate(env, {
|
||||
userId,
|
||||
folderId: folder.id,
|
||||
revisionDate,
|
||||
contextId: readActingDeviceIdentifier(request),
|
||||
});
|
||||
|
||||
return jsonResponse(folderToResponse(folder), 200);
|
||||
}
|
||||
@@ -139,6 +150,12 @@ export async function handleUpdateFolder(request: Request, env: Env, userId: str
|
||||
await storage.saveFolder(folder);
|
||||
const revisionDate = await storage.updateRevisionDate(userId);
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifyUserFolderUpdate(env, {
|
||||
userId,
|
||||
folderId: folder.id,
|
||||
revisionDate,
|
||||
contextId: readActingDeviceIdentifier(request),
|
||||
});
|
||||
|
||||
return jsonResponse(folderToResponse(folder));
|
||||
}
|
||||
@@ -156,6 +173,12 @@ export async function handleDeleteFolder(request: Request, env: Env, userId: str
|
||||
await storage.deleteFolder(id, userId);
|
||||
const revisionDate = await storage.updateRevisionDate(userId);
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifyUserFolderDelete(env, {
|
||||
userId,
|
||||
folderId: id,
|
||||
revisionDate,
|
||||
contextId: readActingDeviceIdentifier(request),
|
||||
});
|
||||
await writeFolderAudit(storage, request, userId, 'folder.delete', {
|
||||
id,
|
||||
});
|
||||
@@ -179,9 +202,23 @@ export async function handleBulkDeleteFolders(request: Request, env: Env, userId
|
||||
return errorResponse('Folder ids are required', 400);
|
||||
}
|
||||
|
||||
const folders = (
|
||||
await Promise.all(ids.map(async (id) => {
|
||||
const folder = await storage.getFolder(id);
|
||||
return folder && folder.userId === userId ? folder : null;
|
||||
}))
|
||||
).filter((folder): folder is Folder => !!folder);
|
||||
const revisionDate = await storage.bulkDeleteFolders(ids, userId);
|
||||
if (revisionDate) {
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
for (const folder of folders) {
|
||||
notifyUserFolderDelete(env, {
|
||||
userId,
|
||||
folderId: folder.id,
|
||||
revisionDate,
|
||||
contextId: readActingDeviceIdentifier(request),
|
||||
});
|
||||
}
|
||||
await writeFolderAudit(storage, request, userId, 'folder.delete.bulk', {
|
||||
count: ids.length,
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import { readAuthRequestDeviceInfo } from '../utils/device';
|
||||
import { createRecoveryCode, recoveryCodeEquals } from '../utils/recovery-code';
|
||||
import { generateUUID } from '../utils/uuid';
|
||||
import { issueSendAccessToken } from './sends';
|
||||
import { registerMobilePushDevice } from '../services/push-relay';
|
||||
import {
|
||||
buildAccountKeys,
|
||||
buildUserDecryptionOptions,
|
||||
@@ -19,15 +20,17 @@ import {
|
||||
assertAccountPasskeyCredential,
|
||||
buildAccountPasskeyTokenUserDecryptionOption,
|
||||
} from './account-passkeys';
|
||||
import { isAuthRequestExpired } from '../services/storage-auth-request-repo';
|
||||
|
||||
const TWO_FACTOR_REMEMBER_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
const TWO_FACTOR_PROVIDER_AUTHENTICATOR = 0;
|
||||
const TWO_FACTOR_PROVIDER_REMEMBER = 5;
|
||||
const TWO_FACTOR_PROVIDER_RECOVERY_CODE = 8;
|
||||
const WEB_REFRESH_COOKIE = 'nodewarden_web_refresh';
|
||||
// Android client (2026.2.x) deserializes TwoFactorProviders2 keys with -1 for recovery code.
|
||||
// Keep request parsing backward-compatible with historical provider values (8 / 100).
|
||||
// Some UI surfaces use -1 for the recovery-code settings dialog. Login itself follows
|
||||
// the official Identity provider enum (RecoveryCode = 8), while request parsing remains
|
||||
// compatible with older/local provider values.
|
||||
const TWO_FACTOR_PROVIDER_RECOVERY_CODE_RESPONSE = '-1';
|
||||
const TWO_FACTOR_PROVIDER_RECOVERY_CODE_LEGACY = 8;
|
||||
const TWO_FACTOR_PROVIDER_RECOVERY_CODE_ANDROID_REQUEST = 100;
|
||||
|
||||
function resolveTotpSecret(userSecret: string | null): string | null {
|
||||
@@ -48,6 +51,44 @@ async function resolveDeviceSession(
|
||||
return { identifier: deviceInfo.deviceIdentifier, sessionStamp };
|
||||
}
|
||||
|
||||
function readDevicePushToken(body: Record<string, string>): string {
|
||||
return String(readBodyValue(body, ['devicePushToken', 'DevicePushToken', 'device_push_token']) || '').trim();
|
||||
}
|
||||
|
||||
async function persistIdentityDevicePushToken(
|
||||
env: Env,
|
||||
storage: StorageService,
|
||||
userId: string,
|
||||
deviceSession: { identifier: string; sessionStamp: string } | null,
|
||||
deviceType: number,
|
||||
body: Record<string, string>
|
||||
): Promise<void> {
|
||||
if (!deviceSession) return;
|
||||
const pushToken = readDevicePushToken(body);
|
||||
if (!pushToken) return;
|
||||
|
||||
const device = await storage.getDevice(userId, deviceSession.identifier);
|
||||
if (!device) return;
|
||||
|
||||
const pushUuid = device.pushUuid || generateUUID();
|
||||
await storage.updateDevicePushToken(userId, deviceSession.identifier, pushUuid, pushToken);
|
||||
const registered = await registerMobilePushDevice(env, {
|
||||
userId,
|
||||
deviceIdentifier: deviceSession.identifier,
|
||||
type: device.type || deviceType,
|
||||
pushUuid,
|
||||
pushToken,
|
||||
});
|
||||
console.info('Mobile push token updated from identity token request', {
|
||||
userId,
|
||||
deviceIdentifier: deviceSession.identifier,
|
||||
deviceType: device.type || deviceType,
|
||||
pushUuid,
|
||||
pushTokenLength: pushToken.length,
|
||||
relayRegistered: registered,
|
||||
});
|
||||
}
|
||||
|
||||
function shouldUseWebSession(request: Request): boolean {
|
||||
return String(request.headers.get('X-NodeWarden-Web-Session') || '').trim() === '1';
|
||||
}
|
||||
@@ -76,6 +117,14 @@ function constantTimeEquals(a: string, b: string): boolean {
|
||||
return diff === 0;
|
||||
}
|
||||
|
||||
function readBodyValue(body: Record<string, string>, names: string[]): string | undefined {
|
||||
for (const name of names) {
|
||||
const value = body[name];
|
||||
if (value != null) return value;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function buildRefreshCookie(request: Request, refreshToken: string, maxAgeSeconds: number): string {
|
||||
const isHttps = new URL(request.url).protocol === 'https:';
|
||||
const parts = [
|
||||
@@ -130,19 +179,32 @@ function buildPreloginResponse(
|
||||
};
|
||||
}
|
||||
|
||||
function twoFactorRequiredResponse(message: string = 'Two factor required.', includeRecoveryCode: boolean = false): Response {
|
||||
const providers = includeRecoveryCode
|
||||
? [String(TWO_FACTOR_PROVIDER_AUTHENTICATOR), TWO_FACTOR_PROVIDER_RECOVERY_CODE_RESPONSE]
|
||||
: [String(TWO_FACTOR_PROVIDER_AUTHENTICATOR)];
|
||||
const providers2: Record<string, null> = {};
|
||||
for (const provider of providers) providers2[provider] = null;
|
||||
function masterPasswordPolicyResponse(): TokenResponse['MasterPasswordPolicy'] {
|
||||
return {
|
||||
minComplexity: 0,
|
||||
minLength: 0,
|
||||
requireUpper: false,
|
||||
requireLower: false,
|
||||
requireNumbers: false,
|
||||
requireSpecial: false,
|
||||
enforceOnLogin: false,
|
||||
Object: 'masterPasswordPolicy',
|
||||
object: 'masterPasswordPolicy',
|
||||
};
|
||||
}
|
||||
|
||||
function twoFactorRequiredResponse(message: string = 'Two factor required.'): Response {
|
||||
// Match Bitwarden Identity: TwoFactorProviders2 lists enabled 2FA providers only.
|
||||
// Clients expose recovery-code entry points themselves; Android 2026.4 fails to
|
||||
// parse the challenge if an unknown recovery provider key such as "8" is included.
|
||||
const providers = [String(TWO_FACTOR_PROVIDER_AUTHENTICATOR)];
|
||||
const providers2: Record<string, { Email: null }> = {};
|
||||
for (const provider of providers) providers2[provider] = { Email: null };
|
||||
const customResponse = {
|
||||
TwoFactorProviders: providers,
|
||||
TwoFactorProviders2: providers2,
|
||||
SsoEmail2faSessionToken: null,
|
||||
MasterPasswordPolicy: {
|
||||
Object: 'masterPasswordPolicy',
|
||||
},
|
||||
MasterPasswordPolicy: masterPasswordPolicyResponse(),
|
||||
};
|
||||
|
||||
// Bitwarden clients rely on these fields to trigger the 2FA UI flow.
|
||||
@@ -228,9 +290,10 @@ export async function handleToken(request: Request, env: Env): Promise<Response>
|
||||
// Login with password
|
||||
const email = body.username?.toLowerCase();
|
||||
const passwordHash = body.password;
|
||||
const twoFactorToken = body.twoFactorToken;
|
||||
const twoFactorProvider = body.twoFactorProvider;
|
||||
const twoFactorRemember = body.twoFactorRemember;
|
||||
const authRequestId = readBodyValue(body, ['authRequest', 'AuthRequest']);
|
||||
const twoFactorToken = readBodyValue(body, ['twoFactorToken', 'TwoFactorToken']);
|
||||
const twoFactorProvider = readBodyValue(body, ['twoFactorProvider', 'TwoFactorProvider']);
|
||||
const twoFactorRemember = readBodyValue(body, ['twoFactorRemember', 'TwoFactorRemember']);
|
||||
const loginIdentifier = clientIdentifier;
|
||||
const deviceInfo = readAuthRequestDeviceInfo(body, request);
|
||||
|
||||
@@ -272,11 +335,31 @@ export async function handleToken(request: Request, env: Env): Promise<Response>
|
||||
return identityErrorResponse('Account is disabled', 'invalid_grant', 400);
|
||||
}
|
||||
|
||||
const valid = await auth.verifyPassword(passwordHash, user.masterPasswordHash, user.email);
|
||||
let validatedAuthRequestId: string | null = null;
|
||||
let valid = false;
|
||||
const normalizedAuthRequestId = String(authRequestId || '').trim();
|
||||
if (normalizedAuthRequestId) {
|
||||
const authRequest = await storage.getAuthRequestById(normalizedAuthRequestId);
|
||||
valid = !!(
|
||||
authRequest &&
|
||||
authRequest.userId === user.id &&
|
||||
authRequest.type === 0 &&
|
||||
authRequest.approved === true &&
|
||||
authRequest.responseDate &&
|
||||
!authRequest.authenticationDate &&
|
||||
!isAuthRequestExpired(authRequest) &&
|
||||
constantTimeEquals(authRequest.accessCode, passwordHash)
|
||||
);
|
||||
if (valid) {
|
||||
validatedAuthRequestId = authRequest!.id;
|
||||
}
|
||||
} else {
|
||||
valid = await auth.verifyPassword(passwordHash, user.masterPasswordHash, user.email);
|
||||
}
|
||||
if (!valid) {
|
||||
await safeWriteAuditEvent(env, {
|
||||
actorUserId: user.id,
|
||||
action: 'auth.login.failed.bad_password',
|
||||
action: normalizedAuthRequestId ? 'auth.login.failed.bad_auth_request' : 'auth.login.failed.bad_password',
|
||||
category: 'auth',
|
||||
level: 'warn',
|
||||
targetType: 'user',
|
||||
@@ -298,7 +381,6 @@ export async function handleToken(request: Request, env: Env): Promise<Response>
|
||||
let trustedTwoFactorTokenToReturn: string | undefined;
|
||||
const effectiveTotpSecret = resolveTotpSecret(user.totpSecret);
|
||||
if (effectiveTotpSecret) {
|
||||
const canUseRecoveryCode = !!user.totpRecoveryCode;
|
||||
const normalizedTwoFactorProvider = String(twoFactorProvider ?? '').trim();
|
||||
const normalizedTwoFactorToken = String(twoFactorToken ?? '').trim();
|
||||
let rememberRequested = ['1', 'true', 'True', 'TRUE', 'on', 'yes', 'Yes', 'YES'].includes(String(twoFactorRemember || '').trim());
|
||||
@@ -308,7 +390,7 @@ export async function handleToken(request: Request, env: Env): Promise<Response>
|
||||
// Upstream-compatible behavior: if 2FA is required and either provider or token is missing,
|
||||
// respond with a 2FA challenge payload.
|
||||
if (!hasProvider || !hasToken) {
|
||||
return twoFactorRequiredResponse('Two factor required.', canUseRecoveryCode);
|
||||
return twoFactorRequiredResponse('Two factor required.');
|
||||
}
|
||||
|
||||
let passedByRememberToken = false;
|
||||
@@ -323,7 +405,7 @@ export async function handleToken(request: Request, env: Env): Promise<Response>
|
||||
|
||||
// Remember token missing/invalid/expired should re-enter the 2FA challenge flow.
|
||||
if (!passedByRememberToken) {
|
||||
return twoFactorRequiredResponse('Two factor required.', canUseRecoveryCode);
|
||||
return twoFactorRequiredResponse('Two factor required.');
|
||||
}
|
||||
} else if (normalizedTwoFactorProvider === String(TWO_FACTOR_PROVIDER_AUTHENTICATOR)) {
|
||||
const totpOk = await verifyTotpToken(effectiveTotpSecret, normalizedTwoFactorToken);
|
||||
@@ -332,7 +414,7 @@ export async function handleToken(request: Request, env: Env): Promise<Response>
|
||||
}
|
||||
} else if (
|
||||
normalizedTwoFactorProvider === TWO_FACTOR_PROVIDER_RECOVERY_CODE_RESPONSE ||
|
||||
normalizedTwoFactorProvider === String(TWO_FACTOR_PROVIDER_RECOVERY_CODE_LEGACY) ||
|
||||
normalizedTwoFactorProvider === String(TWO_FACTOR_PROVIDER_RECOVERY_CODE) ||
|
||||
normalizedTwoFactorProvider === String(TWO_FACTOR_PROVIDER_RECOVERY_CODE_ANDROID_REQUEST)
|
||||
) {
|
||||
if (!recoveryCodeEquals(normalizedTwoFactorToken, user.totpRecoveryCode)) {
|
||||
@@ -371,10 +453,14 @@ export async function handleToken(request: Request, env: Env): Promise<Response>
|
||||
deviceInfo.deviceType,
|
||||
deviceSession.sessionStamp
|
||||
);
|
||||
await persistIdentityDevicePushToken(env, storage, user.id, deviceSession, deviceInfo.deviceType, body);
|
||||
}
|
||||
|
||||
// Successful login - clear failed attempts
|
||||
await rateLimit.clearLoginAttempts(loginIdentifier);
|
||||
if (validatedAuthRequestId) {
|
||||
await storage.markAuthRequestAuthenticated(validatedAuthRequestId);
|
||||
}
|
||||
|
||||
const accessToken = await auth.generateAccessToken(user, deviceSession);
|
||||
const refreshToken = await auth.generateRefreshToken(user.id, deviceSession);
|
||||
@@ -412,9 +498,7 @@ export async function handleToken(request: Request, env: Env): Promise<Response>
|
||||
KdfParallelism: user.kdfParallelism,
|
||||
ForcePasswordReset: false,
|
||||
ResetMasterPassword: false,
|
||||
MasterPasswordPolicy: {
|
||||
Object: 'masterPasswordPolicy',
|
||||
},
|
||||
MasterPasswordPolicy: masterPasswordPolicyResponse(),
|
||||
ApiUseKeyConnector: false,
|
||||
scope: 'api offline_access',
|
||||
unofficialServer: true,
|
||||
@@ -492,6 +576,7 @@ export async function handleToken(request: Request, env: Env): Promise<Response>
|
||||
deviceInfo.deviceType,
|
||||
deviceSession.sessionStamp
|
||||
);
|
||||
await persistIdentityDevicePushToken(env, storage, user.id, deviceSession, deviceInfo.deviceType, body);
|
||||
}
|
||||
|
||||
await rateLimit.clearLoginAttempts(loginIdentifier);
|
||||
@@ -532,9 +617,7 @@ export async function handleToken(request: Request, env: Env): Promise<Response>
|
||||
KdfParallelism: user.kdfParallelism,
|
||||
ForcePasswordReset: false,
|
||||
ResetMasterPassword: false,
|
||||
MasterPasswordPolicy: {
|
||||
Object: 'masterPasswordPolicy',
|
||||
},
|
||||
MasterPasswordPolicy: masterPasswordPolicyResponse(),
|
||||
ApiUseKeyConnector: false,
|
||||
scope: 'api offline_access',
|
||||
unofficialServer: true,
|
||||
@@ -622,6 +705,7 @@ export async function handleToken(request: Request, env: Env): Promise<Response>
|
||||
deviceInfo.deviceType,
|
||||
deviceSession.sessionStamp
|
||||
);
|
||||
await persistIdentityDevicePushToken(env, storage, user.id, deviceSession, deviceInfo.deviceType, body);
|
||||
}
|
||||
|
||||
// Successful login - clear failed attempts
|
||||
@@ -662,9 +746,7 @@ export async function handleToken(request: Request, env: Env): Promise<Response>
|
||||
KdfParallelism: user.kdfParallelism,
|
||||
ForcePasswordReset: false,
|
||||
ResetMasterPassword: false,
|
||||
MasterPasswordPolicy: {
|
||||
Object: 'masterPasswordPolicy',
|
||||
},
|
||||
MasterPasswordPolicy: masterPasswordPolicyResponse(),
|
||||
ApiUseKeyConnector: false,
|
||||
scope: 'api offline_access',
|
||||
unofficialServer: true,
|
||||
@@ -802,9 +884,7 @@ export async function handleToken(request: Request, env: Env): Promise<Response>
|
||||
KdfParallelism: user.kdfParallelism,
|
||||
ForcePasswordReset: false,
|
||||
ResetMasterPassword: false,
|
||||
MasterPasswordPolicy: {
|
||||
Object: 'masterPasswordPolicy',
|
||||
},
|
||||
MasterPasswordPolicy: masterPasswordPolicyResponse(),
|
||||
ApiUseKeyConnector: false,
|
||||
scope: 'api offline_access',
|
||||
unofficialServer: true,
|
||||
|
||||
@@ -5,7 +5,7 @@ import { errorResponse, jsonResponse } from '../utils/response';
|
||||
import { readActingDeviceIdentifier } from '../utils/device';
|
||||
import { generateUUID } from '../utils/uuid';
|
||||
import { LIMITS } from '../config/limits';
|
||||
import { normalizeCipherLoginForStorage, normalizeCipherSshKeyForCompatibility } from './ciphers';
|
||||
import { normalizeCipherLoginForStorage, normalizeCipherSshKeyForCompatibility, validateCipherEncryptedFieldsForCompatibility } from './ciphers';
|
||||
|
||||
// Bitwarden client import request format
|
||||
interface CiphersImportRequest {
|
||||
@@ -252,6 +252,10 @@ export async function handleCiphersImport(request: Request, env: Env, userId: st
|
||||
deletedAt: null,
|
||||
};
|
||||
cipher.login = normalizeCipherLoginForStorage(cipher.login);
|
||||
const compatibilityError = validateCipherEncryptedFieldsForCompatibility(cipher);
|
||||
if (compatibilityError) {
|
||||
return errorResponse(`Cipher ${i + 1}: ${compatibilityError}`, 400);
|
||||
}
|
||||
|
||||
cipherRows.push(cipher);
|
||||
cipherMapRows.push({ index: i, sourceId, id: cipher.id });
|
||||
|
||||
@@ -56,3 +56,18 @@ export async function handleNotificationsHub(request: Request, env: Env): Promis
|
||||
}
|
||||
return stub.fetch(new Request(forwardedUrl.toString(), request));
|
||||
}
|
||||
|
||||
export async function handleAnonymousNotificationsHub(request: Request, env: Env): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
const authRequestId = String(url.searchParams.get('Token') || url.searchParams.get('token') || '').trim();
|
||||
if (!authRequestId) return errorResponse('Token is required', 400);
|
||||
if (request.headers.get('Upgrade')?.toLowerCase() !== 'websocket') {
|
||||
return errorResponse('Expected websocket', 426);
|
||||
}
|
||||
|
||||
const id = env.NOTIFICATIONS_HUB.idFromName(authRequestId);
|
||||
const stub = env.NOTIFICATIONS_HUB.get(id);
|
||||
const forwardedUrl = new URL(request.url);
|
||||
forwardedUrl.searchParams.set('nw_auth_request_id', authRequestId);
|
||||
return stub.fetch(new Request(forwardedUrl.toString(), request));
|
||||
}
|
||||
|
||||
@@ -16,6 +16,9 @@ import {
|
||||
formatSize,
|
||||
getAliasedProp,
|
||||
normalizeEmails,
|
||||
notifySendCreateForRequest,
|
||||
notifySendDeleteForRequest,
|
||||
notifySendUpdateForRequest,
|
||||
notifyVaultSyncForRequest,
|
||||
parseDate,
|
||||
parseFileLength,
|
||||
@@ -99,6 +102,7 @@ async function processSendFileUpload(
|
||||
const storage = new StorageService(env.DB);
|
||||
const revisionDate = await storage.updateRevisionDate(send.userId);
|
||||
notifyVaultSyncForRequest(request, env, send.userId, revisionDate);
|
||||
notifySendUpdateForRequest(request, env, send.id, send.userId, revisionDate);
|
||||
|
||||
return new Response(null, { status: 201 });
|
||||
}
|
||||
@@ -249,6 +253,7 @@ export async function handleCreateSend(request: Request, env: Env, userId: strin
|
||||
await storage.saveSend(send);
|
||||
const revisionDate = await storage.updateRevisionDate(userId);
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifySendCreateForRequest(request, env, send.id, userId, revisionDate);
|
||||
|
||||
return jsonResponse(sendToResponse(send));
|
||||
}
|
||||
@@ -372,6 +377,7 @@ export async function handleCreateFileSendV2(request: Request, env: Env, userId:
|
||||
await storage.saveSend(send);
|
||||
const revisionDate = await storage.updateRevisionDate(userId);
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifySendCreateForRequest(request, env, send.id, userId, revisionDate);
|
||||
const jwtSecret = getSafeJwtSecret(env);
|
||||
if (!jwtSecret) {
|
||||
return errorResponse('Server configuration error', 500);
|
||||
@@ -619,6 +625,7 @@ export async function handleUpdateSend(request: Request, env: Env, userId: strin
|
||||
await storage.saveSend(send);
|
||||
const revisionDate = await storage.updateRevisionDate(userId);
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifySendUpdateForRequest(request, env, send.id, userId, revisionDate);
|
||||
|
||||
return jsonResponse(sendToResponse(send));
|
||||
}
|
||||
@@ -641,6 +648,7 @@ export async function handleDeleteSend(request: Request, env: Env, userId: strin
|
||||
await storage.deleteSend(sendId, userId);
|
||||
const revisionDate = await storage.updateRevisionDate(userId);
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifySendDeleteForRequest(request, env, sendId, userId, revisionDate);
|
||||
await writeSendAudit(storage, request, userId, 'send.delete', {
|
||||
id: sendId,
|
||||
type: send.type,
|
||||
@@ -676,6 +684,9 @@ export async function handleBulkDeleteSends(request: Request, env: Env, userId:
|
||||
const revisionDate = await storage.bulkDeleteSends(body.ids, userId);
|
||||
if (revisionDate) {
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
for (const send of sends) {
|
||||
notifySendDeleteForRequest(request, env, send.id, userId, revisionDate);
|
||||
}
|
||||
await writeSendAudit(storage, request, userId, 'send.delete.bulk', {
|
||||
count: sends.length,
|
||||
requestedCount: body.ids.length,
|
||||
@@ -697,6 +708,7 @@ export async function handleRemoveSendPassword(request: Request, env: Env, userI
|
||||
await storage.saveSend(send);
|
||||
const revisionDate = await storage.updateRevisionDate(userId);
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifySendUpdateForRequest(request, env, send.id, userId, revisionDate);
|
||||
await writeSendAudit(storage, request, userId, 'send.password.remove', {
|
||||
id: send.id,
|
||||
type: send.type,
|
||||
@@ -718,6 +730,7 @@ export async function handleRemoveSendAuth(request: Request, env: Env, userId: s
|
||||
await storage.saveSend(send);
|
||||
const revisionDate = await storage.updateRevisionDate(userId);
|
||||
notifyVaultSyncForRequest(request, env, userId, revisionDate);
|
||||
notifySendUpdateForRequest(request, env, send.id, userId, revisionDate);
|
||||
await writeSendAudit(storage, request, userId, 'send.auth.remove', {
|
||||
id: send.id,
|
||||
type: send.type,
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
getSafeJwtSecret,
|
||||
hasEmailAuth,
|
||||
isSendAvailable,
|
||||
notifySendUpdateForRequest,
|
||||
notifyVaultSyncForRequest,
|
||||
parseStoredSendData,
|
||||
resolveSendFromIdOrAccessId,
|
||||
@@ -33,6 +34,14 @@ import {
|
||||
verifySendPasswordHashB64,
|
||||
} from './sends-shared';
|
||||
|
||||
function contentDispositionAttachment(fileName: string | null | undefined): string {
|
||||
const fallback = 'send-file';
|
||||
const value = String(fileName || fallback)
|
||||
.replace(/[\r\n"]/g, '_')
|
||||
.trim() || fallback;
|
||||
return `attachment; filename="${value}"`;
|
||||
}
|
||||
|
||||
export async function handleAccessSend(request: Request, env: Env, accessId: string): Promise<Response> {
|
||||
const storage = new StorageService(env.DB);
|
||||
const sendId = fromAccessId(accessId);
|
||||
@@ -90,6 +99,7 @@ export async function handleAccessSend(request: Request, env: Env, accessId: str
|
||||
send.accessCount += 1;
|
||||
const revisionDate = await storage.updateRevisionDate(send.userId);
|
||||
notifyVaultSyncForRequest(request, env, send.userId, revisionDate);
|
||||
notifySendUpdateForRequest(request, env, send.id, send.userId, revisionDate);
|
||||
}
|
||||
|
||||
const creatorIdentifier = await getCreatorIdentifier(storage, send);
|
||||
@@ -163,6 +173,7 @@ export async function handleAccessSendFile(
|
||||
send.accessCount += 1;
|
||||
const revisionDate = await storage.updateRevisionDate(send.userId);
|
||||
notifyVaultSyncForRequest(request, env, send.userId, revisionDate);
|
||||
notifySendUpdateForRequest(request, env, send.id, send.userId, revisionDate);
|
||||
|
||||
const token = await createSendFileDownloadToken(send.id, fileId, secret);
|
||||
const url = new URL(request.url);
|
||||
@@ -203,6 +214,7 @@ export async function handleAccessSendV2(request: Request, env: Env): Promise<Re
|
||||
send.accessCount += 1;
|
||||
const revisionDate = await storage.updateRevisionDate(send.userId);
|
||||
notifyVaultSyncForRequest(request, env, send.userId, revisionDate);
|
||||
notifySendUpdateForRequest(request, env, send.id, send.userId, revisionDate);
|
||||
}
|
||||
|
||||
const creatorIdentifier = await getCreatorIdentifier(storage, send);
|
||||
@@ -242,6 +254,7 @@ export async function handleAccessSendFileV2(request: Request, env: Env, fileId:
|
||||
send.accessCount += 1;
|
||||
const revisionDate = await storage.updateRevisionDate(send.userId);
|
||||
notifyVaultSyncForRequest(request, env, send.userId, revisionDate);
|
||||
notifySendUpdateForRequest(request, env, send.id, send.userId, revisionDate);
|
||||
|
||||
const downloadToken = await createSendFileDownloadToken(send.id, fileId, jwt.secret);
|
||||
const url = new URL(request.url);
|
||||
@@ -282,6 +295,9 @@ export async function handleDownloadSendFile(
|
||||
if (!object) {
|
||||
return errorResponse('Send file not found', 404);
|
||||
}
|
||||
const send = await storage.getSend(sendId);
|
||||
const data = send ? parseStoredSendData(send) : {};
|
||||
const fileName = typeof data.fileName === 'string' ? data.fileName : fileId;
|
||||
|
||||
const firstUse = await storage.consumeAttachmentDownloadToken(`send:${claims.jti}`, claims.exp);
|
||||
if (!firstUse) {
|
||||
@@ -292,7 +308,9 @@ export async function handleDownloadSendFile(
|
||||
headers: {
|
||||
'Content-Type': object.contentType || 'application/octet-stream',
|
||||
'Content-Length': String(object.size),
|
||||
'Content-Disposition': contentDispositionAttachment(fileName),
|
||||
'Cache-Control': 'private, no-cache',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { Env, Send, SendAuthType, SendResponse, SendType, DEFAULT_DEV_SECRET } from '../types';
|
||||
import { notifyUserVaultSync } from '../durable/notifications-hub';
|
||||
import {
|
||||
notifyUserSendCreate,
|
||||
notifyUserSendDelete,
|
||||
notifyUserSendUpdate,
|
||||
notifyUserVaultSync,
|
||||
} from '../durable/notifications-hub';
|
||||
import { StorageService } from '../services/storage';
|
||||
import { jsonResponse, errorResponse } from '../utils/response';
|
||||
import { readActingDeviceIdentifier } from '../utils/device';
|
||||
@@ -18,6 +23,51 @@ export function notifyVaultSyncForRequest(
|
||||
notifyUserVaultSync(env, userId, revisionDate, readActingDeviceIdentifier(request));
|
||||
}
|
||||
|
||||
export function notifySendCreateForRequest(
|
||||
request: Request,
|
||||
env: Env,
|
||||
sendId: string,
|
||||
userId: string,
|
||||
revisionDate: string
|
||||
): void {
|
||||
notifyUserSendCreate(env, {
|
||||
userId,
|
||||
sendId,
|
||||
revisionDate,
|
||||
contextId: readActingDeviceIdentifier(request),
|
||||
});
|
||||
}
|
||||
|
||||
export function notifySendUpdateForRequest(
|
||||
request: Request,
|
||||
env: Env,
|
||||
sendId: string,
|
||||
userId: string,
|
||||
revisionDate: string
|
||||
): void {
|
||||
notifyUserSendUpdate(env, {
|
||||
userId,
|
||||
sendId,
|
||||
revisionDate,
|
||||
contextId: readActingDeviceIdentifier(request),
|
||||
});
|
||||
}
|
||||
|
||||
export function notifySendDeleteForRequest(
|
||||
request: Request,
|
||||
env: Env,
|
||||
sendId: string,
|
||||
userId: string,
|
||||
revisionDate: string
|
||||
): void {
|
||||
notifyUserSendDelete(env, {
|
||||
userId,
|
||||
sendId,
|
||||
revisionDate,
|
||||
contextId: readActingDeviceIdentifier(request),
|
||||
});
|
||||
}
|
||||
|
||||
export function getAliasedProp(source: unknown, aliases: string[]): { present: boolean; value: unknown } {
|
||||
if (!source || typeof source !== 'object') return { present: false, value: undefined };
|
||||
for (const key of aliases) {
|
||||
|
||||
@@ -5,12 +5,12 @@ import { cipherToResponse, isCipherResponseSyncCompatible, shouldPreserveRepaira
|
||||
import { sendToResponse } from './sends';
|
||||
import { LIMITS } from '../config/limits';
|
||||
import {
|
||||
buildAccountKeys,
|
||||
buildUserDecryptionCompat,
|
||||
buildUserDecryptionOptions,
|
||||
} from '../utils/user-decryption';
|
||||
import { buildDomainsResponse } from '../services/domain-rules';
|
||||
import { buildWebAuthnPrfOption } from '../utils/account-passkeys';
|
||||
import { buildProfileResponse } from '../utils/profile-response';
|
||||
|
||||
// CONTRACT:
|
||||
// /api/sync reuses cipherToResponse() as the single cipher response shaper.
|
||||
@@ -84,36 +84,12 @@ export async function handleSync(request: Request, env: Env, userId: string): Pr
|
||||
storage.getAttachmentsByUserId(userId),
|
||||
excludeDomains ? Promise.resolve(null) : storage.getUserDomainSettings(userId),
|
||||
]);
|
||||
const accountKeys = buildAccountKeys(user);
|
||||
const webAuthnPrfOptions = accountPasskeys
|
||||
.map(buildWebAuthnPrfOption)
|
||||
.filter((option): option is NonNullable<typeof option> => !!option);
|
||||
const userDecryptionOptions = buildUserDecryptionOptions(user, webAuthnPrfOptions[0] || null);
|
||||
|
||||
const profile: ProfileResponse = {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
emailVerified: true,
|
||||
premium: true,
|
||||
premiumFromOrganization: false,
|
||||
usesKeyConnector: false,
|
||||
masterPasswordHint: user.masterPasswordHint,
|
||||
culture: 'en-US',
|
||||
twoFactorEnabled: !!user.totpSecret,
|
||||
key: user.key,
|
||||
privateKey: user.privateKey,
|
||||
accountKeys,
|
||||
securityStamp: user.securityStamp || user.id,
|
||||
organizations: [],
|
||||
providers: [],
|
||||
providerOrganizations: [],
|
||||
forcePasswordReset: false,
|
||||
avatarColor: null,
|
||||
creationDate: user.createdAt,
|
||||
verifyDevices: user.verifyDevices,
|
||||
object: 'profile',
|
||||
};
|
||||
const profile: ProfileResponse = buildProfileResponse(user, env);
|
||||
|
||||
const cipherResponses: CipherResponse[] = [];
|
||||
for (const cipher of ciphers) {
|
||||
@@ -149,6 +125,7 @@ export async function handleSync(request: Request, env: Env, userId: string): Pr
|
||||
{ omitExcludedGlobals: true }
|
||||
),
|
||||
policies: [],
|
||||
policiesNew: [],
|
||||
sends: sendResponses,
|
||||
UserDecryption: {
|
||||
MasterPasswordUnlock: userDecryptionOptions.MasterPasswordUnlock,
|
||||
@@ -156,6 +133,7 @@ export async function handleSync(request: Request, env: Env, userId: string): Pr
|
||||
KeyConnectorOption: null,
|
||||
WebAuthnPrfOption: webAuthnPrfOptions[0] || null,
|
||||
WebAuthnPrfOptions: webAuthnPrfOptions,
|
||||
V2UpgradeToken: null,
|
||||
Object: 'userDecryption',
|
||||
},
|
||||
UserDecryptionOptions: userDecryptionOptions,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { errorResponse, jsonResponse } from './utils/response';
|
||||
import {
|
||||
handleGetProfile,
|
||||
handleUpdateProfile,
|
||||
handleGetKeys,
|
||||
handleSetKeys,
|
||||
handleGetRevisionDate,
|
||||
handleVerifyPassword,
|
||||
@@ -11,6 +12,10 @@ import {
|
||||
handleGetTotpStatus,
|
||||
handleSetTotpStatus,
|
||||
handleGetTotpRecoveryCode,
|
||||
handleGetTwoFactorProviders,
|
||||
handleGetTwoFactorAuthenticator,
|
||||
handlePutTwoFactorAuthenticator,
|
||||
handleDisableTwoFactorProvider,
|
||||
handleGetApiKey,
|
||||
handleRotateApiKey,
|
||||
} from './handlers/accounts';
|
||||
@@ -74,6 +79,12 @@ import {
|
||||
handleGetAccountPasskeyUpdateAssertionOptions,
|
||||
handleUpdateAccountPasskeyEncryption,
|
||||
} from './handlers/account-passkeys';
|
||||
import {
|
||||
handleGetAuthRequest,
|
||||
handleListAuthRequests,
|
||||
handleListPendingAuthRequests,
|
||||
handleUpdateAuthRequest,
|
||||
} from './handlers/auth-requests';
|
||||
|
||||
export async function handleAuthenticatedRoute(
|
||||
request: Request,
|
||||
@@ -105,8 +116,10 @@ export async function handleAuthenticatedRoute(
|
||||
return handleChangePassword(request, env, userId);
|
||||
}
|
||||
|
||||
if (path === '/api/accounts/keys' && method === 'POST') {
|
||||
return handleSetKeys(request, env, userId);
|
||||
if (path === '/api/accounts/keys') {
|
||||
if (method === 'GET') return handleGetKeys(request, env, userId);
|
||||
if (method === 'POST') return handleSetKeys(request, env, userId);
|
||||
return errorResponse('Method not allowed', 405);
|
||||
}
|
||||
|
||||
if (path === '/api/accounts/totp') {
|
||||
@@ -119,6 +132,25 @@ export async function handleAuthenticatedRoute(
|
||||
return handleGetTotpRecoveryCode(request, env, userId);
|
||||
}
|
||||
|
||||
if (path === '/api/two-factor') {
|
||||
if (method === 'GET') return handleGetTwoFactorProviders(request, env, userId);
|
||||
return errorResponse('Method not allowed', 405);
|
||||
}
|
||||
|
||||
if (path === '/api/two-factor/get-authenticator' && method === 'POST') {
|
||||
return handleGetTwoFactorAuthenticator(request, env, userId);
|
||||
}
|
||||
|
||||
if (path === '/api/two-factor/authenticator') {
|
||||
if (method === 'PUT' || method === 'POST') return handlePutTwoFactorAuthenticator(request, env, userId);
|
||||
if (method === 'DELETE') return handleDisableTwoFactorProvider(request, env, userId);
|
||||
return errorResponse('Method not allowed', 405);
|
||||
}
|
||||
|
||||
if (path === '/api/two-factor/disable' && (method === 'PUT' || method === 'POST')) {
|
||||
return handleDisableTwoFactorProvider(request, env, userId);
|
||||
}
|
||||
|
||||
if (path === '/api/accounts/revision-date' && method === 'GET') {
|
||||
return handleGetRevisionDate(request, env, userId);
|
||||
}
|
||||
@@ -262,8 +294,21 @@ export async function handleAuthenticatedRoute(
|
||||
if (method === 'DELETE') return handleDeleteFolder(request, env, userId, folderId);
|
||||
}
|
||||
|
||||
if (path.startsWith('/api/auth-requests')) {
|
||||
return jsonResponse({ data: [], object: 'list', continuationToken: null });
|
||||
if (path === '/api/auth-requests' || path === '/api/auth-requests/') {
|
||||
if (method === 'GET') return handleListAuthRequests(request, env, userId);
|
||||
return errorResponse('Method not allowed', 405);
|
||||
}
|
||||
|
||||
if (path === '/api/auth-requests/pending') {
|
||||
if (method === 'GET') return handleListPendingAuthRequests(request, env, userId);
|
||||
return errorResponse('Method not allowed', 405);
|
||||
}
|
||||
|
||||
const authRequestMatch = path.match(/^\/api\/auth-requests\/([a-f0-9-]+)$/i);
|
||||
if (authRequestMatch) {
|
||||
if (method === 'GET') return handleGetAuthRequest(request, env, userId, authRequestMatch[1]);
|
||||
if (method === 'PUT') return handleUpdateAuthRequest(request, env, userId, authRequestMatch[1]);
|
||||
return errorResponse('Method not allowed', 405);
|
||||
}
|
||||
|
||||
if (path === '/api/collections' || path.startsWith('/api/collections/')) {
|
||||
|
||||
@@ -20,6 +20,10 @@ import {
|
||||
handleClearDeviceToken,
|
||||
} from './handlers/devices';
|
||||
|
||||
function devicesPath(pattern: string): RegExp {
|
||||
return new RegExp(`^/(?:api/)?devices${pattern}$`, 'i');
|
||||
}
|
||||
|
||||
export async function handleAuthenticatedDeviceRoute(
|
||||
request: Request,
|
||||
env: Env,
|
||||
@@ -27,31 +31,31 @@ export async function handleAuthenticatedDeviceRoute(
|
||||
path: string,
|
||||
method: string
|
||||
): Promise<Response | null> {
|
||||
if (path === '/api/devices') {
|
||||
if (path === '/api/devices' || path === '/devices') {
|
||||
if (method === 'GET') return handleGetDevices(request, env, userId);
|
||||
if (method === 'DELETE') return handleDeleteAllDevices(request, env, userId);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (path === '/api/devices/authorized') {
|
||||
if (path === '/api/devices/authorized' || path === '/devices/authorized') {
|
||||
if (method === 'GET') return handleGetAuthorizedDevices(request, env, userId);
|
||||
if (method === 'DELETE') return handleRevokeAllTrustedDevices(request, env, userId);
|
||||
return null;
|
||||
}
|
||||
|
||||
const authorizedDeviceMatch = path.match(/^\/api\/devices\/authorized\/([^/]+)$/i);
|
||||
const authorizedDeviceMatch = path.match(devicesPath('/authorized/([^/]+)'));
|
||||
if (authorizedDeviceMatch && method === 'DELETE') {
|
||||
const deviceIdentifier = decodeURIComponent(authorizedDeviceMatch[1]);
|
||||
return handleRevokeTrustedDevice(request, env, userId, deviceIdentifier);
|
||||
}
|
||||
|
||||
const permanentAuthorizedDeviceMatch = path.match(/^\/api\/devices\/authorized\/([^/]+)\/permanent$/i);
|
||||
const permanentAuthorizedDeviceMatch = path.match(devicesPath('/authorized/([^/]+)/permanent'));
|
||||
if (permanentAuthorizedDeviceMatch && method === 'POST') {
|
||||
const deviceIdentifier = decodeURIComponent(permanentAuthorizedDeviceMatch[1]);
|
||||
return handleTrustDevicePermanently(request, env, userId, deviceIdentifier);
|
||||
}
|
||||
|
||||
const deleteDeviceMatch = path.match(/^\/api\/devices\/([^/]+)$/i);
|
||||
const deleteDeviceMatch = path.match(devicesPath('/([^/]+)'));
|
||||
if (deleteDeviceMatch && method === 'GET') {
|
||||
const deviceIdentifier = decodeURIComponent(deleteDeviceMatch[1]);
|
||||
return handleGetDevice(request, env, userId, deviceIdentifier);
|
||||
@@ -61,59 +65,59 @@ export async function handleAuthenticatedDeviceRoute(
|
||||
return handleDeleteDevice(request, env, userId, deviceIdentifier);
|
||||
}
|
||||
|
||||
const updateDeviceNameMatch = path.match(/^\/api\/devices\/([^/]+)\/name$/i);
|
||||
const updateDeviceNameMatch = path.match(devicesPath('/([^/]+)/name'));
|
||||
if (updateDeviceNameMatch && method === 'PUT') {
|
||||
const deviceIdentifier = decodeURIComponent(updateDeviceNameMatch[1]);
|
||||
return handleUpdateDeviceName(request, env, userId, deviceIdentifier);
|
||||
}
|
||||
|
||||
const identifierMatch = path.match(/^\/api\/devices\/identifier\/([^/]+)$/i);
|
||||
const identifierMatch = path.match(devicesPath('/identifier/([^/]+)'));
|
||||
if (identifierMatch && method === 'GET') {
|
||||
const deviceIdentifier = decodeURIComponent(identifierMatch[1]);
|
||||
return handleGetDeviceByIdentifier(request, env, userId, deviceIdentifier);
|
||||
}
|
||||
|
||||
const deviceKeysMatch = path.match(/^\/api\/devices\/([^/]+)\/keys$/i) || path.match(/^\/api\/devices\/identifier\/([^/]+)\/keys$/i);
|
||||
const deviceKeysMatch = path.match(devicesPath('/([^/]+)/keys')) || path.match(devicesPath('/identifier/([^/]+)/keys'));
|
||||
if (deviceKeysMatch && (method === 'PUT' || method === 'POST')) {
|
||||
const deviceIdentifier = decodeURIComponent(deviceKeysMatch[1]);
|
||||
return handleUpdateDeviceKeys(request, env, userId, deviceIdentifier);
|
||||
}
|
||||
|
||||
const identifierTokenMatch = path.match(/^\/api\/devices\/identifier\/([^/]+)\/token$/i);
|
||||
const identifierTokenMatch = path.match(devicesPath('/identifier/([^/]+)/token'));
|
||||
if (identifierTokenMatch && (method === 'PUT' || method === 'POST')) {
|
||||
const deviceIdentifier = decodeURIComponent(identifierTokenMatch[1]);
|
||||
return handleUpdateDeviceToken(request, env, userId, deviceIdentifier);
|
||||
}
|
||||
|
||||
const identifierWebPushMatch = path.match(/^\/api\/devices\/identifier\/([^/]+)\/web-push-auth$/i);
|
||||
const identifierWebPushMatch = path.match(devicesPath('/identifier/([^/]+)/web-push-auth'));
|
||||
if (identifierWebPushMatch && (method === 'PUT' || method === 'POST')) {
|
||||
const deviceIdentifier = decodeURIComponent(identifierWebPushMatch[1]);
|
||||
return handleUpdateDeviceWebPushAuth(request, env, userId, deviceIdentifier);
|
||||
}
|
||||
|
||||
const identifierClearTokenMatch = path.match(/^\/api\/devices\/identifier\/([^/]+)\/clear-token$/i);
|
||||
const identifierClearTokenMatch = path.match(devicesPath('/identifier/([^/]+)/clear-token'));
|
||||
if (identifierClearTokenMatch && (method === 'PUT' || method === 'POST')) {
|
||||
const deviceIdentifier = decodeURIComponent(identifierClearTokenMatch[1]);
|
||||
return handleClearDeviceToken(request, env, userId, deviceIdentifier);
|
||||
}
|
||||
|
||||
const identifierRetrieveKeysMatch = path.match(/^\/api\/devices\/([^/]+)\/retrieve-keys$/i);
|
||||
const identifierRetrieveKeysMatch = path.match(devicesPath('/([^/]+)/retrieve-keys'));
|
||||
if (identifierRetrieveKeysMatch && method === 'POST') {
|
||||
const deviceIdentifier = decodeURIComponent(identifierRetrieveKeysMatch[1]);
|
||||
return handleRetrieveDeviceKeys(request, env, userId, deviceIdentifier);
|
||||
}
|
||||
|
||||
const identifierDeactivateMatch = path.match(/^\/api\/devices\/([^/]+)\/deactivate$/i);
|
||||
const identifierDeactivateMatch = path.match(devicesPath('/([^/]+)/deactivate'));
|
||||
if (identifierDeactivateMatch && (method === 'POST' || method === 'DELETE')) {
|
||||
const deviceIdentifier = decodeURIComponent(identifierDeactivateMatch[1]);
|
||||
return handleDeactivateDevice(request, env, userId, deviceIdentifier);
|
||||
}
|
||||
|
||||
if (path === '/api/devices/update-trust' && method === 'POST') {
|
||||
if ((path === '/api/devices/update-trust' || path === '/devices/update-trust') && method === 'POST') {
|
||||
return handleUpdateDeviceTrust(request, env, userId);
|
||||
}
|
||||
|
||||
if (path === '/api/devices/untrust' && method === 'POST') {
|
||||
if ((path === '/api/devices/untrust' || path === '/devices/untrust') && method === 'POST') {
|
||||
return handleUntrustDevices(request, env, userId);
|
||||
}
|
||||
|
||||
|
||||
@@ -15,9 +15,14 @@ import {
|
||||
handleGetPasswordHint,
|
||||
handleRecoverTwoFactor,
|
||||
} from './handlers/accounts';
|
||||
import {
|
||||
handleCreateAuthRequest,
|
||||
handleGetAuthRequestResponse,
|
||||
} from './handlers/auth-requests';
|
||||
import { handlePublicDownloadAttachment } from './handlers/attachments';
|
||||
import { handlePublicUploadAttachment } from './handlers/attachments';
|
||||
import {
|
||||
handleAnonymousNotificationsHub,
|
||||
handleNotificationsHub,
|
||||
handleNotificationsNegotiate,
|
||||
} from './handlers/notifications';
|
||||
@@ -390,6 +395,19 @@ export async function handlePublicRoute(
|
||||
return handleDownloadSendFile(request, env, sendDownloadMatch[1], sendDownloadMatch[2]);
|
||||
}
|
||||
|
||||
if ((path === '/api/auth-requests' || path === '/api/auth-requests/') && method === 'POST') {
|
||||
const blocked = await enforcePublicRateLimit('public-sensitive', LIMITS.rateLimit.sensitivePublicRequestsPerMinute);
|
||||
if (blocked) return blocked;
|
||||
return handleCreateAuthRequest(request, env);
|
||||
}
|
||||
|
||||
const authRequestResponseMatch = path.match(/^\/api\/auth-requests\/([a-f0-9-]+)\/response$/i);
|
||||
if (authRequestResponseMatch && method === 'GET') {
|
||||
const blocked = await enforcePublicRateLimit('public-sensitive', LIMITS.rateLimit.sensitivePublicRequestsPerMinute);
|
||||
if (blocked) return blocked;
|
||||
return handleGetAuthRequestResponse(request, env, authRequestResponseMatch[1]);
|
||||
}
|
||||
|
||||
if (path === '/identity/connect/token' && method === 'POST') {
|
||||
return handleToken(request, env);
|
||||
}
|
||||
@@ -477,5 +495,9 @@ export async function handlePublicRoute(
|
||||
if (path === '/notifications/hub' && method === 'GET') {
|
||||
return handleNotificationsHub(request, env);
|
||||
}
|
||||
|
||||
if (path === '/notifications/anonymous-hub' && method === 'GET') {
|
||||
return handleAnonymousNotificationsHub(request, env);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -68,6 +68,7 @@ export interface BackupPayload {
|
||||
ciphers: SqlRow[];
|
||||
attachments: SqlRow[];
|
||||
webauthn_credentials?: SqlRow[];
|
||||
trusted_two_factor_device_tokens?: SqlRow[];
|
||||
};
|
||||
}
|
||||
|
||||
@@ -302,6 +303,7 @@ export function validateBackupPayloadContents(
|
||||
const cipherRows = ensureRowArray(payload.db.ciphers, 'ciphers');
|
||||
const attachmentRows = ensureRowArray(payload.db.attachments, 'attachments');
|
||||
const accountPasskeyRows = ensureRowArray(payload.db.webauthn_credentials || [], 'webauthn_credentials');
|
||||
const trustedTwoFactorTokenRows = ensureRowArray(payload.db.trusted_two_factor_device_tokens || [], 'trusted_two_factor_device_tokens');
|
||||
const externalAttachmentKeys = new Set<string>(
|
||||
options.allowExternalAttachmentBlobs
|
||||
? (payload.manifest.attachmentBlobs || []).map((item) => `attachments/${String(item.cipherId || '').trim()}/${String(item.attachmentId || '').trim()}.bin`)
|
||||
@@ -390,6 +392,21 @@ export function validateBackupPayloadContents(
|
||||
accountPasskeyIds.add(id);
|
||||
accountPasskeyCredentialIds.add(credentialId);
|
||||
}
|
||||
|
||||
const trustedTwoFactorTokens = new Set<string>();
|
||||
for (const row of trustedTwoFactorTokenRows) {
|
||||
const token = String(row.token || '').trim();
|
||||
const userId = String(row.user_id || '').trim();
|
||||
const deviceIdentifier = String(row.device_identifier || '').trim();
|
||||
const expiresAt = Number(row.expires_at || 0);
|
||||
if (!token || !userIds.has(userId) || !deviceIdentifier || !Number.isFinite(expiresAt) || expiresAt <= 0) {
|
||||
throw new Error('Backup archive contains an invalid trusted two-factor device token row');
|
||||
}
|
||||
if (trustedTwoFactorTokens.has(token)) {
|
||||
throw new Error(`Backup archive contains duplicate trusted two-factor device token: ${token}`);
|
||||
}
|
||||
trustedTwoFactorTokens.add(token);
|
||||
}
|
||||
}
|
||||
|
||||
export async function buildBackupArchive(
|
||||
@@ -408,7 +425,7 @@ export async function buildBackupArchive(
|
||||
includeAttachments,
|
||||
});
|
||||
const encoder = new TextEncoder();
|
||||
const [configRows, userRows, domainSettingsRows, revisionRows, folderRows, cipherRows, attachmentRows, accountPasskeyRows] = await Promise.all([
|
||||
const [configRows, userRows, domainSettingsRows, revisionRows, folderRows, cipherRows, attachmentRows, accountPasskeyRows, trustedTwoFactorTokenRows] = await Promise.all([
|
||||
queryRows(env.DB, 'SELECT key, value FROM config ORDER BY key ASC'),
|
||||
queryRows(env.DB, 'SELECT id, email, name, master_password_hint, master_password_hash, key, private_key, public_key, kdf_type, kdf_iterations, kdf_memory, kdf_parallelism, security_stamp, role, status, verify_devices, totp_secret, totp_recovery_code, created_at, updated_at FROM users ORDER BY created_at ASC'),
|
||||
queryRows(env.DB, 'SELECT user_id, equivalent_domains, custom_equivalent_domains, excluded_global_equivalent_domains, updated_at FROM domain_settings ORDER BY user_id ASC'),
|
||||
@@ -417,6 +434,7 @@ export async function buildBackupArchive(
|
||||
queryRows(env.DB, 'SELECT id, user_id, type, folder_id, name, notes, favorite, data, reprompt, key, created_at, updated_at, archived_at, deleted_at FROM ciphers ORDER BY created_at ASC'),
|
||||
queryRows(env.DB, 'SELECT id, cipher_id, file_name, size, size_name, key FROM attachments ORDER BY cipher_id ASC, id ASC'),
|
||||
queryRows(env.DB, 'SELECT id, user_id, name, public_key, credential_id, counter, type, aa_guid, transports, encrypted_user_key, encrypted_public_key, encrypted_private_key, supports_prf, created_at, updated_at FROM webauthn_credentials ORDER BY created_at ASC'),
|
||||
queryRows(env.DB, 'SELECT token, user_id, device_identifier, expires_at FROM trusted_two_factor_device_tokens WHERE expires_at >= ? ORDER BY user_id ASC, device_identifier ASC, expires_at DESC', date.getTime()),
|
||||
]);
|
||||
const exportedConfigRows = sanitizeConfigRowsForExport(configRows);
|
||||
const exportedAttachmentRows = includeAttachments ? attachmentRows : [];
|
||||
@@ -445,6 +463,7 @@ export async function buildBackupArchive(
|
||||
ciphers: cipherRows.length,
|
||||
attachments: exportedAttachmentRows.length,
|
||||
webauthn_credentials: accountPasskeyRows.length,
|
||||
trusted_two_factor_device_tokens: trustedTwoFactorTokenRows.length,
|
||||
},
|
||||
includes: {
|
||||
attachments: includeAttachments,
|
||||
@@ -468,6 +487,7 @@ export async function buildBackupArchive(
|
||||
ciphers: cipherRows,
|
||||
attachments: exportedAttachmentRows,
|
||||
webauthn_credentials: accountPasskeyRows,
|
||||
trusted_two_factor_device_tokens: trustedTwoFactorTokenRows,
|
||||
}, null, BACKUP_JSON_INDENT)),
|
||||
};
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
type BackupRuntimeState,
|
||||
type BackupScheduleConfig,
|
||||
type BackupSettings,
|
||||
type S3BackupAddressingStyle,
|
||||
type S3BackupDestination,
|
||||
type WebDavBackupDestination,
|
||||
createBackupRandomId,
|
||||
@@ -35,6 +36,7 @@ export type {
|
||||
BackupRuntimeState,
|
||||
BackupScheduleConfig,
|
||||
BackupSettings,
|
||||
S3BackupAddressingStyle,
|
||||
S3BackupDestination,
|
||||
WebDavBackupDestination,
|
||||
} from '../../shared/backup-schema';
|
||||
@@ -109,6 +111,9 @@ function normalizeS3Destination(value: unknown, allowIncomplete = false): S3Back
|
||||
const source = isPlainObject(value) ? value : {};
|
||||
const endpoint = asTrimmedString(source.endpoint);
|
||||
const bucket = asTrimmedString(source.bucket);
|
||||
const addressingStyleRaw = asTrimmedString(source.addressingStyle);
|
||||
const addressingStyle: S3BackupAddressingStyle =
|
||||
addressingStyleRaw === 'virtual-hosted-style' ? 'virtual-hosted-style' : 'path-style';
|
||||
const accessKeyId = asTrimmedString(source.accessKeyId);
|
||||
const secretAccessKey = asTrimmedString(source.secretAccessKey);
|
||||
const region = asTrimmedString(source.region) || 'auto';
|
||||
@@ -131,6 +136,7 @@ function normalizeS3Destination(value: unknown, allowIncomplete = false): S3Back
|
||||
return {
|
||||
endpoint: endpoint ? endpoint.replace(/\/+$/, '') : '',
|
||||
bucket,
|
||||
addressingStyle,
|
||||
region,
|
||||
accessKeyId,
|
||||
secretAccessKey,
|
||||
|
||||
@@ -24,6 +24,7 @@ type BackupTableName =
|
||||
| 'users'
|
||||
| 'domain_settings'
|
||||
| 'user_revisions'
|
||||
| 'trusted_two_factor_device_tokens'
|
||||
| 'webauthn_credentials'
|
||||
| 'folders'
|
||||
| 'ciphers'
|
||||
@@ -34,6 +35,7 @@ const BACKUP_TABLES: BackupTableName[] = [
|
||||
'users',
|
||||
'domain_settings',
|
||||
'user_revisions',
|
||||
'trusted_two_factor_device_tokens',
|
||||
'webauthn_credentials',
|
||||
'folders',
|
||||
'ciphers',
|
||||
@@ -51,6 +53,7 @@ export interface BackupImportResultBody {
|
||||
users: number;
|
||||
domainSettings: number;
|
||||
userRevisions: number;
|
||||
trustedTwoFactorDeviceTokens: number;
|
||||
webauthnCredentials: number;
|
||||
folders: number;
|
||||
ciphers: number;
|
||||
@@ -172,6 +175,7 @@ function buildResetImportTargetStatements(db: D1Database): D1PreparedStatement[]
|
||||
'DELETE FROM ciphers',
|
||||
'DELETE FROM folders',
|
||||
'DELETE FROM webauthn_credentials',
|
||||
'DELETE FROM trusted_two_factor_device_tokens',
|
||||
'DELETE FROM domain_settings',
|
||||
'DELETE FROM user_revisions',
|
||||
'DELETE FROM users',
|
||||
@@ -296,6 +300,7 @@ async function importPreparedBackupRows(db: D1Database, payload: BackupPayload['
|
||||
})),
|
||||
domain_settings: cloneRows(payload.domain_settings || []),
|
||||
user_revisions: cloneRows(payload.user_revisions || []),
|
||||
trusted_two_factor_device_tokens: cloneRows(payload.trusted_two_factor_device_tokens || []),
|
||||
webauthn_credentials: cloneRows(payload.webauthn_credentials || []),
|
||||
folders: cloneRows(payload.folders || []),
|
||||
ciphers: cloneRows(payload.ciphers || []).map((row) => ({
|
||||
@@ -634,6 +639,16 @@ async function importBackupRows(db: D1Database, payload: BackupPayload['db'], us
|
||||
true
|
||||
)
|
||||
);
|
||||
await runInsertBatch(
|
||||
db,
|
||||
tableName('trusted_two_factor_device_tokens'),
|
||||
buildInsertStatements(
|
||||
db,
|
||||
tableName('trusted_two_factor_device_tokens'),
|
||||
['token', 'user_id', 'device_identifier', 'expires_at'],
|
||||
payload.trusted_two_factor_device_tokens || []
|
||||
)
|
||||
);
|
||||
await runInsertBatch(
|
||||
db,
|
||||
tableName('webauthn_credentials'),
|
||||
@@ -712,6 +727,7 @@ export async function importBackupArchiveBytes(
|
||||
users: (db.users || []).length,
|
||||
domain_settings: (db.domain_settings || []).length,
|
||||
user_revisions: (db.user_revisions || []).length,
|
||||
trusted_two_factor_device_tokens: (db.trusted_two_factor_device_tokens || []).length,
|
||||
webauthn_credentials: (db.webauthn_credentials || []).length,
|
||||
folders: (db.folders || []).length,
|
||||
ciphers: (db.ciphers || []).length,
|
||||
@@ -735,6 +751,7 @@ export async function importBackupArchiveBytes(
|
||||
users: (db.users || []).length,
|
||||
domain_settings: (db.domain_settings || []).length,
|
||||
user_revisions: (db.user_revisions || []).length,
|
||||
trusted_two_factor_device_tokens: (db.trusted_two_factor_device_tokens || []).length,
|
||||
webauthn_credentials: (db.webauthn_credentials || []).length,
|
||||
folders: (db.folders || []).length,
|
||||
ciphers: (db.ciphers || []).length,
|
||||
@@ -776,6 +793,7 @@ export async function importBackupArchiveBytes(
|
||||
users: (db.users || []).length,
|
||||
domainSettings: (db.domain_settings || []).length,
|
||||
userRevisions: (db.user_revisions || []).length,
|
||||
trustedTwoFactorDeviceTokens: (db.trusted_two_factor_device_tokens || []).length,
|
||||
webauthnCredentials: (db.webauthn_credentials || []).length,
|
||||
folders: (db.folders || []).length,
|
||||
ciphers: (db.ciphers || []).length,
|
||||
@@ -853,6 +871,7 @@ export async function importRemoteBackupArchiveBytes(
|
||||
users: (db.users || []).length,
|
||||
domain_settings: (db.domain_settings || []).length,
|
||||
user_revisions: (db.user_revisions || []).length,
|
||||
trusted_two_factor_device_tokens: (db.trusted_two_factor_device_tokens || []).length,
|
||||
webauthn_credentials: (db.webauthn_credentials || []).length,
|
||||
folders: (db.folders || []).length,
|
||||
ciphers: (db.ciphers || []).length,
|
||||
@@ -876,6 +895,7 @@ export async function importRemoteBackupArchiveBytes(
|
||||
users: (db.users || []).length,
|
||||
domain_settings: (db.domain_settings || []).length,
|
||||
user_revisions: (db.user_revisions || []).length,
|
||||
trusted_two_factor_device_tokens: (db.trusted_two_factor_device_tokens || []).length,
|
||||
webauthn_credentials: (db.webauthn_credentials || []).length,
|
||||
folders: (db.folders || []).length,
|
||||
ciphers: (db.ciphers || []).length,
|
||||
@@ -923,6 +943,7 @@ export async function importRemoteBackupArchiveBytes(
|
||||
users: (db.users || []).length,
|
||||
domainSettings: (db.domain_settings || []).length,
|
||||
userRevisions: (db.user_revisions || []).length,
|
||||
trustedTwoFactorDeviceTokens: (db.trusted_two_factor_device_tokens || []).length,
|
||||
webauthnCredentials: (db.webauthn_credentials || []).length,
|
||||
folders: (db.folders || []).length,
|
||||
ciphers: (db.ciphers || []).length,
|
||||
|
||||
@@ -448,8 +448,27 @@ async function existsInWebDav(config: WebDavBackupDestination, relativePath: str
|
||||
return true;
|
||||
}
|
||||
|
||||
function isBucketHostedS3Endpoint(endpoint: URL, bucket: string): boolean {
|
||||
const hostname = endpoint.hostname.toLowerCase();
|
||||
const bucketName = bucket.trim().toLowerCase();
|
||||
return !!bucketName && (hostname === bucketName || hostname.startsWith(`${bucketName}.`));
|
||||
}
|
||||
|
||||
function s3BucketBaseUrl(config: S3BackupDestination): URL {
|
||||
return new URL(`${config.endpoint.replace(/\/+$/, '')}/${encodeURIComponent(config.bucket)}`);
|
||||
const endpoint = new URL(config.endpoint.replace(/\/+$/, ''));
|
||||
const bucket = config.bucket.trim();
|
||||
|
||||
if (config.addressingStyle === 'virtual-hosted-style') {
|
||||
if (isBucketHostedS3Endpoint(endpoint, bucket)) return endpoint;
|
||||
endpoint.hostname = `${bucket}.${endpoint.hostname}`;
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
return new URL(`${endpoint.toString().replace(/\/+$/, '')}/${encodeURIComponent(bucket)}`);
|
||||
}
|
||||
|
||||
function s3ObjectUrl(config: S3BackupDestination, objectKey: string): URL {
|
||||
return new URL(`${s3BucketBaseUrl(config).toString().replace(/\/+$/, '')}/${encodePathSegments(objectKey)}`);
|
||||
}
|
||||
|
||||
function normalizeS3ObjectKey(config: S3BackupDestination, relativePath: string): string {
|
||||
@@ -501,7 +520,7 @@ async function putToS3(
|
||||
options: RemoteBackupFilePutOptions = {}
|
||||
): Promise<void> {
|
||||
const objectKey = normalizeS3ObjectKey(config, relativePath);
|
||||
const url = new URL(`${s3BucketBaseUrl(config).toString()}/${encodePathSegments(objectKey)}`);
|
||||
const url = s3ObjectUrl(config, objectKey);
|
||||
const response = await signedS3Request(config, 'PUT', url, bytes, options.contentType);
|
||||
|
||||
if (!response.ok) {
|
||||
@@ -594,7 +613,7 @@ async function downloadFromS3(config: S3BackupDestination, relativePath: string)
|
||||
throw new Error('Please select a backup file');
|
||||
}
|
||||
const objectKey = normalizeS3ObjectKey(config, normalized);
|
||||
const url = new URL(`${s3BucketBaseUrl(config).toString()}/${encodePathSegments(objectKey)}`);
|
||||
const url = s3ObjectUrl(config, objectKey);
|
||||
const response = await signedS3Request(config, 'GET', url);
|
||||
if (!response.ok) {
|
||||
throw new Error(`S3 download failed: ${response.status}`);
|
||||
@@ -610,7 +629,7 @@ async function downloadFromS3(config: S3BackupDestination, relativePath: string)
|
||||
|
||||
async function deleteFromS3(config: S3BackupDestination, relativePath: string): Promise<void> {
|
||||
const objectKey = normalizeS3ObjectKey(config, relativePath);
|
||||
const url = new URL(`${s3BucketBaseUrl(config).toString()}/${encodePathSegments(objectKey)}`);
|
||||
const url = s3ObjectUrl(config, objectKey);
|
||||
const response = await signedS3Request(config, 'DELETE', url);
|
||||
if (!response.ok && response.status !== 404) {
|
||||
throw new Error(`S3 delete failed: ${response.status}`);
|
||||
@@ -619,7 +638,7 @@ async function deleteFromS3(config: S3BackupDestination, relativePath: string):
|
||||
|
||||
async function existsInS3(config: S3BackupDestination, relativePath: string): Promise<boolean> {
|
||||
const objectKey = normalizeS3ObjectKey(config, relativePath);
|
||||
const url = new URL(`${s3BucketBaseUrl(config).toString()}/${encodePathSegments(objectKey)}`);
|
||||
const url = s3ObjectUrl(config, objectKey);
|
||||
const response = await signedS3Request(config, 'HEAD', url);
|
||||
if (response.status === 404) return false;
|
||||
if (!response.ok) {
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
import type { Env } from '../types';
|
||||
import {
|
||||
setConfigValue as saveConfigValue,
|
||||
} from './storage-config-repo';
|
||||
|
||||
const PUSH_RELAY_URI = 'https://push.bitwarden.com';
|
||||
const PUSH_IDENTITY_URI = 'https://identity.bitwarden.com';
|
||||
const INSTALLATIONS_URI = 'https://api.bitwarden.com/installations';
|
||||
const PUSH_INSTALLATION_ID_KEY = 'push.installation.id';
|
||||
const PUSH_INSTALLATION_KEY_KEY = 'push.installation.key';
|
||||
const PUSH_REQUEST_TIMEOUT_MS = 5000;
|
||||
|
||||
interface CachedPushAccessToken {
|
||||
token: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
let cachedPushAccessToken: CachedPushAccessToken | null = null;
|
||||
|
||||
async function fetchPushEndpoint(url: string, init: RequestInit, errorMessage: string): Promise<Response | null> {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), PUSH_REQUEST_TIMEOUT_MS);
|
||||
try {
|
||||
return await fetch(url, { ...init, signal: controller.signal });
|
||||
} catch (error) {
|
||||
console.error(errorMessage, error);
|
||||
return null;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
function randomInstallationEmail(): string {
|
||||
const bytes = new Uint8Array(10);
|
||||
crypto.getRandomValues(bytes);
|
||||
const localPart = Array.from(bytes, (byte) => (byte % 36).toString(36)).join('');
|
||||
return `${localPart}@nodewarden.app`;
|
||||
}
|
||||
|
||||
async function getConfigKeyPresence(db: D1Database, key: string): Promise<string | null> {
|
||||
const row = await db.prepare('SELECT value FROM config WHERE key = ? LIMIT 1').bind(key).first<{ value: string }>();
|
||||
return typeof row?.value === 'string' ? row.value : null;
|
||||
}
|
||||
|
||||
async function getPushInstallationCredentials(db: D1Database): Promise<{ id: string; key: string } | null> {
|
||||
const [id, key] = await Promise.all([
|
||||
getConfigKeyPresence(db, PUSH_INSTALLATION_ID_KEY),
|
||||
getConfigKeyPresence(db, PUSH_INSTALLATION_KEY_KEY),
|
||||
]);
|
||||
const normalizedId = String(id || '').trim();
|
||||
const normalizedKey = String(key || '').trim();
|
||||
return normalizedId && normalizedKey ? { id: normalizedId, key: normalizedKey } : null;
|
||||
}
|
||||
|
||||
export async function ensurePushInstallationCredentials(db: D1Database): Promise<{ id: string; key: string } | null> {
|
||||
const existing = await getPushInstallationCredentials(db);
|
||||
if (existing) return existing;
|
||||
|
||||
const response = await fetchPushEndpoint(
|
||||
INSTALLATIONS_URI,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
accept: 'application/json',
|
||||
'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
|
||||
'cache-control': 'no-cache',
|
||||
'content-type': 'application/json',
|
||||
origin: 'https://bitwarden.com',
|
||||
pragma: 'no-cache',
|
||||
priority: 'u=1, i',
|
||||
referer: 'https://bitwarden.com/host/',
|
||||
'sec-ch-ua': '"Google Chrome";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
|
||||
'sec-ch-ua-mobile': '?0',
|
||||
'sec-ch-ua-platform': '"Windows"',
|
||||
'sec-fetch-dest': 'empty',
|
||||
'sec-fetch-mode': 'cors',
|
||||
'sec-fetch-site': 'same-site',
|
||||
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
formName: 'request_host',
|
||||
url: '/host/',
|
||||
locale: 'zh-CN',
|
||||
email: randomInstallationEmail(),
|
||||
region: 'us',
|
||||
}),
|
||||
},
|
||||
'Failed to request Bitwarden push installation:'
|
||||
);
|
||||
if (!response) return null;
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('Failed to request Bitwarden push installation:', response.status, await response.text().catch(() => ''));
|
||||
return null;
|
||||
}
|
||||
|
||||
const body = (await response.json().catch(() => null)) as { id?: string; key?: string; enabled?: boolean } | null;
|
||||
const id = String(body?.id || '').trim();
|
||||
const key = String(body?.key || '').trim();
|
||||
if (!id || !key) {
|
||||
console.error('Bitwarden push installation response did not include id/key');
|
||||
return null;
|
||||
}
|
||||
|
||||
await Promise.all([
|
||||
saveConfigValue(db, PUSH_INSTALLATION_ID_KEY, id),
|
||||
saveConfigValue(db, PUSH_INSTALLATION_KEY_KEY, key),
|
||||
]);
|
||||
return { id, key };
|
||||
}
|
||||
|
||||
async function getPushAccessToken(env: Env): Promise<string | null> {
|
||||
const credentials = await ensurePushInstallationCredentials(env.DB);
|
||||
if (!credentials) return null;
|
||||
|
||||
const now = Date.now();
|
||||
if (cachedPushAccessToken && cachedPushAccessToken.expiresAt > now + 30_000) {
|
||||
return cachedPushAccessToken.token;
|
||||
}
|
||||
|
||||
const params = new URLSearchParams({
|
||||
grant_type: 'client_credentials',
|
||||
scope: 'api.push',
|
||||
client_id: `installation.${credentials.id}`,
|
||||
client_secret: credentials.key,
|
||||
});
|
||||
|
||||
const response = await fetchPushEndpoint(
|
||||
`${PUSH_IDENTITY_URI}/connect/token`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
accept: 'application/json',
|
||||
'content-type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body: params.toString(),
|
||||
},
|
||||
'Failed to get Bitwarden push relay token:'
|
||||
);
|
||||
if (!response) return null;
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('Failed to get Bitwarden push relay token:', response.status, await response.text().catch(() => ''));
|
||||
return null;
|
||||
}
|
||||
|
||||
const body = (await response.json().catch(() => null)) as { access_token?: string; expires_in?: number } | null;
|
||||
const token = String(body?.access_token || '').trim();
|
||||
if (!token) {
|
||||
console.error('Bitwarden push relay token response did not include an access_token');
|
||||
return null;
|
||||
}
|
||||
|
||||
const expiresInSeconds = Math.max(60, Number(body?.expires_in || 3600));
|
||||
cachedPushAccessToken = {
|
||||
token,
|
||||
expiresAt: now + Math.floor(expiresInSeconds * 500),
|
||||
};
|
||||
return token;
|
||||
}
|
||||
|
||||
async function postToPushRelay(env: Env, path: string, body?: unknown): Promise<boolean> {
|
||||
const token = await getPushAccessToken(env);
|
||||
if (!token) return false;
|
||||
|
||||
const response = await fetchPushEndpoint(
|
||||
`${PUSH_RELAY_URI}${path}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
accept: 'application/json',
|
||||
authorization: `Bearer ${token}`,
|
||||
...(body === undefined ? {} : { 'content-type': 'application/json' }),
|
||||
},
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
},
|
||||
`Bitwarden push relay request failed: ${path}`
|
||||
);
|
||||
if (!response) return false;
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('Bitwarden push relay request failed:', path, response.status, await response.text().catch(() => ''));
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function mobilePayloadFromSignalR(updateType: number, userId: string, revisionDate: string, payload: Record<string, unknown> | null | undefined): Record<string, unknown> {
|
||||
const source = payload || {};
|
||||
const id = source.Id ?? source.id;
|
||||
const organizationId = source.OrganizationId ?? source.organizationId ?? null;
|
||||
const collectionIds = source.CollectionIds ?? source.collectionIds ?? null;
|
||||
|
||||
if (id != null) {
|
||||
return {
|
||||
id,
|
||||
userId: source.UserId ?? source.userId ?? userId,
|
||||
organizationId,
|
||||
collectionIds,
|
||||
revisionDate: source.RevisionDate ?? source.revisionDate ?? revisionDate,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
userId: source.UserId ?? source.userId ?? userId,
|
||||
date: source.Date ?? source.date ?? revisionDate,
|
||||
};
|
||||
}
|
||||
|
||||
export async function registerMobilePushDevice(
|
||||
env: Env,
|
||||
input: {
|
||||
userId: string;
|
||||
deviceIdentifier: string;
|
||||
type: number;
|
||||
pushUuid: string;
|
||||
pushToken: string;
|
||||
}
|
||||
): Promise<boolean> {
|
||||
const credentials = await ensurePushInstallationCredentials(env.DB);
|
||||
if (!credentials) return false;
|
||||
|
||||
return postToPushRelay(env, '/push/register', {
|
||||
deviceId: input.pushUuid,
|
||||
pushToken: input.pushToken,
|
||||
userId: input.userId,
|
||||
type: input.type,
|
||||
identifier: input.deviceIdentifier,
|
||||
installationId: credentials.id,
|
||||
});
|
||||
}
|
||||
|
||||
export async function unregisterMobilePushDevice(env: Env, pushUuid: string | null | undefined): Promise<boolean> {
|
||||
const normalized = String(pushUuid || '').trim();
|
||||
if (!normalized) return false;
|
||||
return postToPushRelay(env, `/push/delete/${encodeURIComponent(normalized)}`);
|
||||
}
|
||||
|
||||
export async function notifyMobilePush(
|
||||
env: Env,
|
||||
input: {
|
||||
userId: string;
|
||||
updateType: number;
|
||||
revisionDate: string;
|
||||
contextId: string | null;
|
||||
payload: Record<string, unknown> | null | undefined;
|
||||
}
|
||||
): Promise<void> {
|
||||
const hasPushDevice = await env.DB
|
||||
.prepare('SELECT 1 FROM devices WHERE user_id = ? AND push_token IS NOT NULL AND push_token <> ? LIMIT 1')
|
||||
.bind(input.userId, '')
|
||||
.first<{ '1': number }>();
|
||||
if (!hasPushDevice) return;
|
||||
|
||||
let actingPushUuid: string | null = null;
|
||||
if (input.contextId) {
|
||||
const row = await env.DB
|
||||
.prepare('SELECT push_uuid FROM devices WHERE user_id = ? AND device_identifier = ? LIMIT 1')
|
||||
.bind(input.userId, input.contextId)
|
||||
.first<{ push_uuid: string | null }>();
|
||||
actingPushUuid = row?.push_uuid ?? null;
|
||||
}
|
||||
|
||||
await postToPushRelay(env, '/push/send', {
|
||||
userId: input.userId,
|
||||
organizationId: null,
|
||||
deviceId: actingPushUuid,
|
||||
identifier: input.contextId,
|
||||
type: input.updateType,
|
||||
payload: mobilePayloadFromSignalR(input.updateType, input.userId, input.revisionDate, input.payload),
|
||||
clientType: null,
|
||||
installationId: null,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import type { AuthRequestRecord, AuthRequestType } from '../types';
|
||||
|
||||
const AUTH_REQUEST_EXPIRATION_MS = 15 * 60 * 1000;
|
||||
|
||||
function mapAuthRequestRow(row: any): AuthRequestRecord {
|
||||
return {
|
||||
id: row.id,
|
||||
userId: row.user_id,
|
||||
organizationId: row.organization_id ?? null,
|
||||
type: Number(row.type) as AuthRequestType,
|
||||
requestDeviceIdentifier: row.request_device_identifier,
|
||||
requestDeviceType: Number(row.request_device_type ?? 14),
|
||||
requestIpAddress: row.request_ip_address ?? null,
|
||||
requestCountryName: row.request_country_name ?? null,
|
||||
responseDeviceIdentifier: row.response_device_identifier ?? null,
|
||||
accessCode: row.access_code,
|
||||
publicKey: row.public_key,
|
||||
key: row.key ?? null,
|
||||
masterPasswordHash: row.master_password_hash ?? null,
|
||||
approved: row.approved == null ? null : Number(row.approved) === 1,
|
||||
creationDate: row.creation_date,
|
||||
responseDate: row.response_date ?? null,
|
||||
authenticationDate: row.authentication_date ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function isAuthRequestExpired(request: AuthRequestRecord, nowMs: number = Date.now()): boolean {
|
||||
return new Date(request.creationDate).getTime() + AUTH_REQUEST_EXPIRATION_MS <= nowMs;
|
||||
}
|
||||
|
||||
const AUTH_REQUEST_SELECT =
|
||||
'SELECT id, user_id, organization_id, type, request_device_identifier, request_device_type, request_ip_address, request_country_name, ' +
|
||||
'response_device_identifier, access_code, public_key, key, master_password_hash, approved, creation_date, response_date, authentication_date ' +
|
||||
'FROM auth_requests';
|
||||
|
||||
export async function createAuthRequest(db: D1Database, request: AuthRequestRecord): Promise<void> {
|
||||
await db
|
||||
.prepare(
|
||||
'INSERT INTO auth_requests(' +
|
||||
'id, user_id, organization_id, type, request_device_identifier, request_device_type, request_ip_address, request_country_name, ' +
|
||||
'response_device_identifier, access_code, public_key, key, master_password_hash, approved, creation_date, response_date, authentication_date' +
|
||||
') VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
||||
)
|
||||
.bind(
|
||||
request.id,
|
||||
request.userId,
|
||||
request.organizationId,
|
||||
request.type,
|
||||
request.requestDeviceIdentifier,
|
||||
request.requestDeviceType,
|
||||
request.requestIpAddress,
|
||||
request.requestCountryName,
|
||||
request.responseDeviceIdentifier,
|
||||
request.accessCode,
|
||||
request.publicKey,
|
||||
request.key,
|
||||
request.masterPasswordHash,
|
||||
request.approved == null ? null : (request.approved ? 1 : 0),
|
||||
request.creationDate,
|
||||
request.responseDate,
|
||||
request.authenticationDate
|
||||
)
|
||||
.run();
|
||||
}
|
||||
|
||||
export async function getAuthRequestById(db: D1Database, id: string): Promise<AuthRequestRecord | null> {
|
||||
const row = await db.prepare(`${AUTH_REQUEST_SELECT} WHERE id = ? LIMIT 1`).bind(id).first<any>();
|
||||
return row ? mapAuthRequestRow(row) : null;
|
||||
}
|
||||
|
||||
export async function listAuthRequestsByUserId(db: D1Database, userId: string): Promise<AuthRequestRecord[]> {
|
||||
const res = await db.prepare(`${AUTH_REQUEST_SELECT} WHERE user_id = ? ORDER BY creation_date DESC`).bind(userId).all<any>();
|
||||
return (res.results || []).map(mapAuthRequestRow);
|
||||
}
|
||||
|
||||
export async function listPendingAuthRequestsByUserId(db: D1Database, userId: string, nowMs: number = Date.now()): Promise<AuthRequestRecord[]> {
|
||||
const cutoff = new Date(nowMs - AUTH_REQUEST_EXPIRATION_MS).toISOString();
|
||||
const res = await db
|
||||
.prepare(
|
||||
'SELECT ar.id, ar.user_id, ar.organization_id, ar.type, ar.request_device_identifier, ar.request_device_type, ar.request_ip_address, ar.request_country_name, ' +
|
||||
'ar.response_device_identifier, ar.access_code, ar.public_key, ar.key, ar.master_password_hash, ar.approved, ar.creation_date, ar.response_date, ar.authentication_date ' +
|
||||
'FROM auth_requests ar ' +
|
||||
'JOIN (' +
|
||||
' SELECT request_device_identifier, MAX(creation_date) AS latest_creation_date ' +
|
||||
' FROM auth_requests ' +
|
||||
' WHERE user_id = ? AND type IN (0, 1) AND approved IS NULL AND response_date IS NULL AND authentication_date IS NULL AND creation_date >= ? ' +
|
||||
' GROUP BY request_device_identifier' +
|
||||
') latest ON latest.request_device_identifier = ar.request_device_identifier AND latest.latest_creation_date = ar.creation_date ' +
|
||||
'WHERE ar.user_id = ? AND ar.type IN (0, 1) AND ar.approved IS NULL AND ar.response_date IS NULL AND ar.authentication_date IS NULL ' +
|
||||
'ORDER BY ar.creation_date DESC'
|
||||
)
|
||||
.bind(userId, cutoff, userId)
|
||||
.all<any>();
|
||||
return (res.results || []).map(mapAuthRequestRow).filter((request) => !isAuthRequestExpired(request, nowMs));
|
||||
}
|
||||
|
||||
export async function updateAuthRequestResponse(
|
||||
db: D1Database,
|
||||
id: string,
|
||||
userId: string,
|
||||
update: {
|
||||
approved: boolean;
|
||||
responseDeviceIdentifier: string;
|
||||
key?: string | null;
|
||||
masterPasswordHash?: string | null;
|
||||
responseDate?: string;
|
||||
}
|
||||
): Promise<boolean> {
|
||||
const result = await db
|
||||
.prepare(
|
||||
'UPDATE auth_requests SET approved = ?, response_device_identifier = ?, key = ?, master_password_hash = ?, response_date = ? ' +
|
||||
'WHERE id = ? AND user_id = ? AND approved IS NULL AND response_date IS NULL AND authentication_date IS NULL'
|
||||
)
|
||||
.bind(
|
||||
update.approved ? 1 : 0,
|
||||
update.responseDeviceIdentifier,
|
||||
update.approved ? (update.key ?? null) : null,
|
||||
update.approved ? (update.masterPasswordHash ?? null) : null,
|
||||
update.responseDate || new Date().toISOString(),
|
||||
id,
|
||||
userId
|
||||
)
|
||||
.run();
|
||||
return Number(result.meta.changes ?? 0) > 0;
|
||||
}
|
||||
|
||||
export async function markAuthRequestAuthenticated(db: D1Database, id: string, authenticationDate: string = new Date().toISOString()): Promise<boolean> {
|
||||
const result = await db
|
||||
.prepare('UPDATE auth_requests SET authentication_date = ? WHERE id = ? AND authentication_date IS NULL')
|
||||
.bind(authenticationDate, id)
|
||||
.run();
|
||||
return Number(result.meta.changes ?? 0) > 0;
|
||||
}
|
||||
|
||||
export async function pruneExpiredAuthRequests(db: D1Database, nowMs: number = Date.now()): Promise<number> {
|
||||
const cutoff = new Date(nowMs - AUTH_REQUEST_EXPIRATION_MS).toISOString();
|
||||
const result = await db.prepare('DELETE FROM auth_requests WHERE creation_date < ?').bind(cutoff).run();
|
||||
return Number(result.meta.changes ?? 0);
|
||||
}
|
||||
@@ -87,7 +87,7 @@ function parseCipherRow(row: CipherRow | null | undefined): Cipher | null {
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
archivedAt: row.archived_at ?? parsed.archivedAt ?? parsed.archivedDate ?? null,
|
||||
deletedAt: row.deleted_at ?? null,
|
||||
deletedAt: row.deleted_at ?? parsed.deletedAt ?? parsed.deletedDate ?? null,
|
||||
};
|
||||
} catch {
|
||||
console.error('Corrupted cipher data, id:', row.id);
|
||||
@@ -244,7 +244,9 @@ export async function getCiphersPage(
|
||||
limit: number,
|
||||
offset: number
|
||||
): Promise<Cipher[]> {
|
||||
const whereDeleted = includeDeleted ? '' : 'AND deleted_at IS NULL';
|
||||
const whereDeleted = includeDeleted
|
||||
? ''
|
||||
: "AND deleted_at IS NULL AND json_extract(data, '$.deletedAt') IS NULL AND json_extract(data, '$.deletedDate') IS NULL";
|
||||
const res = await db
|
||||
.prepare(
|
||||
`SELECT ${selectCipherColumns()} FROM ciphers
|
||||
@@ -341,7 +343,10 @@ export async function bulkArchiveCiphers(
|
||||
`UPDATE ciphers
|
||||
SET archived_at = ?, updated_at = ?,
|
||||
data = json_remove(data, '$.archivedAt', '$.archivedDate', '$.updatedAt', '$.revisionDate')
|
||||
WHERE user_id = ? AND id IN (${placeholders}) AND deleted_at IS NULL`
|
||||
WHERE user_id = ? AND id IN (${placeholders})
|
||||
AND deleted_at IS NULL
|
||||
AND json_extract(data, '$.deletedAt') IS NULL
|
||||
AND json_extract(data, '$.deletedDate') IS NULL`
|
||||
)
|
||||
.bind(now, now, userId, ...chunk)
|
||||
.run();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Device, TrustedDeviceTokenSummary, User } from '../types';
|
||||
import { generateUUID } from '../utils/uuid';
|
||||
|
||||
type GetUserByEmail = (email: string) => Promise<User | null>;
|
||||
type TrustedTokenKeyFn = (token: string) => Promise<string>;
|
||||
@@ -14,6 +15,8 @@ function mapDeviceRow(row: any): Device {
|
||||
encryptedUserKey: row.encrypted_user_key ?? null,
|
||||
encryptedPublicKey: row.encrypted_public_key ?? null,
|
||||
encryptedPrivateKey: row.encrypted_private_key ?? null,
|
||||
pushUuid: row.push_uuid ?? null,
|
||||
pushToken: row.push_token ?? null,
|
||||
lastSeenAt: row.last_seen_at ?? null,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
@@ -38,13 +41,15 @@ export async function upsertDevice(
|
||||
const existingDevice = await getDeviceById(userId, deviceIdentifier);
|
||||
const effectiveSessionStamp = String(sessionStamp || '').trim() || existingDevice?.sessionStamp || '';
|
||||
const effectiveName = String(name || '').trim() || String(existingDevice?.name || '').trim();
|
||||
const effectivePushUuid = String(existingDevice?.pushUuid || '').trim() || generateUUID();
|
||||
await db
|
||||
.prepare(
|
||||
'INSERT INTO devices(user_id, device_identifier, name, type, session_stamp, encrypted_user_key, encrypted_public_key, encrypted_private_key, banned, banned_at, device_note, last_seen_at, created_at, updated_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?, 0, NULL, ?, ?, ?, ?) ' +
|
||||
'INSERT INTO devices(user_id, device_identifier, name, type, session_stamp, encrypted_user_key, encrypted_public_key, encrypted_private_key, push_uuid, banned, banned_at, device_note, last_seen_at, created_at, updated_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, 0, NULL, ?, ?, ?, ?) ' +
|
||||
'ON CONFLICT(user_id, device_identifier) DO UPDATE SET name=excluded.name, type=excluded.type, session_stamp=excluded.session_stamp, ' +
|
||||
'encrypted_user_key=COALESCE(excluded.encrypted_user_key, encrypted_user_key), ' +
|
||||
'encrypted_public_key=COALESCE(excluded.encrypted_public_key, encrypted_public_key), ' +
|
||||
'encrypted_private_key=COALESCE(excluded.encrypted_private_key, encrypted_private_key), ' +
|
||||
'push_uuid=COALESCE(push_uuid, excluded.push_uuid), ' +
|
||||
'last_seen_at=excluded.last_seen_at, ' +
|
||||
'updated_at=excluded.updated_at'
|
||||
)
|
||||
@@ -57,6 +62,7 @@ export async function upsertDevice(
|
||||
keys?.encryptedUserKey ?? null,
|
||||
keys?.encryptedPublicKey ?? null,
|
||||
keys?.encryptedPrivateKey ?? null,
|
||||
effectivePushUuid,
|
||||
existingDevice?.deviceNote ?? null,
|
||||
now,
|
||||
now,
|
||||
@@ -166,7 +172,7 @@ export async function isKnownDeviceByEmail(
|
||||
export async function getDevicesByUserId(db: D1Database, userId: string): Promise<Device[]> {
|
||||
const res = await db
|
||||
.prepare(
|
||||
'SELECT user_id, device_identifier, name, type, session_stamp, encrypted_user_key, encrypted_public_key, encrypted_private_key, banned, banned_at, device_note, last_seen_at, created_at, updated_at ' +
|
||||
'SELECT user_id, device_identifier, name, type, session_stamp, encrypted_user_key, encrypted_public_key, encrypted_private_key, push_uuid, push_token, banned, banned_at, device_note, last_seen_at, created_at, updated_at ' +
|
||||
'FROM devices WHERE user_id = ? ORDER BY COALESCE(last_seen_at, created_at) DESC, updated_at DESC'
|
||||
)
|
||||
.bind(userId)
|
||||
@@ -177,7 +183,7 @@ export async function getDevicesByUserId(db: D1Database, userId: string): Promis
|
||||
export async function getDevice(db: D1Database, userId: string, deviceIdentifier: string): Promise<Device | null> {
|
||||
const row = await db
|
||||
.prepare(
|
||||
'SELECT user_id, device_identifier, name, type, session_stamp, encrypted_user_key, encrypted_public_key, encrypted_private_key, banned, banned_at, device_note, last_seen_at, created_at, updated_at ' +
|
||||
'SELECT user_id, device_identifier, name, type, session_stamp, encrypted_user_key, encrypted_public_key, encrypted_private_key, push_uuid, push_token, banned, banned_at, device_note, last_seen_at, created_at, updated_at ' +
|
||||
'FROM devices WHERE user_id = ? AND device_identifier = ? LIMIT 1'
|
||||
)
|
||||
.bind(userId, deviceIdentifier)
|
||||
@@ -185,6 +191,63 @@ export async function getDevice(db: D1Database, userId: string, deviceIdentifier
|
||||
return row ? mapDeviceRow(row) : null;
|
||||
}
|
||||
|
||||
export async function updateDevicePushToken(
|
||||
db: D1Database,
|
||||
userId: string,
|
||||
deviceIdentifier: string,
|
||||
pushUuid: string,
|
||||
pushToken: string
|
||||
): Promise<boolean> {
|
||||
const now = new Date().toISOString();
|
||||
const result = await db
|
||||
.prepare(
|
||||
'UPDATE devices SET push_uuid = ?, push_token = ?, updated_at = ? ' +
|
||||
'WHERE user_id = ? AND device_identifier = ?'
|
||||
)
|
||||
.bind(pushUuid, pushToken, now, userId, deviceIdentifier)
|
||||
.run();
|
||||
return Number(result.meta.changes ?? 0) > 0;
|
||||
}
|
||||
|
||||
export async function clearDevicePushToken(
|
||||
db: D1Database,
|
||||
userId: string,
|
||||
deviceIdentifier: string
|
||||
): Promise<{ pushUuid: string | null } | null> {
|
||||
const existing = await db
|
||||
.prepare('SELECT push_uuid FROM devices WHERE user_id = ? AND device_identifier = ? LIMIT 1')
|
||||
.bind(userId, deviceIdentifier)
|
||||
.first<{ push_uuid: string | null }>();
|
||||
if (!existing) return null;
|
||||
|
||||
await db
|
||||
.prepare('UPDATE devices SET push_token = NULL, updated_at = ? WHERE user_id = ? AND device_identifier = ?')
|
||||
.bind(new Date().toISOString(), userId, deviceIdentifier)
|
||||
.run();
|
||||
|
||||
return { pushUuid: existing.push_uuid ?? null };
|
||||
}
|
||||
|
||||
export async function getDevicePushUuid(
|
||||
db: D1Database,
|
||||
userId: string,
|
||||
deviceIdentifier: string
|
||||
): Promise<string | null> {
|
||||
const row = await db
|
||||
.prepare('SELECT push_uuid FROM devices WHERE user_id = ? AND device_identifier = ? LIMIT 1')
|
||||
.bind(userId, deviceIdentifier)
|
||||
.first<{ push_uuid: string | null }>();
|
||||
return row?.push_uuid ?? null;
|
||||
}
|
||||
|
||||
export async function userHasPushDevice(db: D1Database, userId: string): Promise<boolean> {
|
||||
const row = await db
|
||||
.prepare('SELECT 1 FROM devices WHERE user_id = ? AND push_token IS NOT NULL AND push_token <> ? LIMIT 1')
|
||||
.bind(userId, '')
|
||||
.first<{ '1': number }>();
|
||||
return !!row;
|
||||
}
|
||||
|
||||
export async function deleteDevice(db: D1Database, userId: string, deviceIdentifier: string): Promise<boolean> {
|
||||
const result = await db
|
||||
.prepare('DELETE FROM devices WHERE user_id = ? AND device_identifier = ?')
|
||||
|
||||
@@ -94,7 +94,7 @@ const SCHEMA_STATEMENTS: readonly string[] = [
|
||||
'CREATE INDEX IF NOT EXISTS idx_audit_logs_level_created ON audit_logs(level, created_at)',
|
||||
|
||||
'CREATE TABLE IF NOT EXISTS devices (' +
|
||||
'user_id TEXT NOT NULL, device_identifier TEXT NOT NULL, name TEXT NOT NULL, type INTEGER NOT NULL, session_stamp TEXT, encrypted_user_key TEXT, encrypted_public_key TEXT, encrypted_private_key TEXT, banned INTEGER NOT NULL DEFAULT 0, banned_at TEXT, device_note TEXT, last_seen_at TEXT, ' +
|
||||
'user_id TEXT NOT NULL, device_identifier TEXT NOT NULL, name TEXT NOT NULL, type INTEGER NOT NULL, session_stamp TEXT, encrypted_user_key TEXT, encrypted_public_key TEXT, encrypted_private_key TEXT, push_uuid TEXT, push_token TEXT, banned INTEGER NOT NULL DEFAULT 0, banned_at TEXT, device_note TEXT, last_seen_at TEXT, ' +
|
||||
'created_at TEXT NOT NULL, updated_at TEXT NOT NULL, ' +
|
||||
'PRIMARY KEY (user_id, device_identifier), ' +
|
||||
'FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE)',
|
||||
@@ -103,11 +103,23 @@ const SCHEMA_STATEMENTS: readonly string[] = [
|
||||
'ALTER TABLE devices ADD COLUMN encrypted_user_key TEXT',
|
||||
'ALTER TABLE devices ADD COLUMN encrypted_public_key TEXT',
|
||||
'ALTER TABLE devices ADD COLUMN encrypted_private_key TEXT',
|
||||
'ALTER TABLE devices ADD COLUMN push_uuid TEXT',
|
||||
'ALTER TABLE devices ADD COLUMN push_token TEXT',
|
||||
'ALTER TABLE devices ADD COLUMN banned INTEGER NOT NULL DEFAULT 0',
|
||||
'ALTER TABLE devices ADD COLUMN banned_at TEXT',
|
||||
'ALTER TABLE devices ADD COLUMN device_note TEXT',
|
||||
'ALTER TABLE devices ADD COLUMN last_seen_at TEXT',
|
||||
'CREATE INDEX IF NOT EXISTS idx_devices_user_last_seen ON devices(user_id, last_seen_at)',
|
||||
'CREATE INDEX IF NOT EXISTS idx_devices_user_push ON devices(user_id, push_token)',
|
||||
|
||||
'CREATE TABLE IF NOT EXISTS auth_requests (' +
|
||||
'id TEXT PRIMARY KEY, user_id TEXT NOT NULL, organization_id TEXT, type INTEGER NOT NULL, request_device_identifier TEXT NOT NULL, request_device_type INTEGER NOT NULL, ' +
|
||||
'request_ip_address TEXT, request_country_name TEXT, response_device_identifier TEXT, access_code TEXT NOT NULL, public_key TEXT NOT NULL, key TEXT, master_password_hash TEXT, ' +
|
||||
'approved INTEGER, creation_date TEXT NOT NULL, response_date TEXT, authentication_date TEXT, ' +
|
||||
'FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE)',
|
||||
'CREATE INDEX IF NOT EXISTS idx_auth_requests_user_created ON auth_requests(user_id, creation_date)',
|
||||
'CREATE INDEX IF NOT EXISTS idx_auth_requests_user_pending ON auth_requests(user_id, approved, response_date, authentication_date, creation_date)',
|
||||
'CREATE INDEX IF NOT EXISTS idx_auth_requests_device_pending ON auth_requests(user_id, request_device_identifier, creation_date)',
|
||||
|
||||
'CREATE TABLE IF NOT EXISTS trusted_two_factor_device_tokens (' +
|
||||
'token TEXT PRIMARY KEY, user_id TEXT NOT NULL, device_identifier TEXT NOT NULL, expires_at INTEGER NOT NULL, ' +
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { User, Cipher, Folder, Attachment, Device, Invite, AuditLog, Send, TrustedDeviceTokenSummary, RefreshTokenRecord, CustomEquivalentDomain, AccountPasskeyChallenge, AccountPasskeyChallengeScope, AccountPasskeyCredential } from '../types';
|
||||
import { User, Cipher, Folder, Attachment, Device, Invite, AuditLog, Send, TrustedDeviceTokenSummary, RefreshTokenRecord, CustomEquivalentDomain, AccountPasskeyChallenge, AccountPasskeyChallengeScope, AccountPasskeyCredential, AuthRequestRecord } from '../types';
|
||||
import { LIMITS } from '../config/limits';
|
||||
import { ensurePushInstallationCredentials } from './push-relay';
|
||||
import { ensureStorageSchema } from './storage-schema';
|
||||
import {
|
||||
getConfigValue as getStoredConfigValue,
|
||||
@@ -87,10 +88,12 @@ import {
|
||||
import {
|
||||
deleteDevice as deleteStoredDevice,
|
||||
deleteDevicesByUserId as deleteStoredDevicesByUserId,
|
||||
clearDevicePushToken as clearStoredDevicePushToken,
|
||||
clearDeviceKeys as clearStoredDeviceKeys,
|
||||
deleteTrustedTwoFactorTokensByDevice as deleteStoredTrustedTokensByDevice,
|
||||
deleteTrustedTwoFactorTokensByUserId as deleteStoredTrustedTokensByUserId,
|
||||
getDevice as findStoredDevice,
|
||||
getDevicePushUuid as findStoredDevicePushUuid,
|
||||
getDevicesByUserId as listStoredDevicesByUserId,
|
||||
getTrustedDeviceTokenSummariesByUserId as listStoredTrustedTokenSummaries,
|
||||
getTrustedTwoFactorDeviceTokenUserId as findStoredTrustedTokenUserId,
|
||||
@@ -101,8 +104,19 @@ import {
|
||||
upsertDevice as saveStoredDevice,
|
||||
updateDeviceName as updateStoredDeviceName,
|
||||
updateDeviceKeys as updateStoredDeviceKeys,
|
||||
updateDevicePushToken as updateStoredDevicePushToken,
|
||||
updateTrustedTwoFactorTokensExpiryByDevice as updateStoredTrustedTokensExpiryByDevice,
|
||||
userHasPushDevice as getUserHasPushDevice,
|
||||
} from './storage-device-repo';
|
||||
import {
|
||||
createAuthRequest as createStoredAuthRequest,
|
||||
getAuthRequestById as findStoredAuthRequestById,
|
||||
listAuthRequestsByUserId as listStoredAuthRequestsByUserId,
|
||||
listPendingAuthRequestsByUserId as listStoredPendingAuthRequestsByUserId,
|
||||
markAuthRequestAuthenticated as markStoredAuthRequestAuthenticated,
|
||||
pruneExpiredAuthRequests as pruneStoredExpiredAuthRequests,
|
||||
updateAuthRequestResponse as updateStoredAuthRequestResponse,
|
||||
} from './storage-auth-request-repo';
|
||||
import {
|
||||
ensureUsedAttachmentDownloadTokenTable as ensureStoredAttachmentTokenTable,
|
||||
consumeAttachmentDownloadToken as consumeStoredAttachmentDownloadToken,
|
||||
@@ -134,8 +148,8 @@ const STORAGE_SCHEMA_VERSION_KEY = 'schema.version';
|
||||
// Bump this whenever src/services/storage-schema.ts or migrations/0001_init.sql
|
||||
// changes. Existing D1 installs only rerun ensureStorageSchema() when this value
|
||||
// differs from config.schema.version.
|
||||
const STORAGE_SCHEMA_VERSION = '2026-06-09-account-passkeys';
|
||||
const REQUIRED_ACCOUNT_PASSKEY_TABLES = ['webauthn_credentials', 'webauthn_challenges'] as const;
|
||||
const STORAGE_SCHEMA_VERSION = '2026-06-22-push-notifications';
|
||||
const REQUIRED_SCHEMA_TABLES = ['webauthn_credentials', 'webauthn_challenges', 'auth_requests'] as const;
|
||||
|
||||
// D1-backed storage.
|
||||
// Contract:
|
||||
@@ -166,14 +180,14 @@ export class StorageService {
|
||||
return stmt.bind(...values.map(v => v === undefined ? null : v));
|
||||
}
|
||||
|
||||
private async hasAccountPasskeyTables(): Promise<boolean> {
|
||||
const placeholders = REQUIRED_ACCOUNT_PASSKEY_TABLES.map(() => '?').join(', ');
|
||||
private async hasRequiredSchemaTables(): Promise<boolean> {
|
||||
const placeholders = REQUIRED_SCHEMA_TABLES.map(() => '?').join(', ');
|
||||
const result = await this.db
|
||||
.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (${placeholders})`)
|
||||
.bind(...REQUIRED_ACCOUNT_PASSKEY_TABLES)
|
||||
.bind(...REQUIRED_SCHEMA_TABLES)
|
||||
.all<{ name: string }>();
|
||||
const found = new Set((result.results || []).map((row) => row.name));
|
||||
return REQUIRED_ACCOUNT_PASSKEY_TABLES.every((table) => found.has(table));
|
||||
return REQUIRED_SCHEMA_TABLES.every((table) => found.has(table));
|
||||
}
|
||||
|
||||
private sqlChunkSize(fixedBindCount: number): number {
|
||||
@@ -220,12 +234,13 @@ export class StorageService {
|
||||
await this.db.prepare('CREATE TABLE IF NOT EXISTS config (key TEXT PRIMARY KEY, value TEXT NOT NULL)').run();
|
||||
const schemaVersion = await getStoredConfigValue(this.db, STORAGE_SCHEMA_VERSION_KEY);
|
||||
const schemaMissingRequiredTables = schemaVersion === STORAGE_SCHEMA_VERSION
|
||||
? !(await this.hasAccountPasskeyTables())
|
||||
? !(await this.hasRequiredSchemaTables())
|
||||
: true;
|
||||
if (schemaVersion !== STORAGE_SCHEMA_VERSION || schemaMissingRequiredTables) {
|
||||
await ensureStorageSchema(this.db);
|
||||
await saveConfigValue(this.db, STORAGE_SCHEMA_VERSION_KEY, STORAGE_SCHEMA_VERSION);
|
||||
}
|
||||
await ensurePushInstallationCredentials(this.db);
|
||||
|
||||
StorageService.schemaVerified = true;
|
||||
}
|
||||
@@ -704,6 +719,27 @@ export class StorageService {
|
||||
return touchStoredDeviceLastSeen(this.db, userId, deviceIdentifier);
|
||||
}
|
||||
|
||||
async updateDevicePushToken(
|
||||
userId: string,
|
||||
deviceIdentifier: string,
|
||||
pushUuid: string,
|
||||
pushToken: string
|
||||
): Promise<boolean> {
|
||||
return updateStoredDevicePushToken(this.db, userId, deviceIdentifier, pushUuid, pushToken);
|
||||
}
|
||||
|
||||
async clearDevicePushToken(userId: string, deviceIdentifier: string): Promise<{ pushUuid: string | null } | null> {
|
||||
return clearStoredDevicePushToken(this.db, userId, deviceIdentifier);
|
||||
}
|
||||
|
||||
async getDevicePushUuid(userId: string, deviceIdentifier: string): Promise<string | null> {
|
||||
return findStoredDevicePushUuid(this.db, userId, deviceIdentifier);
|
||||
}
|
||||
|
||||
async userHasPushDevice(userId: string): Promise<boolean> {
|
||||
return getUserHasPushDevice(this.db, userId);
|
||||
}
|
||||
|
||||
async clearDeviceKeys(userId: string, deviceIdentifiers: string[]): Promise<number> {
|
||||
return clearStoredDeviceKeys(this.db, userId, deviceIdentifiers);
|
||||
}
|
||||
@@ -716,6 +752,45 @@ export class StorageService {
|
||||
return deleteStoredDevicesByUserId(this.db, userId);
|
||||
}
|
||||
|
||||
// --- Auth requests / Login with device ---
|
||||
|
||||
async createAuthRequest(request: AuthRequestRecord): Promise<void> {
|
||||
await createStoredAuthRequest(this.db, request);
|
||||
}
|
||||
|
||||
async getAuthRequestById(id: string): Promise<AuthRequestRecord | null> {
|
||||
return findStoredAuthRequestById(this.db, id);
|
||||
}
|
||||
|
||||
async listAuthRequestsByUserId(userId: string): Promise<AuthRequestRecord[]> {
|
||||
return listStoredAuthRequestsByUserId(this.db, userId);
|
||||
}
|
||||
|
||||
async listPendingAuthRequestsByUserId(userId: string): Promise<AuthRequestRecord[]> {
|
||||
return listStoredPendingAuthRequestsByUserId(this.db, userId);
|
||||
}
|
||||
|
||||
async updateAuthRequestResponse(
|
||||
id: string,
|
||||
userId: string,
|
||||
update: {
|
||||
approved: boolean;
|
||||
responseDeviceIdentifier: string;
|
||||
key?: string | null;
|
||||
masterPasswordHash?: string | null;
|
||||
}
|
||||
): Promise<boolean> {
|
||||
return updateStoredAuthRequestResponse(this.db, id, userId, update);
|
||||
}
|
||||
|
||||
async markAuthRequestAuthenticated(id: string): Promise<boolean> {
|
||||
return markStoredAuthRequestAuthenticated(this.db, id);
|
||||
}
|
||||
|
||||
async pruneExpiredAuthRequests(): Promise<number> {
|
||||
return pruneStoredExpiredAuthRequests(this.db);
|
||||
}
|
||||
|
||||
async getTrustedDeviceTokenSummariesByUserId(userId: string): Promise<TrustedDeviceTokenSummary[]> {
|
||||
return listStoredTrustedTokenSummaries(this.db, userId);
|
||||
}
|
||||
|
||||
@@ -231,6 +231,8 @@ export interface Device {
|
||||
encryptedUserKey: string | null;
|
||||
encryptedPublicKey: string | null;
|
||||
encryptedPrivateKey: string | null;
|
||||
pushUuid: string | null;
|
||||
pushToken: string | null;
|
||||
devicePendingAuthRequest?: DevicePendingAuthRequest | null;
|
||||
lastSeenAt: string | null;
|
||||
createdAt: string;
|
||||
@@ -273,6 +275,28 @@ export interface DevicePendingAuthRequest {
|
||||
creationDate: string;
|
||||
}
|
||||
|
||||
export type AuthRequestType = 0 | 1 | 2;
|
||||
|
||||
export interface AuthRequestRecord {
|
||||
id: string;
|
||||
userId: string;
|
||||
organizationId: string | null;
|
||||
type: AuthRequestType;
|
||||
requestDeviceIdentifier: string;
|
||||
requestDeviceType: number;
|
||||
requestIpAddress: string | null;
|
||||
requestCountryName: string | null;
|
||||
responseDeviceIdentifier: string | null;
|
||||
accessCode: string;
|
||||
publicKey: string;
|
||||
key: string | null;
|
||||
masterPasswordHash: string | null;
|
||||
approved: boolean | null;
|
||||
creationDate: string;
|
||||
responseDate: string | null;
|
||||
authenticationDate: string | null;
|
||||
}
|
||||
|
||||
export interface DeviceResponse {
|
||||
id: string;
|
||||
userId?: string | null;
|
||||
@@ -443,7 +467,15 @@ export interface TokenResponse {
|
||||
scope: string;
|
||||
unofficialServer: boolean;
|
||||
MasterPasswordPolicy?: {
|
||||
minComplexity: number;
|
||||
minLength: number;
|
||||
requireUpper: boolean;
|
||||
requireLower: boolean;
|
||||
requireNumbers: boolean;
|
||||
requireSpecial: boolean;
|
||||
enforceOnLogin: boolean;
|
||||
Object: string;
|
||||
object?: string;
|
||||
} | null;
|
||||
ApiUseKeyConnector?: boolean;
|
||||
AccountKeys?: any | null;
|
||||
@@ -472,12 +504,13 @@ export interface ProfileResponse {
|
||||
accountKeys: any | null;
|
||||
securityStamp: string;
|
||||
organizations: any[];
|
||||
organizationsNew?: any[];
|
||||
providers: any[];
|
||||
providerOrganizations: any[];
|
||||
forcePasswordReset: boolean;
|
||||
avatarColor: string | null;
|
||||
creationDate: string;
|
||||
verifyDevices?: boolean;
|
||||
verifyDevices: boolean;
|
||||
role?: UserRole;
|
||||
status?: UserStatus;
|
||||
object: string;
|
||||
@@ -536,6 +569,7 @@ export interface SyncResponse {
|
||||
ciphers: CipherResponse[];
|
||||
domains: any;
|
||||
policies: any[];
|
||||
policiesNew?: any[];
|
||||
sends: SendResponse[];
|
||||
UserDecryption?: {
|
||||
MasterPasswordUnlock: MasterPasswordUnlock | null;
|
||||
@@ -543,6 +577,10 @@ export interface SyncResponse {
|
||||
KeyConnectorOption?: null;
|
||||
WebAuthnPrfOption?: WebAuthnPrfDecryptionOption | null;
|
||||
WebAuthnPrfOptions?: WebAuthnPrfDecryptionOption[];
|
||||
V2UpgradeToken?: {
|
||||
WrappedUserKey1: string;
|
||||
WrappedUserKey2: string;
|
||||
} | null;
|
||||
Object?: string;
|
||||
} | null;
|
||||
// PascalCase for desktop/browser clients
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { Env, ProfileResponse, User } from '../types';
|
||||
import { buildAccountKeys } from './user-decryption';
|
||||
|
||||
export function buildProfileResponse(user: User, env?: Env): ProfileResponse {
|
||||
void env;
|
||||
const organizations: any[] = [];
|
||||
const accountKeys = buildAccountKeys(user);
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
emailVerified: true,
|
||||
premium: true,
|
||||
premiumFromOrganization: false,
|
||||
usesKeyConnector: false,
|
||||
masterPasswordHint: user.masterPasswordHint,
|
||||
culture: 'en-US',
|
||||
twoFactorEnabled: !!user.totpSecret,
|
||||
key: user.key,
|
||||
privateKey: user.privateKey,
|
||||
accountKeys,
|
||||
securityStamp: user.securityStamp || user.id,
|
||||
organizations,
|
||||
organizationsNew: organizations,
|
||||
providers: [],
|
||||
providerOrganizations: [],
|
||||
forcePasswordReset: false,
|
||||
avatarColor: null,
|
||||
creationDate: user.createdAt,
|
||||
verifyDevices: user.verifyDevices !== false,
|
||||
role: user.role,
|
||||
status: user.status,
|
||||
object: 'profile',
|
||||
};
|
||||
}
|
||||
@@ -16,6 +16,7 @@ export function buildAccountKeys(user: Pick<User, 'privateKey' | 'publicKey'>):
|
||||
publicKeyEncryptionKeyPair: {
|
||||
wrappedPrivateKey: user.privateKey,
|
||||
publicKey,
|
||||
signedPublicKey: null,
|
||||
Object: 'publicKeyEncryptionKeyPair',
|
||||
},
|
||||
Object: 'privateKeys',
|
||||
|
||||
|
Before Width: | Height: | Size: 4.0 KiB After Width: | Height: | Size: 3.2 KiB |
|
Before Width: | Height: | Size: 1.0 KiB After Width: | Height: | Size: 619 B |
|
Before Width: | Height: | Size: 4.3 KiB After Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1,10 @@
|
||||
<svg width="512" height="512" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<!-- Full-bleed background for any/maskable -->
|
||||
<rect width="512" height="512" fill="#116FF9"/>
|
||||
<!-- Logo scaled to ~50% centered in safe zone (inner 66% = Android adaptive icon guideline) -->
|
||||
<g transform="translate(256,256) scale(0.5) translate(-380,-380)">
|
||||
<path d="M386.5 183C497.785 183 588 271.2 588 380C588 419.877 575.879 456.986 555.046 488H17.6816C16.5766 481.834 16 475.484 16 469C16 413.617 58.0774 368.061 112.008 362.558C108.771 353.989 107 344.701 107 335C107 291.922 141.922 257 185 257C198.365 257 210.945 260.362 221.94 266.286C258.437 215.895 318.539 183 386.5 183Z" fill="#F6821F"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M92.6568 91.0069C88.7796 262.923 101.55 381.119 143.869 469.459C186.188 557.799 258.092 616.353 372.665 668.892C485.877 616.354 556.929 557.802 598.746 469.461C640.564 381.12 653.181 262.923 649.35 91.0069H92.6568ZM539.796 432.933C570.479 365.533 581.347 278.379 582.419 153.939L582.422 153.432H377.661V593.786L378.405 593.364C458.602 547.962 509.101 500.36 539.796 432.933Z" fill="white"/>
|
||||
<path d="M604.465 305C680.976 305 743 367.233 743 444C743 459.378 740.509 474.172 735.913 488H379V423.553C391.721 397.751 418.287 380 449 380C459.483 380 469.482 382.068 478.613 385.818C500.559 338.11 548.658 305 604.465 305Z" fill="#FD9C33"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
|
Before Width: | Height: | Size: 1.9 KiB After Width: | Height: | Size: 1.1 KiB |
@@ -3,6 +3,7 @@ import { useLocation } from 'wouter';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import AppAuthenticatedShell from '@/components/AppAuthenticatedShell';
|
||||
import AppGlobalOverlays, { type AppConfirmState } from '@/components/AppGlobalOverlays';
|
||||
import AuthRequestApprovalDialog from '@/components/AuthRequestApprovalDialog';
|
||||
import AuthViews from '@/components/AuthViews';
|
||||
import NotFoundPage from '@/components/NotFoundPage';
|
||||
import PublicSendPage from '@/components/PublicSendPage';
|
||||
@@ -19,14 +20,21 @@ import {
|
||||
saveProfileSnapshot,
|
||||
revokeCurrentSession,
|
||||
getTotpStatus,
|
||||
getVaultRevisionDate,
|
||||
saveSession,
|
||||
stripProfileSecrets,
|
||||
} from '@/lib/api/auth';
|
||||
import {
|
||||
encryptSessionUserKeyForAuthRequest,
|
||||
isPendingAuthRequest,
|
||||
listPendingAuthRequests,
|
||||
respondToAuthRequest,
|
||||
} from '@/lib/api/auth-requests';
|
||||
import { clearAuditLogs, getAuditLogSettings, listAdminInvites, listAdminUsers, listAuditLogs, saveAuditLogSettings, type AuditLogFilters } from '@/lib/api/admin';
|
||||
import { getDomainRules, saveDomainRules } from '@/lib/api/domains';
|
||||
import { getSends } from '@/lib/api/send';
|
||||
import { repairCipherKeyMismatches, repairCipherUriChecksums } from '@/lib/api/vault';
|
||||
import { getCachedVaultCoreSnapshot, invalidateVaultCoreSyncSnapshot, loadVaultCoreSyncSnapshot } from '@/lib/api/vault-sync';
|
||||
import { getSendById, getSends } from '@/lib/api/send';
|
||||
import { getCipherById, getFolderById, repairCipherKeyMismatches, repairCipherUriChecksums } from '@/lib/api/vault';
|
||||
import { getCachedVaultCoreSnapshot, invalidateVaultCoreSyncSnapshot, loadVaultCoreSyncSnapshot, saveVaultCoreSyncSnapshot } from '@/lib/api/vault-sync';
|
||||
import { silentlyRepairBackupSettingsIfNeeded } from '@/lib/backup-settings-repair';
|
||||
import {
|
||||
parseSignalRTextFrames,
|
||||
@@ -74,7 +82,7 @@ import {
|
||||
createDemoMainRoutesProps,
|
||||
} from '@/lib/demo';
|
||||
import type { AdminBackupSettings } from '@/lib/api/backup';
|
||||
import type { AdminInvite, AdminUser, AppPhase, AuditLogSettings, AuthorizedDevice, Cipher, CustomEquivalentDomain, DomainRules, Folder as VaultFolder, Profile, Send, SessionState } from '@/lib/types';
|
||||
import type { AdminInvite, AdminUser, AppPhase, AuditLogSettings, AuthRequest, AuthorizedDevice, Cipher, CustomEquivalentDomain, DomainRules, Folder as VaultFolder, Profile, Send, SessionState } from '@/lib/types';
|
||||
import type { VaultCoreSnapshot } from '@/lib/vault-cache';
|
||||
|
||||
function isBackupProgressDetail(value: unknown): value is BackupProgressDetail {
|
||||
@@ -94,6 +102,8 @@ const IMPORT_ROUTE_ALIASES: ReadonlySet<string> = new Set(IMPORT_ROUTE_PATHS.fil
|
||||
const SETTINGS_HOME_ROUTE = '/settings';
|
||||
const SETTINGS_ACCOUNT_ROUTE = '/settings/account';
|
||||
const SETTINGS_DOMAIN_RULES_ROUTE = '/settings/domain-rules';
|
||||
const DEVICE_MANAGEMENT_ROUTE = '/settings/security/device-management';
|
||||
const LEGACY_DEVICE_MANAGEMENT_ROUTE = '/security/devices';
|
||||
const AUTH_ROUTE_PATHS = ['/', '/login', '/register', '/lock', '/recover-2fa'] as const;
|
||||
const APP_ROUTE_PATHS = [
|
||||
'/',
|
||||
@@ -102,7 +112,8 @@ const APP_ROUTE_PATHS = [
|
||||
'/sends',
|
||||
'/admin',
|
||||
'/logs',
|
||||
'/security/devices',
|
||||
LEGACY_DEVICE_MANAGEMENT_ROUTE,
|
||||
DEVICE_MANAGEMENT_ROUTE,
|
||||
'/backup',
|
||||
'/settings',
|
||||
SETTINGS_ACCOUNT_ROUTE,
|
||||
@@ -124,10 +135,22 @@ function normalizeRoutePath(path: string): string {
|
||||
}
|
||||
const THEME_STORAGE_KEY = 'nodewarden.theme.preference.v1';
|
||||
const SIGNALR_RECORD_SEPARATOR = String.fromCharCode(0x1e);
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_CIPHER_UPDATE = 0;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_CIPHER_CREATE = 1;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_FOLDER_DELETE = 3;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_CIPHERS = 4;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_VAULT = 5;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_FOLDER_CREATE = 7;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_FOLDER_UPDATE = 8;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_CIPHER_DELETE = 9;
|
||||
const SIGNALR_UPDATE_TYPE_LOG_OUT = 11;
|
||||
const SIGNALR_UPDATE_TYPE_DEVICE_STATUS = 12;
|
||||
const SIGNALR_UPDATE_TYPE_BACKUP_RESTORE_PROGRESS = 13;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_SEND_CREATE = 12;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_SEND_UPDATE = 13;
|
||||
const SIGNALR_UPDATE_TYPE_SYNC_SEND_DELETE = 14;
|
||||
const SIGNALR_UPDATE_TYPE_AUTH_REQUEST = 15;
|
||||
const SIGNALR_UPDATE_TYPE_AUTH_REQUEST_RESPONSE = 16;
|
||||
const SIGNALR_UPDATE_TYPE_DEVICE_STATUS = 101;
|
||||
const SIGNALR_UPDATE_TYPE_BACKUP_RESTORE_PROGRESS = 102;
|
||||
|
||||
type ThemePreference = 'system' | 'light' | 'dark';
|
||||
type LockTimeoutMinutes = 0 | 1 | 5 | 15 | 30;
|
||||
@@ -213,6 +236,8 @@ export default function App() {
|
||||
const [disableTotpOpen, setDisableTotpOpen] = useState(false);
|
||||
const [disableTotpPassword, setDisableTotpPassword] = useState('');
|
||||
const [disableTotpSubmitting, setDisableTotpSubmitting] = useState(false);
|
||||
const [authRequestDialogDismissedId, setAuthRequestDialogDismissedId] = useState<string | null>(null);
|
||||
const [authRequestSubmittingId, setAuthRequestSubmittingId] = useState<string | null>(null);
|
||||
const [recoverValues, setRecoverValues] = useState({ email: '', password: '', recoveryCode: '' });
|
||||
const [themePreference, setThemePreference] = useState<ThemePreference>(() => readThemePreference());
|
||||
const [systemTheme, setSystemTheme] = useState<'light' | 'dark'>(() => resolveSystemTheme());
|
||||
@@ -237,6 +262,7 @@ export default function App() {
|
||||
const sessionRef = useRef<SessionState | null>(initialBootstrap.session);
|
||||
const silentRefreshVaultRef = useRef<() => Promise<void>>(async () => {});
|
||||
const refreshAuthorizedDevicesRef = useRef<() => Promise<void>>(async () => {});
|
||||
const refreshPendingAuthRequestsRef = useRef<() => Promise<void>>(async () => {});
|
||||
const repairAttemptRef = useRef<string>('');
|
||||
const uriChecksumRepairAttemptRef = useRef<string>('');
|
||||
const pendingVaultCoreQueryRefreshRef = useRef<Promise<{ data?: VaultCoreSnapshot } | unknown> | null>(null);
|
||||
@@ -479,7 +505,7 @@ export default function App() {
|
||||
};
|
||||
}, [phase, session?.email, location, navigate]);
|
||||
|
||||
async function finalizeLogin(login: CompletedLogin, successMessage = t('txt_login_success')) {
|
||||
async function finalizeLogin(login: CompletedLogin) {
|
||||
setSession(login.session);
|
||||
setProfile(login.profile);
|
||||
setUnlockPreparing(false);
|
||||
@@ -493,7 +519,6 @@ export default function App() {
|
||||
if (location === '/' || location === '/login' || location === '/register' || location === '/lock') {
|
||||
navigate('/vault');
|
||||
}
|
||||
pushToast('success', successMessage);
|
||||
void (async () => {
|
||||
try {
|
||||
const hydratedProfile = await login.profilePromise;
|
||||
@@ -510,7 +535,7 @@ export default function App() {
|
||||
if (IS_DEMO_MODE) {
|
||||
setPendingAuthAction('login');
|
||||
try {
|
||||
await finalizeLogin(createDemoCompletedLogin(loginValues.email), t('txt_login_success'));
|
||||
await finalizeLogin(createDemoCompletedLogin(loginValues.email));
|
||||
} finally {
|
||||
setPendingAuthAction(null);
|
||||
}
|
||||
@@ -582,7 +607,7 @@ export default function App() {
|
||||
try {
|
||||
const result = await performPasskeyLogin(defaultKdfIterations, expectedEmail);
|
||||
if (result.kind === 'success') {
|
||||
await finalizeLogin(result.login, t('txt_unlocked'));
|
||||
await finalizeLogin(result.login);
|
||||
return;
|
||||
}
|
||||
if (result.kind === 'password') {
|
||||
@@ -624,7 +649,7 @@ export default function App() {
|
||||
setTotpSubmitting(true);
|
||||
try {
|
||||
const login = await performTotpLogin(pendingTotp, totpCode, rememberDevice);
|
||||
await finalizeLogin(login, pendingTotpMode === 'unlock' ? t('txt_unlocked') : t('txt_login_success'));
|
||||
await finalizeLogin(login);
|
||||
} catch (error) {
|
||||
pushToast('error', error instanceof Error ? error.message : t('txt_totp_verify_failed'));
|
||||
} finally {
|
||||
@@ -764,7 +789,7 @@ export default function App() {
|
||||
if (IS_DEMO_MODE) {
|
||||
setPendingAuthAction('unlock');
|
||||
try {
|
||||
await finalizeLogin(createDemoCompletedLogin(session.email), t('txt_unlocked'));
|
||||
await finalizeLogin(createDemoCompletedLogin(session.email));
|
||||
} finally {
|
||||
setPendingAuthAction(null);
|
||||
}
|
||||
@@ -778,7 +803,7 @@ export default function App() {
|
||||
try {
|
||||
const result = await performUnlock(session, profile, unlockPassword, defaultKdfIterations);
|
||||
if (result.kind === 'success') {
|
||||
await finalizeLogin(result.login, t('txt_unlocked'));
|
||||
await finalizeLogin(result.login);
|
||||
return;
|
||||
}
|
||||
if (result.kind === 'totp') {
|
||||
@@ -1060,6 +1085,53 @@ export default function App() {
|
||||
enabled: !IS_DEMO_MODE && phase === 'app' && !!session?.accessToken && vaultInitialDecryptDone,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
const pendingAuthRequestsQueryKey = useMemo(() => ['auth-requests-pending', vaultCacheKey || session?.email] as const, [vaultCacheKey, session?.email]);
|
||||
const pendingAuthRequestsQuery = useQuery({
|
||||
queryKey: pendingAuthRequestsQueryKey,
|
||||
queryFn: () => listPendingAuthRequests(authedFetch, profile?.email || session?.email || ''),
|
||||
enabled: !IS_DEMO_MODE && phase === 'app' && !!session?.accessToken && !!session?.symEncKey && !!session?.symMacKey && !!(profile?.email || session?.email),
|
||||
staleTime: 5_000,
|
||||
refetchInterval: 15_000,
|
||||
refetchIntervalInBackground: true,
|
||||
});
|
||||
const pendingAuthRequests = (pendingAuthRequestsQuery.data || []).filter(isPendingAuthRequest);
|
||||
const latestPendingAuthRequest = pendingAuthRequests[0] || null;
|
||||
const authRequestDialogOpen = !!latestPendingAuthRequest && latestPendingAuthRequest.id !== authRequestDialogDismissedId;
|
||||
|
||||
async function approveAuthRequest(authRequest: AuthRequest): Promise<void> {
|
||||
if (!session) throw new Error(t('txt_vault_key_unavailable'));
|
||||
setAuthRequestSubmittingId(authRequest.id);
|
||||
try {
|
||||
const key = await encryptSessionUserKeyForAuthRequest(session, authRequest);
|
||||
await respondToAuthRequest(authedFetch, authRequest.id, {
|
||||
key,
|
||||
masterPasswordHash: null,
|
||||
deviceIdentifier: getCurrentDeviceIdentifier(),
|
||||
requestApproved: true,
|
||||
});
|
||||
setAuthRequestDialogDismissedId(null);
|
||||
pushToast('success', t('txt_auth_request_approved'));
|
||||
await pendingAuthRequestsQuery.refetch();
|
||||
} finally {
|
||||
setAuthRequestSubmittingId(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function denyAuthRequest(authRequest: AuthRequest): Promise<void> {
|
||||
setAuthRequestSubmittingId(authRequest.id);
|
||||
try {
|
||||
await respondToAuthRequest(authedFetch, authRequest.id, {
|
||||
deviceIdentifier: getCurrentDeviceIdentifier(),
|
||||
requestApproved: false,
|
||||
});
|
||||
setAuthRequestDialogDismissedId(null);
|
||||
pushToast('success', t('txt_auth_request_denied'));
|
||||
await pendingAuthRequestsQuery.refetch();
|
||||
} finally {
|
||||
setAuthRequestSubmittingId(null);
|
||||
}
|
||||
}
|
||||
|
||||
function handleSaveDomainRules(customEquivalentDomains: CustomEquivalentDomain[], excludedGlobalEquivalentDomains: number[]): Promise<void> {
|
||||
const equivalentDomains = customEquivalentDomains.filter((rule) => !rule.excluded).map((rule) => rule.domains);
|
||||
const excludedGlobalTypes = new Set(excludedGlobalEquivalentDomains);
|
||||
@@ -1269,6 +1341,193 @@ export default function App() {
|
||||
|
||||
silentRefreshVaultRef.current = refreshVaultSilently;
|
||||
|
||||
function normalizeVaultCoreSnapshot(snapshot?: Partial<VaultCoreSnapshot> | null): VaultCoreSnapshot {
|
||||
return {
|
||||
ciphers: Array.isArray(snapshot?.ciphers) ? snapshot.ciphers : [],
|
||||
folders: Array.isArray(snapshot?.folders) ? snapshot.folders : [],
|
||||
sends: Array.isArray(snapshot?.sends) ? snapshot.sends : [],
|
||||
};
|
||||
}
|
||||
|
||||
function upsertById<T extends { id: string }>(items: T[], nextItem: T): T[] {
|
||||
const nextId = String(nextItem.id || '').trim();
|
||||
if (!nextId) return items;
|
||||
const index = items.findIndex((item) => String(item.id || '').trim() === nextId);
|
||||
if (index < 0) return [...items, nextItem];
|
||||
const next = items.slice();
|
||||
next[index] = nextItem;
|
||||
return next;
|
||||
}
|
||||
|
||||
function removeById<T extends { id: string }>(items: T[], id: string): T[] {
|
||||
const normalizedId = String(id || '').trim();
|
||||
if (!normalizedId) return items;
|
||||
return items.filter((item) => String(item.id || '').trim() !== normalizedId);
|
||||
}
|
||||
|
||||
function revisionStampFromIso(value: unknown): number | null {
|
||||
const stamp = new Date(String(value || '').trim()).getTime();
|
||||
return Number.isFinite(stamp) && stamp > 0 ? stamp : null;
|
||||
}
|
||||
|
||||
function patchVaultCoreSnapshot(
|
||||
updater: (snapshot: VaultCoreSnapshot) => VaultCoreSnapshot,
|
||||
options?: { revisionStamp?: number | null }
|
||||
): void {
|
||||
if (!vaultCacheKey) return;
|
||||
let nextSnapshot: VaultCoreSnapshot | null = null;
|
||||
queryClient.setQueryData(['vault-core', vaultCacheKey], (previous?: VaultCoreSnapshot) => {
|
||||
const base = normalizeVaultCoreSnapshot(previous || cachedVaultCore);
|
||||
nextSnapshot = updater(base);
|
||||
return nextSnapshot;
|
||||
});
|
||||
if (nextSnapshot) {
|
||||
setCachedVaultCore(nextSnapshot);
|
||||
void saveVaultCoreSyncSnapshot(vaultCacheKey, nextSnapshot, options?.revisionStamp ?? null);
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshVaultCoreRevisionStamp(): Promise<void> {
|
||||
if (!vaultCacheKey || !session?.accessToken) return;
|
||||
try {
|
||||
const revisionStamp = await getVaultRevisionDate(authedFetch);
|
||||
const currentSnapshot = normalizeVaultCoreSnapshot(
|
||||
queryClient.getQueryData<VaultCoreSnapshot>(['vault-core', vaultCacheKey]) || cachedVaultCore
|
||||
);
|
||||
await saveVaultCoreSyncSnapshot(vaultCacheKey, currentSnapshot, revisionStamp);
|
||||
} catch {
|
||||
// A stale revision stamp only affects the next cache validation; the local resource patch remains valid.
|
||||
}
|
||||
}
|
||||
|
||||
function upsertEncryptedCipher(cipher: Cipher, revisionStamp?: number | null): void {
|
||||
patchVaultCoreSnapshot((snapshot) => ({
|
||||
...snapshot,
|
||||
ciphers: upsertById(snapshot.ciphers, cipher),
|
||||
}), { revisionStamp: revisionStamp ?? revisionStampFromIso(cipher.revisionDate) });
|
||||
}
|
||||
|
||||
function deleteCipherLocally(cipherId: string, revisionStamp?: number | null): void {
|
||||
const id = String(cipherId || '').trim();
|
||||
if (!id) return;
|
||||
patchVaultCoreSnapshot((snapshot) => ({
|
||||
...snapshot,
|
||||
ciphers: removeById(snapshot.ciphers, id),
|
||||
}), { revisionStamp });
|
||||
setDecryptedCiphers((current) => removeById(current, id));
|
||||
}
|
||||
|
||||
function upsertEncryptedFolder(folder: VaultFolder, revisionStamp?: number | null): void {
|
||||
patchVaultCoreSnapshot((snapshot) => ({
|
||||
...snapshot,
|
||||
folders: upsertById(snapshot.folders, folder),
|
||||
}), { revisionStamp: revisionStamp ?? revisionStampFromIso(folder.revisionDate) });
|
||||
}
|
||||
|
||||
function deleteFolderLocally(folderId: string, revisionStamp?: number | null): void {
|
||||
const id = String(folderId || '').trim();
|
||||
if (!id) return;
|
||||
patchVaultCoreSnapshot((snapshot) => ({
|
||||
...snapshot,
|
||||
folders: removeById(snapshot.folders, id),
|
||||
ciphers: snapshot.ciphers.map((cipher) => (
|
||||
String(cipher.folderId || '').trim() === id ? { ...cipher, folderId: null } : cipher
|
||||
)),
|
||||
}), { revisionStamp });
|
||||
setDecryptedFolders((current) => removeById(current, id));
|
||||
setDecryptedCiphers((current) => current.map((cipher) => (
|
||||
String(cipher.folderId || '').trim() === id ? { ...cipher, folderId: null } : cipher
|
||||
)));
|
||||
}
|
||||
|
||||
function upsertEncryptedSend(send: Send, revisionStamp?: number | null): void {
|
||||
patchVaultCoreSnapshot((snapshot) => ({
|
||||
...snapshot,
|
||||
sends: upsertById(snapshot.sends, send),
|
||||
}), { revisionStamp: revisionStamp ?? revisionStampFromIso(send.revisionDate) });
|
||||
queryClient.setQueryData(sendsQueryKey, (previous?: Send[]) => upsertById(Array.isArray(previous) ? previous : [], send));
|
||||
}
|
||||
|
||||
function deleteSendLocally(sendId: string, revisionStamp?: number | null): void {
|
||||
const id = String(sendId || '').trim();
|
||||
if (!id) return;
|
||||
patchVaultCoreSnapshot((snapshot) => ({
|
||||
...snapshot,
|
||||
sends: removeById(snapshot.sends, id),
|
||||
}), { revisionStamp });
|
||||
queryClient.setQueryData(sendsQueryKey, (previous?: Send[]) => removeById(Array.isArray(previous) ? previous : [], id));
|
||||
setDecryptedSends((current) => removeById(current, id));
|
||||
}
|
||||
|
||||
async function upsertCipherFromNotification(cipherId: string, revisionStamp?: number | null): Promise<void> {
|
||||
const id = String(cipherId || '').trim();
|
||||
if (!id || !session?.symEncKey || !session?.symMacKey) return;
|
||||
try {
|
||||
const encrypted = await getCipherById(authedFetch, id);
|
||||
upsertEncryptedCipher(encrypted, revisionStamp);
|
||||
const result = await decryptVaultCore({
|
||||
folders: [],
|
||||
ciphers: [encrypted],
|
||||
symEncKeyB64: session.symEncKey,
|
||||
symMacKeyB64: session.symMacKey,
|
||||
});
|
||||
const decrypted = result.ciphers[0];
|
||||
if (decrypted) setDecryptedCiphers((current) => upsertById(current, decrypted));
|
||||
} catch (error) {
|
||||
if ((error as { status?: number }).status === 404) {
|
||||
deleteCipherLocally(id);
|
||||
return;
|
||||
}
|
||||
console.warn('Failed to upsert cipher from notification:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async function upsertFolderFromNotification(folderId: string, revisionStamp?: number | null): Promise<void> {
|
||||
const id = String(folderId || '').trim();
|
||||
if (!id || !session?.symEncKey || !session?.symMacKey) return;
|
||||
try {
|
||||
const encrypted = await getFolderById(authedFetch, id);
|
||||
upsertEncryptedFolder(encrypted, revisionStamp);
|
||||
const result = await decryptVaultCore({
|
||||
folders: [encrypted],
|
||||
ciphers: [],
|
||||
symEncKeyB64: session.symEncKey,
|
||||
symMacKeyB64: session.symMacKey,
|
||||
});
|
||||
const decrypted = result.folders[0];
|
||||
if (decrypted) setDecryptedFolders((current) => upsertById(current, decrypted));
|
||||
} catch (error) {
|
||||
if ((error as { status?: number }).status === 404) {
|
||||
deleteFolderLocally(id);
|
||||
return;
|
||||
}
|
||||
console.warn('Failed to upsert folder from notification:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async function upsertSendFromNotification(sendId: string, revisionStamp?: number | null): Promise<void> {
|
||||
const id = String(sendId || '').trim();
|
||||
if (!id || !session?.symEncKey || !session?.symMacKey) return;
|
||||
try {
|
||||
const encrypted = await getSendById(authedFetch, id);
|
||||
upsertEncryptedSend(encrypted, revisionStamp);
|
||||
const sends = await decryptSends({
|
||||
sends: [encrypted],
|
||||
symEncKeyB64: session.symEncKey,
|
||||
symMacKeyB64: session.symMacKey,
|
||||
origin: window.location.origin,
|
||||
});
|
||||
const decrypted = sends[0];
|
||||
if (decrypted) setDecryptedSends((current) => upsertById(current, decrypted));
|
||||
} catch (error) {
|
||||
if ((error as { status?: number }).status === 404) {
|
||||
deleteSendLocally(id);
|
||||
return;
|
||||
}
|
||||
console.warn('Failed to upsert send from notification:', error);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (IS_DEMO_MODE) return;
|
||||
if (phase !== 'app' || !session?.accessToken || !session?.symEncKey || !session?.symMacKey || !vaultInitialDecryptDone) return;
|
||||
@@ -1345,7 +1604,18 @@ export default function App() {
|
||||
const frames = parseSignalRTextFrames(event.data);
|
||||
for (const frame of frames) {
|
||||
if (frame.type !== 1 || frame.target !== 'ReceiveMessage') continue;
|
||||
const updateType = Number(frame.arguments?.[0]?.Type || 0);
|
||||
const message = frame.arguments?.[0] as Record<string, unknown> | undefined;
|
||||
const updateType = Number(message?.Type || 0);
|
||||
const contextId = String(message?.ContextId || '').trim();
|
||||
const payload = message?.Payload;
|
||||
const payloadRecord = payload && typeof payload === 'object' ? payload as Record<string, unknown> : null;
|
||||
const resourceId = String(payloadRecord?.Id || payloadRecord?.id || '').trim();
|
||||
const revisionStamp = revisionStampFromIso(
|
||||
payloadRecord?.RevisionDate
|
||||
|| payloadRecord?.revisionDate
|
||||
|| message?.Date
|
||||
|| message?.date
|
||||
);
|
||||
if (updateType === SIGNALR_UPDATE_TYPE_LOG_OUT) {
|
||||
logoutNow();
|
||||
return;
|
||||
@@ -1354,14 +1624,16 @@ export default function App() {
|
||||
void refreshAuthorizedDevicesRef.current();
|
||||
continue;
|
||||
}
|
||||
if (updateType === SIGNALR_UPDATE_TYPE_AUTH_REQUEST || updateType === SIGNALR_UPDATE_TYPE_AUTH_REQUEST_RESPONSE) {
|
||||
void refreshPendingAuthRequestsRef.current();
|
||||
continue;
|
||||
}
|
||||
if (updateType === SIGNALR_UPDATE_TYPE_BACKUP_RESTORE_PROGRESS) {
|
||||
const payload = frame.arguments?.[0]?.Payload;
|
||||
if (isBackupProgressDetail(payload)) dispatchBackupProgress(payload);
|
||||
continue;
|
||||
}
|
||||
if (updateType !== SIGNALR_UPDATE_TYPE_SYNC_VAULT) continue;
|
||||
const contextId = String(frame.arguments?.[0]?.ContextId || '').trim();
|
||||
if (contextId && contextId === getCurrentDeviceIdentifier()) continue;
|
||||
if (updateType === SIGNALR_UPDATE_TYPE_SYNC_CIPHERS || updateType === SIGNALR_UPDATE_TYPE_SYNC_VAULT) {
|
||||
if (notificationRefreshTimerRef.current !== null) {
|
||||
window.clearTimeout(notificationRefreshTimerRef.current);
|
||||
}
|
||||
@@ -1369,6 +1641,32 @@ export default function App() {
|
||||
notificationRefreshTimerRef.current = null;
|
||||
void silentRefreshVaultRef.current();
|
||||
}, 250);
|
||||
continue;
|
||||
}
|
||||
if ((updateType === SIGNALR_UPDATE_TYPE_SYNC_CIPHER_CREATE || updateType === SIGNALR_UPDATE_TYPE_SYNC_CIPHER_UPDATE) && resourceId) {
|
||||
void upsertCipherFromNotification(resourceId, revisionStamp);
|
||||
continue;
|
||||
}
|
||||
if (updateType === SIGNALR_UPDATE_TYPE_SYNC_CIPHER_DELETE && resourceId) {
|
||||
deleteCipherLocally(resourceId, revisionStamp);
|
||||
continue;
|
||||
}
|
||||
if ((updateType === SIGNALR_UPDATE_TYPE_SYNC_FOLDER_CREATE || updateType === SIGNALR_UPDATE_TYPE_SYNC_FOLDER_UPDATE) && resourceId) {
|
||||
void upsertFolderFromNotification(resourceId, revisionStamp);
|
||||
continue;
|
||||
}
|
||||
if (updateType === SIGNALR_UPDATE_TYPE_SYNC_FOLDER_DELETE && resourceId) {
|
||||
deleteFolderLocally(resourceId, revisionStamp);
|
||||
continue;
|
||||
}
|
||||
if ((updateType === SIGNALR_UPDATE_TYPE_SYNC_SEND_CREATE || updateType === SIGNALR_UPDATE_TYPE_SYNC_SEND_UPDATE) && resourceId) {
|
||||
void upsertSendFromNotification(resourceId, revisionStamp);
|
||||
continue;
|
||||
}
|
||||
if (updateType === SIGNALR_UPDATE_TYPE_SYNC_SEND_DELETE && resourceId) {
|
||||
deleteSendLocally(resourceId, revisionStamp);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1427,8 +1725,33 @@ export default function App() {
|
||||
},
|
||||
refetchSends: refetchSendsFromVaultCore,
|
||||
onNotify: pushToast,
|
||||
patchEncryptedCiphers: (updater) => {
|
||||
patchVaultCoreSnapshot((snapshot) => ({
|
||||
...snapshot,
|
||||
ciphers: updater(snapshot.ciphers),
|
||||
}));
|
||||
},
|
||||
patchEncryptedFolders: (updater) => {
|
||||
patchVaultCoreSnapshot((snapshot) => ({
|
||||
...snapshot,
|
||||
folders: updater(snapshot.folders),
|
||||
}));
|
||||
},
|
||||
patchEncryptedSends: (updater) => {
|
||||
let nextSends: Send[] = [];
|
||||
patchVaultCoreSnapshot((snapshot) => {
|
||||
nextSends = updater(snapshot.sends);
|
||||
return {
|
||||
...snapshot,
|
||||
sends: nextSends,
|
||||
};
|
||||
});
|
||||
queryClient.setQueryData(sendsQueryKey, nextSends);
|
||||
},
|
||||
patchDecryptedCiphers: setDecryptedCiphers,
|
||||
patchDecryptedFolders: setDecryptedFolders,
|
||||
patchDecryptedSends: setDecryptedSends,
|
||||
refreshVaultRevisionStamp: refreshVaultCoreRevisionStamp,
|
||||
});
|
||||
const accountSecurityActions = useAccountSecurityActions({
|
||||
authedFetch,
|
||||
@@ -1459,6 +1782,11 @@ export default function App() {
|
||||
if (!vaultInitialDecryptDone) return;
|
||||
await authorizedDevicesQuery.refetch();
|
||||
};
|
||||
refreshPendingAuthRequestsRef.current = async () => {
|
||||
if (!vaultInitialDecryptDone || !(profile?.email || session?.email)) return;
|
||||
setAuthRequestDialogDismissedId(null);
|
||||
await pendingAuthRequestsQuery.refetch();
|
||||
};
|
||||
|
||||
const hashPathRaw = typeof window !== 'undefined' ? window.location.hash || '' : '';
|
||||
const hashPath = hashPathRaw.startsWith('#') ? hashPathRaw.slice(1) : hashPathRaw;
|
||||
@@ -1477,7 +1805,7 @@ export default function App() {
|
||||
const isKnownAppRoute = APP_ROUTES.has(routeLocation) || isPublicSendRoute || isImportHashRoute;
|
||||
const isUnknownRoute = isMalformedSendRoute || (phase === 'app' ? !isKnownAppRoute : !isKnownAuthRoute && !APP_ROUTES.has(routeLocation));
|
||||
const isImportRoute = routeLocation === IMPORT_ROUTE || IMPORT_ROUTE_ALIASES.has(routeLocation);
|
||||
const showSidebarToggle = mobileLayout && (location === '/vault' || location === '/sends');
|
||||
const showSidebarToggle = mobileLayout && location === '/sends';
|
||||
const sidebarToggleTitle = location === '/vault' ? t('txt_folders') : t('txt_type');
|
||||
const demoDomainRules = useMemo<DomainRules>(() => ({
|
||||
equivalentDomains: [
|
||||
@@ -1509,7 +1837,7 @@ export default function App() {
|
||||
if (location === '/sends') return t('nav_sends');
|
||||
if (location === '/admin') return t('nav_admin_panel');
|
||||
if (location === '/logs') return t('nav_log_center');
|
||||
if (location === '/security/devices') return t('nav_device_management');
|
||||
if (location === LEGACY_DEVICE_MANAGEMENT_ROUTE || location === DEVICE_MANAGEMENT_ROUTE) return t('nav_device_management');
|
||||
if (location === SETTINGS_DOMAIN_RULES_ROUTE) return t('nav_domain_rules');
|
||||
if (location === '/backup') return t('nav_backup_strategy');
|
||||
if (isImportRoute) return t('nav_import_export');
|
||||
@@ -1518,6 +1846,16 @@ export default function App() {
|
||||
return t('nav_my_vault');
|
||||
})();
|
||||
|
||||
useEffect(() => {
|
||||
if (phase !== 'app') return;
|
||||
if (!hashPath.startsWith('/')) return;
|
||||
if (normalizedHashPath !== DEVICE_MANAGEMENT_ROUTE && normalizedHashPath !== LEGACY_DEVICE_MANAGEMENT_ROUTE) return;
|
||||
if (typeof window !== 'undefined' && typeof window.history?.replaceState === 'function') {
|
||||
window.history.replaceState(null, '', DEVICE_MANAGEMENT_ROUTE);
|
||||
}
|
||||
if (location !== DEVICE_MANAGEMENT_ROUTE) navigate(DEVICE_MANAGEMENT_ROUTE);
|
||||
}, [phase, hashPath, normalizedHashPath, location, navigate]);
|
||||
|
||||
useEffect(() => {
|
||||
if (phase === 'app' && location === '/' && !isPublicSendRoute) navigate('/vault');
|
||||
}, [phase, location, isPublicSendRoute, navigate]);
|
||||
@@ -1624,6 +1962,13 @@ export default function App() {
|
||||
onCreateAccountPasskey: accountSecurityActions.createAccountPasskey,
|
||||
onEnableAccountPasskeyDirectUnlock: accountSecurityActions.enableAccountPasskeyDirectUnlock,
|
||||
onDeleteAccountPasskey: accountSecurityActions.deleteAccountPasskey,
|
||||
pendingAuthRequests,
|
||||
pendingAuthRequestsLoading: pendingAuthRequestsQuery.isFetching,
|
||||
onRefreshPendingAuthRequests: async () => {
|
||||
await pendingAuthRequestsQuery.refetch();
|
||||
},
|
||||
onApproveAuthRequest: approveAuthRequest,
|
||||
onDenyAuthRequest: denyAuthRequest,
|
||||
onLockTimeoutChange: setLockTimeoutMinutes,
|
||||
onSessionTimeoutActionChange: setSessionTimeoutAction,
|
||||
onRefreshAuthorizedDevices: accountSecurityActions.refreshAuthorizedDevices,
|
||||
@@ -1868,6 +2213,24 @@ export default function App() {
|
||||
}}
|
||||
disableTotpSubmitting={disableTotpSubmitting}
|
||||
/>
|
||||
<AuthRequestApprovalDialog
|
||||
open={authRequestDialogOpen}
|
||||
authRequest={latestPendingAuthRequest}
|
||||
submitting={!!authRequestSubmittingId}
|
||||
onApprove={() => {
|
||||
if (!latestPendingAuthRequest) return;
|
||||
void approveAuthRequest(latestPendingAuthRequest).catch((error) => {
|
||||
pushToast('error', error instanceof Error ? error.message : t('txt_auth_request_update_failed'));
|
||||
});
|
||||
}}
|
||||
onDeny={() => {
|
||||
if (!latestPendingAuthRequest) return;
|
||||
void denyAuthRequest(latestPendingAuthRequest).catch((error) => {
|
||||
pushToast('error', error instanceof Error ? error.message : t('txt_auth_request_update_failed'));
|
||||
});
|
||||
}}
|
||||
onClose={() => setAuthRequestDialogDismissedId(latestPendingAuthRequest?.id || null)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -47,6 +47,9 @@ function isAdminProfile(profile: Profile | null): boolean {
|
||||
return String(profile?.role || '').toLowerCase() === 'admin';
|
||||
}
|
||||
|
||||
const DEVICE_MANAGEMENT_ROUTE = '/settings/security/device-management';
|
||||
const LEGACY_DEVICE_MANAGEMENT_ROUTE = '/security/devices';
|
||||
|
||||
export default function AppAuthenticatedShell(props: AppAuthenticatedShellProps) {
|
||||
const routeAnimationKey = props.isImportRoute ? props.importRoute : props.location;
|
||||
const isDomainRulesRoute = props.location === '/settings/domain-rules';
|
||||
@@ -55,7 +58,8 @@ export default function AppAuthenticatedShell(props: AppAuthenticatedShellProps)
|
||||
const vaultActive = props.location === '/vault' || props.location === '/vault/totp';
|
||||
const settingsActive = props.location === props.settingsAccountRoute || props.location === '/settings/domain-rules';
|
||||
const dataActive = props.location === '/backup' || props.isImportRoute;
|
||||
const managementActive = props.location === '/admin' || props.location === '/security/devices' || props.location === '/logs';
|
||||
const deviceManagementActive = props.location === DEVICE_MANAGEMENT_ROUTE || props.location === LEGACY_DEVICE_MANAGEMENT_ROUTE;
|
||||
const managementActive = props.location === '/admin' || deviceManagementActive || props.location === '/logs';
|
||||
const [navLayoutMode, setNavLayoutMode] = useState<NavLayoutMode>(readNavLayoutMode);
|
||||
const [navLayoutPickerOpen, setNavLayoutPickerOpen] = useState(false);
|
||||
const navLayoutPickerRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -177,7 +181,7 @@ export default function AppAuthenticatedShell(props: AppAuthenticatedShellProps)
|
||||
{renderSideLink(props.importRoute, props.isImportRoute, <ArrowUpDown size={16} />, t('nav_import_export'))}
|
||||
{isAdmin && renderSideLink('/admin', props.location === '/admin', <Users size={16} />, t('nav_admin_panel'))}
|
||||
{isAdmin && renderSideLink('/logs', props.location === '/logs', <FileClock size={16} />, t('nav_log_center'))}
|
||||
{renderSideLink('/security/devices', props.location === '/security/devices', <MonitorSmartphone size={16} />, t('nav_device_management'))}
|
||||
{renderSideLink(DEVICE_MANAGEMENT_ROUTE, deviceManagementActive, <MonitorSmartphone size={16} />, t('nav_device_management'))}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -222,7 +226,7 @@ export default function AppAuthenticatedShell(props: AppAuthenticatedShellProps)
|
||||
<>
|
||||
{isAdmin && renderSubLink('/admin', props.location === '/admin', t('nav_admin_panel'))}
|
||||
{isAdmin && renderSubLink('/logs', props.location === '/logs', t('nav_log_center'))}
|
||||
{renderSubLink('/security/devices', props.location === '/security/devices', t('nav_device_management'))}
|
||||
{renderSubLink(DEVICE_MANAGEMENT_ROUTE, deviceManagementActive, t('nav_device_management'))}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -8,7 +8,7 @@ import type { AdminBackupImportResponse, AdminBackupRunResponse, AdminBackupSett
|
||||
import type { AuditLogFilters } from '@/lib/api/admin';
|
||||
import type { CiphersImportPayload } from '@/lib/api/vault';
|
||||
import { t } from '@/lib/i18n';
|
||||
import type { AccountPasskeyCredential, AdminInvite, AdminUser, AuditLogListResult, AuditLogSettings, AuthorizedDevice, Cipher, CustomEquivalentDomain, DomainRules, Folder as VaultFolder, Profile, Send, SendDraft, SessionState, VaultDraft } from '@/lib/types';
|
||||
import type { AccountPasskeyCredential, AdminInvite, AdminUser, AuditLogListResult, AuditLogSettings, AuthRequest, AuthorizedDevice, Cipher, CustomEquivalentDomain, DomainRules, Folder as VaultFolder, Profile, Send, SendDraft, SessionState, VaultDraft } from '@/lib/types';
|
||||
import type { ExportRequest } from '@/lib/export-formats';
|
||||
|
||||
const VaultPage = lazy(() => import('@/components/VaultPage'));
|
||||
@@ -116,6 +116,11 @@ export interface AppMainRoutesProps {
|
||||
onCreateAccountPasskey: (name: string, masterPassword: string, directUnlock: boolean) => Promise<AccountPasskeyCredential | null>;
|
||||
onEnableAccountPasskeyDirectUnlock: (id: string, masterPassword: string) => Promise<void>;
|
||||
onDeleteAccountPasskey: (id: string, masterPassword: string) => Promise<void>;
|
||||
pendingAuthRequests: AuthRequest[];
|
||||
pendingAuthRequestsLoading: boolean;
|
||||
onRefreshPendingAuthRequests: () => Promise<void>;
|
||||
onApproveAuthRequest: (request: AuthRequest) => Promise<void>;
|
||||
onDenyAuthRequest: (request: AuthRequest) => Promise<void>;
|
||||
onLockTimeoutChange: (minutes: 0 | 1 | 5 | 15 | 30) => void;
|
||||
onSessionTimeoutActionChange: (action: 'lock' | 'logout') => void;
|
||||
onRefreshAuthorizedDevices: () => Promise<void>;
|
||||
@@ -153,6 +158,7 @@ export interface AppMainRoutesProps {
|
||||
|
||||
export default function AppMainRoutes(props: AppMainRoutesProps) {
|
||||
const importRoutePaths = [props.importRoute, '/tools/import', '/tools/import-export', '/tools/import-data', '/import', '/import-export'] as const;
|
||||
const deviceManagementRoutePaths = ['/security/devices', '/settings/security/device-management'] as const;
|
||||
const isAdmin = String(props.profile?.role || '').toLowerCase() === 'admin';
|
||||
const importPageContent = (
|
||||
<Suspense fallback={<RouteContentFallback />}>
|
||||
@@ -269,6 +275,11 @@ export default function AppMainRoutes(props: AppMainRoutesProps) {
|
||||
onCreateAccountPasskey={props.onCreateAccountPasskey}
|
||||
onEnableAccountPasskeyDirectUnlock={props.onEnableAccountPasskeyDirectUnlock}
|
||||
onDeleteAccountPasskey={props.onDeleteAccountPasskey}
|
||||
pendingAuthRequests={props.pendingAuthRequests}
|
||||
pendingAuthRequestsLoading={props.pendingAuthRequestsLoading}
|
||||
onRefreshPendingAuthRequests={props.onRefreshPendingAuthRequests}
|
||||
onApproveAuthRequest={props.onApproveAuthRequest}
|
||||
onDenyAuthRequest={props.onDenyAuthRequest}
|
||||
onLockTimeoutChange={props.onLockTimeoutChange}
|
||||
onSessionTimeoutActionChange={props.onSessionTimeoutActionChange}
|
||||
onNotify={props.onNotify}
|
||||
@@ -287,7 +298,7 @@ export default function AppMainRoutes(props: AppMainRoutesProps) {
|
||||
<SettingsIcon size={18} />
|
||||
<span>{t('nav_account_settings')}</span>
|
||||
</Link>
|
||||
<Link href="/security/devices" className="mobile-settings-link">
|
||||
<Link href="/settings/security/device-management" className="mobile-settings-link">
|
||||
<Shield size={18} />
|
||||
<span>{t('nav_device_management')}</span>
|
||||
</Link>
|
||||
@@ -327,7 +338,8 @@ export default function AppMainRoutes(props: AppMainRoutesProps) {
|
||||
<LoadingState card lines={4} />
|
||||
) : null}
|
||||
</Route>
|
||||
<Route path="/security/devices">
|
||||
{deviceManagementRoutePaths.map((path) => (
|
||||
<Route key={path} path={path}>
|
||||
<div className="stack">
|
||||
{props.mobileLayout && (
|
||||
<div className="mobile-settings-subhead">
|
||||
@@ -342,7 +354,12 @@ export default function AppMainRoutes(props: AppMainRoutesProps) {
|
||||
devices={props.authorizedDevices}
|
||||
loading={props.authorizedDevicesLoading}
|
||||
error={props.authorizedDevicesError}
|
||||
pendingAuthRequests={props.pendingAuthRequests}
|
||||
pendingAuthRequestsLoading={props.pendingAuthRequestsLoading}
|
||||
onRefresh={() => void props.onRefreshAuthorizedDevices()}
|
||||
onRefreshPendingAuthRequests={props.onRefreshPendingAuthRequests}
|
||||
onApproveAuthRequest={props.onApproveAuthRequest}
|
||||
onDenyAuthRequest={props.onDenyAuthRequest}
|
||||
onRenameDevice={props.onRenameAuthorizedDevice}
|
||||
onRevokeTrust={props.onRevokeDeviceTrust}
|
||||
onTrustPermanently={props.onTrustDevicePermanently}
|
||||
@@ -353,6 +370,7 @@ export default function AppMainRoutes(props: AppMainRoutesProps) {
|
||||
</Suspense>
|
||||
</div>
|
||||
</Route>
|
||||
))}
|
||||
<Route path="/settings/domain-rules">
|
||||
<div className="stack domain-rules-route">
|
||||
{props.mobileLayout && (
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { ShieldCheck, ShieldX } from 'lucide-preact';
|
||||
import ConfirmDialog from '@/components/ConfirmDialog';
|
||||
import { t } from '@/lib/i18n';
|
||||
import type { AuthRequest } from '@/lib/types';
|
||||
|
||||
interface AuthRequestApprovalDialogProps {
|
||||
open: boolean;
|
||||
authRequest: AuthRequest | null;
|
||||
submitting: boolean;
|
||||
onApprove: () => void;
|
||||
onDeny: () => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
function formatDateTime(value: string | null | undefined): string {
|
||||
if (!value) return t('txt_dash');
|
||||
const parsed = new Date(value);
|
||||
if (Number.isNaN(parsed.getTime())) return value;
|
||||
return parsed.toLocaleString();
|
||||
}
|
||||
|
||||
export default function AuthRequestApprovalDialog(props: AuthRequestApprovalDialogProps) {
|
||||
const authRequest = props.authRequest;
|
||||
return (
|
||||
<ConfirmDialog
|
||||
open={props.open && !!authRequest}
|
||||
title={t('txt_approve_device_login')}
|
||||
message={t('txt_auth_request_approve_message')}
|
||||
confirmText={props.submitting ? t('txt_approving') : t('txt_approve')}
|
||||
cancelText={t('txt_later')}
|
||||
confirmDisabled={props.submitting || !authRequest}
|
||||
cancelDisabled={props.submitting}
|
||||
onConfirm={props.onApprove}
|
||||
onCancel={props.onClose}
|
||||
afterActions={(
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-danger dialog-btn"
|
||||
disabled={props.submitting || !authRequest}
|
||||
onClick={props.onDeny}
|
||||
>
|
||||
<ShieldX size={14} className="btn-icon" />
|
||||
{t('txt_deny')}
|
||||
</button>
|
||||
)}
|
||||
>
|
||||
{authRequest && (
|
||||
<div className="auth-request-details">
|
||||
<div className="auth-request-device">
|
||||
<ShieldCheck size={18} />
|
||||
<div>
|
||||
<strong>{authRequest.requestDeviceType || t('txt_unknown_device')}</strong>
|
||||
<small>{authRequest.requestDeviceIdentifier}</small>
|
||||
</div>
|
||||
</div>
|
||||
<div className="auth-request-kv">
|
||||
<span>{t('txt_created')}</span>
|
||||
<strong>{formatDateTime(authRequest.creationDate)}</strong>
|
||||
</div>
|
||||
{authRequest.requestIpAddress && (
|
||||
<div className="auth-request-kv">
|
||||
<span>{t('txt_ip_address')}</span>
|
||||
<strong>{authRequest.requestIpAddress}</strong>
|
||||
</div>
|
||||
)}
|
||||
<div className="auth-request-fingerprint">
|
||||
<span>{t('txt_fingerprint_phrase')}</span>
|
||||
<strong>{authRequest.fingerprintPhrase || t('txt_dash')}</strong>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</ConfirmDialog>
|
||||
);
|
||||
}
|
||||
@@ -83,6 +83,7 @@ export default function ConfirmDialog(props: ConfirmDialogProps) {
|
||||
const [present, setPresent] = useState(props.open);
|
||||
const [closing, setClosing] = useState(false);
|
||||
const cardRef = useRef<HTMLFormElement | null>(null);
|
||||
const maskPointerStartedRef = useRef(false);
|
||||
const restoreFocusRef = useRef<HTMLElement | null>(null);
|
||||
const dialogId = useMemo(() => `confirm-dialog-${++dialogIdCounter}`, []);
|
||||
const titleId = `${dialogId}-title`;
|
||||
@@ -176,8 +177,11 @@ export default function ConfirmDialog(props: ConfirmDialogProps) {
|
||||
return createPortal((
|
||||
<div
|
||||
className={`dialog-mask ${props.variant === 'warning' ? 'warning' : ''} ${props.open && !closing ? 'open' : ''} ${closing ? 'closing' : ''}`}
|
||||
onPointerDown={(event) => {
|
||||
maskPointerStartedRef.current = event.target === event.currentTarget;
|
||||
}}
|
||||
onClick={(event) => {
|
||||
if (event.target !== event.currentTarget || !canDismiss) return;
|
||||
if (event.target !== event.currentTarget || !maskPointerStartedRef.current || !canDismiss) return;
|
||||
props.onCancel();
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
export function CardSkeleton() {
|
||||
return (
|
||||
<div className="skeleton-card">
|
||||
<div className="skeleton-avatar" />
|
||||
<div className="skeleton-content">
|
||||
<div className="skeleton-line skeleton-line-lg" />
|
||||
<div className="skeleton-line" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ListSkeleton({ count = 5 }: { count?: number }) {
|
||||
return (
|
||||
<>
|
||||
{Array.from({ length: count }).map((_, i) => (
|
||||
<div key={i} className="skeleton-list-item">
|
||||
<div className="skeleton-icon" />
|
||||
<div className="skeleton-content">
|
||||
<div className="skeleton-line skeleton-line-md" />
|
||||
<div className="skeleton-line skeleton-line-sm" />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function PageSkeleton() {
|
||||
return (
|
||||
<div className="skeleton-page">
|
||||
<div className="skeleton-header">
|
||||
<div className="skeleton-line skeleton-line-xl" />
|
||||
</div>
|
||||
<div className="skeleton-body">
|
||||
<ListSkeleton />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -23,7 +23,6 @@ export default function NetworkStatusBadge() {
|
||||
const Icon = status === 'online' ? Wifi : WifiOff;
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let timer = 0;
|
||||
|
||||
const checkService = async () => {
|
||||
@@ -31,10 +30,7 @@ export default function NetworkStatusBadge() {
|
||||
setCurrentNetworkStatus('offline');
|
||||
return;
|
||||
}
|
||||
const reachable = await probeNodeWardenService();
|
||||
if (!cancelled) {
|
||||
setCurrentNetworkStatus(reachable ? 'online' : 'offline');
|
||||
}
|
||||
await probeNodeWardenService();
|
||||
};
|
||||
|
||||
const scheduleNextCheck = () => {
|
||||
@@ -62,7 +58,6 @@ export default function NetworkStatusBadge() {
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
unsubscribe();
|
||||
window.clearTimeout(timer);
|
||||
window.removeEventListener('online', handleOnline);
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { useState } from 'preact/hooks';
|
||||
import { RefreshCw, ShieldCheck, ShieldX } from 'lucide-preact';
|
||||
import LoadingState from '@/components/LoadingState';
|
||||
import type { AuthRequest } from '@/lib/types';
|
||||
import { t } from '@/lib/i18n';
|
||||
|
||||
interface PendingAuthRequestsPanelProps {
|
||||
pendingAuthRequests: AuthRequest[];
|
||||
pendingAuthRequestsLoading: boolean;
|
||||
onRefreshPendingAuthRequests: () => Promise<void>;
|
||||
onApproveAuthRequest: (request: AuthRequest) => Promise<void>;
|
||||
onDenyAuthRequest: (request: AuthRequest) => Promise<void>;
|
||||
className?: string;
|
||||
loadingVariant?: 'placeholder' | 'compact';
|
||||
}
|
||||
|
||||
function formatDateTime(value: string | null | undefined): string {
|
||||
if (!value) return t('txt_dash');
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime()) ? t('txt_dash') : date.toLocaleString();
|
||||
}
|
||||
|
||||
export default function PendingAuthRequestsPanel(props: PendingAuthRequestsPanelProps) {
|
||||
const [authRequestSubmittingId, setAuthRequestSubmittingId] = useState<string | null>(null);
|
||||
|
||||
async function approveAuthRequest(authRequest: AuthRequest): Promise<void> {
|
||||
if (authRequestSubmittingId) return;
|
||||
setAuthRequestSubmittingId(authRequest.id);
|
||||
try {
|
||||
await props.onApproveAuthRequest(authRequest);
|
||||
} finally {
|
||||
setAuthRequestSubmittingId(null);
|
||||
}
|
||||
}
|
||||
|
||||
async function denyAuthRequest(authRequest: AuthRequest): Promise<void> {
|
||||
if (authRequestSubmittingId) return;
|
||||
setAuthRequestSubmittingId(authRequest.id);
|
||||
try {
|
||||
await props.onDenyAuthRequest(authRequest);
|
||||
} finally {
|
||||
setAuthRequestSubmittingId(null);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className={props.className || 'card settings-module'}>
|
||||
<div className="settings-module-head">
|
||||
<h3>{t('txt_pending_device_logins')}</h3>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary small"
|
||||
disabled={props.pendingAuthRequestsLoading}
|
||||
onClick={() => void props.onRefreshPendingAuthRequests()}
|
||||
>
|
||||
<RefreshCw size={14} className="btn-icon" />
|
||||
{t('txt_refresh')}
|
||||
</button>
|
||||
</div>
|
||||
<div className="account-passkeys-list">
|
||||
{props.pendingAuthRequestsLoading && props.pendingAuthRequests.length === 0 ? (
|
||||
props.loadingVariant === 'compact' ? (
|
||||
<LoadingState lines={2} compact />
|
||||
) : (
|
||||
<div className="settings-module-placeholder">
|
||||
<RefreshCw size={20} />
|
||||
<span>{t('txt_loading')}</span>
|
||||
</div>
|
||||
)
|
||||
) : props.pendingAuthRequests.length === 0 ? (
|
||||
<div className="settings-module-placeholder">
|
||||
<ShieldCheck size={20} />
|
||||
<span>{t('txt_no_pending_device_logins')}</span>
|
||||
</div>
|
||||
) : (
|
||||
props.pendingAuthRequests.map((authRequest) => (
|
||||
<div key={authRequest.id} className="account-passkey-row auth-request-row">
|
||||
<div className="account-passkey-main">
|
||||
<strong>{authRequest.requestDeviceType || t('txt_unknown_device')}</strong>
|
||||
<small>{authRequest.requestDeviceIdentifier}</small>
|
||||
<small>{t('txt_created_value', { value: formatDateTime(authRequest.creationDate) })}</small>
|
||||
</div>
|
||||
<span className="auth-request-fingerprint-inline">
|
||||
{authRequest.fingerprintPhrase || t('txt_dash')}
|
||||
</span>
|
||||
<div className="actions account-passkey-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary small"
|
||||
disabled={!!authRequestSubmittingId}
|
||||
onClick={() => void approveAuthRequest(authRequest)}
|
||||
>
|
||||
<ShieldCheck size={14} className="btn-icon" />
|
||||
{authRequestSubmittingId === authRequest.id ? t('txt_approving') : t('txt_approve')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-danger small"
|
||||
disabled={!!authRequestSubmittingId}
|
||||
onClick={() => void denyAuthRequest(authRequest)}
|
||||
>
|
||||
<ShieldX size={14} className="btn-icon" />
|
||||
{t('txt_deny')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -2,14 +2,20 @@ import { useState } from 'preact/hooks';
|
||||
import { Clock3, Pencil, RefreshCw, ShieldCheck, ShieldOff, Trash2 } from 'lucide-preact';
|
||||
import ConfirmDialog from '@/components/ConfirmDialog';
|
||||
import LoadingState from '@/components/LoadingState';
|
||||
import type { AuthorizedDevice } from '@/lib/types';
|
||||
import PendingAuthRequestsPanel from '@/components/PendingAuthRequestsPanel';
|
||||
import type { AuthRequest, AuthorizedDevice } from '@/lib/types';
|
||||
import { t } from '@/lib/i18n';
|
||||
|
||||
interface SecurityDevicesPageProps {
|
||||
devices: AuthorizedDevice[];
|
||||
loading: boolean;
|
||||
error: string;
|
||||
pendingAuthRequests: AuthRequest[];
|
||||
pendingAuthRequestsLoading: boolean;
|
||||
onRefresh: () => void;
|
||||
onRefreshPendingAuthRequests: () => Promise<void>;
|
||||
onApproveAuthRequest: (request: AuthRequest) => Promise<void>;
|
||||
onDenyAuthRequest: (request: AuthRequest) => Promise<void>;
|
||||
onRenameDevice: (device: AuthorizedDevice, name: string) => Promise<void>;
|
||||
onRevokeTrust: (device: AuthorizedDevice) => void;
|
||||
onTrustPermanently: (device: AuthorizedDevice) => void;
|
||||
@@ -72,6 +78,16 @@ export default function SecurityDevicesPage(props: SecurityDevicesPageProps) {
|
||||
return (
|
||||
<>
|
||||
<div className="stack">
|
||||
<PendingAuthRequestsPanel
|
||||
className="card"
|
||||
loadingVariant="compact"
|
||||
pendingAuthRequests={props.pendingAuthRequests}
|
||||
pendingAuthRequestsLoading={props.pendingAuthRequestsLoading}
|
||||
onRefreshPendingAuthRequests={props.onRefreshPendingAuthRequests}
|
||||
onApproveAuthRequest={props.onApproveAuthRequest}
|
||||
onDenyAuthRequest={props.onDenyAuthRequest}
|
||||
/>
|
||||
|
||||
<section className="card">
|
||||
<div className="section-head">
|
||||
<div>
|
||||
|
||||
@@ -2,9 +2,10 @@ import { useEffect, useMemo, useState } from 'preact/hooks';
|
||||
import { Clipboard, KeyRound, RefreshCw, ShieldCheck, ShieldOff, Trash2 } from 'lucide-preact';
|
||||
import { copyTextToClipboard } from '@/lib/clipboard';
|
||||
import qrcode from 'qrcode-generator';
|
||||
import type { AccountPasskeyCredential, Profile } from '@/lib/types';
|
||||
import type { AccountPasskeyCredential, AuthRequest, Profile } from '@/lib/types';
|
||||
import { AVAILABLE_LOCALES, getLocale, setLocale, t, type Locale } from '@/lib/i18n';
|
||||
import ConfirmDialog from '@/components/ConfirmDialog';
|
||||
import PendingAuthRequestsPanel from '@/components/PendingAuthRequestsPanel';
|
||||
|
||||
interface SettingsPageProps {
|
||||
profile: Profile;
|
||||
@@ -22,6 +23,11 @@ interface SettingsPageProps {
|
||||
onCreateAccountPasskey: (name: string, masterPassword: string, directUnlock: boolean) => Promise<AccountPasskeyCredential | null>;
|
||||
onEnableAccountPasskeyDirectUnlock: (id: string, masterPassword: string) => Promise<void>;
|
||||
onDeleteAccountPasskey: (id: string, masterPassword: string) => Promise<void>;
|
||||
pendingAuthRequests: AuthRequest[];
|
||||
pendingAuthRequestsLoading: boolean;
|
||||
onRefreshPendingAuthRequests: () => Promise<void>;
|
||||
onApproveAuthRequest: (request: AuthRequest) => Promise<void>;
|
||||
onDenyAuthRequest: (request: AuthRequest) => Promise<void>;
|
||||
onLockTimeoutChange: (minutes: 0 | 1 | 5 | 15 | 30) => void;
|
||||
onSessionTimeoutActionChange: (action: 'lock' | 'logout') => void;
|
||||
onNotify?: (type: 'success' | 'error' | 'warning', text: string) => void;
|
||||
@@ -76,6 +82,13 @@ function clearLegacyTotpSetupSecrets(): void {
|
||||
}
|
||||
}
|
||||
|
||||
function formatDateTime(value: string | null | undefined): string {
|
||||
if (!value) return t('txt_dash');
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return t('txt_dash');
|
||||
return date.toLocaleString();
|
||||
}
|
||||
|
||||
export default function SettingsPage(props: SettingsPageProps) {
|
||||
const [currentPassword, setCurrentPassword] = useState('');
|
||||
const [newPassword, setNewPassword] = useState('');
|
||||
@@ -219,13 +232,6 @@ export default function SettingsPage(props: SettingsPageProps) {
|
||||
return t('txt_prf_not_supported');
|
||||
}
|
||||
|
||||
function formatDateTime(value: string | null | undefined): string {
|
||||
if (!value) return t('txt_dash');
|
||||
const parsed = new Date(value);
|
||||
if (Number.isNaN(parsed.getTime())) return value;
|
||||
return parsed.toLocaleString();
|
||||
}
|
||||
|
||||
async function changeLocale(next: Locale): Promise<void> {
|
||||
if (next === getLocale()) return;
|
||||
setSelectedLocale(next);
|
||||
@@ -504,6 +510,14 @@ export default function SettingsPage(props: SettingsPageProps) {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<PendingAuthRequestsPanel
|
||||
pendingAuthRequests={props.pendingAuthRequests}
|
||||
pendingAuthRequestsLoading={props.pendingAuthRequestsLoading}
|
||||
onRefreshPendingAuthRequests={props.onRefreshPendingAuthRequests}
|
||||
onApproveAuthRequest={props.onApproveAuthRequest}
|
||||
onDenyAuthRequest={props.onDenyAuthRequest}
|
||||
/>
|
||||
|
||||
<section className="settings-module sensitive-actions-module">
|
||||
<div className="sensitive-actions-grid">
|
||||
<div className="sensitive-action">
|
||||
|
||||
@@ -7,7 +7,7 @@ interface ThemeSwitchProps {
|
||||
export default function ThemeSwitch(props: ThemeSwitchProps) {
|
||||
return (
|
||||
<div className="theme-switch-wrap" title={props.title}>
|
||||
<label className="theme-switch" aria-label={props.title}>
|
||||
<label className={`theme-switch ${props.checked ? 'checked' : 'unchecked'}`} aria-label={props.title}>
|
||||
<span className="sun" aria-hidden="true">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||
<g fill="#ffd43b">
|
||||
|
||||
@@ -12,8 +12,10 @@ export default function ToastHost({ toasts, onClose }: ToastHostProps) {
|
||||
{toasts.map((toast) => (
|
||||
<li key={toast.id} className={`toast-item ${toast.type}`}>
|
||||
<div className="toast-text">{toast.text}</div>
|
||||
<button type="button" className="toast-close" onClick={() => onClose(toast.id)}>
|
||||
x
|
||||
<button type="button" className="toast-close" onClick={() => onClose(toast.id)} aria-label="关闭通知">
|
||||
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true">
|
||||
<path d="M3 3l8 8M11 3l-8 8" />
|
||||
</svg>
|
||||
</button>
|
||||
<div className="toast-progress" />
|
||||
</li>
|
||||
|
||||
@@ -6,7 +6,7 @@ import { t } from '@/lib/i18n';
|
||||
import type { Cipher } from '@/lib/types';
|
||||
import LoadingState from '@/components/LoadingState';
|
||||
import WebsiteIcon from '@/components/vault/WebsiteIcon';
|
||||
import { isCipherVisibleInNormalVault } from '@/components/vault/vault-page-helpers';
|
||||
import { formatTotp, isCipherVisibleInNormalVault } from '@/components/vault/vault-page-helpers';
|
||||
|
||||
interface TotpCodesPageProps {
|
||||
ciphers: Cipher[];
|
||||
@@ -26,13 +26,6 @@ function getTotpTimeState(): { windowId: number; remain: number } {
|
||||
};
|
||||
}
|
||||
|
||||
function formatTotp(code: string): string {
|
||||
if (!code) return code;
|
||||
if (code.length === 5) return `${code.slice(0, 2)} ${code.slice(2)}`;
|
||||
if (code.length < 6) return code;
|
||||
return `${code.slice(0, 3)} ${code.slice(3, 6)}`;
|
||||
}
|
||||
|
||||
function TotpListIcon({ cipher }: { cipher: Cipher }) {
|
||||
return <WebsiteIcon cipher={cipher} fallback={<Globe size={18} />} />;
|
||||
}
|
||||
|
||||
@@ -17,13 +17,14 @@ import {
|
||||
createEmptyDraft,
|
||||
creationTimeValue,
|
||||
draftFromCipher,
|
||||
buildCipherDuplicateSignature,
|
||||
buildCipherDuplicateSignatures,
|
||||
firstCipherUri,
|
||||
firstPasskeyCreationTime,
|
||||
isCipherVisibleInArchive,
|
||||
isCipherVisibleInNormalVault,
|
||||
isCipherVisibleInTrash,
|
||||
sortTimeValue,
|
||||
type DuplicateDetectionMode,
|
||||
type SidebarFilter,
|
||||
type VaultSortMode,
|
||||
} from '@/components/vault/vault-page-helpers';
|
||||
@@ -79,6 +80,7 @@ export default function VaultPage(props: VaultPageProps) {
|
||||
const [sortMenuOpen, setSortMenuOpen] = useState(false);
|
||||
const [folderSortMode, setFolderSortMode] = useState<VaultSortMode>('name');
|
||||
const [folderSortMenuOpen, setFolderSortMenuOpen] = useState(false);
|
||||
const [duplicateMode, setDuplicateMode] = useState<DuplicateDetectionMode>('exact');
|
||||
const [sidebarFilter, setSidebarFilter] = useState<SidebarFilter>({ kind: 'all' });
|
||||
const [selectedCipherId, setSelectedCipherId] = useState('');
|
||||
const [selectedMap, setSelectedMap] = useState<Record<string, boolean>>({});
|
||||
@@ -338,16 +340,41 @@ export default function VaultPage(props: VaultPageProps) {
|
||||
|
||||
const duplicateSignatureInfo = useMemo(() => {
|
||||
if (sidebarFilter.kind !== 'duplicates') return null;
|
||||
const byId = new Map<string, string>();
|
||||
const byId = new Map<string, string[]>();
|
||||
const counts = new Map<string, number>();
|
||||
for (const cipher of props.ciphers) {
|
||||
if (!isCipherVisibleInNormalVault(cipher)) continue;
|
||||
const signature = buildCipherDuplicateSignature(cipher);
|
||||
byId.set(cipher.id, signature);
|
||||
const signatures = Array.from(new Set(buildCipherDuplicateSignatures(cipher, duplicateMode)));
|
||||
byId.set(cipher.id, signatures);
|
||||
for (const signature of signatures) {
|
||||
counts.set(signature, (counts.get(signature) || 0) + 1);
|
||||
}
|
||||
}
|
||||
return { byId, counts };
|
||||
}, [props.ciphers, sidebarFilter.kind]);
|
||||
}, [props.ciphers, sidebarFilter.kind, duplicateMode]);
|
||||
|
||||
const duplicateGroupIndexById = useMemo(() => {
|
||||
if (!duplicateSignatureInfo) return new Map<string, number>();
|
||||
const groupKeyById = new Map<string, string>();
|
||||
const groupKeys = new Set<string>();
|
||||
for (const cipher of props.ciphers) {
|
||||
const groupKey = (duplicateSignatureInfo.byId.get(cipher.id) || [])
|
||||
.filter((signature) => (duplicateSignatureInfo.counts.get(signature) || 0) >= 2)
|
||||
.sort()[0];
|
||||
if (!groupKey) continue;
|
||||
groupKeyById.set(cipher.id, groupKey);
|
||||
groupKeys.add(groupKey);
|
||||
}
|
||||
const groupIndexByKey = new Map<string, number>();
|
||||
Array.from(groupKeys).sort().forEach((groupKey, index) => {
|
||||
groupIndexByKey.set(groupKey, index % 64);
|
||||
});
|
||||
const byId = new Map<string, number>();
|
||||
for (const [cipherId, groupKey] of groupKeyById.entries()) {
|
||||
byId.set(cipherId, groupIndexByKey.get(groupKey) || 0);
|
||||
}
|
||||
return byId;
|
||||
}, [props.ciphers, duplicateSignatureInfo]);
|
||||
|
||||
const filteredCiphers = useMemo(() => {
|
||||
const next = props.ciphers.filter((cipher) => {
|
||||
@@ -358,9 +385,12 @@ export default function VaultPage(props: VaultPageProps) {
|
||||
if (!isCipherVisibleInArchive(cipher)) return false;
|
||||
} else {
|
||||
if (!isCipherVisibleInNormalVault(cipher)) return false;
|
||||
if (sidebarFilter.kind === 'duplicates' && ((duplicateSignatureInfo?.counts.get(duplicateSignatureInfo.byId.get(cipher.id) || '') || 0) < 2)) {
|
||||
if (sidebarFilter.kind === 'duplicates') {
|
||||
const signatures = duplicateSignatureInfo?.byId.get(cipher.id) || [];
|
||||
if (!signatures.some((signature) => (duplicateSignatureInfo?.counts.get(signature) || 0) >= 2)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (sidebarFilter.kind === 'favorite' && !cipher.favorite) return false;
|
||||
if (sidebarFilter.kind === 'type' && meta?.typeKey !== sidebarFilter.value) return false;
|
||||
if (sidebarFilter.kind === 'folder') {
|
||||
@@ -404,8 +434,9 @@ export default function VaultPage(props: VaultPageProps) {
|
||||
const sidebarFilterKey = useMemo(() => {
|
||||
if (sidebarFilter.kind === 'folder') return `folder:${sidebarFilter.folderId ?? 'none'}`;
|
||||
if (sidebarFilter.kind === 'type') return `type:${sidebarFilter.value}`;
|
||||
if (sidebarFilter.kind === 'duplicates') return `duplicates:${duplicateMode}`;
|
||||
return sidebarFilter.kind;
|
||||
}, [sidebarFilter]);
|
||||
}, [sidebarFilter, duplicateMode]);
|
||||
|
||||
useEffect(() => {
|
||||
setListScrollTop(0);
|
||||
@@ -419,6 +450,10 @@ export default function VaultPage(props: VaultPageProps) {
|
||||
}
|
||||
}, [sidebarFilter.kind, sortMode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (sidebarFilter.kind === 'duplicates') setSelectedMap({});
|
||||
}, [sidebarFilter.kind, duplicateMode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isCreating) return;
|
||||
if (!filteredCiphers.length) {
|
||||
@@ -984,10 +1019,11 @@ const folderName = useCallback((id: string | null | undefined): string => {
|
||||
const handleSyncVault = useCallback(() => { void syncVault(); }, [props.onRefresh]);
|
||||
const handleOpenBulkDelete = useCallback(() => setBulkDeleteOpen(true), []);
|
||||
const handleSelectDuplicates = useCallback(() => {
|
||||
if (duplicateMode !== 'exact') return;
|
||||
const map: Record<string, boolean> = {};
|
||||
const seen = new Set<string>();
|
||||
for (const cipher of filteredCiphers) {
|
||||
const signature = duplicateSignatureInfo?.byId.get(cipher.id) || buildCipherDuplicateSignature(cipher);
|
||||
const signature = duplicateSignatureInfo?.byId.get(cipher.id)?.[0] || buildCipherDuplicateSignatures(cipher, 'exact')[0];
|
||||
if (seen.has(signature)) {
|
||||
map[cipher.id] = true;
|
||||
continue;
|
||||
@@ -995,7 +1031,7 @@ const folderName = useCallback((id: string | null | undefined): string => {
|
||||
seen.add(signature);
|
||||
}
|
||||
setSelectedMap(map);
|
||||
}, [filteredCiphers, duplicateSignatureInfo]);
|
||||
}, [filteredCiphers, duplicateSignatureInfo, duplicateMode]);
|
||||
const handleSelectAll = useCallback(() => {
|
||||
const map: Record<string, boolean> = {};
|
||||
for (const cipher of filteredCiphers) map[cipher.id] = true;
|
||||
@@ -1079,13 +1115,16 @@ const folderName = useCallback((id: string | null | undefined): string => {
|
||||
busy={busy}
|
||||
loading={props.loading}
|
||||
error={props.error}
|
||||
folders={props.folders}
|
||||
searchInput={searchInput}
|
||||
sortMode={sortMode}
|
||||
sortMenuOpen={sortMenuOpen}
|
||||
duplicateMode={duplicateMode}
|
||||
selectedCount={selectedCount}
|
||||
totalCipherCount={totalCipherCount}
|
||||
filteredCiphers={filteredCiphers}
|
||||
visibleCiphers={visibleCiphers}
|
||||
duplicateGroupIndexById={duplicateGroupIndexById}
|
||||
virtualRange={virtualRange}
|
||||
selectedCipherId={selectedCipherId}
|
||||
selectedMap={selectedMap}
|
||||
@@ -1102,6 +1141,8 @@ const folderName = useCallback((id: string | null | undefined): string => {
|
||||
onSearchCompositionEnd={handleSearchCompositionEnd}
|
||||
onToggleSortMenu={handleToggleSortMenu}
|
||||
onSelectSortMode={handleSelectSortMode}
|
||||
onDuplicateModeChange={setDuplicateMode}
|
||||
onChangeFilter={setSidebarFilter}
|
||||
onSyncVault={handleSyncVault}
|
||||
onOpenBulkDelete={handleOpenBulkDelete}
|
||||
onSelectDuplicates={handleSelectDuplicates}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { CloudUpload, Save, Trash2 } from 'lucide-preact';
|
||||
import type {
|
||||
BackupDestinationRecord,
|
||||
RemoteBackupBrowserResponse,
|
||||
S3BackupAddressingStyle,
|
||||
S3BackupDestination,
|
||||
WebDavBackupDestination,
|
||||
} from '@/lib/api/backup';
|
||||
@@ -401,7 +402,7 @@ export function BackupDestinationDetail(props: BackupDestinationDetailProps) {
|
||||
|
||||
{props.selectedDestination.type === 's3' ? (
|
||||
<div className="field-grid">
|
||||
<label className="field field-span-2">
|
||||
<label className="field">
|
||||
<span>{t('txt_backup_s3_endpoint')}</span>
|
||||
<input
|
||||
className="input"
|
||||
@@ -417,6 +418,24 @@ export function BackupDestinationDetail(props: BackupDestinationDetailProps) {
|
||||
}))}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>{t('txt_backup_s3_addressing_style')}</span>
|
||||
<select
|
||||
className="input"
|
||||
value={(props.selectedDestination.destination as S3BackupDestination).addressingStyle || 'path-style'}
|
||||
disabled={props.loadingSettings || props.disableWhileBusy}
|
||||
onChange={(event) => props.onUpdateDestination((destination) => ({
|
||||
...destination,
|
||||
destination: {
|
||||
...(destination.destination as S3BackupDestination),
|
||||
addressingStyle: (event.currentTarget as HTMLSelectElement).value as S3BackupAddressingStyle,
|
||||
},
|
||||
}))}
|
||||
>
|
||||
<option value="path-style">{t('txt_backup_s3_addressing_path_style')}</option>
|
||||
<option value="virtual-hosted-style">{t('txt_backup_s3_addressing_virtual_hosted_style')}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>{t('txt_backup_s3_bucket')}</span>
|
||||
<input
|
||||
|
||||
@@ -1,15 +1,40 @@
|
||||
import type { RefObject } from 'preact';
|
||||
import type { ComponentChildren, RefObject } from 'preact';
|
||||
import { useEffect, useRef, useState } from 'preact/hooks';
|
||||
import { memo } from 'preact/compat';
|
||||
import { createPortal } from 'preact/compat';
|
||||
import { Archive, ArrowUpDown, Check, CheckCheck, FolderInput, Plus, RefreshCw, RotateCcw, Trash2, X } from 'lucide-preact';
|
||||
import {
|
||||
Archive,
|
||||
ArrowUpDown,
|
||||
Check,
|
||||
CheckCheck,
|
||||
ChevronDown,
|
||||
Copy,
|
||||
CreditCard,
|
||||
Folder as FolderIcon,
|
||||
FolderInput,
|
||||
FolderX,
|
||||
Globe,
|
||||
KeyRound,
|
||||
LayoutGrid,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
RotateCcw,
|
||||
ShieldUser,
|
||||
Star,
|
||||
StickyNote,
|
||||
Trash2,
|
||||
X,
|
||||
} from 'lucide-preact';
|
||||
import LoadingState from '@/components/LoadingState';
|
||||
import type { Cipher } from '@/lib/types';
|
||||
import type { Cipher, Folder } from '@/lib/types';
|
||||
import { t } from '@/lib/i18n';
|
||||
import {
|
||||
CreateTypeIcon,
|
||||
getCreateTypeOptions,
|
||||
getDuplicateDetectionOptions,
|
||||
getVaultSortOptions,
|
||||
VaultListIcon,
|
||||
type DuplicateDetectionMode,
|
||||
type SidebarFilter,
|
||||
type VaultSortMode,
|
||||
} from '@/components/vault/vault-page-helpers';
|
||||
@@ -25,13 +50,16 @@ interface VaultListPanelProps {
|
||||
busy: boolean;
|
||||
loading: boolean;
|
||||
error: string;
|
||||
folders: Folder[];
|
||||
searchInput: string;
|
||||
sortMode: VaultSortMode;
|
||||
sortMenuOpen: boolean;
|
||||
duplicateMode: DuplicateDetectionMode;
|
||||
selectedCount: number;
|
||||
totalCipherCount: number;
|
||||
filteredCiphers: Cipher[];
|
||||
visibleCiphers: Cipher[];
|
||||
duplicateGroupIndexById: Map<string, number>;
|
||||
virtualRange: VirtualRange;
|
||||
selectedCipherId: string;
|
||||
selectedMap: Record<string, boolean>;
|
||||
@@ -48,6 +76,8 @@ interface VaultListPanelProps {
|
||||
onSearchCompositionEnd: (value: string) => void;
|
||||
onToggleSortMenu: () => void;
|
||||
onSelectSortMode: (value: VaultSortMode) => void;
|
||||
onDuplicateModeChange: (value: DuplicateDetectionMode) => void;
|
||||
onChangeFilter: (filter: SidebarFilter) => void;
|
||||
onSyncVault: () => void;
|
||||
onOpenBulkDelete: () => void;
|
||||
onSelectDuplicates: () => void;
|
||||
@@ -69,15 +99,28 @@ interface CipherListItemProps {
|
||||
cipher: Cipher;
|
||||
selected: boolean;
|
||||
checked: boolean;
|
||||
duplicateGroupIndex: number | null;
|
||||
subtitle: string;
|
||||
onToggleSelected: (cipherId: string, checked: boolean) => void;
|
||||
onSelectCipher: (cipherId: string) => void;
|
||||
}
|
||||
|
||||
type MobileFilterMenuKey = 'duplicate' | 'menu' | 'type' | 'folder';
|
||||
|
||||
interface MobileFilterOption {
|
||||
value: string;
|
||||
label: string;
|
||||
icon: ComponentChildren;
|
||||
active: boolean;
|
||||
onSelect: () => void;
|
||||
}
|
||||
|
||||
const CipherListItem = memo(function CipherListItem(props: CipherListItemProps) {
|
||||
const duplicateGroupHue = props.duplicateGroupIndex === null ? null : (props.duplicateGroupIndex * 137.508) % 360;
|
||||
return (
|
||||
<div
|
||||
className={`list-item ${props.selected ? 'active' : ''}`}
|
||||
className={`list-item ${props.selected ? 'active' : ''} ${duplicateGroupHue === null ? '' : 'duplicate-group-item'}`}
|
||||
style={duplicateGroupHue === null ? undefined : { '--duplicate-group-hue': `${duplicateGroupHue}deg` }}
|
||||
onClick={(event) => {
|
||||
const target = event.target as HTMLElement;
|
||||
if (target.closest('.row-check')) return;
|
||||
@@ -107,13 +150,116 @@ const CipherListItem = memo(function CipherListItem(props: CipherListItemProps)
|
||||
});
|
||||
|
||||
export default function VaultListPanel(props: VaultListPanelProps) {
|
||||
const [mobileFilterOpen, setMobileFilterOpen] = useState<MobileFilterMenuKey | null>(null);
|
||||
const mobileFilterRef = useRef<HTMLDivElement | null>(null);
|
||||
const createTypeOptions = getCreateTypeOptions();
|
||||
const duplicateDetectionOptions = getDuplicateDetectionOptions();
|
||||
const vaultSortOptions = getVaultSortOptions();
|
||||
const createMenu = (
|
||||
<div className="create-menu-wrap mobile-fab-wrap" ref={props.createMenuRef}>
|
||||
const duplicateModeOptions: MobileFilterOption[] = duplicateDetectionOptions.map((option) => ({
|
||||
value: option.value,
|
||||
label: option.label,
|
||||
icon: option.value === 'login-site' ? <Globe size={14} /> : option.value === 'exact' ? <Copy size={14} /> : <KeyRound size={14} />,
|
||||
active: props.duplicateMode === option.value,
|
||||
onSelect: () => props.onDuplicateModeChange(option.value),
|
||||
}));
|
||||
const menuFilterOptions: MobileFilterOption[] = [
|
||||
{ value: 'all', label: t('txt_all_items'), icon: <LayoutGrid size={14} />, active: props.sidebarFilter.kind === 'all', onSelect: () => props.onChangeFilter({ kind: 'all' }) },
|
||||
{ value: 'favorite', label: t('txt_favorites'), icon: <Star size={14} />, active: props.sidebarFilter.kind === 'favorite', onSelect: () => props.onChangeFilter({ kind: 'favorite' }) },
|
||||
{ value: 'archive', label: t('txt_archive'), icon: <Archive size={14} />, active: props.sidebarFilter.kind === 'archive', onSelect: () => props.onChangeFilter({ kind: 'archive' }) },
|
||||
{ value: 'trash', label: t('txt_trash'), icon: <Trash2 size={14} />, active: props.sidebarFilter.kind === 'trash', onSelect: () => props.onChangeFilter({ kind: 'trash' }) },
|
||||
{ value: 'duplicates', label: t('txt_duplicates'), icon: <Copy size={14} />, active: props.sidebarFilter.kind === 'duplicates', onSelect: () => props.onChangeFilter({ kind: 'duplicates' }) },
|
||||
];
|
||||
const typeMobileFilterOptions: MobileFilterOption[] = [
|
||||
{ value: 'login', label: t('txt_login'), icon: <Globe size={14} />, active: props.sidebarFilter.kind === 'type' && props.sidebarFilter.value === 'login', onSelect: () => props.onChangeFilter({ kind: 'type', value: 'login' }) },
|
||||
{ value: 'card', label: t('txt_card'), icon: <CreditCard size={14} />, active: props.sidebarFilter.kind === 'type' && props.sidebarFilter.value === 'card', onSelect: () => props.onChangeFilter({ kind: 'type', value: 'card' }) },
|
||||
{ value: 'identity', label: t('txt_identity'), icon: <ShieldUser size={14} />, active: props.sidebarFilter.kind === 'type' && props.sidebarFilter.value === 'identity', onSelect: () => props.onChangeFilter({ kind: 'type', value: 'identity' }) },
|
||||
{ value: 'note', label: t('txt_note'), icon: <StickyNote size={14} />, active: props.sidebarFilter.kind === 'type' && props.sidebarFilter.value === 'note', onSelect: () => props.onChangeFilter({ kind: 'type', value: 'note' }) },
|
||||
{ value: 'ssh', label: t('txt_ssh_key'), icon: <KeyRound size={14} />, active: props.sidebarFilter.kind === 'type' && props.sidebarFilter.value === 'ssh', onSelect: () => props.onChangeFilter({ kind: 'type', value: 'ssh' }) },
|
||||
];
|
||||
const folderMobileFilterOptions: MobileFilterOption[] = [
|
||||
{ value: '__none__', label: t('txt_no_folder'), icon: <FolderX size={14} />, active: props.sidebarFilter.kind === 'folder' && props.sidebarFilter.folderId === null, onSelect: () => props.onChangeFilter({ kind: 'folder', folderId: null }) },
|
||||
...props.folders.map((folder) => ({
|
||||
value: folder.id,
|
||||
label: folder.decName || folder.name || folder.id,
|
||||
icon: <FolderIcon size={14} />,
|
||||
active: props.sidebarFilter.kind === 'folder' && props.sidebarFilter.folderId === folder.id,
|
||||
onSelect: () => props.onChangeFilter({ kind: 'folder', folderId: folder.id }),
|
||||
})),
|
||||
];
|
||||
const menuFilterSelected = menuFilterOptions.find((option) => option.active);
|
||||
const typeFilterSelected = typeMobileFilterOptions.find((option) => option.active);
|
||||
const folderFilterSelected = folderMobileFilterOptions.find((option) => option.active);
|
||||
const duplicateModeSelected = duplicateModeOptions.find((option) => option.active);
|
||||
|
||||
useEffect(() => {
|
||||
const onPointerDown = (event: Event) => {
|
||||
if (!mobileFilterOpen) return;
|
||||
const target = event.target as Node | null;
|
||||
if (mobileFilterRef.current && target && !mobileFilterRef.current.contains(target)) {
|
||||
setMobileFilterOpen(null);
|
||||
}
|
||||
};
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') setMobileFilterOpen(null);
|
||||
};
|
||||
document.addEventListener('pointerdown', onPointerDown);
|
||||
document.addEventListener('keydown', onKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener('pointerdown', onPointerDown);
|
||||
document.removeEventListener('keydown', onKeyDown);
|
||||
};
|
||||
}, [mobileFilterOpen]);
|
||||
|
||||
const renderMobileFilterMenu = (
|
||||
key: MobileFilterMenuKey,
|
||||
label: string,
|
||||
selected: MobileFilterOption | undefined,
|
||||
fallbackIcon: ComponentChildren,
|
||||
options: MobileFilterOption[]
|
||||
) => (
|
||||
<div className="mobile-vault-filter-control">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary small mobile-fab-trigger"
|
||||
className={`mobile-vault-filter-trigger ${mobileFilterOpen === key ? 'active' : ''}`}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={mobileFilterOpen === key}
|
||||
onClick={() => setMobileFilterOpen((open) => open === key ? null : key)}
|
||||
>
|
||||
<span className="mobile-vault-filter-trigger-icon">{selected?.icon || fallbackIcon}</span>
|
||||
<span className="mobile-vault-filter-trigger-label">{selected?.label || label}</span>
|
||||
<ChevronDown size={13} className="mobile-vault-filter-chevron" />
|
||||
</button>
|
||||
{mobileFilterOpen === key && (
|
||||
<div className="sort-menu mobile-vault-filter-menu" role="menu">
|
||||
{options.map((option) => (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
className={`sort-menu-item mobile-vault-filter-item ${option.active ? 'active' : ''}`}
|
||||
onClick={() => {
|
||||
option.onSelect();
|
||||
setMobileFilterOpen(null);
|
||||
}}
|
||||
role="menuitemradio"
|
||||
aria-checked={option.active}
|
||||
>
|
||||
<span className="mobile-vault-filter-item-main">
|
||||
<span className="mobile-vault-filter-item-icon">{option.icon}</span>
|
||||
<span>{option.label}</span>
|
||||
</span>
|
||||
{option.active ? <Check size={14} /> : <span className="sort-menu-check-placeholder" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
const createMenu = (
|
||||
<div className={`create-menu-wrap ${props.isMobileLayout ? 'mobile-fab-wrap' : 'desktop-create-menu-wrap'}`} ref={props.createMenuRef}>
|
||||
<button
|
||||
type="button"
|
||||
className={`btn btn-primary small ${props.isMobileLayout ? 'mobile-fab-trigger' : 'desktop-create-trigger'}`}
|
||||
aria-label={t('txt_add')}
|
||||
title={t('txt_add')}
|
||||
onClick={props.onToggleCreateMenu}
|
||||
@@ -135,11 +281,54 @@ export default function VaultListPanel(props: VaultListPanelProps) {
|
||||
|
||||
return (
|
||||
<section className="list-col">
|
||||
<div className="list-head">
|
||||
<div className="list-toolbar-stack" ref={mobileFilterRef}>
|
||||
<div className={`list-head ${props.selectedCount > 0 ? 'selection-mode' : ''}`}>
|
||||
{props.selectedCount > 0 ? (
|
||||
<>
|
||||
{props.sidebarFilter.kind !== 'duplicates' && (
|
||||
<button type="button" className="btn btn-secondary small" disabled={!props.filteredCiphers.length} onClick={props.onSelectAll}>
|
||||
<CheckCheck size={14} className="btn-icon" /> {t('txt_select_all')}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="btn btn-secondary small" onClick={props.onClearSelection}>
|
||||
<X size={14} className="btn-icon" /> {t('txt_cancel')}
|
||||
</button>
|
||||
{props.sidebarFilter.kind === 'trash' && (
|
||||
<button type="button" className="btn btn-secondary small" disabled={props.busy} onClick={props.onBulkRestore}>
|
||||
<RefreshCw size={14} className="btn-icon" /> {t('txt_restore')}
|
||||
</button>
|
||||
)}
|
||||
{props.sidebarFilter.kind === 'archive' && (
|
||||
<button type="button" className="btn btn-secondary small" disabled={props.busy} onClick={props.onBulkUnarchive}>
|
||||
<RotateCcw size={14} className="btn-icon" /> {t('txt_unarchive')}
|
||||
</button>
|
||||
)}
|
||||
{props.sidebarFilter.kind !== 'trash' && props.sidebarFilter.kind !== 'archive' && props.sidebarFilter.kind !== 'duplicates' && (
|
||||
<button type="button" className="btn btn-secondary small" disabled={props.busy} onClick={props.onBulkArchive}>
|
||||
<Archive size={14} className="btn-icon" /> {t('txt_archive_selected')}
|
||||
</button>
|
||||
)}
|
||||
{props.sidebarFilter.kind !== 'trash' && props.sidebarFilter.kind !== 'archive' && props.sidebarFilter.kind !== 'duplicates' && (
|
||||
<button type="button" className="btn btn-secondary small" disabled={props.busy} onClick={props.onOpenMove}>
|
||||
<FolderInput size={14} className="btn-icon" /> {t('txt_move')}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="btn btn-danger small" disabled={props.busy} onClick={props.onOpenBulkDelete}>
|
||||
<Trash2 size={14} className="btn-icon" /> {props.sidebarFilter.kind === 'trash' ? t('txt_delete_permanently') : t('txt_delete_selected')}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="search-input-wrap">
|
||||
{props.sidebarFilter.kind === 'duplicates' && props.isMobileLayout ? (
|
||||
<div className="duplicate-mode-head-menu">
|
||||
{renderMobileFilterMenu('duplicate', t('txt_duplicate_detection_mode'), duplicateModeSelected, <Copy size={14} />, duplicateModeOptions)}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<input
|
||||
className="search-input"
|
||||
placeholder={t('txt_search_your_secure_vault')}
|
||||
placeholder={t('txt_search_items_count', { count: props.totalCipherCount })}
|
||||
value={props.searchInput}
|
||||
onInput={(e) => props.onSearchInput((e.currentTarget as HTMLInputElement).value)}
|
||||
onCompositionStart={props.onSearchCompositionStart}
|
||||
@@ -161,16 +350,23 @@ export default function VaultListPanel(props: VaultListPanelProps) {
|
||||
<X size={14} />
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{props.sidebarFilter.kind === 'duplicates' && !props.isMobileLayout && (
|
||||
<div className="duplicate-mode-head-menu">
|
||||
{renderMobileFilterMenu('duplicate', t('txt_duplicate_detection_mode'), duplicateModeSelected, <Copy size={14} />, duplicateModeOptions)}
|
||||
</div>
|
||||
)}
|
||||
<div className="sort-menu-wrap" ref={props.sortMenuRef}>
|
||||
<button
|
||||
type="button"
|
||||
className={`btn btn-secondary small sort-trigger ${props.sortMenuOpen ? 'active' : ''}`}
|
||||
className={`btn btn-secondary small sort-trigger sort-trigger-labeled ${props.sortMenuOpen ? 'active' : ''}`}
|
||||
aria-label={t('txt_sort')}
|
||||
title={t('txt_sort')}
|
||||
onClick={props.onToggleSortMenu}
|
||||
>
|
||||
<ArrowUpDown size={14} className="btn-icon" />
|
||||
<ArrowUpDown size={14} className="btn-icon" /> <span>{t('txt_sort')}</span>
|
||||
</button>
|
||||
{props.sortMenuOpen && (
|
||||
<div className="sort-menu">
|
||||
@@ -188,55 +384,24 @@ export default function VaultListPanel(props: VaultListPanelProps) {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="list-count" title={t('txt_total_items_count', { count: props.totalCipherCount })}>
|
||||
{t('txt_total_items_count', { count: props.totalCipherCount })}
|
||||
</div>
|
||||
<button type="button" className="btn btn-secondary small list-icon-btn" disabled={props.busy || props.loading} onClick={props.onSyncVault}>
|
||||
<RefreshCw size={14} className="btn-icon" /> {t('txt_sync_vault')}
|
||||
</button>
|
||||
{!props.isMobileLayout && props.sidebarFilter !== undefined && createMenu}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="toolbar actions">
|
||||
{props.sidebarFilter.kind === 'duplicates' && (
|
||||
<button type="button" className="btn btn-secondary small" disabled={!props.filteredCiphers.length || props.busy} onClick={props.onSelectDuplicates}>
|
||||
<Check size={14} className="btn-icon" /> {t('txt_select_duplicate_items')}
|
||||
</button>
|
||||
)}
|
||||
{props.selectedCount > 0 && props.sidebarFilter.kind === 'trash' && (
|
||||
<button type="button" className="btn btn-secondary small" disabled={props.busy} onClick={props.onBulkRestore}>
|
||||
<RefreshCw size={14} className="btn-icon" /> {t('txt_restore')}
|
||||
</button>
|
||||
)}
|
||||
{props.selectedCount > 0 && props.sidebarFilter.kind === 'archive' && (
|
||||
<button type="button" className="btn btn-secondary small" disabled={props.busy} onClick={props.onBulkUnarchive}>
|
||||
<RotateCcw size={14} className="btn-icon" /> {t('txt_unarchive')}
|
||||
</button>
|
||||
)}
|
||||
{props.selectedCount > 0 && props.sidebarFilter.kind !== 'trash' && props.sidebarFilter.kind !== 'archive' && props.sidebarFilter.kind !== 'duplicates' && (
|
||||
<button type="button" className="btn btn-secondary small" disabled={props.busy} onClick={props.onBulkArchive}>
|
||||
<Archive size={14} className="btn-icon" /> {t('txt_archive_selected')}
|
||||
</button>
|
||||
)}
|
||||
{props.selectedCount > 0 && props.sidebarFilter.kind !== 'trash' && props.sidebarFilter.kind !== 'archive' && props.sidebarFilter.kind !== 'duplicates' && (
|
||||
<button type="button" className="btn btn-secondary small" disabled={props.busy} onClick={props.onOpenMove}>
|
||||
<FolderInput size={14} className="btn-icon" /> {t('txt_move')}
|
||||
</button>
|
||||
)}
|
||||
{props.selectedCount > 0 && (
|
||||
<button type="button" className="btn btn-secondary small" onClick={props.onClearSelection}>
|
||||
<X size={14} className="btn-icon" /> {t('txt_cancel')}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="btn btn-danger small" disabled={!props.selectedCount || props.busy} onClick={props.onOpenBulkDelete}>
|
||||
<Trash2 size={14} className="btn-icon" /> {props.sidebarFilter.kind === 'trash' ? t('txt_delete_permanently') : t('txt_delete_selected')}
|
||||
</button>
|
||||
<button type="button" className="btn btn-secondary small" disabled={!props.filteredCiphers.length} onClick={props.onSelectAll}>
|
||||
<CheckCheck size={14} className="btn-icon" /> {t('txt_select_all')}
|
||||
</button>
|
||||
{props.isMobileLayout && typeof document !== 'undefined'
|
||||
? props.mobileFabVisible ? createPortal(createMenu, document.body) : null
|
||||
: createMenu}
|
||||
{props.isMobileLayout && (
|
||||
<div className="mobile-vault-filter-row" aria-label={t('txt_filter')}>
|
||||
{renderMobileFilterMenu('menu', t('txt_menu'), menuFilterSelected, <LayoutGrid size={14} />, menuFilterOptions)}
|
||||
{renderMobileFilterMenu('type', t('txt_type'), typeFilterSelected, <Globe size={14} />, typeMobileFilterOptions)}
|
||||
{renderMobileFilterMenu('folder', t('txt_folder'), folderFilterSelected, <FolderIcon size={14} />, folderMobileFilterOptions)}
|
||||
</div>
|
||||
|
||||
)}
|
||||
</div>
|
||||
{!props.selectedCount && props.isMobileLayout && props.sidebarFilter.kind !== 'duplicates' && typeof document !== 'undefined' && props.mobileFabVisible
|
||||
? createPortal(createMenu, document.body)
|
||||
: null}
|
||||
<div className="list-panel" ref={props.listPanelRef} onScroll={(event) => props.onScroll((event.currentTarget as HTMLDivElement).scrollTop)}>
|
||||
{props.loading && !props.filteredCiphers.length && <LoadingState lines={7} compact />}
|
||||
{!props.loading && !!props.error && !props.filteredCiphers.length && (
|
||||
@@ -255,6 +420,7 @@ export default function VaultListPanel(props: VaultListPanelProps) {
|
||||
cipher={cipher}
|
||||
selected={props.selectedCipherId === cipher.id}
|
||||
checked={!!props.selectedMap[cipher.id]}
|
||||
duplicateGroupIndex={props.sidebarFilter.kind === 'duplicates' ? props.duplicateGroupIndexById.get(cipher.id) ?? null : null}
|
||||
subtitle={props.listSubtitle(cipher)}
|
||||
onToggleSelected={props.onToggleSelected}
|
||||
onSelectCipher={props.onSelectCipher}
|
||||
|
||||
@@ -10,10 +10,13 @@ import {
|
||||
import { copyTextToClipboard } from '@/lib/clipboard';
|
||||
import { t } from '@/lib/i18n';
|
||||
import type { Cipher, CipherAttachment, CustomFieldType, VaultDraft, VaultDraftField, VaultDraftLoginUri } from '@/lib/types';
|
||||
import { firstCipherUri, hostFromUri, websiteIconUrl } from '@/lib/website-utils';
|
||||
import { normalizeEquivalentDomain } from '@shared/domain-normalize';
|
||||
import WebsiteIcon from './WebsiteIcon';
|
||||
|
||||
export type TypeFilter = 'login' | 'card' | 'identity' | 'note' | 'ssh';
|
||||
export type VaultSortMode = 'edited' | 'created' | 'name';
|
||||
export type DuplicateDetectionMode = 'exact' | 'login-site' | 'login-credentials' | 'password';
|
||||
export type SidebarFilter =
|
||||
| { kind: 'all' }
|
||||
| { kind: 'favorite' }
|
||||
@@ -126,6 +129,16 @@ export const FOLDER_SORT_STORAGE_KEY = 'nodewarden.folder-sort.v1';
|
||||
export const MOBILE_LAYOUT_QUERY = '(max-width: 1180px)';
|
||||
export const VAULT_LIST_ROW_HEIGHT = 74;
|
||||
export const VAULT_LIST_OVERSCAN = 10;
|
||||
|
||||
export function getDuplicateDetectionOptions(): Array<{ value: DuplicateDetectionMode; label: string }> {
|
||||
return [
|
||||
{ value: 'exact', label: t('txt_duplicate_mode_exact') },
|
||||
{ value: 'login-site', label: t('txt_duplicate_mode_login_site') },
|
||||
{ value: 'login-credentials', label: t('txt_duplicate_mode_login_credentials') },
|
||||
{ value: 'password', label: t('txt_duplicate_mode_password') },
|
||||
];
|
||||
}
|
||||
|
||||
export function getVaultSortOptions(): Array<{ value: VaultSortMode; label: string }> {
|
||||
return [
|
||||
{ value: 'edited', label: t('txt_sort_last_edited') },
|
||||
@@ -242,7 +255,7 @@ export function toBooleanFieldValue(raw: string): boolean {
|
||||
return v === '1' || v === 'true' || v === 'yes' || v === 'on';
|
||||
}
|
||||
|
||||
export { firstCipherUri, hostFromUri, websiteIconUrl } from '@/lib/website-utils';
|
||||
export { firstCipherUri, hostFromUri, websiteIconUrl };
|
||||
|
||||
export function createEmptyLoginUri(): VaultDraftLoginUri {
|
||||
return { uri: '', match: null, originalUri: '', extra: {} };
|
||||
@@ -257,6 +270,30 @@ function valueOrFallback(value: string | null | undefined): string {
|
||||
return String(value || '');
|
||||
}
|
||||
|
||||
function duplicateLoginUsername(cipher: Cipher): string {
|
||||
return valueOrFallback(cipher.login?.decUsername ?? cipher.login?.username).trim().toLowerCase();
|
||||
}
|
||||
|
||||
function duplicateLoginPassword(cipher: Cipher): string {
|
||||
return valueOrFallback(cipher.login?.decPassword ?? cipher.login?.password);
|
||||
}
|
||||
|
||||
function duplicateLoginSites(cipher: Cipher): string[] {
|
||||
const sites = new Set<string>();
|
||||
for (const uri of cipher.login?.uris || []) {
|
||||
const raw = valueOrFallback(uri.decUri ?? uri.uri).trim();
|
||||
if (!raw) continue;
|
||||
const host = hostFromUri(raw).trim().toLowerCase().replace(/^www\./, '');
|
||||
const site = normalizeEquivalentDomain(raw) || host;
|
||||
if (site) sites.add(site);
|
||||
}
|
||||
return Array.from(sites).sort();
|
||||
}
|
||||
|
||||
function duplicateSignature(parts: string[]): string {
|
||||
return JSON.stringify(parts);
|
||||
}
|
||||
|
||||
export function buildCipherDuplicateSignature(cipher: Cipher): string {
|
||||
const normalized = {
|
||||
type: Number(cipher.type || 1),
|
||||
@@ -326,13 +363,30 @@ export function buildCipherDuplicateSignature(cipher: Cipher): string {
|
||||
linkedId: field.linkedId ?? null,
|
||||
})),
|
||||
passwordHistory: (cipher.passwordHistory || []).map((entry) => ({
|
||||
password: valueOrFallback(entry.password),
|
||||
password: valueOrFallback(entry.decPassword ?? entry.password),
|
||||
lastUsedDate: valueOrFallback(entry.lastUsedDate),
|
||||
})),
|
||||
};
|
||||
return JSON.stringify(normalized);
|
||||
}
|
||||
|
||||
export function buildCipherDuplicateSignatures(cipher: Cipher, mode: DuplicateDetectionMode): string[] {
|
||||
if (mode === 'exact') return [buildCipherDuplicateSignature(cipher)];
|
||||
if (Number(cipher.type || 1) !== 1 || !cipher.login) return [];
|
||||
|
||||
const username = duplicateLoginUsername(cipher);
|
||||
const password = duplicateLoginPassword(cipher);
|
||||
if (mode === 'password') {
|
||||
return password ? [duplicateSignature(['password', password])] : [];
|
||||
}
|
||||
if (!username || !password) return [];
|
||||
if (mode === 'login-credentials') {
|
||||
return [duplicateSignature(['login-credentials', username, password])];
|
||||
}
|
||||
|
||||
return duplicateLoginSites(cipher).map((site) => duplicateSignature(['login-site', site, username, password]));
|
||||
}
|
||||
|
||||
export function createEmptyDraft(type: number): VaultDraft {
|
||||
return {
|
||||
type,
|
||||
@@ -453,8 +507,9 @@ export function maskSecret(value: string): string {
|
||||
export function formatTotp(code: string): string {
|
||||
if (!code) return code;
|
||||
if (code.length === 5) return `${code.slice(0, 2)} ${code.slice(2)}`;
|
||||
if (code.length < 6) return code;
|
||||
return `${code.slice(0, 3)} ${code.slice(3, 6)}`;
|
||||
if (code.length <= 4) return code;
|
||||
if (code.length === 8) return `${code.slice(0, 4)} ${code.slice(4)}`;
|
||||
return code.replace(/(.{3})(?=.)/g, '$1 ');
|
||||
}
|
||||
|
||||
export function formatHistoryTime(value: string | null | undefined): string {
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { ExportRequest, ZipAttachmentEntry } from '@/lib/export-formats';
|
||||
import {
|
||||
attachNodeWardenEncryptedAttachmentPayload,
|
||||
buildAccountEncryptedBitwardenJsonString,
|
||||
buildBitwardenCsvString,
|
||||
buildBitwardenZipBytes,
|
||||
buildExportFileName,
|
||||
buildNodeWardenAttachmentRecords,
|
||||
@@ -40,6 +41,7 @@ import {
|
||||
downloadCipherAttachmentDecrypted,
|
||||
encryptFolderImportName,
|
||||
getAttachmentDownloadInfo,
|
||||
getCipherById,
|
||||
importCiphers,
|
||||
permanentDeleteCipher,
|
||||
type CiphersImportPayload,
|
||||
@@ -68,8 +70,13 @@ interface UseVaultSendActionsOptions {
|
||||
refetchFolders: () => Promise<{ data?: VaultFolder[] | undefined } | unknown>;
|
||||
refetchSends: () => Promise<unknown>;
|
||||
onNotify: Notify;
|
||||
patchEncryptedCiphers: (updater: (prev: Cipher[]) => Cipher[]) => void;
|
||||
patchEncryptedFolders: (updater: (prev: VaultFolder[]) => VaultFolder[]) => void;
|
||||
patchEncryptedSends: (updater: (prev: Send[]) => Send[]) => void;
|
||||
patchDecryptedCiphers: (updater: (prev: Cipher[]) => Cipher[]) => void;
|
||||
patchDecryptedFolders: (updater: (prev: VaultFolder[]) => VaultFolder[]) => void;
|
||||
patchDecryptedSends: (updater: (prev: Send[]) => Send[]) => void;
|
||||
refreshVaultRevisionStamp: () => Promise<void>;
|
||||
}
|
||||
|
||||
function extractImportIdMaps(cipherMap: ImportedCipherMapEntry[] | null) {
|
||||
@@ -287,8 +294,13 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
refetchFolders,
|
||||
refetchSends,
|
||||
onNotify,
|
||||
patchEncryptedCiphers,
|
||||
patchEncryptedFolders,
|
||||
patchEncryptedSends,
|
||||
patchDecryptedCiphers,
|
||||
patchDecryptedFolders,
|
||||
patchDecryptedSends,
|
||||
refreshVaultRevisionStamp,
|
||||
} = options;
|
||||
const [downloadingAttachmentKey, setDownloadingAttachmentKey] = useState('');
|
||||
const [attachmentDownloadPercent, setAttachmentDownloadPercent] = useState<number | null>(null);
|
||||
@@ -307,21 +319,20 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
throw new Error(t('txt_offline_vault_readonly'));
|
||||
};
|
||||
|
||||
const syncVaultCoreInBackground = (options?: { includeFolders?: boolean }) => {
|
||||
const tasks: Promise<unknown>[] = [Promise.resolve(refetchCiphers())];
|
||||
if (options?.includeFolders) {
|
||||
tasks.push(Promise.resolve(refetchFolders()));
|
||||
}
|
||||
void Promise.all(tasks).catch((err) => {
|
||||
console.warn('Background vault sync failed:', err);
|
||||
});
|
||||
};
|
||||
|
||||
async function decryptAndPatch(encrypted: Cipher) {
|
||||
if (!session?.symEncKey || !session?.symMacKey) {
|
||||
await refetchCiphers();
|
||||
return;
|
||||
}
|
||||
patchEncryptedCiphers((prev) => {
|
||||
const idx = prev.findIndex((c) => c.id === encrypted.id);
|
||||
if (idx >= 0) {
|
||||
const next = [...prev];
|
||||
next[idx] = encrypted;
|
||||
return next;
|
||||
}
|
||||
return [encrypted, ...prev];
|
||||
});
|
||||
const encKey = base64ToBytes(session.symEncKey);
|
||||
const macKey = base64ToBytes(session.symMacKey);
|
||||
const decrypted = await decryptSingleCipher(encrypted, encKey, macKey);
|
||||
@@ -341,6 +352,7 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
await refetchCiphers();
|
||||
return;
|
||||
}
|
||||
patchEncryptedCiphers((prev) => [encrypted, ...prev.filter((cipher) => cipher.id !== optimisticId && cipher.id !== encrypted.id)]);
|
||||
const encKey = base64ToBytes(session.symEncKey);
|
||||
const macKey = base64ToBytes(session.symMacKey);
|
||||
const decrypted = await decryptSingleCipher(encrypted, encKey, macKey);
|
||||
@@ -351,12 +363,36 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
}
|
||||
|
||||
function removeCipherFromState(id: string) {
|
||||
patchEncryptedCiphers((prev) => prev.filter((c) => c.id !== id));
|
||||
patchDecryptedCiphers((prev) => prev.filter((c) => c.id !== id));
|
||||
}
|
||||
|
||||
function patchCipherBatch(ids: string[], updater: (cipher: Cipher) => Cipher | null) {
|
||||
function patchCipherBatch(
|
||||
ids: string[],
|
||||
updater: (cipher: Cipher) => Cipher | null,
|
||||
options?: { patchEncrypted?: boolean; patchDecrypted?: boolean }
|
||||
) {
|
||||
const idSet = new Set(ids.map((id) => String(id || '').trim()).filter(Boolean));
|
||||
if (!idSet.size) return;
|
||||
const shouldPatchEncrypted = options?.patchEncrypted !== false;
|
||||
const shouldPatchDecrypted = options?.patchDecrypted !== false;
|
||||
if (shouldPatchEncrypted) {
|
||||
patchEncryptedCiphers((prev) => {
|
||||
let changed = false;
|
||||
const next: Cipher[] = [];
|
||||
for (const cipher of prev) {
|
||||
if (!idSet.has(cipher.id)) {
|
||||
next.push(cipher);
|
||||
continue;
|
||||
}
|
||||
const updated = updater(cipher);
|
||||
changed = true;
|
||||
if (updated) next.push(updated);
|
||||
}
|
||||
return changed ? next : prev;
|
||||
});
|
||||
}
|
||||
if (shouldPatchDecrypted) {
|
||||
patchDecryptedCiphers((prev) => {
|
||||
let changed = false;
|
||||
const next: Cipher[] = [];
|
||||
@@ -372,10 +408,25 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
return changed ? next : prev;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function patchFolderBatch(ids: string[], updater: (folder: VaultFolder) => VaultFolder | null) {
|
||||
const idSet = new Set(ids.map((id) => String(id || '').trim()).filter(Boolean));
|
||||
if (!idSet.size) return;
|
||||
patchEncryptedFolders((prev) => {
|
||||
let changed = false;
|
||||
const next: VaultFolder[] = [];
|
||||
for (const folder of prev) {
|
||||
if (!idSet.has(folder.id)) {
|
||||
next.push(folder);
|
||||
continue;
|
||||
}
|
||||
const updated = updater(folder);
|
||||
changed = true;
|
||||
if (updated) next.push(updated);
|
||||
}
|
||||
return changed ? next : prev;
|
||||
});
|
||||
patchDecryptedFolders((prev) => {
|
||||
let changed = false;
|
||||
const next: VaultFolder[] = [];
|
||||
@@ -392,6 +443,31 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
});
|
||||
}
|
||||
|
||||
function upsertEncryptedFolder(folder: VaultFolder) {
|
||||
patchEncryptedFolders((prev) => {
|
||||
const index = prev.findIndex((item) => item.id === folder.id);
|
||||
if (index < 0) return [folder, ...prev];
|
||||
const next = [...prev];
|
||||
next[index] = folder;
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
function upsertSend(send: Send) {
|
||||
patchEncryptedSends((prev) => {
|
||||
const index = prev.findIndex((item) => item.id === send.id);
|
||||
if (index < 0) return [send, ...prev];
|
||||
const next = [...prev];
|
||||
next[index] = send;
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
function removeSend(id: string) {
|
||||
patchEncryptedSends((prev) => prev.filter((send) => send.id !== id));
|
||||
patchDecryptedSends((prev) => prev.filter((send) => send.id !== id));
|
||||
}
|
||||
|
||||
const uploadImportedAttachments = async (
|
||||
attachments: ImportAttachmentFile[],
|
||||
idMaps: { byIndex: Map<number, string>; bySourceId: Map<string, string> }
|
||||
@@ -467,8 +543,9 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
setAttachmentUploadPercent(0);
|
||||
await uploadCipherAttachment(authedFetch, session, created.id, file, undefined, setAttachmentUploadPercent);
|
||||
}
|
||||
await decryptAndReplaceOptimistic(optimistic.id, created);
|
||||
syncVaultCoreInBackground({ includeFolders: !!draft.folderId || attachments.length > 0 });
|
||||
const finalCipher = attachments.length ? await getCipherById(authedFetch, created.id) : created;
|
||||
await decryptAndReplaceOptimistic(optimistic.id, finalCipher);
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_item_created'));
|
||||
} catch (error) {
|
||||
patchDecryptedCiphers((prev) => prev.filter((cipher) => cipher.id !== optimistic.id));
|
||||
@@ -510,7 +587,7 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
.filter((attachment) => !removedSet.has(String(attachment?.id || '').trim()))
|
||||
.map((attachment) => ({ ...attachment }));
|
||||
}
|
||||
patchCipherBatch([cipher.id], () => optimistic);
|
||||
patchCipherBatch([cipher.id], () => optimistic, { patchEncrypted: false });
|
||||
try {
|
||||
const updated = await updateCipher(authedFetch, session, cipher, draft);
|
||||
for (const attachmentId of removeAttachmentIds) {
|
||||
@@ -523,16 +600,14 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
setAttachmentUploadPercent(0);
|
||||
await uploadCipherAttachment(authedFetch, session, cipher.id, file, cipher, setAttachmentUploadPercent);
|
||||
}
|
||||
await decryptAndPatch(updated);
|
||||
syncVaultCoreInBackground({
|
||||
includeFolders:
|
||||
draft.folderId !== (cipher.folderId || '')
|
||||
|| addFiles.length > 0
|
||||
|| removeAttachmentIds.length > 0,
|
||||
});
|
||||
const finalCipher = addFiles.length || removeAttachmentIds.length
|
||||
? await getCipherById(authedFetch, cipher.id)
|
||||
: updated;
|
||||
await decryptAndPatch(finalCipher);
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_item_updated'));
|
||||
} catch (error) {
|
||||
patchCipherBatch([cipher.id], () => previousCipher);
|
||||
patchCipherBatch([cipher.id], () => previousCipher, { patchEncrypted: false });
|
||||
onNotify('error', error instanceof Error ? error.message : t('txt_update_item_failed'));
|
||||
throw error;
|
||||
} finally {
|
||||
@@ -571,7 +646,7 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
try {
|
||||
await permanentDeleteCipher(authedFetch, cipher.id);
|
||||
patchCipherBatch([cipher.id], () => null);
|
||||
syncVaultCoreInBackground({ includeFolders: true });
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_item_deleted_permanently'));
|
||||
} catch (error) {
|
||||
onNotify('error', error instanceof Error ? error.message : t('txt_permanent_delete_item_failed'));
|
||||
@@ -584,10 +659,10 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
try {
|
||||
const deleted = await deleteCipher(authedFetch, cipher.id);
|
||||
await decryptAndPatch(deleted);
|
||||
syncVaultCoreInBackground({ includeFolders: true });
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_item_deleted'));
|
||||
} catch (error) {
|
||||
patchCipherBatch([cipher.id], () => previousCipher);
|
||||
patchCipherBatch([cipher.id], () => previousCipher, { patchEncrypted: false });
|
||||
onNotify('error', error instanceof Error ? error.message : t('txt_delete_item_failed'));
|
||||
throw error;
|
||||
}
|
||||
@@ -606,10 +681,10 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
try {
|
||||
const archived = await archiveCipher(authedFetch, cipher.id);
|
||||
await decryptAndPatch(archived);
|
||||
syncVaultCoreInBackground({ includeFolders: true });
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_item_archived'));
|
||||
} catch (error) {
|
||||
patchCipherBatch([cipher.id], () => previousCipher);
|
||||
patchCipherBatch([cipher.id], () => previousCipher, { patchEncrypted: false });
|
||||
onNotify('error', error instanceof Error ? error.message : t('txt_archive_item_failed'));
|
||||
throw error;
|
||||
}
|
||||
@@ -628,10 +703,10 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
try {
|
||||
const unarchived = await unarchiveCipher(authedFetch, cipher.id);
|
||||
await decryptAndPatch(unarchived);
|
||||
syncVaultCoreInBackground({ includeFolders: true });
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_item_unarchived'));
|
||||
} catch (error) {
|
||||
patchCipherBatch([cipher.id], () => previousCipher);
|
||||
patchCipherBatch([cipher.id], () => previousCipher, { patchEncrypted: false });
|
||||
onNotify('error', error instanceof Error ? error.message : t('txt_unarchive_item_failed'));
|
||||
throw error;
|
||||
}
|
||||
@@ -648,7 +723,7 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
await bulkDeleteCiphers(authedFetch, ids);
|
||||
const deletedDate = new Date().toISOString();
|
||||
patchCipherBatch(ids, (cipher) => ({ ...cipher, deletedDate, archivedDate: null }));
|
||||
syncVaultCoreInBackground({ includeFolders: true });
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_deleted_selected_items'));
|
||||
} catch (error) {
|
||||
onNotify('error', error instanceof Error ? error.message : t('txt_bulk_delete_failed'));
|
||||
@@ -667,7 +742,7 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
await bulkArchiveCiphers(authedFetch, ids);
|
||||
const archivedDate = new Date().toISOString();
|
||||
patchCipherBatch(ids, (cipher) => ({ ...cipher, archivedDate, deletedDate: null }));
|
||||
syncVaultCoreInBackground({ includeFolders: true });
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_archived_selected_items'));
|
||||
} catch (error) {
|
||||
onNotify('error', error instanceof Error ? error.message : t('txt_bulk_archive_failed'));
|
||||
@@ -685,7 +760,7 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
try {
|
||||
await bulkUnarchiveCiphers(authedFetch, ids);
|
||||
patchCipherBatch(ids, (cipher) => ({ ...cipher, archivedDate: null }));
|
||||
syncVaultCoreInBackground({ includeFolders: true });
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_unarchived_selected_items'));
|
||||
} catch (error) {
|
||||
onNotify('error', error instanceof Error ? error.message : t('txt_bulk_unarchive_failed'));
|
||||
@@ -703,7 +778,7 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
try {
|
||||
await bulkMoveCiphers(authedFetch, ids, folderId);
|
||||
patchCipherBatch(ids, (cipher) => ({ ...cipher, folderId }));
|
||||
syncVaultCoreInBackground({ includeFolders: true });
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_moved_selected_items'));
|
||||
} catch (error) {
|
||||
onNotify('error', error instanceof Error ? error.message : t('txt_bulk_move_failed'));
|
||||
@@ -726,15 +801,18 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
try {
|
||||
if (!session) throw new Error(t('txt_vault_key_unavailable'));
|
||||
const created = await createFolder(authedFetch, session, folderName);
|
||||
upsertEncryptedFolder(created);
|
||||
patchDecryptedFolders((prev) => [
|
||||
{
|
||||
id: created.id,
|
||||
name: created.name || folderName,
|
||||
decName: folderName,
|
||||
revisionDate: created.revisionDate,
|
||||
creationDate: created.creationDate,
|
||||
},
|
||||
...prev,
|
||||
]);
|
||||
syncVaultCoreInBackground({ includeFolders: true });
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_folder_created'));
|
||||
} catch (error) {
|
||||
onNotify('error', error instanceof Error ? error.message : t('txt_create_folder_failed'));
|
||||
@@ -757,8 +835,9 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
try {
|
||||
await deleteFolder(authedFetch, id);
|
||||
patchFolderBatch([id], () => null);
|
||||
patchEncryptedCiphers((prev) => prev.map((cipher) => (cipher.folderId === id ? { ...cipher, folderId: null } : cipher)));
|
||||
patchDecryptedCiphers((prev) => prev.map((cipher) => (cipher.folderId === id ? { ...cipher, folderId: null } : cipher)));
|
||||
syncVaultCoreInBackground({ includeFolders: true });
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_folder_deleted'));
|
||||
} catch (error) {
|
||||
onNotify('error', error instanceof Error ? error.message : t('txt_delete_folder_failed'));
|
||||
@@ -785,9 +864,14 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
}
|
||||
try {
|
||||
if (!session) throw new Error(t('txt_vault_key_unavailable'));
|
||||
await updateFolder(authedFetch, session, id, nextName);
|
||||
patchFolderBatch([id], (folder) => ({ ...folder, decName: nextName }));
|
||||
syncVaultCoreInBackground({ includeFolders: true });
|
||||
const updated = await updateFolder(authedFetch, session, id, nextName);
|
||||
upsertEncryptedFolder(updated);
|
||||
patchDecryptedFolders((prev) => prev.map((folder) => (
|
||||
folder.id === id
|
||||
? { ...folder, name: updated.name || folder.name, decName: nextName, revisionDate: updated.revisionDate }
|
||||
: folder
|
||||
)));
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_folder_updated'));
|
||||
} catch (error) {
|
||||
onNotify('error', error instanceof Error ? error.message : t('txt_update_folder_failed'));
|
||||
@@ -805,7 +889,7 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
try {
|
||||
await bulkRestoreCiphers(authedFetch, ids);
|
||||
patchCipherBatch(ids, (cipher) => ({ ...cipher, deletedDate: null }));
|
||||
syncVaultCoreInBackground({ includeFolders: true });
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_restored_selected_items'));
|
||||
} catch (error) {
|
||||
onNotify('error', error instanceof Error ? error.message : t('txt_bulk_restore_failed'));
|
||||
@@ -823,7 +907,7 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
try {
|
||||
await bulkPermanentDeleteCiphers(authedFetch, ids);
|
||||
patchCipherBatch(ids, () => null);
|
||||
syncVaultCoreInBackground({ includeFolders: true });
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_deleted_selected_items_permanently'));
|
||||
} catch (error) {
|
||||
onNotify('error', error instanceof Error ? error.message : t('txt_bulk_permanent_delete_failed'));
|
||||
@@ -843,9 +927,11 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
try {
|
||||
await bulkDeleteFolders(authedFetch, ids);
|
||||
const removedIds = new Set(ids);
|
||||
patchEncryptedFolders((prev) => prev.filter((folder) => !removedIds.has(folder.id)));
|
||||
patchEncryptedCiphers((prev) => prev.map((cipher) => (cipher.folderId && removedIds.has(cipher.folderId) ? { ...cipher, folderId: null } : cipher)));
|
||||
patchDecryptedFolders((prev) => prev.filter((folder) => !removedIds.has(folder.id)));
|
||||
patchDecryptedCiphers((prev) => prev.map((cipher) => (cipher.folderId && removedIds.has(cipher.folderId) ? { ...cipher, folderId: null } : cipher)));
|
||||
syncVaultCoreInBackground({ includeFolders: true });
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_folders_deleted'));
|
||||
} catch (error) {
|
||||
onNotify('error', error instanceof Error ? error.message : t('txt_delete_all_folders_failed'));
|
||||
@@ -873,7 +959,8 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
setSendUploadPercent(0);
|
||||
}
|
||||
const created = await createSend(authedFetch, session, draft, fileName ? setSendUploadPercent : undefined);
|
||||
await refetchSends();
|
||||
upsertSend(created);
|
||||
void refreshVaultRevisionStamp();
|
||||
if (autoCopyLink && created.key && session.symEncKey && session.symMacKey) {
|
||||
const keyPart = await buildSendShareKey(created.key, session.symEncKey, session.symMacKey);
|
||||
const shareUrl = buildPublicSendUrl(window.location.origin, created.accessId, keyPart);
|
||||
@@ -899,7 +986,8 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
}
|
||||
try {
|
||||
const updated = await updateSend(authedFetch, session, send, draft);
|
||||
await refetchSends();
|
||||
upsertSend(updated);
|
||||
void refreshVaultRevisionStamp();
|
||||
if (autoCopyLink && updated.key && session.symEncKey && session.symMacKey) {
|
||||
const keyPart = await buildSendShareKey(updated.key, session.symEncKey, session.symMacKey);
|
||||
const shareUrl = buildPublicSendUrl(window.location.origin, updated.accessId, keyPart);
|
||||
@@ -921,7 +1009,8 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
}
|
||||
try {
|
||||
await deleteSend(authedFetch, send.id);
|
||||
await refetchSends();
|
||||
removeSend(send.id);
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_send_deleted'));
|
||||
} catch (error) {
|
||||
onNotify('error', error instanceof Error ? error.message : t('txt_delete_send_failed'));
|
||||
@@ -938,7 +1027,10 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
}
|
||||
try {
|
||||
await bulkDeleteSends(authedFetch, ids);
|
||||
await refetchSends();
|
||||
const idSet = new Set(ids.map((id) => String(id || '').trim()).filter(Boolean));
|
||||
patchEncryptedSends((prev) => prev.filter((send) => !idSet.has(send.id)));
|
||||
patchDecryptedSends((prev) => prev.filter((send) => !idSet.has(send.id)));
|
||||
void refreshVaultRevisionStamp();
|
||||
onNotify('success', t('txt_deleted_selected_sends'));
|
||||
} catch (error) {
|
||||
onNotify('error', error instanceof Error ? error.message : t('txt_bulk_delete_sends_failed'));
|
||||
@@ -1190,6 +1282,12 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
mimeType: 'application/json',
|
||||
bytes: new TextEncoder().encode(await getPlainJson()),
|
||||
};
|
||||
} else if (format === 'bitwarden_csv') {
|
||||
result = {
|
||||
fileName: buildExportFileName(format),
|
||||
mimeType: 'text/csv;charset=utf-8',
|
||||
bytes: new TextEncoder().encode(buildBitwardenCsvString(await getPlainJsonDoc())),
|
||||
};
|
||||
} else if (format === 'bitwarden_encrypted_json') {
|
||||
if (request.encryptedJsonMode === 'password') {
|
||||
const plainJson = await getPlainJson();
|
||||
@@ -1292,10 +1390,17 @@ export default function useVaultSendActions(options: UseVaultSendActionsOptions)
|
||||
encryptedFolders,
|
||||
importAuthedFetch,
|
||||
onNotify,
|
||||
patchDecryptedCiphers,
|
||||
patchDecryptedFolders,
|
||||
patchDecryptedSends,
|
||||
patchEncryptedCiphers,
|
||||
patchEncryptedFolders,
|
||||
patchEncryptedSends,
|
||||
profile,
|
||||
refetchCiphers,
|
||||
refetchFolders,
|
||||
refetchSends,
|
||||
refreshVaultRevisionStamp,
|
||||
session,
|
||||
sendUploadPercent,
|
||||
uploadingAttachmentName,
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { base64ToBytes, bytesToBase64, hkdfExpand, toBufferSource } from '@/lib/crypto';
|
||||
import { EFFLongWordList } from '@/lib/fingerprint-wordlist';
|
||||
import { t } from '@/lib/i18n';
|
||||
import type { AuthRequest, ListResponse, SessionState } from '@/lib/types';
|
||||
import type { AuthedFetch } from './shared';
|
||||
import { parseErrorMessage, parseJson } from './shared';
|
||||
|
||||
function readResponseProperty<T>(source: Record<string, any>, camel: string, pascal: string, fallback: T): T {
|
||||
return (source[camel] ?? source[pascal] ?? fallback) as T;
|
||||
}
|
||||
|
||||
function normalizeAuthRequest(raw: Record<string, any>): AuthRequest {
|
||||
return {
|
||||
id: String(readResponseProperty(raw, 'id', 'Id', '')),
|
||||
publicKey: String(readResponseProperty(raw, 'publicKey', 'PublicKey', '')),
|
||||
requestDeviceType: readResponseProperty(raw, 'requestDeviceType', 'RequestDeviceType', null),
|
||||
requestDeviceTypeValue: readResponseProperty(raw, 'requestDeviceTypeValue', 'RequestDeviceTypeValue', null),
|
||||
requestDeviceIdentifier: String(readResponseProperty(raw, 'requestDeviceIdentifier', 'RequestDeviceIdentifier', '')),
|
||||
requestIpAddress: readResponseProperty(raw, 'requestIpAddress', 'RequestIpAddress', null),
|
||||
requestCountryName: readResponseProperty(raw, 'requestCountryName', 'RequestCountryName', null),
|
||||
key: readResponseProperty(raw, 'key', 'Key', null),
|
||||
creationDate: String(readResponseProperty(raw, 'creationDate', 'CreationDate', '')),
|
||||
requestApproved: readResponseProperty(raw, 'requestApproved', 'RequestApproved', null),
|
||||
responseDate: readResponseProperty(raw, 'responseDate', 'ResponseDate', null),
|
||||
deviceId: readResponseProperty(raw, 'deviceId', 'DeviceId', null),
|
||||
requestDeviceId: readResponseProperty(raw, 'requestDeviceId', 'RequestDeviceId', null),
|
||||
};
|
||||
}
|
||||
|
||||
async function withFingerprintPhrase(email: string, request: AuthRequest): Promise<AuthRequest> {
|
||||
if (!request.publicKey) return request;
|
||||
try {
|
||||
return {
|
||||
...request,
|
||||
fingerprintPhrase: await getFingerprintPhrase(email, base64ToBytes(request.publicKey)),
|
||||
};
|
||||
} catch {
|
||||
return request;
|
||||
}
|
||||
}
|
||||
|
||||
export async function listPendingAuthRequests(authedFetch: AuthedFetch, email: string): Promise<AuthRequest[]> {
|
||||
const resp = await authedFetch('/api/auth-requests/pending');
|
||||
if (!resp.ok) throw new Error(await parseErrorMessage(resp, t('txt_auth_requests_load_failed')));
|
||||
const body = await parseJson<ListResponse<Record<string, any>> & { Data?: Record<string, any>[] }>(resp);
|
||||
const rows = (body?.data || body?.Data || []).map(normalizeAuthRequest);
|
||||
return Promise.all(rows.map((row) => withFingerprintPhrase(email, row)));
|
||||
}
|
||||
|
||||
export async function respondToAuthRequest(
|
||||
authedFetch: AuthedFetch,
|
||||
requestId: string,
|
||||
payload: {
|
||||
key?: string | null;
|
||||
masterPasswordHash?: string | null;
|
||||
deviceIdentifier: string;
|
||||
requestApproved: boolean;
|
||||
}
|
||||
): Promise<AuthRequest> {
|
||||
const resp = await authedFetch(`/api/auth-requests/${encodeURIComponent(requestId)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!resp.ok) throw new Error(await parseErrorMessage(resp, t('txt_auth_request_update_failed')));
|
||||
const body = await parseJson<Record<string, any>>(resp);
|
||||
if (!body) throw new Error(t('txt_auth_request_update_failed'));
|
||||
return normalizeAuthRequest(body);
|
||||
}
|
||||
|
||||
export function isPendingAuthRequest(request: AuthRequest): boolean {
|
||||
if (!request.id || !request.creationDate) return false;
|
||||
if (request.responseDate) return false;
|
||||
const createdAt = new Date(request.creationDate).getTime();
|
||||
if (!Number.isFinite(createdAt)) return true;
|
||||
return Date.now() - createdAt < 15 * 60 * 1000;
|
||||
}
|
||||
|
||||
export async function encryptSessionUserKeyForAuthRequest(session: SessionState, authRequest: AuthRequest): Promise<string> {
|
||||
if (!session.symEncKey || !session.symMacKey) throw new Error(t('txt_vault_key_unavailable'));
|
||||
if (!authRequest.publicKey) throw new Error(t('txt_auth_request_missing_public_key'));
|
||||
|
||||
const userKeyBytes = new Uint8Array(64);
|
||||
userKeyBytes.set(base64ToBytes(session.symEncKey), 0);
|
||||
userKeyBytes.set(base64ToBytes(session.symMacKey), 32);
|
||||
const publicKey = await crypto.subtle.importKey(
|
||||
'spki',
|
||||
toBufferSource(base64ToBytes(authRequest.publicKey)),
|
||||
{ name: 'RSA-OAEP', hash: 'SHA-1' },
|
||||
false,
|
||||
['encrypt']
|
||||
);
|
||||
const encryptedBytes = new Uint8Array(await crypto.subtle.encrypt(
|
||||
{ name: 'RSA-OAEP' },
|
||||
publicKey,
|
||||
toBufferSource(userKeyBytes)
|
||||
));
|
||||
return `4.${bytesToBase64(encryptedBytes)}`;
|
||||
}
|
||||
|
||||
export async function getFingerprintPhrase(email: string, publicKey: Uint8Array): Promise<string> {
|
||||
const keyFingerprint = new Uint8Array(await crypto.subtle.digest('SHA-256', toBufferSource(publicKey)));
|
||||
const userFingerprint = await hkdfExpand(keyFingerprint, email.toLowerCase(), 32);
|
||||
return hashPhrase(userFingerprint).join('-');
|
||||
}
|
||||
|
||||
function hashPhrase(hash: Uint8Array, minimumEntropy = 64): string[] {
|
||||
const entropyPerWord = Math.log(EFFLongWordList.length) / Math.log(2);
|
||||
let numWords = Math.ceil(minimumEntropy / entropyPerWord);
|
||||
if (numWords * entropyPerWord > hash.length * 4) {
|
||||
throw new Error('Output entropy of hash function is too small');
|
||||
}
|
||||
|
||||
let hashNumber = 0n;
|
||||
for (const byte of hash) {
|
||||
hashNumber = (hashNumber * 256n) + BigInt(byte);
|
||||
}
|
||||
|
||||
const phrase: string[] = [];
|
||||
const wordCount = BigInt(EFFLongWordList.length);
|
||||
while (numWords > 0) {
|
||||
const remainder = Number(hashNumber % wordCount);
|
||||
hashNumber /= wordCount;
|
||||
phrase.push(EFFLongWordList[remainder]);
|
||||
numWords -= 1;
|
||||
}
|
||||
return phrase;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
TokenSuccess,
|
||||
} from '../types';
|
||||
import type { AccountPasskeyAssertion, AccountPasskeyPrfKeySet } from '../account-passkeys';
|
||||
import { recordNodeWardenReachable, recordNodeWardenUnreachable } from '../network-status';
|
||||
import { parseJson, type AuthedFetch, type SessionSetter } from './shared';
|
||||
|
||||
const SESSION_KEY = 'nodewarden.web.session.v4';
|
||||
@@ -474,6 +475,7 @@ export function createAuthedFetch(getSession: () => SessionState | null, setSess
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
||||
try {
|
||||
const response = await fetch(input, { ...init, headers });
|
||||
recordNodeWardenReachable();
|
||||
if (response.status !== 429 && (response.status < 500 || response.status >= 600)) {
|
||||
return response;
|
||||
}
|
||||
@@ -484,6 +486,7 @@ export function createAuthedFetch(getSession: () => SessionState | null, setSess
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (attempt === maxAttempts - 1) {
|
||||
recordNodeWardenUnreachable();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -497,7 +500,6 @@ export function createAuthedFetch(getSession: () => SessionState | null, setSess
|
||||
if (!session?.accessToken) throw new Error(t('txt_offline_vault_readonly'));
|
||||
const headers = new Headers(init.headers || {});
|
||||
headers.set('Authorization', `Bearer ${session.accessToken}`);
|
||||
headers.set('X-NodeWarden-Web', '1');
|
||||
|
||||
let resp = await retryableRequest(headers);
|
||||
if (resp.status !== 401 || (!session.refreshToken && session.authMode !== 'web-cookie')) return resp;
|
||||
@@ -506,7 +508,6 @@ export function createAuthedFetch(getSession: () => SessionState | null, setSess
|
||||
if (latest?.accessToken && latest.accessToken !== session.accessToken) {
|
||||
const latestHeaders = new Headers(init.headers || {});
|
||||
latestHeaders.set('Authorization', `Bearer ${latest.accessToken}`);
|
||||
latestHeaders.set('X-NodeWarden-Web', '1');
|
||||
resp = await retryableRequest(latestHeaders);
|
||||
if (resp.status !== 401) return resp;
|
||||
}
|
||||
@@ -532,7 +533,6 @@ export function createAuthedFetch(getSession: () => SessionState | null, setSess
|
||||
|
||||
const retryHeaders = new Headers(init.headers || {});
|
||||
retryHeaders.set('Authorization', `Bearer ${nextSession.accessToken}`);
|
||||
retryHeaders.set('X-NodeWarden-Web', '1');
|
||||
resp = await retryableRequest(retryHeaders);
|
||||
return resp;
|
||||
};
|
||||
@@ -596,14 +596,35 @@ export async function changeMasterPassword(
|
||||
const nextEnc = await hkdfExpand(nextMasterKey, 'enc', 32);
|
||||
const nextMac = await hkdfExpand(nextMasterKey, 'mac', 32);
|
||||
const newKey = await encryptBw(userSym.slice(0, 64), nextEnc, nextMac);
|
||||
const newMasterPasswordHash = bytesToBase64(nextHash);
|
||||
|
||||
const resp = await authedFetch('/api/accounts/password', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
currentPasswordHash: current.hash,
|
||||
newMasterPasswordHash: bytesToBase64(nextHash),
|
||||
newKey,
|
||||
masterPasswordHash: current.hash,
|
||||
newMasterPasswordHash,
|
||||
key: newKey,
|
||||
authenticationData: {
|
||||
kdf: {
|
||||
kdfType: 0,
|
||||
iterations: current.kdfIterations,
|
||||
memory: null,
|
||||
parallelism: null,
|
||||
},
|
||||
masterPasswordAuthenticationHash: newMasterPasswordHash,
|
||||
salt: args.email.trim().toLowerCase(),
|
||||
},
|
||||
unlockData: {
|
||||
kdf: {
|
||||
kdfType: 0,
|
||||
iterations: current.kdfIterations,
|
||||
memory: null,
|
||||
parallelism: null,
|
||||
},
|
||||
masterKeyWrappedUserKey: newKey,
|
||||
salt: args.email.trim().toLowerCase(),
|
||||
},
|
||||
kdf: 0,
|
||||
kdfIterations: current.kdfIterations,
|
||||
}),
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
BackupRuntimeState,
|
||||
BackupScheduleConfig,
|
||||
BackupSettings as AdminBackupSettings,
|
||||
S3BackupAddressingStyle,
|
||||
S3BackupDestination,
|
||||
WebDavBackupDestination,
|
||||
} from '@shared/backup-schema';
|
||||
@@ -26,6 +27,7 @@ export type {
|
||||
BackupRuntimeState,
|
||||
BackupScheduleConfig,
|
||||
AdminBackupSettings,
|
||||
S3BackupAddressingStyle,
|
||||
S3BackupDestination,
|
||||
WebDavBackupDestination,
|
||||
};
|
||||
@@ -96,6 +98,7 @@ export interface AdminBackupImportCounts {
|
||||
users: number;
|
||||
domainSettings?: number;
|
||||
userRevisions: number;
|
||||
trustedTwoFactorDeviceTokens?: number;
|
||||
webauthnCredentials?: number;
|
||||
folders: number;
|
||||
ciphers: number;
|
||||
|
||||
@@ -67,6 +67,17 @@ export async function getSends(authedFetch: AuthedFetch): Promise<Send[]> {
|
||||
return body?.data || [];
|
||||
}
|
||||
|
||||
export async function getSendById(authedFetch: AuthedFetch, sendId: string): Promise<Send> {
|
||||
const id = String(sendId || '').trim();
|
||||
if (!id) throw new Error('Send id is required');
|
||||
const resp = await authedFetch(`/api/sends/${encodeURIComponent(id)}`);
|
||||
if (resp.status === 404) throw createApiError('Send not found', 404);
|
||||
if (!resp.ok) throw new Error(await parseErrorMessage(resp, 'Load send failed'));
|
||||
const body = await parseJson<Send>(resp);
|
||||
if (!body?.id) throw new Error('Load send failed');
|
||||
return body;
|
||||
}
|
||||
|
||||
export async function createSend(
|
||||
authedFetch: AuthedFetch,
|
||||
session: SessionState,
|
||||
|
||||
@@ -51,6 +51,29 @@ export async function invalidateVaultCoreSyncSnapshot(cacheKey: string): Promise
|
||||
await clearCachedVaultCoreSnapshot(normalizedKey);
|
||||
}
|
||||
|
||||
export async function saveVaultCoreSyncSnapshot(
|
||||
cacheKey: string,
|
||||
snapshot: VaultCoreSnapshot,
|
||||
revisionStamp?: number | null
|
||||
): Promise<void> {
|
||||
const normalizedKey = String(cacheKey || '').trim();
|
||||
if (!normalizedKey) return;
|
||||
|
||||
const normalizedSnapshot = normalizeCachedSnapshot(snapshot);
|
||||
const currentMemory = memoryVaultCoreCache.get(normalizedKey);
|
||||
let nextRevisionStamp = Number(revisionStamp);
|
||||
if (!Number.isFinite(nextRevisionStamp) || nextRevisionStamp <= 0) {
|
||||
const cached = await loadCachedVaultCoreSnapshot(normalizedKey);
|
||||
nextRevisionStamp = currentMemory?.revisionStamp || cached?.revisionStamp || Date.now();
|
||||
}
|
||||
|
||||
memoryVaultCoreCache.set(normalizedKey, {
|
||||
revisionStamp: nextRevisionStamp,
|
||||
snapshot: normalizedSnapshot,
|
||||
});
|
||||
await saveCachedVaultCoreSnapshot(normalizedKey, nextRevisionStamp, normalizedSnapshot);
|
||||
}
|
||||
|
||||
export async function loadVaultCoreSyncSnapshot(authedFetch: AuthedFetch, cacheKey: string): Promise<VaultCoreSnapshot> {
|
||||
const normalizedKey = String(cacheKey || '').trim();
|
||||
if (!normalizedKey) return { ciphers: [], folders: [], sends: [] };
|
||||
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
import {
|
||||
BULK_API_CHUNK_SIZE,
|
||||
chunkArray,
|
||||
createApiError,
|
||||
parseErrorMessage,
|
||||
parseJson,
|
||||
uploadDirectEncryptedPayload,
|
||||
@@ -20,17 +21,29 @@ import { readResponseBytesWithProgress } from '../download';
|
||||
import { loadVaultCoreSyncSnapshot } from './vault-sync';
|
||||
|
||||
type CipherLoginData = NonNullable<Cipher['login']>;
|
||||
const NODEWARDEN_WEB_REPAIR_HEADER = 'X-NodeWarden-Web';
|
||||
|
||||
export async function getFolders(authedFetch: AuthedFetch, cacheKey: string): Promise<Folder[]> {
|
||||
const body = await loadVaultCoreSyncSnapshot(authedFetch, cacheKey);
|
||||
return body.folders || [];
|
||||
}
|
||||
|
||||
export async function getFolderById(authedFetch: AuthedFetch, folderId: string): Promise<Folder> {
|
||||
const id = String(folderId || '').trim();
|
||||
if (!id) throw new Error('Folder id is required');
|
||||
const resp = await authedFetch(`/api/folders/${encodeURIComponent(id)}`);
|
||||
if (resp.status === 404) throw createApiError('Folder not found', 404);
|
||||
if (!resp.ok) throw new Error(await parseErrorMessage(resp, 'Load folder failed'));
|
||||
const body = await parseJson<Folder>(resp);
|
||||
if (!body?.id) throw new Error('Load folder failed');
|
||||
return body;
|
||||
}
|
||||
|
||||
export async function createFolder(
|
||||
authedFetch: AuthedFetch,
|
||||
session: SessionState,
|
||||
name: string
|
||||
): Promise<{ id: string; name?: string | null }> {
|
||||
): Promise<Folder> {
|
||||
if (!session.symEncKey || !session.symMacKey) throw new Error('Vault key unavailable');
|
||||
const enc = base64ToBytes(session.symEncKey);
|
||||
const mac = base64ToBytes(session.symMacKey);
|
||||
@@ -41,9 +54,9 @@ export async function createFolder(
|
||||
body: JSON.stringify({ name: encryptedName }),
|
||||
});
|
||||
if (!resp.ok) throw new Error('Create folder failed');
|
||||
const body = await parseJson<{ id?: string; name?: string | null }>(resp);
|
||||
const body = await parseJson<Folder>(resp);
|
||||
if (!body?.id) throw new Error('Create folder failed');
|
||||
return { id: body.id, name: body.name ?? null };
|
||||
return body;
|
||||
}
|
||||
|
||||
export async function encryptFolderImportName(session: SessionState, name: string): Promise<string> {
|
||||
@@ -79,7 +92,7 @@ export async function updateFolder(
|
||||
session: SessionState,
|
||||
folderId: string,
|
||||
name: string
|
||||
): Promise<void> {
|
||||
): Promise<Folder> {
|
||||
const id = String(folderId || '').trim();
|
||||
if (!id) throw new Error('Folder id is required');
|
||||
if (!session.symEncKey || !session.symMacKey) throw new Error('Vault key unavailable');
|
||||
@@ -92,6 +105,9 @@ export async function updateFolder(
|
||||
body: JSON.stringify({ name: encryptedName }),
|
||||
});
|
||||
if (!resp.ok) throw new Error('Update folder failed');
|
||||
const body = await parseJson<Folder>(resp);
|
||||
if (!body?.id) throw new Error('Update folder failed');
|
||||
return body;
|
||||
}
|
||||
|
||||
export async function getCiphers(authedFetch: AuthedFetch, cacheKey: string): Promise<Cipher[]> {
|
||||
@@ -99,6 +115,17 @@ export async function getCiphers(authedFetch: AuthedFetch, cacheKey: string): Pr
|
||||
return body.ciphers || [];
|
||||
}
|
||||
|
||||
export async function getCipherById(authedFetch: AuthedFetch, cipherId: string): Promise<Cipher> {
|
||||
const id = String(cipherId || '').trim();
|
||||
if (!id) throw new Error('Cipher id is required');
|
||||
const resp = await authedFetch(`/api/ciphers/${encodeURIComponent(id)}`);
|
||||
if (resp.status === 404) throw createApiError('Cipher not found', 404);
|
||||
if (!resp.ok) throw new Error(await parseErrorMessage(resp, 'Load cipher failed'));
|
||||
const body = await parseJson<Cipher>(resp);
|
||||
if (!body?.id) throw new Error('Load cipher failed');
|
||||
return body;
|
||||
}
|
||||
|
||||
export interface CiphersImportPayload {
|
||||
ciphers: Array<Record<string, unknown>>;
|
||||
folders: Array<{ name: string }>;
|
||||
@@ -933,7 +960,7 @@ export async function repairCipherUriChecksums(
|
||||
|
||||
const resp = await authedFetch(`/api/ciphers/${encodeURIComponent(cipher.id)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: { 'Content-Type': 'application/json', [NODEWARDEN_WEB_REPAIR_HEADER]: '1' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!resp.ok) throw new Error(await parseErrorMessage(resp, 'Repair URI checksum failed'));
|
||||
@@ -1092,9 +1119,14 @@ export async function repairCipherKeyMismatches(
|
||||
if (!cipher?.id || !looksLikeCipherString(cipher.key)) continue;
|
||||
if (!(await hasItemKeyFieldMismatch(cipher, userEnc, userMac))) continue;
|
||||
if (hasUnresolvedEncryptedFields(cipher)) continue;
|
||||
await updateCipher(authedFetch, session, cipher, draftFromDecryptedCipher(cipher), {
|
||||
preserveRevisionDate: true,
|
||||
});
|
||||
await updateCipher(
|
||||
authedFetch,
|
||||
session,
|
||||
cipher,
|
||||
draftFromDecryptedCipher(cipher),
|
||||
{ preserveRevisionDate: true },
|
||||
{ webRepair: true }
|
||||
);
|
||||
repaired += 1;
|
||||
}
|
||||
|
||||
@@ -1229,7 +1261,8 @@ export async function updateCipher(
|
||||
session: SessionState,
|
||||
cipher: Cipher,
|
||||
draft: VaultDraft,
|
||||
extraPayload?: Record<string, unknown>
|
||||
extraPayload?: Record<string, unknown>,
|
||||
options?: { webRepair?: boolean }
|
||||
): Promise<Cipher> {
|
||||
const payload = await buildCipherPayload(session, draft, cipher);
|
||||
if (extraPayload) {
|
||||
@@ -1238,7 +1271,10 @@ export async function updateCipher(
|
||||
|
||||
const resp = await authedFetch(`/api/ciphers/${encodeURIComponent(cipher.id)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(options?.webRepair ? { [NODEWARDEN_WEB_REPAIR_HEADER]: '1' } : {}),
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!resp.ok) throw new Error('Update item failed');
|
||||
|
||||
@@ -279,20 +279,16 @@ export async function hydrateLockedSession(
|
||||
fallbackProfile: Profile | null = null
|
||||
): Promise<{ session: SessionState | null; profile: Profile | null }> {
|
||||
const hasOfflineUnlock = hasOfflineUnlockRecord(session.email);
|
||||
let serviceReachable = true;
|
||||
if (hasOfflineUnlock) {
|
||||
serviceReachable = await probeNodeWardenService();
|
||||
if (!serviceReachable) {
|
||||
if (hasOfflineUnlock && browserReportsOffline()) {
|
||||
return {
|
||||
session,
|
||||
profile: fallbackProfile || loadOfflineProfileSnapshot(session.email),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const refreshedSession = await maybeRefreshSession(session);
|
||||
if (!refreshedSession?.accessToken) {
|
||||
if (hasOfflineUnlock && !serviceReachable) {
|
||||
if (hasOfflineUnlock && (browserReportsOffline() || !(await probeNodeWardenService()))) {
|
||||
return {
|
||||
session,
|
||||
profile: fallbackProfile || loadOfflineProfileSnapshot(session.email),
|
||||
@@ -571,15 +567,9 @@ export async function performUnlock(
|
||||
}
|
||||
};
|
||||
|
||||
if (hasOfflineUnlock) {
|
||||
if (browserReportsOffline()) {
|
||||
if (hasOfflineUnlock && browserReportsOffline()) {
|
||||
return unlockOffline();
|
||||
}
|
||||
const serviceReachable = await probeNodeWardenService();
|
||||
if (!serviceReachable) {
|
||||
return unlockOffline();
|
||||
}
|
||||
}
|
||||
|
||||
let token: TokenSuccess | { TwoFactorProviders?: unknown; error_description?: string; error?: string };
|
||||
try {
|
||||
|
||||
@@ -220,6 +220,25 @@ function normalizeTotpSecret(secret: string): string {
|
||||
return secret.toUpperCase().replace(/[\s-]/g, '').replace(/=+$/g, '');
|
||||
}
|
||||
|
||||
function readOtpAuthParam(raw: string, name: string): string {
|
||||
const queryStart = raw.indexOf('?');
|
||||
if (queryStart < 0) return '';
|
||||
const fragmentStart = raw.indexOf('#', queryStart + 1);
|
||||
const query = raw.slice(queryStart + 1, fragmentStart > queryStart ? fragmentStart : undefined);
|
||||
for (const part of query.split('&')) {
|
||||
const eq = part.indexOf('=');
|
||||
const key = eq >= 0 ? part.slice(0, eq) : part;
|
||||
if (key.trim().toLowerCase() !== name.toLowerCase()) continue;
|
||||
const value = eq >= 0 ? part.slice(eq + 1) : '';
|
||||
try {
|
||||
return decodeURIComponent(value.replace(/\+/g, ' '));
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function parseSteamSecret(raw: string): string {
|
||||
const match = raw.trim().match(/^steam:\/\/([^/?#]+)(?:[/?#].*)?$/i);
|
||||
if (!match?.[1]) return '';
|
||||
@@ -276,7 +295,8 @@ function parseTotpConfig(raw: string): TotpConfig {
|
||||
if (/^otpauth:\/\//i.test(s)) {
|
||||
try {
|
||||
const u = new URL(s);
|
||||
if (u.hostname.toLowerCase() !== 'totp') {
|
||||
const otpType = u.hostname.toLowerCase();
|
||||
if (otpType !== 'totp') {
|
||||
return { secret: '', steam: false, ...DEFAULT_TOTP_CONFIG };
|
||||
}
|
||||
const label = decodeURIComponent((u.pathname || '').replace(/^\/+/, '')).toLowerCase();
|
||||
@@ -291,7 +311,16 @@ function parseTotpConfig(raw: string): TotpConfig {
|
||||
period: parseTotpPositiveInt(u.searchParams.get('period'), DEFAULT_TOTP_CONFIG.period, 1, 3600),
|
||||
};
|
||||
} catch {
|
||||
return { secret: '', steam: false, ...DEFAULT_TOTP_CONFIG };
|
||||
const issuer = readOtpAuthParam(s, 'issuer').trim().toLowerCase();
|
||||
const algorithm = readOtpAuthParam(s, 'algorithm').trim().toLowerCase();
|
||||
const steam = issuer === 'steam' || algorithm === 'steam';
|
||||
return {
|
||||
secret: normalizeTotpSecret(readOtpAuthParam(s, 'secret')),
|
||||
steam,
|
||||
algorithm: steam ? 'SHA-1' : parseTotpHashAlgorithm(algorithm),
|
||||
digits: steam ? 5 : parseTotpPositiveInt(readOtpAuthParam(s, 'digits'), DEFAULT_TOTP_CONFIG.digits, 1, 10),
|
||||
period: parseTotpPositiveInt(readOtpAuthParam(s, 'period'), DEFAULT_TOTP_CONFIG.period, 1, 3600),
|
||||
};
|
||||
}
|
||||
}
|
||||
return { secret: normalizeTotpSecret(s), steam: false, ...DEFAULT_TOTP_CONFIG };
|
||||
|
||||
@@ -9,6 +9,7 @@ configureZipJs({ useWebWorkers: false });
|
||||
|
||||
export const EXPORT_FORMATS = [
|
||||
{ id: 'bitwarden_json', label: 'Bitwarden (vault as json)' },
|
||||
{ id: 'bitwarden_csv', label: 'Bitwarden (vault as csv)' },
|
||||
{ id: 'bitwarden_encrypted_json', label: 'Bitwarden (encrypted vault as json)' },
|
||||
{ id: 'bitwarden_json_zip', label: 'Bitwarden (vault + attachments as zip)' },
|
||||
{ id: 'bitwarden_encrypted_json_zip', label: 'Bitwarden (encrypted vault + attachments as zip)' },
|
||||
@@ -70,6 +71,31 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === 'object';
|
||||
}
|
||||
|
||||
function csvText(value: unknown): string {
|
||||
if (value === null || value === undefined) return '';
|
||||
if (typeof value === 'string') return value;
|
||||
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
|
||||
try {
|
||||
return JSON.stringify(value);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
function escapeCsvCell(value: unknown): string {
|
||||
const text = csvText(value);
|
||||
if (!/[",\r\n]/.test(text)) return text;
|
||||
return `"${text.replace(/"/g, '""')}"`;
|
||||
}
|
||||
|
||||
function buildCsvString(rows: string[][]): string {
|
||||
return `${rows.map((row) => row.map(escapeCsvCell).join(',')).join('\r\n')}\r\n`;
|
||||
}
|
||||
|
||||
function buildSingleRowCsvString(values: string[]): string {
|
||||
return values.map(escapeCsvCell).join(',');
|
||||
}
|
||||
|
||||
function isCipherString(value: string): boolean {
|
||||
return /^\d+\.[A-Za-z0-9+/=]+\|[A-Za-z0-9+/=]+(?:\|[A-Za-z0-9+/=]+)?$/.test(String(value || '').trim());
|
||||
}
|
||||
@@ -383,6 +409,106 @@ export async function buildPlainBitwardenJsonString(args: BuildPlainJsonArgs): P
|
||||
return JSON.stringify(doc, null, 2);
|
||||
}
|
||||
|
||||
const BITWARDEN_CSV_HEADERS = [
|
||||
'folder',
|
||||
'favorite',
|
||||
'type',
|
||||
'name',
|
||||
'notes',
|
||||
'fields',
|
||||
'reprompt',
|
||||
'login_uri',
|
||||
'login_username',
|
||||
'login_password',
|
||||
'login_totp',
|
||||
] as const;
|
||||
|
||||
function bitwardenCsvType(type: number): 'login' | 'note' {
|
||||
return type === 1 ? 'login' : 'note';
|
||||
}
|
||||
|
||||
function sourceTypeLabel(type: number): string {
|
||||
if (type === 3) return 'card';
|
||||
if (type === 4) return 'identity';
|
||||
if (type === 5) return 'sshKey';
|
||||
if (type === 2) return 'note';
|
||||
return `type ${type}`;
|
||||
}
|
||||
|
||||
function appendFieldLine(lines: string[], name: unknown, value: unknown): void {
|
||||
const key = csvText(name).trim();
|
||||
const text = csvText(value);
|
||||
if (!key || !text) return;
|
||||
lines.push(`${key}: ${text}`);
|
||||
}
|
||||
|
||||
function appendRecordFieldLines(lines: string[], prefix: string, value: unknown): void {
|
||||
if (!isRecord(value)) return;
|
||||
for (const [key, fieldValue] of Object.entries(value)) {
|
||||
appendFieldLine(lines, `${prefix}.${key}`, fieldValue);
|
||||
}
|
||||
}
|
||||
|
||||
function buildBitwardenCsvFields(item: Record<string, unknown>, type: number): string {
|
||||
const lines: string[] = [];
|
||||
const fields = Array.isArray(item.fields) ? item.fields : [];
|
||||
for (const field of fields) {
|
||||
if (!isRecord(field)) continue;
|
||||
appendFieldLine(lines, field.name, field.value);
|
||||
}
|
||||
if (type !== 1 && type !== 2) {
|
||||
appendFieldLine(lines, 'nodewardenType', sourceTypeLabel(type));
|
||||
appendRecordFieldLines(lines, sourceTypeLabel(type), item[sourceTypeLabel(type)]);
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function buildFolderNameById(foldersRaw: unknown): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
const folders = Array.isArray(foldersRaw) ? foldersRaw : [];
|
||||
for (const folder of folders) {
|
||||
if (!isRecord(folder)) continue;
|
||||
const id = csvText(folder.id).trim();
|
||||
if (!id) continue;
|
||||
out.set(id, csvText(folder.name));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function buildBitwardenCsvLoginUri(login: Record<string, unknown> | null): string {
|
||||
const uris = Array.isArray(login?.uris) ? login.uris : [];
|
||||
return buildSingleRowCsvString(uris
|
||||
.map((uri) => (isRecord(uri) ? csvText(uri.uri).trim() : ''))
|
||||
.filter(Boolean));
|
||||
}
|
||||
|
||||
export function buildBitwardenCsvString(bitwardenJsonDoc: Record<string, unknown>): string {
|
||||
const folderNameById = buildFolderNameById(bitwardenJsonDoc.folders);
|
||||
const rows: string[][] = [[...BITWARDEN_CSV_HEADERS]];
|
||||
const items = Array.isArray(bitwardenJsonDoc.items) ? bitwardenJsonDoc.items : [];
|
||||
for (const itemRaw of items) {
|
||||
if (!isRecord(itemRaw)) continue;
|
||||
const type = normalizeNumber(itemRaw.type, 1);
|
||||
const isLogin = type === 1;
|
||||
const login = isRecord(itemRaw.login) ? itemRaw.login : null;
|
||||
const folderId = csvText(itemRaw.folderId).trim();
|
||||
rows.push([
|
||||
folderNameById.get(folderId) || '',
|
||||
itemRaw.favorite ? '1' : '0',
|
||||
bitwardenCsvType(type),
|
||||
csvText(itemRaw.name) || '--',
|
||||
csvText(itemRaw.notes),
|
||||
buildBitwardenCsvFields(itemRaw, type),
|
||||
String(normalizeNumber(itemRaw.reprompt, 0)),
|
||||
isLogin ? buildBitwardenCsvLoginUri(login) : '',
|
||||
isLogin ? csvText(login?.username) : '',
|
||||
isLogin ? csvText(login?.password) : '',
|
||||
isLogin ? csvText(login?.totp) : '',
|
||||
]);
|
||||
}
|
||||
return `\uFEFF${buildCsvString(rows)}`;
|
||||
}
|
||||
|
||||
export async function buildAccountEncryptedBitwardenJsonString(args: BuildEncryptedJsonArgs): Promise<string> {
|
||||
const userEnc = base64ToBytes(args.userEncB64);
|
||||
const userMac = base64ToBytes(args.userMacB64);
|
||||
@@ -566,11 +692,13 @@ function nowStamp(now = new Date()): string {
|
||||
export function buildExportFileName(format: ExportFormatId, zipEncrypted = false): string {
|
||||
const stamp = nowStamp();
|
||||
if (
|
||||
format === 'bitwarden_csv' ||
|
||||
format === 'bitwarden_json' ||
|
||||
format === 'bitwarden_encrypted_json' ||
|
||||
format === 'nodewarden_json' ||
|
||||
format === 'nodewarden_encrypted_json'
|
||||
) {
|
||||
if (format === 'bitwarden_csv') return `bitwarden_export_${stamp}.csv`;
|
||||
if (format.startsWith('nodewarden_')) return `nodewarden_export_${stamp}.json`;
|
||||
return `bitwarden_export_${stamp}.json`;
|
||||
}
|
||||
|
||||
@@ -267,6 +267,9 @@ const en: Record<string, string> = {
|
||||
"txt_backup_webdav_password": "WebDAV Password",
|
||||
"txt_backup_webdav_path": "Remote Folder",
|
||||
"txt_backup_s3_endpoint": "S3 Endpoint",
|
||||
"txt_backup_s3_addressing_style": "S3 Addressing Style",
|
||||
"txt_backup_s3_addressing_path_style": "path-style (default)",
|
||||
"txt_backup_s3_addressing_virtual_hosted_style": "virtual-hosted-style",
|
||||
"txt_backup_s3_bucket": "Bucket",
|
||||
"txt_backup_s3_region": "Region",
|
||||
"txt_backup_s3_access_key": "Access Key",
|
||||
@@ -447,6 +450,11 @@ const en: Record<string, string> = {
|
||||
"txt_favorite": "Favorite",
|
||||
"txt_favorites": "Favorites",
|
||||
"txt_duplicates": "Duplicates",
|
||||
"txt_duplicate_detection_mode": "Match by",
|
||||
"txt_duplicate_mode_exact": "Exact item",
|
||||
"txt_duplicate_mode_login_site": "Site + username + password",
|
||||
"txt_duplicate_mode_login_credentials": "Username + password",
|
||||
"txt_duplicate_mode_password": "Reused password",
|
||||
"txt_field": "Field",
|
||||
"txt_field_label": "Field Label",
|
||||
"txt_field_label_is_required": "Field label is required.",
|
||||
@@ -750,6 +758,7 @@ const en: Record<string, string> = {
|
||||
"txt_search_sends": "Search sends...",
|
||||
"txt_session_refresh_failed": "Session refresh failed. Please sign in again.",
|
||||
"txt_search_your_secure_vault": "Search your secure vault...",
|
||||
"txt_search_items_count": "Search within {count} items...",
|
||||
"txt_clear_search": "Clear search",
|
||||
"txt_clear_search_esc": "Clear search (Esc)",
|
||||
"txt_sort": "Sort",
|
||||
@@ -1172,7 +1181,22 @@ const en: Record<string, string> = {
|
||||
"txt_target": "Target",
|
||||
"txt_time": "Time",
|
||||
"txt_time_range": "Time range",
|
||||
"txt_remove_domain": "Remove domain"
|
||||
"txt_remove_domain": "Remove domain",
|
||||
"txt_approve_device_login": "Approve device login",
|
||||
"txt_auth_request_approve_message": "Unlock Bitwarden on your device or approve from the web app. Before approving, make sure the fingerprint phrase matches the one below.",
|
||||
"txt_approve": "Approve",
|
||||
"txt_approving": "Approving...",
|
||||
"txt_deny": "Deny",
|
||||
"txt_later": "Later",
|
||||
"txt_pending_device_logins": "Pending device logins",
|
||||
"txt_no_pending_device_logins": "No pending device logins",
|
||||
"txt_fingerprint_phrase": "Fingerprint phrase",
|
||||
"txt_auth_requests_load_failed": "Failed to load device login requests",
|
||||
"txt_auth_request_update_failed": "Failed to update device login request",
|
||||
"txt_auth_request_approved": "Device login approved",
|
||||
"txt_auth_request_denied": "Device login denied",
|
||||
"txt_auth_request_missing_public_key": "Device login request is missing a public key",
|
||||
"txt_ip_address": "IP address"
|
||||
};
|
||||
|
||||
export default en;
|
||||
|
||||
@@ -267,6 +267,9 @@ const es: Record<string, string> = {
|
||||
"txt_backup_webdav_password": "Contraseña WebDAV",
|
||||
"txt_backup_webdav_path": "Carpeta remota",
|
||||
"txt_backup_s3_endpoint": "Endpoint S3",
|
||||
"txt_backup_s3_addressing_style": "Estilo de direccionamiento S3",
|
||||
"txt_backup_s3_addressing_path_style": "path-style (predeterminado)",
|
||||
"txt_backup_s3_addressing_virtual_hosted_style": "virtual-hosted-style",
|
||||
"txt_backup_s3_bucket": "Bucket S3",
|
||||
"txt_backup_s3_region": "Región",
|
||||
"txt_backup_s3_access_key": "Clave de acceso",
|
||||
@@ -447,6 +450,11 @@ const es: Record<string, string> = {
|
||||
"txt_favorite": "Favorito",
|
||||
"txt_favorites": "Favoritos",
|
||||
"txt_duplicates": "Duplicados",
|
||||
"txt_duplicate_detection_mode": "Coincidir por",
|
||||
"txt_duplicate_mode_exact": "Elemento exacto",
|
||||
"txt_duplicate_mode_login_site": "Sitio + usuario + contraseña",
|
||||
"txt_duplicate_mode_login_credentials": "Usuario + contraseña",
|
||||
"txt_duplicate_mode_password": "Contraseña reutilizada",
|
||||
"txt_field": "Campo",
|
||||
"txt_field_label": "Etiqueta del campo",
|
||||
"txt_field_label_is_required": "La etiqueta del campo es obligatoria.",
|
||||
@@ -750,6 +758,7 @@ const es: Record<string, string> = {
|
||||
"txt_search_sends": "Buscar envíos...",
|
||||
"txt_session_refresh_failed": "Error al actualizar la sesión. Inicia sesión de nuevo.",
|
||||
"txt_search_your_secure_vault": "Buscar en su bóveda segura...",
|
||||
"txt_search_items_count": "Buscar entre {count} elementos...",
|
||||
"txt_clear_search": "Limpiar búsqueda",
|
||||
"txt_clear_search_esc": "Limpiar búsqueda (Esc)",
|
||||
"txt_sort": "Ordenar",
|
||||
@@ -1172,7 +1181,22 @@ const es: Record<string, string> = {
|
||||
"txt_target": "Destino",
|
||||
"txt_time": "Hora",
|
||||
"txt_time_range": "Rango de tiempo",
|
||||
"txt_remove_domain": "Quitar dominio"
|
||||
"txt_remove_domain": "Quitar dominio",
|
||||
"txt_approve_device_login": "Aprobar inicio de sesión con dispositivo",
|
||||
"txt_auth_request_approve_message": "Desbloquee Bitwarden en su dispositivo o apruebe desde la aplicación web. Antes de aprobar, asegúrese de que la frase de huella coincida con la siguiente.",
|
||||
"txt_fingerprint_phrase": "Frase de huella",
|
||||
"txt_ip_address": "Dirección IP",
|
||||
"txt_approve": "Aprobar",
|
||||
"txt_approving": "Aprobando...",
|
||||
"txt_deny": "Denegar",
|
||||
"txt_later": "Más tarde",
|
||||
"txt_pending_device_logins": "Inicios de sesión con dispositivo pendientes",
|
||||
"txt_no_pending_device_logins": "No hay inicios de sesión con dispositivo pendientes",
|
||||
"txt_auth_requests_load_failed": "No se pudieron cargar las solicitudes de inicio de sesión con dispositivo",
|
||||
"txt_auth_request_update_failed": "No se pudo actualizar la solicitud de inicio de sesión con dispositivo",
|
||||
"txt_auth_request_approved": "Inicio de sesión con dispositivo aprobado",
|
||||
"txt_auth_request_denied": "Inicio de sesión con dispositivo denegado",
|
||||
"txt_auth_request_missing_public_key": "La solicitud de inicio de sesión con dispositivo no incluye una clave pública"
|
||||
};
|
||||
|
||||
export default es;
|
||||
|
||||
@@ -267,6 +267,9 @@ const ru: Record<string, string> = {
|
||||
"txt_backup_webdav_password": "Пароль WebDAV",
|
||||
"txt_backup_webdav_path": "Удаленная папка",
|
||||
"txt_backup_s3_endpoint": "S3 endpoint",
|
||||
"txt_backup_s3_addressing_style": "Стиль адресации S3",
|
||||
"txt_backup_s3_addressing_path_style": "path-style (по умолчанию)",
|
||||
"txt_backup_s3_addressing_virtual_hosted_style": "virtual-hosted-style",
|
||||
"txt_backup_s3_bucket": "Бакет",
|
||||
"txt_backup_s3_region": "Регион",
|
||||
"txt_backup_s3_access_key": "Ключ доступа",
|
||||
@@ -447,6 +450,11 @@ const ru: Record<string, string> = {
|
||||
"txt_favorite": "Любимый",
|
||||
"txt_favorites": "Избранное",
|
||||
"txt_duplicates": "Дубликаты",
|
||||
"txt_duplicate_detection_mode": "Сравнивать по",
|
||||
"txt_duplicate_mode_exact": "Полное совпадение",
|
||||
"txt_duplicate_mode_login_site": "Сайт + логин + пароль",
|
||||
"txt_duplicate_mode_login_credentials": "Логин + пароль",
|
||||
"txt_duplicate_mode_password": "Повтор пароля",
|
||||
"txt_field": "Поле",
|
||||
"txt_field_label": "Метка поля",
|
||||
"txt_field_label_is_required": "Метка поля обязательна.",
|
||||
@@ -750,6 +758,7 @@ const ru: Record<string, string> = {
|
||||
"txt_search_sends": "Поиск отправляет...",
|
||||
"txt_session_refresh_failed": "Не удалось обновить сеанс. Войдите снова.",
|
||||
"txt_search_your_secure_vault": "Найдите свое безопасное хранилище...",
|
||||
"txt_search_items_count": "Поиск по {count} элементам...",
|
||||
"txt_clear_search": "Очистить поиск",
|
||||
"txt_clear_search_esc": "Очистить поиск (Esc)",
|
||||
"txt_sort": "Сортировать",
|
||||
@@ -1172,7 +1181,22 @@ const ru: Record<string, string> = {
|
||||
"txt_target": "Цель",
|
||||
"txt_time": "Время",
|
||||
"txt_time_range": "Период",
|
||||
"txt_remove_domain": "Удалить домен"
|
||||
"txt_remove_domain": "Удалить домен",
|
||||
"txt_approve_device_login": "Подтвердить вход с устройства",
|
||||
"txt_auth_request_approve_message": "Разблокируйте Bitwarden на устройстве или подтвердите вход через веб-приложение. Перед подтверждением убедитесь, что фраза отпечатка совпадает с указанной ниже.",
|
||||
"txt_fingerprint_phrase": "Фраза отпечатка",
|
||||
"txt_ip_address": "IP-адрес",
|
||||
"txt_approve": "Подтвердить",
|
||||
"txt_approving": "Подтверждение...",
|
||||
"txt_deny": "Отклонить",
|
||||
"txt_later": "Позже",
|
||||
"txt_pending_device_logins": "Ожидающие входы с устройств",
|
||||
"txt_no_pending_device_logins": "Нет ожидающих входов с устройств",
|
||||
"txt_auth_requests_load_failed": "Не удалось загрузить запросы входа с устройств",
|
||||
"txt_auth_request_update_failed": "Не удалось обновить запрос входа с устройства",
|
||||
"txt_auth_request_approved": "Вход с устройства подтвержден",
|
||||
"txt_auth_request_denied": "Вход с устройства отклонен",
|
||||
"txt_auth_request_missing_public_key": "В запросе входа с устройства отсутствует открытый ключ"
|
||||
};
|
||||
|
||||
export default ru;
|
||||
|
||||
@@ -267,6 +267,9 @@ const zhCN: Record<string, string> = {
|
||||
"txt_backup_webdav_password": "WebDAV 密码",
|
||||
"txt_backup_webdav_path": "远程目录",
|
||||
"txt_backup_s3_endpoint": "S3 端点",
|
||||
"txt_backup_s3_addressing_style": "S3 寻址方式",
|
||||
"txt_backup_s3_addressing_path_style": "path-style(默认)",
|
||||
"txt_backup_s3_addressing_virtual_hosted_style": "virtual-hosted-style",
|
||||
"txt_backup_s3_bucket": "存储桶",
|
||||
"txt_backup_s3_region": "区域",
|
||||
"txt_backup_s3_access_key": "访问密钥",
|
||||
@@ -447,6 +450,11 @@ const zhCN: Record<string, string> = {
|
||||
"txt_favorite": "收藏",
|
||||
"txt_favorites": "收藏",
|
||||
"txt_duplicates": "重复项",
|
||||
"txt_duplicate_detection_mode": "匹配方式",
|
||||
"txt_duplicate_mode_exact": "完全相同",
|
||||
"txt_duplicate_mode_login_site": "网站+账号+密码",
|
||||
"txt_duplicate_mode_login_credentials": "账号+密码",
|
||||
"txt_duplicate_mode_password": "密码复用",
|
||||
"txt_field": "字段",
|
||||
"txt_field_label": "字段标签",
|
||||
"txt_field_label_is_required": "字段标签不能为空",
|
||||
@@ -750,6 +758,7 @@ const zhCN: Record<string, string> = {
|
||||
"txt_search_sends": "搜索 Send...",
|
||||
"txt_session_refresh_failed": "会话刷新失败,请重新登录",
|
||||
"txt_search_your_secure_vault": "搜索你的密码库...",
|
||||
"txt_search_items_count": "共 {count} 项中搜索...",
|
||||
"txt_clear_search": "清空搜索",
|
||||
"txt_clear_search_esc": "清空搜索(Esc)",
|
||||
"txt_sort": "排序",
|
||||
@@ -1172,7 +1181,22 @@ const zhCN: Record<string, string> = {
|
||||
"txt_target": "目标",
|
||||
"txt_time": "时间",
|
||||
"txt_time_range": "时间范围",
|
||||
"txt_remove_domain": "移除域名"
|
||||
"txt_remove_domain": "移除域名",
|
||||
"txt_approve_device_login": "批准设备登录",
|
||||
"txt_auth_request_approve_message": "解锁您设备上的 Bitwarden,或通过网页 App 批准。批准前,请确保指纹短语与下面的相匹配。",
|
||||
"txt_approve": "批准",
|
||||
"txt_approving": "正在批准...",
|
||||
"txt_deny": "拒绝",
|
||||
"txt_later": "稍后",
|
||||
"txt_pending_device_logins": "待处理设备登录",
|
||||
"txt_no_pending_device_logins": "没有待处理设备登录",
|
||||
"txt_fingerprint_phrase": "指纹短语",
|
||||
"txt_auth_requests_load_failed": "加载设备登录请求失败",
|
||||
"txt_auth_request_update_failed": "更新设备登录请求失败",
|
||||
"txt_auth_request_approved": "已批准设备登录",
|
||||
"txt_auth_request_denied": "已拒绝设备登录",
|
||||
"txt_auth_request_missing_public_key": "设备登录请求缺少公钥",
|
||||
"txt_ip_address": "IP 地址"
|
||||
};
|
||||
|
||||
export default zhCN;
|
||||
|
||||
@@ -267,6 +267,9 @@ const zhTW: Record<string, string> = {
|
||||
"txt_backup_webdav_password": "WebDAV 密碼",
|
||||
"txt_backup_webdav_path": "遠程目錄",
|
||||
"txt_backup_s3_endpoint": "S3 端點",
|
||||
"txt_backup_s3_addressing_style": "S3 定址方式",
|
||||
"txt_backup_s3_addressing_path_style": "path-style(預設)",
|
||||
"txt_backup_s3_addressing_virtual_hosted_style": "virtual-hosted-style",
|
||||
"txt_backup_s3_bucket": "儲存桶",
|
||||
"txt_backup_s3_region": "區域",
|
||||
"txt_backup_s3_access_key": "存取金鑰",
|
||||
@@ -447,6 +450,11 @@ const zhTW: Record<string, string> = {
|
||||
"txt_favorite": "收藏",
|
||||
"txt_favorites": "收藏",
|
||||
"txt_duplicates": "重複項",
|
||||
"txt_duplicate_detection_mode": "匹配方式",
|
||||
"txt_duplicate_mode_exact": "完全相同",
|
||||
"txt_duplicate_mode_login_site": "網站+帳號+密碼",
|
||||
"txt_duplicate_mode_login_credentials": "帳號+密碼",
|
||||
"txt_duplicate_mode_password": "密碼重複使用",
|
||||
"txt_field": "字段",
|
||||
"txt_field_label": "字段標籤",
|
||||
"txt_field_label_is_required": "字段標籤不能為空",
|
||||
@@ -750,6 +758,7 @@ const zhTW: Record<string, string> = {
|
||||
"txt_search_sends": "搜索 Send...",
|
||||
"txt_session_refresh_failed": "會話刷新失敗,請重新登入",
|
||||
"txt_search_your_secure_vault": "搜索你的密碼庫...",
|
||||
"txt_search_items_count": "在共 {count} 項中搜索...",
|
||||
"txt_clear_search": "清空搜索",
|
||||
"txt_clear_search_esc": "清空搜索(Esc)",
|
||||
"txt_sort": "排序",
|
||||
@@ -1172,7 +1181,22 @@ const zhTW: Record<string, string> = {
|
||||
"txt_target": "目標",
|
||||
"txt_time": "時間",
|
||||
"txt_time_range": "時間範圍",
|
||||
"txt_remove_domain": "移除域名"
|
||||
"txt_remove_domain": "移除域名",
|
||||
"txt_approve_device_login": "批准裝置登入",
|
||||
"txt_auth_request_approve_message": "解鎖您裝置上的 Bitwarden,或透過網頁 App 批准。批准前,請確保指紋短語與下面的相符。",
|
||||
"txt_fingerprint_phrase": "指紋短語",
|
||||
"txt_ip_address": "IP 位址",
|
||||
"txt_approve": "批准",
|
||||
"txt_approving": "正在批准...",
|
||||
"txt_deny": "拒絕",
|
||||
"txt_later": "稍後",
|
||||
"txt_pending_device_logins": "待處理裝置登入",
|
||||
"txt_no_pending_device_logins": "沒有待處理裝置登入",
|
||||
"txt_auth_requests_load_failed": "載入裝置登入請求失敗",
|
||||
"txt_auth_request_update_failed": "更新裝置登入請求失敗",
|
||||
"txt_auth_request_approved": "已批准裝置登入",
|
||||
"txt_auth_request_denied": "已拒絕裝置登入",
|
||||
"txt_auth_request_missing_public_key": "裝置登入請求缺少公鑰"
|
||||
};
|
||||
|
||||
export default zhTW;
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
export type NetworkStatus = 'online' | 'offline';
|
||||
|
||||
const STATUS_PROBE_TIMEOUT_MS = 3500;
|
||||
const STATUS_PROBE_TIMEOUT_MS = 8000;
|
||||
const STATUS_PROBE_CACHE_MS = 5000;
|
||||
const PROBE_FAILURES_BEFORE_OFFLINE = 2;
|
||||
const listeners = new Set<(status: NetworkStatus) => void>();
|
||||
let currentStatus: NetworkStatus = getInitialNetworkStatus();
|
||||
let pendingProbe: Promise<boolean> | null = null;
|
||||
let lastProbeAt = 0;
|
||||
let lastProbeResult = currentStatus === 'online';
|
||||
let consecutiveProbeFailures = 0;
|
||||
|
||||
export function browserReportsOffline(): boolean {
|
||||
return typeof navigator !== 'undefined' && navigator.onLine === false;
|
||||
@@ -35,8 +37,23 @@ export function subscribeNetworkStatus(listener: (status: NetworkStatus) => void
|
||||
};
|
||||
}
|
||||
|
||||
export function recordNodeWardenReachable(): void {
|
||||
consecutiveProbeFailures = 0;
|
||||
lastProbeResult = true;
|
||||
setCurrentNetworkStatus('online');
|
||||
}
|
||||
|
||||
export function recordNodeWardenUnreachable(): void {
|
||||
lastProbeResult = false;
|
||||
consecutiveProbeFailures += 1;
|
||||
if (browserReportsOffline() || consecutiveProbeFailures >= PROBE_FAILURES_BEFORE_OFFLINE) {
|
||||
setCurrentNetworkStatus('offline');
|
||||
}
|
||||
}
|
||||
|
||||
export async function probeNodeWardenService(): Promise<boolean> {
|
||||
if (browserReportsOffline()) {
|
||||
consecutiveProbeFailures = PROBE_FAILURES_BEFORE_OFFLINE;
|
||||
setCurrentNetworkStatus('offline');
|
||||
return false;
|
||||
}
|
||||
@@ -68,8 +85,11 @@ export async function probeNodeWardenService(): Promise<boolean> {
|
||||
.catch(() => false)
|
||||
.then((result) => {
|
||||
lastProbeAt = Date.now();
|
||||
lastProbeResult = result;
|
||||
setCurrentNetworkStatus(result ? 'online' : 'offline');
|
||||
if (result) {
|
||||
recordNodeWardenReachable();
|
||||
} else {
|
||||
recordNodeWardenUnreachable();
|
||||
}
|
||||
return result;
|
||||
})
|
||||
.finally(() => {
|
||||
|
||||
@@ -338,6 +338,23 @@ export interface AccountPasskeyCredential {
|
||||
revisionDate?: string;
|
||||
}
|
||||
|
||||
export interface AuthRequest {
|
||||
id: string;
|
||||
publicKey: string;
|
||||
requestDeviceType?: string | null;
|
||||
requestDeviceTypeValue?: number | null;
|
||||
requestDeviceIdentifier: string;
|
||||
requestIpAddress?: string | null;
|
||||
requestCountryName?: string | null;
|
||||
key?: string | null;
|
||||
creationDate: string;
|
||||
requestApproved?: boolean | null;
|
||||
responseDate?: string | null;
|
||||
deviceId?: string | null;
|
||||
requestDeviceId?: string | null;
|
||||
fingerprintPhrase?: string;
|
||||
}
|
||||
|
||||
export interface AccountPasskeyAssertionOptionsResponse {
|
||||
options: PublicKeyCredentialRequestOptions;
|
||||
token: string;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { Send } from './types';
|
||||
import { getCurrentNetworkStatus } from './network-status';
|
||||
import type { DecryptSendsArgs, DecryptVaultCoreArgs, DecryptVaultCoreResult } from './vault-decrypt';
|
||||
|
||||
type WorkerSuccess<T> = { id: number; ok: true; result: T };
|
||||
@@ -13,7 +12,6 @@ const pending = new Map<number, { resolve: (value: any) => void; reject: (error:
|
||||
function getWorker(): Worker | null {
|
||||
if (typeof Worker === 'undefined') return null;
|
||||
if (worker) return worker;
|
||||
if (getCurrentNetworkStatus() === 'offline') return null;
|
||||
worker = new Worker(new URL('../workers/vault-decrypt.worker.ts', import.meta.url), { type: 'module' });
|
||||
worker.addEventListener('message', (event: MessageEvent<WorkerResponse<unknown>>) => {
|
||||
const message = event.data;
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
@import './styles/management.css';
|
||||
@import './styles/overlays.css';
|
||||
@import './styles/motion.css';
|
||||
@import './styles/skeleton.css';
|
||||
@import './styles/responsive.css';
|
||||
@import './styles/dark.css';
|
||||
|
||||
@@ -595,7 +596,7 @@ h4 {
|
||||
}
|
||||
|
||||
.list-head {
|
||||
margin-bottom: 8px;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.list-count {
|
||||
@@ -809,6 +810,101 @@ h4 {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
/* Typography refinement: stronger scan targets for dense vault/admin surfaces. */
|
||||
body {
|
||||
font-family: var(--font-sans);
|
||||
font-size: var(--font-base);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
button,
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.side-link,
|
||||
.side-group-trigger,
|
||||
.side-sub-link,
|
||||
.tree-btn,
|
||||
.mobile-settings-link,
|
||||
.backup-destination-item,
|
||||
.backup-browser-entry,
|
||||
.sort-menu-item,
|
||||
.create-menu-item,
|
||||
.nav-layout-option {
|
||||
font-size: var(--font-sm);
|
||||
font-weight: 600;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.side-link.active,
|
||||
.side-group-trigger.active,
|
||||
.side-sub-link.active,
|
||||
.tree-btn.active,
|
||||
.mobile-tab.active,
|
||||
.mobile-settings-link.active,
|
||||
.nav-layout-option.active {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.sidebar-title,
|
||||
.list-count,
|
||||
.field > span,
|
||||
.table th,
|
||||
.dialog-warning-kicker,
|
||||
.backup-recommendation-group-title {
|
||||
font-weight: 700;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.list-title {
|
||||
color: var(--text);
|
||||
font-size: var(--font-base);
|
||||
font-weight: 600;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.list-sub,
|
||||
.detail-sub,
|
||||
.backup-destination-meta,
|
||||
.totp-code-username,
|
||||
.field-help,
|
||||
.settings-field-note {
|
||||
font-size: var(--font-sm);
|
||||
line-height: var(--leading-snug);
|
||||
}
|
||||
|
||||
.btn,
|
||||
.input,
|
||||
.search-input,
|
||||
.user-chip,
|
||||
.network-status-badge {
|
||||
font-weight: 600;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.btn-primary,
|
||||
.btn-danger,
|
||||
.btn.full,
|
||||
.topbar-actions .btn,
|
||||
.network-status-badge {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.card h4,
|
||||
.settings-module h3,
|
||||
.section-head h3,
|
||||
.section-head h4,
|
||||
.detail-title,
|
||||
.totp-code-name,
|
||||
.backup-destination-name,
|
||||
.mobile-sidebar-title {
|
||||
font-weight: 700;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.toast-item,
|
||||
.dialog-card {
|
||||
border-radius: var(--radius-lg);
|
||||
@@ -973,6 +1069,7 @@ h4 {
|
||||
.list-panel {
|
||||
padding: 6px;
|
||||
border-radius: var(--radius-md);
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.list-item {
|
||||
|
||||
@@ -8,7 +8,15 @@ body,
|
||||
@apply m-0 h-full w-full p-0;
|
||||
color: var(--text);
|
||||
background: var(--bg-accent);
|
||||
font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', 'Noto Sans SC', sans-serif;
|
||||
font-family: var(--font-sans);
|
||||
font-size: var(--font-base);
|
||||
line-height: var(--leading-normal);
|
||||
letter-spacing: var(--tracking-normal);
|
||||
font-feature-settings: 'liga' 1, 'kern' 1, 'calt' 1;
|
||||
font-variant-numeric: tabular-nums;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
html {
|
||||
@@ -16,7 +24,7 @@ html {
|
||||
}
|
||||
|
||||
body {
|
||||
@apply relative antialiased;
|
||||
@apply relative;
|
||||
transition: background-color var(--dur-medium) var(--ease-smooth), color var(--dur-medium) var(--ease-smooth);
|
||||
}
|
||||
|
||||
@@ -25,6 +33,28 @@ body.dialog-open {
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
h1, h2, h3, h4, h5, h6 {
|
||||
font-weight: 700;
|
||||
letter-spacing: 0;
|
||||
line-height: var(--leading-tight);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
h1 { font-size: var(--font-4xl); }
|
||||
h2 { font-size: var(--font-3xl); }
|
||||
h3 { font-size: var(--font-xl); }
|
||||
h4 { font-size: var(--font-lg); }
|
||||
|
||||
p {
|
||||
margin: 0;
|
||||
line-height: var(--leading-relaxed);
|
||||
}
|
||||
|
||||
small {
|
||||
font-size: var(--font-sm);
|
||||
line-height: var(--leading-snug);
|
||||
}
|
||||
|
||||
::selection {
|
||||
background: color-mix(in srgb, var(--primary) 20%, transparent);
|
||||
color: var(--text);
|
||||
|
||||
@@ -70,6 +70,7 @@
|
||||
:root[data-theme='dark'] .textarea,
|
||||
:root[data-theme='dark'] select.input,
|
||||
:root[data-theme='dark'] .search-input,
|
||||
:root[data-theme='dark'] .mobile-vault-filter-trigger,
|
||||
:root[data-theme='dark'] .dialog input,
|
||||
:root[data-theme='dark'] .dialog textarea,
|
||||
:root[data-theme='dark'] .dialog select {
|
||||
@@ -79,6 +80,13 @@
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
:root[data-theme='dark'] .mobile-vault-filter-trigger:hover,
|
||||
:root[data-theme='dark'] .mobile-vault-filter-trigger.active {
|
||||
background: var(--panel-muted);
|
||||
border-color: color-mix(in srgb, var(--primary) 42%, var(--line));
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
:root[data-theme='dark'] .input::placeholder,
|
||||
:root[data-theme='dark'] .textarea::placeholder,
|
||||
:root[data-theme='dark'] input::placeholder,
|
||||
@@ -200,6 +208,21 @@
|
||||
box-shadow: 0 10px 28px rgba(0, 0, 0, 0.24), 0 0 0 1px rgba(139, 184, 255, 0.12);
|
||||
}
|
||||
|
||||
:root[data-theme='dark'] .list-item.duplicate-group-item {
|
||||
background: hsl(var(--duplicate-group-hue) 34% 18%);
|
||||
border-color: hsl(var(--duplicate-group-hue) 28% 30%);
|
||||
}
|
||||
|
||||
:root[data-theme='dark'] .list-item.duplicate-group-item:hover {
|
||||
background: hsl(var(--duplicate-group-hue) 36% 21%);
|
||||
border-color: hsl(var(--duplicate-group-hue) 34% 38%);
|
||||
}
|
||||
|
||||
:root[data-theme='dark'] .list-item.duplicate-group-item.active {
|
||||
background: hsl(var(--duplicate-group-hue) 38% 24%);
|
||||
border-color: hsl(var(--duplicate-group-hue) 42% 48%);
|
||||
}
|
||||
|
||||
:root[data-theme='dark'] .card-brand-icon {
|
||||
color: #bfdbfe;
|
||||
background: linear-gradient(180deg, #1f2937 0%, #111827 100%);
|
||||
|
||||
@@ -1,36 +1,42 @@
|
||||
.muted {
|
||||
@apply m-0 mb-4 text-center leading-relaxed text-muted;
|
||||
@apply m-0 mb-4 text-center text-muted;
|
||||
font-size: var(--font-sm);
|
||||
line-height: var(--leading-relaxed);
|
||||
letter-spacing: var(--tracking-normal);
|
||||
}
|
||||
|
||||
.field {
|
||||
@apply mb-3.5 block;
|
||||
@apply mb-4 block;
|
||||
}
|
||||
|
||||
.field > span {
|
||||
@apply mb-2 mt-2.5 block text-sm font-semibold;
|
||||
@apply mb-2 block;
|
||||
font-size: var(--font-sm);
|
||||
font-weight: 600;
|
||||
letter-spacing: var(--tracking-wide);
|
||||
color: var(--muted-strong);
|
||||
line-height: var(--leading-snug);
|
||||
}
|
||||
|
||||
.input {
|
||||
@apply h-12 w-full rounded-xl border px-3.5 py-2.5 text-base leading-normal text-ink outline-none transition;
|
||||
@apply h-12 w-full rounded-xl border px-3.5 py-2.5 outline-none;
|
||||
background: var(--panel);
|
||||
border-color: rgba(74, 103, 150, 0.34);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.82);
|
||||
transition: all var(--dur-fast) var(--ease-smooth);
|
||||
font-size: var(--font-base);
|
||||
line-height: var(--leading-snug);
|
||||
letter-spacing: var(--tracking-normal);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
select.input {
|
||||
@apply py-0 pr-[42px];
|
||||
@apply py-0 pr-3.5;
|
||||
line-height: 1.5;
|
||||
appearance: none;
|
||||
-webkit-appearance: none;
|
||||
-moz-appearance: none;
|
||||
background-image:
|
||||
linear-gradient(45deg, transparent 50%, #365fa8 50%),
|
||||
linear-gradient(135deg, #365fa8 50%, transparent 50%);
|
||||
background-position:
|
||||
calc(100% - 18px) calc(50% - 3px),
|
||||
calc(100% - 12px) calc(50% - 3px);
|
||||
background-size: 6px 6px, 6px 6px;
|
||||
background-repeat: no-repeat;
|
||||
appearance: auto;
|
||||
-webkit-appearance: auto;
|
||||
-moz-appearance: auto;
|
||||
background-image: none;
|
||||
}
|
||||
|
||||
input[type='file'].input {
|
||||
@@ -54,9 +60,10 @@ input[type='file'].input::file-selector-button:hover {
|
||||
}
|
||||
|
||||
.input:focus {
|
||||
border-color: rgba(43, 102, 217, 0.6);
|
||||
border-color: var(--primary);
|
||||
background-color: #fbfdff;
|
||||
box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.10), 0 8px 18px rgba(37, 99, 235, 0.06), inset 0 1px 0 rgba(255, 255, 255, 0.95);
|
||||
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.12), 0 8px 20px rgba(37, 99, 235, 0.08), inset 0 1px 0 rgba(255, 255, 255, 0.95);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.input-readonly {
|
||||
@@ -115,7 +122,12 @@ input[type='file'].input::file-selector-button:hover {
|
||||
}
|
||||
|
||||
.btn {
|
||||
@apply inline-flex h-9 cursor-pointer items-center justify-center gap-1.5 rounded-full border border-transparent px-4 text-[15px] font-bold no-underline transition;
|
||||
@apply inline-flex h-9 cursor-pointer items-center justify-center gap-1.5 rounded-full border border-transparent px-4 no-underline;
|
||||
font-size: var(--font-sm);
|
||||
font-weight: 600;
|
||||
letter-spacing: var(--tracking-wide);
|
||||
line-height: 1;
|
||||
transition: all var(--dur-fast) var(--ease-smooth);
|
||||
}
|
||||
|
||||
.topbar-actions .btn,
|
||||
@@ -161,28 +173,53 @@ input[type='file'].input::file-selector-button:hover {
|
||||
}
|
||||
|
||||
.btn.full {
|
||||
@apply my-2.5 h-12 w-full text-lg;
|
||||
@apply my-2.5 h-12 w-full;
|
||||
font-size: var(--font-md);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
@apply border-blue-700/30 bg-blue-600 text-white;
|
||||
box-shadow: 0 10px 22px rgba(37, 99, 235, 0.20);
|
||||
@apply text-white;
|
||||
background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
|
||||
border: 1px solid rgba(37, 99, 235, 0.4);
|
||||
box-shadow: 0 4px 14px rgba(37, 99, 235, 0.25), inset 0 1px 0 rgba(255, 255, 255, 0.2);
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.btn-primary::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: linear-gradient(135deg, rgba(255, 255, 255, 0.2) 0%, transparent 50%);
|
||||
opacity: 0;
|
||||
transition: opacity var(--dur-fast) var(--ease-smooth);
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
@apply bg-blue-700;
|
||||
box-shadow: 0 12px 26px rgba(37, 99, 235, 0.22);
|
||||
background: linear-gradient(135deg, #1d4ed8 0%, #1e3a8a 100%);
|
||||
box-shadow: 0 6px 20px rgba(37, 99, 235, 0.35), inset 0 1px 0 rgba(255, 255, 255, 0.25);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.btn-primary:hover::before {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.btn-primary:active:not(:disabled) {
|
||||
transform: translateY(0) scale(0.98);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
@apply bg-panel text-brand-strong;
|
||||
border-color: rgba(37, 99, 235, 0.20);
|
||||
box-shadow: 0 6px 14px rgba(13, 31, 68, 0.04);
|
||||
border: 1px solid rgba(37, 99, 235, 0.22);
|
||||
box-shadow: 0 2px 8px rgba(15, 23, 42, 0.06), inset 0 1px 0 rgba(255, 255, 255, 0.8);
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: #f4f8ff;
|
||||
border-color: rgba(37, 99, 235, 0.34);
|
||||
background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
|
||||
border-color: rgba(37, 99, 235, 0.40);
|
||||
box-shadow: 0 4px 12px rgba(37, 99, 235, 0.15), inset 0 1px 0 rgba(255, 255, 255, 1);
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
@@ -200,11 +237,21 @@ input[type='file'].input::file-selector-button:hover {
|
||||
}
|
||||
|
||||
.or {
|
||||
@apply text-center text-slate-700;
|
||||
@apply text-center;
|
||||
font-size: var(--font-sm);
|
||||
color: var(--muted);
|
||||
line-height: var(--leading-snug);
|
||||
letter-spacing: var(--tracking-wide);
|
||||
text-transform: uppercase;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.field-help {
|
||||
@apply mt-2 text-[13px] leading-normal text-slate-500;
|
||||
@apply mt-2;
|
||||
font-size: var(--font-xs);
|
||||
line-height: var(--leading-relaxed);
|
||||
letter-spacing: var(--tracking-normal);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.check-line-compact {
|
||||
@@ -216,14 +263,21 @@ input[type='file'].input::file-selector-button:hover {
|
||||
}
|
||||
|
||||
.auth-link-btn {
|
||||
@apply cursor-pointer border-0 bg-transparent p-0 text-[13px] font-bold text-blue-700 transition;
|
||||
@apply cursor-pointer border-0 bg-transparent p-0 transition;
|
||||
font-size: var(--font-xs);
|
||||
font-weight: 600;
|
||||
letter-spacing: var(--tracking-wide);
|
||||
color: var(--primary-strong);
|
||||
line-height: var(--leading-snug);
|
||||
}
|
||||
|
||||
.auth-link-btn:hover {
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
transform: translateX(2px);
|
||||
}
|
||||
|
||||
.auth-link-btn:disabled {
|
||||
@apply cursor-not-allowed text-slate-400 no-underline;
|
||||
@apply cursor-not-allowed no-underline;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
@@ -64,6 +64,26 @@
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
@keyframes shimmer {
|
||||
0% { background-position: -200% center; }
|
||||
100% { background-position: 200% center; }
|
||||
}
|
||||
|
||||
@keyframes pulse-glow {
|
||||
0%, 100% { box-shadow: 0 0 20px rgba(37, 99, 235, 0.3); }
|
||||
50% { box-shadow: 0 0 30px rgba(37, 99, 235, 0.5), 0 0 40px rgba(37, 99, 235, 0.2); }
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
@keyframes skeleton-pulse {
|
||||
0%, 100% { opacity: 1; }
|
||||
50% { opacity: 0.5; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*,
|
||||
*::before,
|
||||
|
||||
@@ -209,14 +209,29 @@
|
||||
}
|
||||
|
||||
.toast-close {
|
||||
@apply cursor-pointer border-0 bg-transparent text-xl;
|
||||
@apply flex cursor-pointer items-center justify-center border-0;
|
||||
flex-shrink: 0;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
transition: transform var(--dur-fast) var(--ease-out-soft), opacity var(--dur-fast) var(--ease-smooth);
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
transition: background 120ms ease, opacity 120ms ease;
|
||||
}
|
||||
|
||||
.toast-close:hover {
|
||||
transform: scale(1.08);
|
||||
opacity: 0.84;
|
||||
background: rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
.toast-close:active {
|
||||
background: rgba(0, 0, 0, 0.14);
|
||||
}
|
||||
|
||||
.toast-close:focus-visible {
|
||||
outline: 2px solid currentColor;
|
||||
outline-offset: -2px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.toast-progress {
|
||||
|
||||
@@ -133,7 +133,10 @@
|
||||
}
|
||||
|
||||
.topbar-actions > .network-status-badge {
|
||||
@apply h-8 px-2 text-[0];
|
||||
@apply inline-flex h-9 w-9 min-w-9 justify-center gap-0 rounded-xl p-0 text-[0];
|
||||
background: color-mix(in srgb, var(--panel) 88%, transparent);
|
||||
border-color: var(--line);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.topbar-actions > .network-status-badge svg {
|
||||
@@ -142,7 +145,10 @@
|
||||
|
||||
.mobile-sidebar-toggle,
|
||||
.mobile-lock-btn {
|
||||
@apply inline-flex h-9 w-9 min-w-9 justify-center gap-0 p-0 text-[0];
|
||||
@apply inline-flex h-9 w-9 min-w-9 justify-center gap-0 rounded-xl p-0 text-[0];
|
||||
background: color-mix(in srgb, var(--panel) 88%, transparent);
|
||||
border-color: var(--line);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.mobile-sidebar-toggle .btn-icon,
|
||||
@@ -155,10 +161,46 @@
|
||||
}
|
||||
|
||||
.mobile-theme-btn .theme-switch {
|
||||
transform: scale(0.8);
|
||||
@apply h-9 w-9 rounded-xl border;
|
||||
background: color-mix(in srgb, var(--panel) 88%, transparent);
|
||||
border-color: var(--line);
|
||||
box-shadow: none;
|
||||
transform: none;
|
||||
transform-origin: center;
|
||||
}
|
||||
|
||||
.mobile-theme-btn .theme-switch-slider,
|
||||
.mobile-theme-btn .theme-switch-slider::before {
|
||||
@apply hidden;
|
||||
}
|
||||
|
||||
.mobile-theme-btn .theme-switch .sun svg,
|
||||
.mobile-theme-btn .theme-switch .moon svg {
|
||||
@apply h-[18px] w-[18px];
|
||||
top: 7px;
|
||||
left: 8px;
|
||||
z-index: 1;
|
||||
opacity: 0;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.mobile-theme-btn .theme-switch.unchecked .sun svg,
|
||||
.mobile-theme-btn .theme-switch.checked .moon svg {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.mobile-theme-btn .theme-switch.checked .moon svg {
|
||||
fill: var(--primary);
|
||||
}
|
||||
|
||||
.topbar-actions > .network-status-badge:hover,
|
||||
.mobile-sidebar-toggle:hover,
|
||||
.mobile-lock-btn:hover,
|
||||
.mobile-theme-btn .theme-switch:hover {
|
||||
background: var(--panel-subtle);
|
||||
border-color: color-mix(in srgb, var(--primary) 28%, var(--line));
|
||||
}
|
||||
|
||||
.app-main {
|
||||
@apply flex min-h-0 flex-col;
|
||||
}
|
||||
@@ -302,10 +344,15 @@
|
||||
}
|
||||
|
||||
.list-head {
|
||||
@apply grid items-center gap-2;
|
||||
@apply grid items-center gap-1.5;
|
||||
grid-template-columns: minmax(0, 1fr) auto auto auto;
|
||||
}
|
||||
|
||||
.list-head.selection-mode {
|
||||
@apply justify-stretch;
|
||||
grid-template-columns: repeat(5, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.list-count {
|
||||
grid-column: auto;
|
||||
@apply w-auto whitespace-nowrap text-xs;
|
||||
@@ -316,11 +363,50 @@
|
||||
}
|
||||
|
||||
.list-head .search-input {
|
||||
@apply h-[42px] w-full min-w-0 rounded-[14px];
|
||||
@apply h-[34px] w-full min-w-0 rounded-[10px] px-3 py-0 text-[13px] font-semibold;
|
||||
line-height: 34px;
|
||||
}
|
||||
|
||||
.mobile-vault-filter-row {
|
||||
@apply grid min-w-0 gap-1.5;
|
||||
grid-column: 1 / -1;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.list-head .duplicate-mode-head-select {
|
||||
@apply h-[34px] min-w-0 w-auto max-w-full rounded-[10px];
|
||||
}
|
||||
|
||||
.list-icon-btn {
|
||||
@apply w-auto min-w-0 gap-1.5 whitespace-nowrap px-3 py-0 text-[13px];
|
||||
@apply h-[34px] w-auto min-w-0 gap-1.5 whitespace-nowrap rounded-[10px] px-3 py-0 text-[13px];
|
||||
}
|
||||
|
||||
.list-head.selection-mode > .btn.small {
|
||||
@apply h-[34px] min-w-0 w-full justify-center gap-1 px-2 text-[12px];
|
||||
}
|
||||
|
||||
.list-head.selection-mode > .btn.small .btn-icon {
|
||||
@apply m-0;
|
||||
}
|
||||
|
||||
.sort-trigger {
|
||||
@apply h-[34px] w-[34px] min-w-[34px] rounded-[10px];
|
||||
}
|
||||
|
||||
.sort-trigger.sort-trigger-labeled {
|
||||
@apply h-[34px] w-auto min-w-0 gap-1.5 px-3 text-[13px];
|
||||
}
|
||||
|
||||
.sort-trigger.sort-trigger-labeled .btn-icon {
|
||||
@apply mr-0;
|
||||
}
|
||||
|
||||
.desktop-create-menu-wrap {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.duplicate-mode-head-menu .mobile-vault-filter-menu {
|
||||
min-width: max(100%, 190px);
|
||||
}
|
||||
|
||||
.toolbar.actions {
|
||||
@@ -329,6 +415,11 @@
|
||||
gap: var(--actions-gap);
|
||||
}
|
||||
|
||||
.toolbar.actions.duplicates-toolbar {
|
||||
@apply justify-start;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.actions {
|
||||
gap: var(--actions-gap);
|
||||
}
|
||||
@@ -337,6 +428,10 @@
|
||||
@apply h-[34px] w-auto min-w-0 gap-1.5 whitespace-nowrap rounded-full px-3 py-0 text-[13px];
|
||||
}
|
||||
|
||||
.list-count-status {
|
||||
@apply mb-1 px-1;
|
||||
}
|
||||
|
||||
.mobile-fab-wrap {
|
||||
@apply fixed right-3.5 z-[45];
|
||||
bottom: calc(14px + var(--mobile-tabbar-height, 70px) + env(safe-area-inset-bottom));
|
||||
@@ -883,6 +978,10 @@
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.totp-code-main strong {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.settings-module .field,
|
||||
.auth-card .field {
|
||||
margin-bottom: 8px;
|
||||
|
||||
@@ -3,10 +3,15 @@
|
||||
}
|
||||
|
||||
.app-shell {
|
||||
@apply relative mx-auto flex max-w-[1600px] flex-col overflow-hidden border bg-panel-soft shadow-elevated;
|
||||
@apply relative mx-auto flex max-w-[1600px] flex-col overflow-hidden border bg-panel-soft;
|
||||
height: calc(100vh - 40px);
|
||||
border-color: var(--line);
|
||||
@apply rounded-3xl;
|
||||
box-shadow:
|
||||
0 20px 60px rgba(15, 23, 42, 0.12),
|
||||
0 8px 24px rgba(15, 23, 42, 0.08),
|
||||
0 0 0 1px rgba(15, 23, 42, 0.04);
|
||||
transition: box-shadow var(--dur-medium) var(--ease-smooth);
|
||||
}
|
||||
|
||||
.topbar {
|
||||
@@ -104,7 +109,7 @@
|
||||
}
|
||||
|
||||
.theme-switch-slider::before {
|
||||
@apply absolute h-[26px] w-[26px] rounded-full;
|
||||
@apply absolute h-[23px] w-[26px] rounded-full;
|
||||
content: '';
|
||||
left: 2px;
|
||||
bottom: 2px;
|
||||
@@ -119,8 +124,8 @@
|
||||
|
||||
.theme-switch .sun svg {
|
||||
@apply absolute h-[18px] w-[18px];
|
||||
top: 6px;
|
||||
left: 32px;
|
||||
top: 5px;
|
||||
left: 29px;
|
||||
z-index: 1;
|
||||
opacity: 0.95;
|
||||
transition: transform var(--dur-medium) var(--ease-out-soft), opacity var(--dur-fast) var(--ease-smooth);
|
||||
@@ -193,7 +198,13 @@
|
||||
}
|
||||
|
||||
.side-link {
|
||||
@apply flex items-center gap-2.5 rounded-xl border border-transparent px-3 py-2.5 text-sm font-semibold text-muted-strong no-underline transition;
|
||||
@apply flex items-center rounded-xl border border-transparent px-3 py-2.5 no-underline transition;
|
||||
gap: var(--space-2);
|
||||
font-size: var(--font-sm);
|
||||
font-weight: 500;
|
||||
line-height: var(--leading-snug);
|
||||
letter-spacing: var(--tracking-normal);
|
||||
color: var(--muted-strong);
|
||||
}
|
||||
|
||||
.side-link span,
|
||||
@@ -213,24 +224,33 @@
|
||||
}
|
||||
|
||||
.side-group-trigger {
|
||||
@apply flex w-full cursor-pointer items-center gap-2.5 rounded-xl border border-transparent px-3 py-2.5 text-left text-sm font-semibold text-muted-strong transition;
|
||||
@apply flex w-full cursor-pointer items-center rounded-xl border border-transparent px-3 py-2.5 text-left transition;
|
||||
gap: var(--space-2);
|
||||
background: transparent;
|
||||
font-size: var(--font-sm);
|
||||
font-weight: 500;
|
||||
line-height: var(--leading-snug);
|
||||
letter-spacing: var(--tracking-normal);
|
||||
color: var(--muted-strong);
|
||||
}
|
||||
|
||||
.side-link:hover,
|
||||
.side-group-trigger:hover {
|
||||
background: #fff;
|
||||
border-color: rgba(128, 152, 192, 0.18);
|
||||
background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
|
||||
border-color: rgba(128, 152, 192, 0.20);
|
||||
color: var(--text);
|
||||
box-shadow: 0 10px 18px rgba(15, 23, 42, 0.04);
|
||||
box-shadow: 0 2px 8px rgba(15, 23, 42, 0.06), inset 0 1px 0 rgba(255, 255, 255, 1);
|
||||
transform: translateX(2px);
|
||||
}
|
||||
|
||||
.side-link.active,
|
||||
.side-group-trigger.active {
|
||||
background: rgba(37, 99, 235, 0.11);
|
||||
border-color: rgba(37, 99, 235, 0.28);
|
||||
background: linear-gradient(135deg, rgba(37, 99, 235, 0.12) 0%, rgba(37, 99, 235, 0.08) 100%);
|
||||
border-color: rgba(37, 99, 235, 0.32);
|
||||
color: var(--primary-strong);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.58);
|
||||
box-shadow:
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.5),
|
||||
0 2px 8px rgba(37, 99, 235, 0.15);
|
||||
}
|
||||
|
||||
.side-group-chevron {
|
||||
@@ -264,7 +284,13 @@
|
||||
}
|
||||
|
||||
.side-sub-link {
|
||||
@apply flex items-center gap-2 rounded-lg border border-transparent px-2.5 py-2 text-sm font-semibold text-muted no-underline transition;
|
||||
@apply flex items-center rounded-lg border border-transparent px-2.5 py-2 no-underline transition;
|
||||
gap: var(--space-2);
|
||||
font-size: var(--font-sm);
|
||||
font-weight: 500;
|
||||
line-height: var(--leading-snug);
|
||||
letter-spacing: var(--tracking-normal);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.side-sub-link:hover {
|
||||
@@ -363,3 +389,83 @@
|
||||
.mobile-sidebar-head {
|
||||
@apply hidden;
|
||||
}
|
||||
|
||||
.auth-request-details {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
margin: 12px 0 4px;
|
||||
}
|
||||
|
||||
.auth-request-device {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
border: 1px solid var(--line-soft);
|
||||
border-radius: 8px;
|
||||
padding: 10px;
|
||||
background: color-mix(in srgb, var(--primary) 7%, var(--panel));
|
||||
}
|
||||
|
||||
.auth-request-device svg {
|
||||
color: var(--primary-strong);
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.auth-request-device div,
|
||||
.account-passkey-main {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.auth-request-device strong,
|
||||
.auth-request-device small {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.auth-request-device small {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.auth-request-kv {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
font-size: var(--font-sm);
|
||||
}
|
||||
|
||||
.auth-request-kv span,
|
||||
.auth-request-fingerprint span {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.auth-request-kv strong {
|
||||
color: var(--text);
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.auth-request-fingerprint {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
border: 1px solid var(--line-soft);
|
||||
border-radius: 8px;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.auth-request-fingerprint strong,
|
||||
.auth-request-fingerprint-inline {
|
||||
overflow-wrap: anywhere;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
|
||||
font-size: var(--font-sm);
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.auth-request-row {
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.auth-request-fingerprint-inline {
|
||||
color: var(--muted-strong);
|
||||
max-width: 260px;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
.skeleton-card,
|
||||
.skeleton-list-item {
|
||||
@apply flex items-center gap-3 rounded-xl border p-4;
|
||||
background: var(--panel);
|
||||
border-color: var(--line-soft);
|
||||
animation: skeleton-pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
|
||||
}
|
||||
|
||||
.skeleton-avatar {
|
||||
@apply h-12 w-12 shrink-0 rounded-full;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
var(--panel-muted) 0%,
|
||||
var(--panel-soft) 50%,
|
||||
var(--panel-muted) 100%
|
||||
);
|
||||
background-size: 200% 100%;
|
||||
animation: shimmer 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.skeleton-icon {
|
||||
@apply h-10 w-10 shrink-0 rounded-lg;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
var(--panel-muted) 0%,
|
||||
var(--panel-soft) 50%,
|
||||
var(--panel-muted) 100%
|
||||
);
|
||||
background-size: 200% 100%;
|
||||
animation: shimmer 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.skeleton-content {
|
||||
@apply min-w-0 flex-1 space-y-2;
|
||||
}
|
||||
|
||||
.skeleton-line {
|
||||
@apply h-3 rounded-full;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
var(--panel-muted) 0%,
|
||||
var(--panel-soft) 50%,
|
||||
var(--panel-muted) 100%
|
||||
);
|
||||
background-size: 200% 100%;
|
||||
animation: shimmer 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.skeleton-line-sm {
|
||||
@apply w-1/3;
|
||||
}
|
||||
|
||||
.skeleton-line-md {
|
||||
@apply w-2/3;
|
||||
}
|
||||
|
||||
.skeleton-line-lg {
|
||||
@apply w-4/5;
|
||||
}
|
||||
|
||||
.skeleton-line-xl {
|
||||
@apply w-full;
|
||||
}
|
||||
|
||||
.skeleton-page {
|
||||
@apply h-full space-y-4 p-4;
|
||||
}
|
||||
|
||||
.skeleton-header {
|
||||
@apply mb-6;
|
||||
}
|
||||
|
||||
.skeleton-body {
|
||||
@apply space-y-3;
|
||||
}
|
||||
@@ -7,66 +7,114 @@
|
||||
--surface: #ffffff;
|
||||
--line: rgba(100, 116, 139, 0.24);
|
||||
--line-soft: rgba(100, 116, 139, 0.14);
|
||||
--text: #111827;
|
||||
--text: #0f172a;
|
||||
--text-muted: #64748b;
|
||||
--muted: #64748b;
|
||||
--muted-strong: #334155;
|
||||
--primary: #2457c5;
|
||||
--primary-hover: #1d4aa7;
|
||||
--primary-strong: #173f8f;
|
||||
--primary: #2563eb;
|
||||
--primary-hover: #1d4ed8;
|
||||
--primary-strong: #1e40af;
|
||||
--brand: var(--primary);
|
||||
--brand-strong: var(--primary-strong);
|
||||
--accent: #0f766e;
|
||||
--accent: #0d9488;
|
||||
--accent-soft: #e6f6f3;
|
||||
--danger: #c92f4e;
|
||||
--success: #0f766e;
|
||||
--warning: #b7791f;
|
||||
--overlay-strong: rgba(15, 23, 42, 0.58);
|
||||
--shadow-sm: 0 1px 2px rgba(15, 23, 42, 0.045);
|
||||
--shadow-md: 0 8px 18px rgba(15, 23, 42, 0.075);
|
||||
--shadow-lg: 0 18px 44px rgba(15, 23, 42, 0.105);
|
||||
--danger: #dc2626;
|
||||
--success: #059669;
|
||||
--warning: #d97706;
|
||||
--overlay-strong: rgba(15, 23, 42, 0.62);
|
||||
--shadow-sm: 0 1px 3px rgba(15, 23, 42, 0.06), 0 1px 2px rgba(15, 23, 42, 0.04);
|
||||
--shadow-md: 0 4px 6px -1px rgba(15, 23, 42, 0.08), 0 2px 4px -1px rgba(15, 23, 42, 0.05);
|
||||
--shadow-lg: 0 20px 25px -5px rgba(15, 23, 42, 0.10), 0 10px 10px -5px rgba(15, 23, 42, 0.04);
|
||||
--shadow-xl: 0 25px 50px -12px rgba(15, 23, 42, 0.25);
|
||||
--shadow-glow: 0 0 20px rgba(37, 99, 235, 0.15), 0 8px 24px rgba(37, 99, 235, 0.12);
|
||||
--radius-sm: 6px;
|
||||
--radius-md: 8px;
|
||||
--radius-lg: 10px;
|
||||
--radius-xl: 14px;
|
||||
--radius-2xl: 18px;
|
||||
--ease-out-strong: cubic-bezier(0.22, 1, 0.36, 1);
|
||||
--ease-out-soft: cubic-bezier(0.24, 0.8, 0.32, 1);
|
||||
--ease-smooth: cubic-bezier(0.4, 0, 0.2, 1);
|
||||
--ease-out-expo: cubic-bezier(0.16, 1, 0.3, 1);
|
||||
--ease-spring: cubic-bezier(0.34, 1.56, 0.64, 1);
|
||||
--ease-bounce: cubic-bezier(0.68, -0.55, 0.265, 1.55);
|
||||
--dur-instant: 80ms;
|
||||
--dur-quick: 120ms;
|
||||
--dur-fast: 180ms;
|
||||
--dur-medium: 240ms;
|
||||
--dur-panel: 280ms;
|
||||
--dur-slow: 350ms;
|
||||
--actions-gap: clamp(5px, calc((100vw - 520px) * 1), 10px);
|
||||
|
||||
/* Typography Families */
|
||||
--font-sans: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI',
|
||||
'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei UI', 'Microsoft YaHei',
|
||||
'Noto Sans CJK SC', 'Noto Sans SC', Arial, sans-serif;
|
||||
--font-mono: 'SFMono-Regular', 'Cascadia Code', 'Cascadia Mono', Consolas, 'Liberation Mono', monospace;
|
||||
|
||||
/* Typography Scale */
|
||||
--font-xs: 11px;
|
||||
--font-sm: 14px;
|
||||
--font-base: 15px;
|
||||
--font-md: 16px;
|
||||
--font-lg: 17px;
|
||||
--font-xl: 19px;
|
||||
--font-2xl: 21px;
|
||||
--font-3xl: 25px;
|
||||
--font-4xl: 29px;
|
||||
|
||||
/* Line Heights */
|
||||
--leading-tight: 1.25;
|
||||
--leading-snug: 1.375;
|
||||
--leading-normal: 1.5;
|
||||
--leading-relaxed: 1.625;
|
||||
--leading-loose: 1.75;
|
||||
|
||||
/* Letter Spacing */
|
||||
--tracking-tighter: 0;
|
||||
--tracking-tight: 0;
|
||||
--tracking-normal: 0;
|
||||
--tracking-wide: 0;
|
||||
--tracking-wider: 0;
|
||||
|
||||
/* Spacing Scale */
|
||||
--space-1: 4px;
|
||||
--space-2: 8px;
|
||||
--space-3: 12px;
|
||||
--space-4: 16px;
|
||||
--space-5: 20px;
|
||||
--space-6: 24px;
|
||||
--space-8: 32px;
|
||||
--space-10: 40px;
|
||||
}
|
||||
|
||||
:root[data-theme='dark'] {
|
||||
--bg-accent: #101418;
|
||||
--panel: #171d25;
|
||||
--panel-soft: #131922;
|
||||
--panel-muted: #0f151d;
|
||||
--panel-subtle: #1c2430;
|
||||
--surface: #171d25;
|
||||
--line: rgba(148, 163, 184, 0.18);
|
||||
--line-soft: rgba(148, 163, 184, 0.11);
|
||||
--text: #e8edf4;
|
||||
--text-muted: #9aa8ba;
|
||||
--muted: #9aa8ba;
|
||||
--muted-strong: #c4cfdc;
|
||||
--primary: #80b6ff;
|
||||
--primary-hover: #a6cbff;
|
||||
--primary-strong: #d7e8ff;
|
||||
--bg-accent: #0a0e13;
|
||||
--panel: #151b24;
|
||||
--panel-soft: #111720;
|
||||
--panel-muted: #0d1219;
|
||||
--panel-subtle: #1a2230;
|
||||
--surface: #151b24;
|
||||
--line: rgba(148, 163, 184, 0.16);
|
||||
--line-soft: rgba(148, 163, 184, 0.09);
|
||||
--text: #f1f5f9;
|
||||
--text-muted: #94a3b8;
|
||||
--muted: #94a3b8;
|
||||
--muted-strong: #cbd5e1;
|
||||
--primary: #60a5fa;
|
||||
--primary-hover: #93c5fd;
|
||||
--primary-strong: #bfdbfe;
|
||||
--brand: var(--primary);
|
||||
--brand-strong: var(--primary-strong);
|
||||
--accent: #5eead4;
|
||||
--accent-soft: rgba(94, 234, 212, 0.12);
|
||||
--danger: #fb7185;
|
||||
--success: #5eead4;
|
||||
--accent: #2dd4bf;
|
||||
--accent-soft: rgba(45, 212, 191, 0.12);
|
||||
--danger: #f87171;
|
||||
--success: #34d399;
|
||||
--warning: #fbbf24;
|
||||
--overlay-strong: rgba(2, 6, 23, 0.74);
|
||||
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.26);
|
||||
--shadow-md: 0 8px 24px rgba(0, 0, 0, 0.30);
|
||||
--shadow-lg: 0 14px 38px rgba(0, 0, 0, 0.34);
|
||||
--overlay-strong: rgba(0, 0, 0, 0.75);
|
||||
--shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.4), 0 1px 2px rgba(0, 0, 0, 0.3);
|
||||
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.45), 0 2px 4px -1px rgba(0, 0, 0, 0.35);
|
||||
--shadow-lg: 0 20px 25px -5px rgba(0, 0, 0, 0.50), 0 10px 10px -5px rgba(0, 0, 0, 0.40);
|
||||
--shadow-xl: 0 25px 50px -12px rgba(0, 0, 0, 0.60);
|
||||
--shadow-glow: 0 0 20px rgba(96, 165, 250, 0.20), 0 8px 24px rgba(96, 165, 250, 0.15);
|
||||
}
|
||||
|
||||
@@ -21,7 +21,13 @@
|
||||
}
|
||||
|
||||
.sidebar-title {
|
||||
@apply mb-2 text-[13px] font-bold text-slate-700;
|
||||
@apply mb-2;
|
||||
font-size: var(--font-xs);
|
||||
font-weight: 700;
|
||||
letter-spacing: var(--tracking-wider);
|
||||
text-transform: uppercase;
|
||||
color: var(--muted);
|
||||
line-height: var(--leading-tight);
|
||||
}
|
||||
|
||||
.sidebar-title-row {
|
||||
@@ -86,17 +92,25 @@
|
||||
}
|
||||
|
||||
.tree-btn {
|
||||
@apply mb-1 flex w-full min-w-0 cursor-pointer items-center gap-2 rounded-lg border-0 bg-transparent px-2.5 py-2 text-left transition;
|
||||
@apply mb-1 flex w-full min-w-0 cursor-pointer items-center border-0 bg-transparent px-2.5 py-2 text-left transition;
|
||||
gap: var(--space-2);
|
||||
border-radius: var(--radius-md);
|
||||
font-size: var(--font-sm);
|
||||
font-weight: 500;
|
||||
line-height: var(--leading-snug);
|
||||
letter-spacing: var(--tracking-normal);
|
||||
color: var(--muted-strong);
|
||||
}
|
||||
|
||||
.tree-btn:hover {
|
||||
background: rgba(37, 99, 235, 0.05);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.tree-btn.active {
|
||||
background: rgba(37, 99, 235, 0.09);
|
||||
color: var(--primary-strong);
|
||||
font-weight: 700;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.tree-icon {
|
||||
@@ -170,29 +184,170 @@
|
||||
gap: var(--actions-gap);
|
||||
}
|
||||
|
||||
.toolbar.actions.duplicates-toolbar {
|
||||
@apply items-center;
|
||||
}
|
||||
|
||||
.toolbar .btn.small {
|
||||
@apply h-[30px] rounded-full text-xs;
|
||||
@apply h-[32px] rounded-full text-xs;
|
||||
}
|
||||
|
||||
.duplicate-mode-select {
|
||||
@apply h-8 min-w-[150px] rounded-full py-0 pl-3 pr-6 text-xs;
|
||||
border-color: rgba(74, 103, 150, 0.26);
|
||||
box-shadow: none;
|
||||
line-height: 32px;
|
||||
background-position:
|
||||
calc(100% - 10px) calc(50% - 2px),
|
||||
calc(100% - 6px) calc(50% - 2px);
|
||||
background-size: 5px 5px, 5px 5px;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
|
||||
select.input.duplicate-mode-toolbar-select {
|
||||
height: 32px;
|
||||
padding-top: 0;
|
||||
padding-right: 24px;
|
||||
padding-bottom: 0;
|
||||
line-height: 32px;
|
||||
background-position:
|
||||
calc(100% - 10px) calc(50% - 2px),
|
||||
calc(100% - 6px) calc(50% - 2px);
|
||||
background-size: 5px 5px, 5px 5px;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
|
||||
.duplicate-mode-head-select {
|
||||
@apply h-[34px] w-auto min-w-[156px] max-w-full;
|
||||
}
|
||||
|
||||
.duplicate-mode-head-menu {
|
||||
@apply min-w-0;
|
||||
}
|
||||
|
||||
.duplicate-mode-toolbar-select {
|
||||
@apply w-auto max-w-[170px] shrink-0;
|
||||
}
|
||||
|
||||
.list-head {
|
||||
@apply mb-2 flex items-center gap-2.5;
|
||||
@apply mb-1.5 flex items-center gap-2;
|
||||
min-height: 34px;
|
||||
}
|
||||
|
||||
.list-head .search-input-wrap {
|
||||
.list-head.selection-mode {
|
||||
@apply gap-2;
|
||||
}
|
||||
|
||||
.list-head.selection-mode > .btn.small {
|
||||
@apply min-w-0 flex-1 justify-center;
|
||||
}
|
||||
|
||||
.list-head .search-input-wrap,
|
||||
.duplicate-mode-head-menu {
|
||||
@apply min-w-0 flex-auto;
|
||||
}
|
||||
|
||||
.list-head .search-input {
|
||||
@apply h-[42px];
|
||||
@apply h-[34px] rounded-[10px] px-3 py-0 text-[13px] font-semibold;
|
||||
line-height: 34px;
|
||||
}
|
||||
|
||||
.list-head .btn {
|
||||
@apply whitespace-nowrap;
|
||||
@apply h-[34px] whitespace-nowrap rounded-[10px] px-3 py-0 text-[13px];
|
||||
}
|
||||
|
||||
.list-head .btn,
|
||||
.list-head .search-input,
|
||||
.list-head .sort-trigger,
|
||||
.list-head .list-icon-btn {
|
||||
animation: none !important;
|
||||
transition: none !important;
|
||||
transform: none !important;
|
||||
}
|
||||
|
||||
.list-head .btn:hover:not(:disabled),
|
||||
.list-head .btn:active:not(:disabled) {
|
||||
transform: none !important;
|
||||
}
|
||||
|
||||
.mobile-vault-filter-row {
|
||||
@apply hidden;
|
||||
}
|
||||
|
||||
.mobile-vault-filter-control {
|
||||
@apply relative min-w-0;
|
||||
}
|
||||
|
||||
.mobile-vault-filter-trigger {
|
||||
@apply flex h-[34px] w-full min-w-0 cursor-pointer items-center gap-1.5 rounded-[10px] border px-2.5 py-0 text-left text-[13px] font-semibold;
|
||||
background: var(--panel);
|
||||
border-color: rgba(74, 103, 150, 0.28);
|
||||
color: var(--muted-strong);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.74);
|
||||
transition:
|
||||
border-color var(--dur-fast) var(--ease-smooth),
|
||||
background-color var(--dur-fast) var(--ease-smooth),
|
||||
color var(--dur-fast) var(--ease-smooth),
|
||||
box-shadow var(--dur-fast) var(--ease-smooth);
|
||||
}
|
||||
|
||||
.mobile-vault-filter-trigger:hover,
|
||||
.mobile-vault-filter-trigger.active {
|
||||
border-color: rgba(43, 102, 217, 0.46);
|
||||
background: #f8fbff;
|
||||
color: var(--primary-strong);
|
||||
}
|
||||
|
||||
.mobile-vault-filter-trigger:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.14), inset 0 1px 0 rgba(255, 255, 255, 0.86);
|
||||
}
|
||||
|
||||
.mobile-vault-filter-trigger-icon,
|
||||
.mobile-vault-filter-item-icon {
|
||||
@apply inline-flex shrink-0 items-center justify-center;
|
||||
}
|
||||
|
||||
.mobile-vault-filter-trigger-label {
|
||||
@apply min-w-0 flex-1 overflow-hidden text-ellipsis whitespace-nowrap;
|
||||
}
|
||||
|
||||
.mobile-vault-filter-chevron {
|
||||
@apply shrink-0;
|
||||
}
|
||||
|
||||
.mobile-vault-filter-trigger.active .mobile-vault-filter-chevron {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
|
||||
.mobile-vault-filter-menu {
|
||||
@apply left-0 right-auto max-h-[280px] min-w-full overflow-auto;
|
||||
min-width: max(100%, 168px);
|
||||
}
|
||||
|
||||
.mobile-vault-filter-control:last-child .mobile-vault-filter-menu {
|
||||
@apply left-auto right-0;
|
||||
}
|
||||
|
||||
.mobile-vault-filter-item {
|
||||
@apply gap-2;
|
||||
}
|
||||
|
||||
.mobile-vault-filter-item-main {
|
||||
@apply flex min-w-0 items-center gap-2;
|
||||
}
|
||||
|
||||
.mobile-vault-filter-item-main span:last-child {
|
||||
@apply min-w-0 overflow-hidden text-ellipsis whitespace-nowrap;
|
||||
}
|
||||
|
||||
.list-count {
|
||||
@apply shrink-0 whitespace-nowrap text-xs;
|
||||
color: var(--text-muted);
|
||||
@apply shrink-0 whitespace-nowrap;
|
||||
font-size: var(--font-xs);
|
||||
font-weight: 600;
|
||||
letter-spacing: var(--tracking-wide);
|
||||
color: var(--muted);
|
||||
line-height: var(--leading-tight);
|
||||
}
|
||||
|
||||
.list-icon-btn {
|
||||
@@ -207,6 +362,10 @@
|
||||
@apply w-9 min-w-9 justify-center gap-0 p-0;
|
||||
}
|
||||
|
||||
.sort-trigger.sort-trigger-labeled {
|
||||
@apply h-[34px] w-auto min-w-0 gap-1.5 rounded-[10px] px-3;
|
||||
}
|
||||
|
||||
.sort-trigger.active {
|
||||
background: #e9f1ff;
|
||||
border-color: #a9c2ee;
|
||||
@@ -248,6 +407,30 @@
|
||||
@apply h-3.5 w-3.5 shrink-0;
|
||||
}
|
||||
|
||||
.desktop-create-menu-wrap {
|
||||
@apply shrink-0;
|
||||
}
|
||||
|
||||
.desktop-create-trigger {
|
||||
@apply h-[34px] w-[34px] min-w-[34px] gap-0 rounded-[10px] p-0 text-[0];
|
||||
}
|
||||
|
||||
.desktop-create-trigger .btn-icon {
|
||||
@apply m-0;
|
||||
}
|
||||
|
||||
.duplicates-helper-toolbar {
|
||||
@apply justify-start pb-0.5;
|
||||
}
|
||||
|
||||
.duplicates-helper-toolbar .btn.small {
|
||||
@apply h-[34px] rounded-[10px] px-3 py-0 text-[13px];
|
||||
}
|
||||
|
||||
.list-count-status {
|
||||
@apply mb-1 pl-1;
|
||||
}
|
||||
|
||||
.list-panel {
|
||||
@apply min-h-0 overflow-auto p-2;
|
||||
/* Virtualized rows update top/bottom spacers while scrolling. Chrome's scroll anchoring
|
||||
@@ -263,6 +446,11 @@
|
||||
overflow-anchor: none;
|
||||
}
|
||||
|
||||
.list-item.duplicate-group-item {
|
||||
background: hsl(var(--duplicate-group-hue) 84% 94%);
|
||||
border-color: hsl(var(--duplicate-group-hue) 42% 78%);
|
||||
}
|
||||
|
||||
.list-item::before {
|
||||
content: '';
|
||||
@apply absolute inset-0 opacity-0;
|
||||
@@ -343,6 +531,11 @@
|
||||
box-shadow: 0 10px 22px rgba(15, 23, 42, 0.06), 0 0 0 1px rgba(37, 99, 235, 0.04);
|
||||
}
|
||||
|
||||
.list-item.duplicate-group-item:hover {
|
||||
background: hsl(var(--duplicate-group-hue) 88% 92%);
|
||||
border-color: hsl(var(--duplicate-group-hue) 52% 68%);
|
||||
}
|
||||
|
||||
.list-item:hover::before {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
@@ -354,6 +547,11 @@
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.42);
|
||||
}
|
||||
|
||||
.list-item.duplicate-group-item.active {
|
||||
background: hsl(var(--duplicate-group-hue) 88% 89%);
|
||||
border-color: hsl(var(--duplicate-group-hue) 58% 58%);
|
||||
}
|
||||
|
||||
.list-item.active::before {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
@@ -525,7 +723,12 @@
|
||||
}
|
||||
|
||||
.list-title {
|
||||
@apply flex min-w-0 items-center gap-1.5 text-[15px] font-bold;
|
||||
@apply flex min-w-0 items-center;
|
||||
gap: var(--space-2);
|
||||
font-size: var(--font-base);
|
||||
font-weight: 600;
|
||||
line-height: var(--leading-tight);
|
||||
letter-spacing: var(--tracking-tight);
|
||||
color: var(--primary-strong);
|
||||
transition: color var(--dur-fast) var(--ease-smooth), letter-spacing 220ms var(--ease-out-soft);
|
||||
}
|
||||
@@ -569,7 +772,7 @@
|
||||
|
||||
.list-item:hover .list-title,
|
||||
.list-item.active .list-title {
|
||||
letter-spacing: -0.012em;
|
||||
letter-spacing: var(--tracking-tighter);
|
||||
}
|
||||
|
||||
.list-item:hover .list-sub,
|
||||
@@ -614,11 +817,19 @@
|
||||
|
||||
.detail-title {
|
||||
@apply m-0 overflow-hidden text-ellipsis whitespace-nowrap;
|
||||
font-size: var(--font-2xl);
|
||||
font-weight: 600;
|
||||
line-height: var(--leading-tight);
|
||||
letter-spacing: var(--tracking-tighter);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.detail-sub {
|
||||
@apply mt-2;
|
||||
color: #667085;
|
||||
font-size: var(--font-sm);
|
||||
line-height: var(--leading-relaxed);
|
||||
letter-spacing: var(--tracking-normal);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.password-history-link {
|
||||
@@ -869,7 +1080,7 @@
|
||||
|
||||
.totp-codes-list {
|
||||
@apply grid w-full items-start gap-2.5;
|
||||
grid-template-columns: repeat(var(--totp-columns, 1), minmax(300px, 1fr));
|
||||
grid-template-columns: repeat(var(--totp-columns, 1), minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.totp-code-row {
|
||||
@@ -894,7 +1105,7 @@
|
||||
}
|
||||
|
||||
.totp-code-main strong {
|
||||
@apply whitespace-nowrap text-[22px] leading-none;
|
||||
@apply min-w-0 whitespace-nowrap text-[22px] leading-none;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
|
||||